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.

259986 lines
7.7MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. This monolithic file contains the entire Juce source tree!
  25. To build an app which uses Juce, all you need to do is to add this
  26. file to your project, and include juce.h in your own cpp files.
  27. */
  28. //==============================================================================
  29. #ifdef _WIN32
  30. /********* Start of inlined file: win32_headers.h *********/
  31. #ifndef __WIN32_HEADERS_JUCEHEADER__
  32. #define __WIN32_HEADERS_JUCEHEADER__
  33. #ifndef STRICT
  34. #define STRICT 1
  35. #endif
  36. #define WIN32_LEAN_AND_MEAN
  37. // don't want to get told about microsoft's mistakes..
  38. #ifdef _MSC_VER
  39. #pragma warning (push)
  40. #pragma warning (disable : 4100 4201)
  41. #endif
  42. // use Platform SDK as win2000 unless this is disabled
  43. #ifndef DISABLE_TRANSPARENT_WINDOWS
  44. #define _WIN32_WINNT 0x0500
  45. #endif
  46. #define _UNICODE 1
  47. #define UNICODE 1
  48. #include <windows.h>
  49. #include <commdlg.h>
  50. #include <shellapi.h>
  51. #include <mmsystem.h>
  52. #include <vfw.h>
  53. #include <tchar.h>
  54. #undef PACKED
  55. #ifdef _MSC_VER
  56. #pragma warning (pop)
  57. #endif
  58. #endif // __WIN32_HEADERS_JUCEHEADER__
  59. /********* End of inlined file: win32_headers.h *********/
  60. #include <winsock2.h>
  61. #include <mapi.h>
  62. #include <ctime>
  63. #if JUCE_QUICKTIME
  64. #include <Movies.h>
  65. #include <QTML.h>
  66. #include <QuickTimeComponents.h>
  67. #include <MediaHandlers.h>
  68. #include <ImageCodec.h>
  69. #undef TARGET_OS_MAC // quicktime sets these, but they confuse some of the 3rd party libs
  70. #undef MACOS
  71. #endif
  72. #elif defined (LINUX)
  73. #else
  74. #include <Carbon/Carbon.h>
  75. #include <CoreAudio/HostTime.h>
  76. #define __Point__
  77. #include <IOKit/IOKitLib.h>
  78. #include <IOKit/graphics/IOGraphicsTypes.h>
  79. #include <IOKit/network/IOEthernetInterface.h>
  80. #include <IOKit/network/IONetworkInterface.h>
  81. #include <IOKit/network/IOEthernetController.h>
  82. #include <IOKit/IOCFPlugIn.h>
  83. #include <IOKit/hid/IOHIDLib.h>
  84. #include <IOKit/hid/IOHIDKeys.h>
  85. #include <sys/filedesc.h>
  86. #include <sys/time.h>
  87. #include <sys/proc.h>
  88. #include <Kernel/libkern/OSTypes.h>
  89. #endif
  90. //==============================================================================
  91. #define DONT_SET_USING_JUCE_NAMESPACE 1
  92. #include "juce_amalgamated.h"
  93. #define NO_DUMMY_DECL
  94. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  95. #pragma warning (disable: 4309 4305)
  96. #endif
  97. //==============================================================================
  98. /********* Start of inlined file: juce_FileLogger.cpp *********/
  99. BEGIN_JUCE_NAMESPACE
  100. FileLogger::FileLogger (const File& logFile_,
  101. const String& welcomeMessage,
  102. const int maxInitialFileSizeBytes)
  103. : logFile (logFile_)
  104. {
  105. if (maxInitialFileSizeBytes >= 0)
  106. trimFileSize (maxInitialFileSizeBytes);
  107. if (! logFile_.exists())
  108. {
  109. // do this so that the parent directories get created..
  110. logFile_.create();
  111. }
  112. logStream = logFile_.createOutputStream (256);
  113. jassert (logStream != 0);
  114. String welcome;
  115. welcome << "\r\n**********************************************************\r\n"
  116. << welcomeMessage
  117. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  118. << "\r\n";
  119. logMessage (welcome);
  120. }
  121. FileLogger::~FileLogger()
  122. {
  123. deleteAndZero (logStream);
  124. }
  125. void FileLogger::logMessage (const String& message)
  126. {
  127. if (logStream != 0)
  128. {
  129. Logger::outputDebugString (message);
  130. const ScopedLock sl (logLock);
  131. (*logStream) << message << T("\r\n");
  132. logStream->flush();
  133. }
  134. }
  135. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  136. {
  137. if (maxFileSizeBytes <= 0)
  138. {
  139. logFile.deleteFile();
  140. }
  141. else
  142. {
  143. const int64 fileSize = logFile.getSize();
  144. if (fileSize > maxFileSizeBytes)
  145. {
  146. FileInputStream* const in = logFile.createInputStream();
  147. jassert (in != 0);
  148. if (in != 0)
  149. {
  150. in->setPosition (fileSize - maxFileSizeBytes);
  151. String content;
  152. {
  153. MemoryBlock contentToSave;
  154. contentToSave.setSize (maxFileSizeBytes + 4);
  155. contentToSave.fillWith (0);
  156. in->read (contentToSave.getData(), maxFileSizeBytes);
  157. delete in;
  158. content = contentToSave.toString();
  159. }
  160. int newStart = 0;
  161. while (newStart < fileSize
  162. && content[newStart] != '\n'
  163. && content[newStart] != '\r')
  164. ++newStart;
  165. logFile.deleteFile();
  166. logFile.appendText (content.substring (newStart), false, false);
  167. }
  168. }
  169. }
  170. }
  171. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  172. const String& logFileName,
  173. const String& welcomeMessage,
  174. const int maxInitialFileSizeBytes)
  175. {
  176. #if JUCE_MAC
  177. File logFile ("~/Library/Logs");
  178. logFile = logFile.getChildFile (logFileName);
  179. #else
  180. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  181. if (logFile.isDirectory())
  182. {
  183. logFile = logFile.getChildFile (logFileSubDirectoryName)
  184. .getChildFile (logFileName);
  185. }
  186. #endif
  187. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  188. }
  189. END_JUCE_NAMESPACE
  190. /********* End of inlined file: juce_FileLogger.cpp *********/
  191. /********* Start of inlined file: juce_Logger.cpp *********/
  192. BEGIN_JUCE_NAMESPACE
  193. Logger::Logger()
  194. {
  195. }
  196. Logger::~Logger()
  197. {
  198. }
  199. static Logger* currentLogger = 0;
  200. void Logger::setCurrentLogger (Logger* const newLogger,
  201. const bool deleteOldLogger)
  202. {
  203. Logger* const oldLogger = currentLogger;
  204. currentLogger = newLogger;
  205. if (deleteOldLogger && (oldLogger != 0))
  206. delete oldLogger;
  207. }
  208. void Logger::writeToLog (const String& message)
  209. {
  210. if (currentLogger != 0)
  211. currentLogger->logMessage (message);
  212. else
  213. outputDebugString (message);
  214. }
  215. #if JUCE_LOG_ASSERTIONS
  216. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  217. {
  218. String m ("JUCE Assertion failure in ");
  219. m << filename << ", line " << lineNum;
  220. Logger::writeToLog (m);
  221. }
  222. #endif
  223. END_JUCE_NAMESPACE
  224. /********* End of inlined file: juce_Logger.cpp *********/
  225. /********* Start of inlined file: juce_Random.cpp *********/
  226. BEGIN_JUCE_NAMESPACE
  227. Random::Random (const int64 seedValue) throw()
  228. : seed (seedValue)
  229. {
  230. }
  231. Random::~Random() throw()
  232. {
  233. }
  234. void Random::setSeed (const int64 newSeed) throw()
  235. {
  236. seed = newSeed;
  237. }
  238. int Random::nextInt() throw()
  239. {
  240. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  241. return (int) (seed >> 16);
  242. }
  243. int Random::nextInt (const int maxValue) throw()
  244. {
  245. jassert (maxValue > 0);
  246. return (nextInt() & 0x7fffffff) % maxValue;
  247. }
  248. int64 Random::nextInt64() throw()
  249. {
  250. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  251. }
  252. bool Random::nextBool() throw()
  253. {
  254. return (nextInt() & 0x80000000) != 0;
  255. }
  256. float Random::nextFloat() throw()
  257. {
  258. return ((uint32) nextInt()) / (float) 0xffffffff;
  259. }
  260. double Random::nextDouble() throw()
  261. {
  262. return ((uint32) nextInt()) / (double) 0xffffffff;
  263. }
  264. static Random sysRand (1);
  265. Random& Random::getSystemRandom() throw()
  266. {
  267. return sysRand;
  268. }
  269. END_JUCE_NAMESPACE
  270. /********* End of inlined file: juce_Random.cpp *********/
  271. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  272. BEGIN_JUCE_NAMESPACE
  273. RelativeTime::RelativeTime (const double seconds_) throw()
  274. : seconds (seconds_)
  275. {
  276. }
  277. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  278. : seconds (other.seconds)
  279. {
  280. }
  281. RelativeTime::~RelativeTime() throw()
  282. {
  283. }
  284. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  285. {
  286. return RelativeTime (milliseconds * 0.001);
  287. }
  288. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  289. {
  290. return RelativeTime (milliseconds * 0.001);
  291. }
  292. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  293. {
  294. return RelativeTime (numberOfMinutes * 60.0);
  295. }
  296. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  297. {
  298. return RelativeTime (numberOfHours * (60.0 * 60.0));
  299. }
  300. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  301. {
  302. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  303. }
  304. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  305. {
  306. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  307. }
  308. int64 RelativeTime::inMilliseconds() const throw()
  309. {
  310. return (int64)(seconds * 1000.0);
  311. }
  312. double RelativeTime::inMinutes() const throw()
  313. {
  314. return seconds / 60.0;
  315. }
  316. double RelativeTime::inHours() const throw()
  317. {
  318. return seconds / (60.0 * 60.0);
  319. }
  320. double RelativeTime::inDays() const throw()
  321. {
  322. return seconds / (60.0 * 60.0 * 24.0);
  323. }
  324. double RelativeTime::inWeeks() const throw()
  325. {
  326. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  327. }
  328. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  329. {
  330. if (seconds < 0.001 && seconds > -0.001)
  331. return returnValueForZeroTime;
  332. String result;
  333. if (seconds < 0)
  334. result = T("-");
  335. int fieldsShown = 0;
  336. int n = abs ((int) inWeeks());
  337. if (n > 0)
  338. {
  339. result << n << ((n == 1) ? TRANS(" week ")
  340. : TRANS(" weeks "));
  341. ++fieldsShown;
  342. }
  343. n = abs ((int) inDays()) % 7;
  344. if (n > 0)
  345. {
  346. result << n << ((n == 1) ? TRANS(" day ")
  347. : TRANS(" days "));
  348. ++fieldsShown;
  349. }
  350. if (fieldsShown < 2)
  351. {
  352. n = abs ((int) inHours()) % 24;
  353. if (n > 0)
  354. {
  355. result << n << ((n == 1) ? TRANS(" hr ")
  356. : TRANS(" hrs "));
  357. ++fieldsShown;
  358. }
  359. if (fieldsShown < 2)
  360. {
  361. n = abs ((int) inMinutes()) % 60;
  362. if (n > 0)
  363. {
  364. result << n << ((n == 1) ? TRANS(" min ")
  365. : TRANS(" mins "));
  366. ++fieldsShown;
  367. }
  368. if (fieldsShown < 2)
  369. {
  370. n = abs ((int) inSeconds()) % 60;
  371. if (n > 0)
  372. {
  373. result << n << ((n == 1) ? TRANS(" sec ")
  374. : TRANS(" secs "));
  375. ++fieldsShown;
  376. }
  377. if (fieldsShown < 1)
  378. {
  379. n = abs ((int) inMilliseconds()) % 1000;
  380. if (n > 0)
  381. {
  382. result << n << TRANS(" ms");
  383. ++fieldsShown;
  384. }
  385. }
  386. }
  387. }
  388. }
  389. return result.trimEnd();
  390. }
  391. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  392. {
  393. seconds = other.seconds;
  394. return *this;
  395. }
  396. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  397. {
  398. return seconds == other.seconds;
  399. }
  400. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  401. {
  402. return seconds != other.seconds;
  403. }
  404. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  405. {
  406. return seconds > other.seconds;
  407. }
  408. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  409. {
  410. return seconds < other.seconds;
  411. }
  412. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  413. {
  414. return seconds >= other.seconds;
  415. }
  416. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  417. {
  418. return seconds <= other.seconds;
  419. }
  420. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  421. {
  422. return RelativeTime (seconds + timeToAdd.seconds);
  423. }
  424. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  425. {
  426. return RelativeTime (seconds - timeToSubtract.seconds);
  427. }
  428. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  429. {
  430. return RelativeTime (seconds + secondsToAdd);
  431. }
  432. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  433. {
  434. return RelativeTime (seconds - secondsToSubtract);
  435. }
  436. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  437. {
  438. seconds += timeToAdd.seconds;
  439. return *this;
  440. }
  441. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  442. {
  443. seconds -= timeToSubtract.seconds;
  444. return *this;
  445. }
  446. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  447. {
  448. seconds += secondsToAdd;
  449. return *this;
  450. }
  451. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  452. {
  453. seconds -= secondsToSubtract;
  454. return *this;
  455. }
  456. END_JUCE_NAMESPACE
  457. /********* End of inlined file: juce_RelativeTime.cpp *********/
  458. /********* Start of inlined file: juce_SystemStats.cpp *********/
  459. BEGIN_JUCE_NAMESPACE
  460. void juce_initialiseStrings();
  461. const String SystemStats::getJUCEVersion() throw()
  462. {
  463. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  464. }
  465. static bool juceInitialisedNonGUI = false;
  466. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  467. {
  468. if (! juceInitialisedNonGUI)
  469. {
  470. #ifdef JUCE_DEBUG
  471. // Some simple test code to keep an eye on things and make sure these functions
  472. // work ok on all platforms. Let me know if any of these assertions fail!
  473. int n = 1;
  474. atomicIncrement (n);
  475. jassert (atomicIncrementAndReturn (n) == 3);
  476. atomicDecrement (n);
  477. jassert (atomicDecrementAndReturn (n) == 1);
  478. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  479. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  480. SystemStats* nullPointer = 0;
  481. juce_free (nullPointer);
  482. delete[] nullPointer;
  483. delete nullPointer;
  484. #endif
  485. // Now the real initialisation..
  486. juceInitialisedNonGUI = true;
  487. DBG (SystemStats::getJUCEVersion());
  488. juce_initialiseStrings();
  489. SystemStats::initialiseStats();
  490. Random::getSystemRandom().setSeed (Time::currentTimeMillis());
  491. }
  492. }
  493. #if JUCE_WIN32
  494. // This is imported from the sockets code..
  495. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  496. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  497. #endif
  498. #if JUCE_DEBUG
  499. extern void juce_CheckForDanglingStreams();
  500. #endif
  501. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  502. {
  503. if (juceInitialisedNonGUI)
  504. {
  505. #if JUCE_WIN32
  506. // need to shut down sockets if they were used..
  507. if (juce_CloseWin32SocketLib != 0)
  508. (*juce_CloseWin32SocketLib)();
  509. #endif
  510. LocalisedStrings::setCurrentMappings (0);
  511. Thread::stopAllThreads (3000);
  512. #if JUCE_DEBUG
  513. juce_CheckForDanglingStreams();
  514. #endif
  515. juceInitialisedNonGUI = false;
  516. }
  517. }
  518. #ifdef JUCE_DLL
  519. void* juce_Malloc (const int size)
  520. {
  521. return malloc (size);
  522. }
  523. void* juce_Calloc (const int size)
  524. {
  525. return calloc (1, size);
  526. }
  527. void* juce_Realloc (void* const block, const int size)
  528. {
  529. return realloc (block, size);
  530. }
  531. void juce_Free (void* const block)
  532. {
  533. free (block);
  534. }
  535. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  536. void* juce_DebugMalloc (const int size, const char* file, const int line)
  537. {
  538. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  539. }
  540. void* juce_DebugCalloc (const int size, const char* file, const int line)
  541. {
  542. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  543. }
  544. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  545. {
  546. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  547. }
  548. void juce_DebugFree (void* const block)
  549. {
  550. _free_dbg (block, _NORMAL_BLOCK);
  551. }
  552. #endif
  553. #endif
  554. END_JUCE_NAMESPACE
  555. /********* End of inlined file: juce_SystemStats.cpp *********/
  556. /********* Start of inlined file: juce_Time.cpp *********/
  557. #ifdef _MSC_VER
  558. #pragma warning (disable: 4514)
  559. #pragma warning (push)
  560. #endif
  561. #ifndef JUCE_WIN32
  562. #include <sys/time.h>
  563. #else
  564. #include <ctime>
  565. #endif
  566. #include <sys/timeb.h>
  567. BEGIN_JUCE_NAMESPACE
  568. #ifdef _MSC_VER
  569. #pragma warning (pop)
  570. #ifdef _INC_TIME_INL
  571. #define USE_NEW_SECURE_TIME_FNS
  572. #endif
  573. #endif
  574. static void millisToLocal (const int64 millis, struct tm& result) throw()
  575. {
  576. const int64 seconds = millis / 1000;
  577. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  578. {
  579. // use extended maths for dates beyond 1970 to 2037..
  580. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  581. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  582. const int days = (int) (jdm / literal64bit (86400));
  583. const int a = 32044 + days;
  584. const int b = (4 * a + 3) / 146097;
  585. const int c = a - (b * 146097) / 4;
  586. const int d = (4 * c + 3) / 1461;
  587. const int e = c - (d * 1461) / 4;
  588. const int m = (5 * e + 2) / 153;
  589. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  590. result.tm_mon = m + 2 - 12 * (m / 10);
  591. result.tm_year = b * 100 + d - 6700 + (m / 10);
  592. result.tm_wday = (days + 1) % 7;
  593. result.tm_yday = -1;
  594. int t = (int) (jdm % literal64bit (86400));
  595. result.tm_hour = t / 3600;
  596. t %= 3600;
  597. result.tm_min = t / 60;
  598. result.tm_sec = t % 60;
  599. result.tm_isdst = -1;
  600. }
  601. else
  602. {
  603. time_t now = (time_t) (seconds);
  604. #if JUCE_WIN32
  605. #ifdef USE_NEW_SECURE_TIME_FNS
  606. if (now >= 0 && now <= 0x793406fff)
  607. localtime_s (&result, &now);
  608. else
  609. zeromem (&result, sizeof (result));
  610. #else
  611. result = *localtime (&now);
  612. #endif
  613. #else
  614. // more thread-safe
  615. localtime_r (&now, &result);
  616. #endif
  617. }
  618. }
  619. Time::Time() throw()
  620. : millisSinceEpoch (0)
  621. {
  622. }
  623. Time::Time (const Time& other) throw()
  624. : millisSinceEpoch (other.millisSinceEpoch)
  625. {
  626. }
  627. Time::Time (const int64 ms) throw()
  628. : millisSinceEpoch (ms)
  629. {
  630. }
  631. Time::Time (const int year,
  632. const int month,
  633. const int day,
  634. const int hours,
  635. const int minutes,
  636. const int seconds,
  637. const int milliseconds) throw()
  638. {
  639. jassert (year > 100); // year must be a 4-digit version
  640. if (year < 1971 || year >= 2038)
  641. {
  642. // use extended maths for dates beyond 1970 to 2037..
  643. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  644. const int a = (13 - month) / 12;
  645. const int y = year + 4800 - a;
  646. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  647. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  648. - 32045;
  649. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  650. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  651. + milliseconds;
  652. }
  653. else
  654. {
  655. struct tm t;
  656. t.tm_year = year - 1900;
  657. t.tm_mon = month;
  658. t.tm_mday = day;
  659. t.tm_hour = hours;
  660. t.tm_min = minutes;
  661. t.tm_sec = seconds;
  662. t.tm_isdst = -1;
  663. millisSinceEpoch = 1000 * (int64) mktime (&t);
  664. if (millisSinceEpoch < 0)
  665. millisSinceEpoch = 0;
  666. else
  667. millisSinceEpoch += milliseconds;
  668. }
  669. }
  670. Time::~Time() throw()
  671. {
  672. }
  673. const Time& Time::operator= (const Time& other) throw()
  674. {
  675. millisSinceEpoch = other.millisSinceEpoch;
  676. return *this;
  677. }
  678. int64 Time::currentTimeMillis() throw()
  679. {
  680. static uint32 lastCounterResult = 0xffffffff;
  681. static int64 correction = 0;
  682. const uint32 now = getMillisecondCounter();
  683. // check the counter hasn't wrapped (also triggered the first time this function is called)
  684. if (now < lastCounterResult)
  685. {
  686. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  687. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  688. {
  689. // get the time once using normal library calls, and store the difference needed to
  690. // turn the millisecond counter into a real time.
  691. #if JUCE_WIN32
  692. struct _timeb t;
  693. #ifdef USE_NEW_SECURE_TIME_FNS
  694. _ftime_s (&t);
  695. #else
  696. _ftime (&t);
  697. #endif
  698. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  699. #else
  700. struct timeval tv;
  701. struct timezone tz;
  702. gettimeofday (&tv, &tz);
  703. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  704. #endif
  705. }
  706. }
  707. lastCounterResult = now;
  708. return correction + now;
  709. }
  710. uint32 juce_millisecondsSinceStartup() throw();
  711. static uint32 lastMSCounterValue = 0;
  712. uint32 Time::getMillisecondCounter() throw()
  713. {
  714. const uint32 now = juce_millisecondsSinceStartup();
  715. if (now < lastMSCounterValue)
  716. {
  717. // in multi-threaded apps this might be called concurrently, so
  718. // make sure that our last counter value only increases and doesn't
  719. // go backwards..
  720. if (now < lastMSCounterValue - 1000)
  721. lastMSCounterValue = now;
  722. }
  723. else
  724. {
  725. lastMSCounterValue = now;
  726. }
  727. return now;
  728. }
  729. uint32 Time::getApproximateMillisecondCounter() throw()
  730. {
  731. jassert (lastMSCounterValue != 0);
  732. return lastMSCounterValue;
  733. }
  734. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  735. {
  736. for (;;)
  737. {
  738. const uint32 now = getMillisecondCounter();
  739. if (now >= targetTime)
  740. break;
  741. const int toWait = targetTime - now;
  742. if (toWait > 2)
  743. {
  744. Thread::sleep (jmin (20, toWait >> 1));
  745. }
  746. else
  747. {
  748. // xxx should consider using mutex_pause on the mac as it apparently
  749. // makes it seem less like a spinlock and avoids lowering the thread pri.
  750. for (int i = 10; --i >= 0;)
  751. Thread::yield();
  752. }
  753. }
  754. }
  755. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  756. {
  757. return ticks / (double) getHighResolutionTicksPerSecond();
  758. }
  759. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  760. {
  761. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  762. }
  763. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  764. {
  765. return Time (currentTimeMillis());
  766. }
  767. const String Time::toString (const bool includeDate,
  768. const bool includeTime,
  769. const bool includeSeconds,
  770. const bool use24HourClock) const throw()
  771. {
  772. String result;
  773. if (includeDate)
  774. {
  775. result << getDayOfMonth() << ' '
  776. << getMonthName (true) << ' '
  777. << getYear();
  778. if (includeTime)
  779. result << ' ';
  780. }
  781. if (includeTime)
  782. {
  783. if (includeSeconds)
  784. {
  785. result += String::formatted (T("%d:%02d:%02d "),
  786. (use24HourClock) ? getHours()
  787. : getHoursInAmPmFormat(),
  788. getMinutes(),
  789. getSeconds());
  790. }
  791. else
  792. {
  793. result += String::formatted (T("%d.%02d"),
  794. (use24HourClock) ? getHours()
  795. : getHoursInAmPmFormat(),
  796. getMinutes());
  797. }
  798. if (! use24HourClock)
  799. result << (isAfternoon() ? "pm" : "am");
  800. }
  801. return result.trimEnd();
  802. }
  803. const String Time::formatted (const tchar* const format) const throw()
  804. {
  805. tchar buffer[80];
  806. struct tm t;
  807. millisToLocal (millisSinceEpoch, t);
  808. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  809. {
  810. int bufferSize = 128;
  811. for (;;)
  812. {
  813. MemoryBlock mb (bufferSize * sizeof (tchar));
  814. tchar* const b = (tchar*) mb.getData();
  815. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  816. return String (b);
  817. bufferSize += 128;
  818. }
  819. }
  820. return String (buffer);
  821. }
  822. int Time::getYear() const throw()
  823. {
  824. struct tm t;
  825. millisToLocal (millisSinceEpoch, t);
  826. return t.tm_year + 1900;
  827. }
  828. int Time::getMonth() const throw()
  829. {
  830. struct tm t;
  831. millisToLocal (millisSinceEpoch, t);
  832. return t.tm_mon;
  833. }
  834. int Time::getDayOfMonth() const throw()
  835. {
  836. struct tm t;
  837. millisToLocal (millisSinceEpoch, t);
  838. return t.tm_mday;
  839. }
  840. int Time::getDayOfWeek() const throw()
  841. {
  842. struct tm t;
  843. millisToLocal (millisSinceEpoch, t);
  844. return t.tm_wday;
  845. }
  846. int Time::getHours() const throw()
  847. {
  848. struct tm t;
  849. millisToLocal (millisSinceEpoch, t);
  850. return t.tm_hour;
  851. }
  852. int Time::getHoursInAmPmFormat() const throw()
  853. {
  854. const int hours = getHours();
  855. if (hours == 0)
  856. return 12;
  857. else if (hours <= 12)
  858. return hours;
  859. else
  860. return hours - 12;
  861. }
  862. bool Time::isAfternoon() const throw()
  863. {
  864. return getHours() >= 12;
  865. }
  866. static int extendedModulo (const int64 value, const int modulo) throw()
  867. {
  868. return (int) (value >= 0 ? (value % modulo)
  869. : (value - ((value / modulo) + 1) * modulo));
  870. }
  871. int Time::getMinutes() const throw()
  872. {
  873. return extendedModulo (millisSinceEpoch / 60000, 60);
  874. }
  875. int Time::getSeconds() const throw()
  876. {
  877. return extendedModulo (millisSinceEpoch / 1000, 60);
  878. }
  879. int Time::getMilliseconds() const throw()
  880. {
  881. return extendedModulo (millisSinceEpoch, 1000);
  882. }
  883. bool Time::isDaylightSavingTime() const throw()
  884. {
  885. struct tm t;
  886. millisToLocal (millisSinceEpoch, t);
  887. return t.tm_isdst != 0;
  888. }
  889. const String Time::getTimeZone() const throw()
  890. {
  891. String zone[2];
  892. #if JUCE_WIN32
  893. _tzset();
  894. #ifdef USE_NEW_SECURE_TIME_FNS
  895. {
  896. char name [128];
  897. size_t length;
  898. for (int i = 0; i < 2; ++i)
  899. {
  900. zeromem (name, sizeof (name));
  901. _get_tzname (&length, name, 127, i);
  902. zone[i] = name;
  903. }
  904. }
  905. #else
  906. const char** const zonePtr = (const char**) _tzname;
  907. zone[0] = zonePtr[0];
  908. zone[1] = zonePtr[1];
  909. #endif
  910. #else
  911. tzset();
  912. const char** const zonePtr = (const char**) tzname;
  913. zone[0] = zonePtr[0];
  914. zone[1] = zonePtr[1];
  915. #endif
  916. if (isDaylightSavingTime())
  917. {
  918. zone[0] = zone[1];
  919. if (zone[0].length() > 3
  920. && zone[0].containsIgnoreCase (T("daylight"))
  921. && zone[0].contains (T("GMT")))
  922. zone[0] = "BST";
  923. }
  924. return zone[0].substring (0, 3);
  925. }
  926. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  927. {
  928. return getMonthName (getMonth(), threeLetterVersion);
  929. }
  930. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  931. {
  932. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  933. }
  934. const String Time::getMonthName (int monthNumber,
  935. const bool threeLetterVersion) throw()
  936. {
  937. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  938. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  939. monthNumber %= 12;
  940. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  941. : longMonthNames [monthNumber]);
  942. }
  943. const String Time::getWeekdayName (int day,
  944. const bool threeLetterVersion) throw()
  945. {
  946. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  947. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  948. day %= 7;
  949. return TRANS (threeLetterVersion ? shortDayNames [day]
  950. : longDayNames [day]);
  951. }
  952. END_JUCE_NAMESPACE
  953. /********* End of inlined file: juce_Time.cpp *********/
  954. /********* Start of inlined file: juce_BitArray.cpp *********/
  955. BEGIN_JUCE_NAMESPACE
  956. BitArray::BitArray() throw()
  957. : numValues (4),
  958. highestBit (-1),
  959. negative (false)
  960. {
  961. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  962. }
  963. BitArray::BitArray (const int value) throw()
  964. : numValues (4),
  965. highestBit (31),
  966. negative (value < 0)
  967. {
  968. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  969. values[0] = abs (value);
  970. highestBit = getHighestBit();
  971. }
  972. BitArray::BitArray (int64 value) throw()
  973. : numValues (4),
  974. highestBit (63),
  975. negative (value < 0)
  976. {
  977. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  978. if (value < 0)
  979. value = -value;
  980. values[0] = (unsigned int) value;
  981. values[1] = (unsigned int) (value >> 32);
  982. highestBit = getHighestBit();
  983. }
  984. BitArray::BitArray (const unsigned int value) throw()
  985. : numValues (4),
  986. highestBit (31),
  987. negative (false)
  988. {
  989. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  990. values[0] = value;
  991. highestBit = getHighestBit();
  992. }
  993. BitArray::BitArray (const BitArray& other) throw()
  994. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  995. highestBit (other.getHighestBit()),
  996. negative (other.negative)
  997. {
  998. const int bytes = sizeof (unsigned int) * (numValues + 1);
  999. values = (unsigned int*) juce_malloc (bytes);
  1000. memcpy (values, other.values, bytes);
  1001. }
  1002. BitArray::~BitArray() throw()
  1003. {
  1004. juce_free (values);
  1005. }
  1006. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1007. {
  1008. if (this != &other)
  1009. {
  1010. juce_free (values);
  1011. highestBit = other.getHighestBit();
  1012. numValues = jmax (4, (highestBit >> 5) + 1);
  1013. negative = other.negative;
  1014. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1015. values = (unsigned int*)juce_malloc (memSize);
  1016. memcpy (values, other.values, memSize);
  1017. }
  1018. return *this;
  1019. }
  1020. // result == 0 = the same
  1021. // result < 0 = this number is smaller
  1022. // result > 0 = this number is bigger
  1023. int BitArray::compare (const BitArray& other) const throw()
  1024. {
  1025. if (isNegative() == other.isNegative())
  1026. {
  1027. const int absComp = compareAbsolute (other);
  1028. return isNegative() ? -absComp : absComp;
  1029. }
  1030. else
  1031. {
  1032. return isNegative() ? -1 : 1;
  1033. }
  1034. }
  1035. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1036. {
  1037. const int h1 = getHighestBit();
  1038. const int h2 = other.getHighestBit();
  1039. if (h1 > h2)
  1040. return 1;
  1041. else if (h1 < h2)
  1042. return -1;
  1043. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1044. if (values[i] != other.values[i])
  1045. return (values[i] > other.values[i]) ? 1 : -1;
  1046. return 0;
  1047. }
  1048. bool BitArray::operator== (const BitArray& other) const throw()
  1049. {
  1050. return compare (other) == 0;
  1051. }
  1052. bool BitArray::operator!= (const BitArray& other) const throw()
  1053. {
  1054. return compare (other) != 0;
  1055. }
  1056. bool BitArray::operator[] (const int bit) const throw()
  1057. {
  1058. return bit >= 0 && bit <= highestBit
  1059. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1060. }
  1061. bool BitArray::isEmpty() const throw()
  1062. {
  1063. return getHighestBit() < 0;
  1064. }
  1065. void BitArray::clear() throw()
  1066. {
  1067. if (numValues > 16)
  1068. {
  1069. juce_free (values);
  1070. numValues = 4;
  1071. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1072. }
  1073. else
  1074. {
  1075. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1076. }
  1077. highestBit = -1;
  1078. negative = false;
  1079. }
  1080. void BitArray::setBit (const int bit) throw()
  1081. {
  1082. if (bit >= 0)
  1083. {
  1084. if (bit > highestBit)
  1085. {
  1086. ensureSize (bit >> 5);
  1087. highestBit = bit;
  1088. }
  1089. values [bit >> 5] |= (1 << (bit & 31));
  1090. }
  1091. }
  1092. void BitArray::setBit (const int bit,
  1093. const bool shouldBeSet) throw()
  1094. {
  1095. if (shouldBeSet)
  1096. setBit (bit);
  1097. else
  1098. clearBit (bit);
  1099. }
  1100. void BitArray::clearBit (const int bit) throw()
  1101. {
  1102. if (bit >= 0 && bit <= highestBit)
  1103. values [bit >> 5] &= ~(1 << (bit & 31));
  1104. }
  1105. void BitArray::setRange (int startBit,
  1106. int numBits,
  1107. const bool shouldBeSet) throw()
  1108. {
  1109. while (--numBits >= 0)
  1110. setBit (startBit++, shouldBeSet);
  1111. }
  1112. void BitArray::insertBit (const int bit,
  1113. const bool shouldBeSet) throw()
  1114. {
  1115. if (bit >= 0)
  1116. shiftBits (1, bit);
  1117. setBit (bit, shouldBeSet);
  1118. }
  1119. void BitArray::andWith (const BitArray& other) throw()
  1120. {
  1121. // this operation will only work with the absolute values
  1122. jassert (isNegative() == other.isNegative());
  1123. int n = numValues;
  1124. while (n > other.numValues)
  1125. values[--n] = 0;
  1126. while (--n >= 0)
  1127. values[n] &= other.values[n];
  1128. if (other.highestBit < highestBit)
  1129. highestBit = other.highestBit;
  1130. highestBit = getHighestBit();
  1131. }
  1132. void BitArray::orWith (const BitArray& other) throw()
  1133. {
  1134. if (other.highestBit < 0)
  1135. return;
  1136. // this operation will only work with the absolute values
  1137. jassert (isNegative() == other.isNegative());
  1138. ensureSize (other.highestBit >> 5);
  1139. int n = (other.highestBit >> 5) + 1;
  1140. while (--n >= 0)
  1141. values[n] |= other.values[n];
  1142. if (other.highestBit > highestBit)
  1143. highestBit = other.highestBit;
  1144. highestBit = getHighestBit();
  1145. }
  1146. void BitArray::xorWith (const BitArray& other) throw()
  1147. {
  1148. if (other.highestBit < 0)
  1149. return;
  1150. // this operation will only work with the absolute values
  1151. jassert (isNegative() == other.isNegative());
  1152. ensureSize (other.highestBit >> 5);
  1153. int n = (other.highestBit >> 5) + 1;
  1154. while (--n >= 0)
  1155. values[n] ^= other.values[n];
  1156. if (other.highestBit > highestBit)
  1157. highestBit = other.highestBit;
  1158. highestBit = getHighestBit();
  1159. }
  1160. void BitArray::add (const BitArray& other) throw()
  1161. {
  1162. if (other.isNegative())
  1163. {
  1164. BitArray o (other);
  1165. o.negate();
  1166. subtract (o);
  1167. return;
  1168. }
  1169. if (isNegative())
  1170. {
  1171. if (compareAbsolute (other) < 0)
  1172. {
  1173. BitArray temp (*this);
  1174. temp.negate();
  1175. *this = other;
  1176. subtract (temp);
  1177. }
  1178. else
  1179. {
  1180. negate();
  1181. subtract (other);
  1182. negate();
  1183. }
  1184. return;
  1185. }
  1186. if (other.highestBit > highestBit)
  1187. highestBit = other.highestBit;
  1188. ++highestBit;
  1189. const int numInts = (highestBit >> 5) + 1;
  1190. ensureSize (numInts);
  1191. int64 remainder = 0;
  1192. for (int i = 0; i <= numInts; ++i)
  1193. {
  1194. if (i < numValues)
  1195. remainder += values[i];
  1196. if (i < other.numValues)
  1197. remainder += other.values[i];
  1198. values[i] = (unsigned int) remainder;
  1199. remainder >>= 32;
  1200. }
  1201. jassert (remainder == 0);
  1202. highestBit = getHighestBit();
  1203. }
  1204. void BitArray::subtract (const BitArray& other) throw()
  1205. {
  1206. if (other.isNegative())
  1207. {
  1208. BitArray o (other);
  1209. o.negate();
  1210. add (o);
  1211. return;
  1212. }
  1213. if (! isNegative())
  1214. {
  1215. if (compareAbsolute (other) < 0)
  1216. {
  1217. BitArray temp (*this);
  1218. *this = other;
  1219. subtract (temp);
  1220. negate();
  1221. return;
  1222. }
  1223. }
  1224. else
  1225. {
  1226. negate();
  1227. add (other);
  1228. negate();
  1229. return;
  1230. }
  1231. const int numInts = (highestBit >> 5) + 1;
  1232. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1233. int64 amountToSubtract = 0;
  1234. for (int i = 0; i <= numInts; ++i)
  1235. {
  1236. if (i <= maxOtherInts)
  1237. amountToSubtract += (int64)other.values[i];
  1238. if (values[i] >= amountToSubtract)
  1239. {
  1240. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1241. amountToSubtract = 0;
  1242. }
  1243. else
  1244. {
  1245. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1246. values[i] = (unsigned int) n;
  1247. amountToSubtract = 1;
  1248. }
  1249. }
  1250. }
  1251. void BitArray::multiplyBy (const BitArray& other) throw()
  1252. {
  1253. BitArray total;
  1254. highestBit = getHighestBit();
  1255. const bool wasNegative = isNegative();
  1256. setNegative (false);
  1257. for (int i = 0; i <= highestBit; ++i)
  1258. {
  1259. if (operator[](i))
  1260. {
  1261. BitArray n (other);
  1262. n.setNegative (false);
  1263. n.shiftBits (i);
  1264. total.add (n);
  1265. }
  1266. }
  1267. *this = total;
  1268. negative = wasNegative ^ other.isNegative();
  1269. }
  1270. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1271. {
  1272. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1273. const int divHB = divisor.getHighestBit();
  1274. const int ourHB = getHighestBit();
  1275. if (divHB < 0 || ourHB < 0)
  1276. {
  1277. // division by zero
  1278. remainder.clear();
  1279. clear();
  1280. }
  1281. else
  1282. {
  1283. remainder = *this;
  1284. remainder.setNegative (false);
  1285. const bool wasNegative = isNegative();
  1286. clear();
  1287. BitArray temp (divisor);
  1288. temp.setNegative (false);
  1289. int leftShift = ourHB - divHB;
  1290. temp.shiftBits (leftShift);
  1291. while (leftShift >= 0)
  1292. {
  1293. if (remainder.compareAbsolute (temp) >= 0)
  1294. {
  1295. remainder.subtract (temp);
  1296. setBit (leftShift);
  1297. }
  1298. if (--leftShift >= 0)
  1299. temp.shiftBits (-1);
  1300. }
  1301. negative = wasNegative ^ divisor.isNegative();
  1302. remainder.setNegative (wasNegative);
  1303. }
  1304. }
  1305. void BitArray::modulo (const BitArray& divisor) throw()
  1306. {
  1307. BitArray remainder;
  1308. divideBy (divisor, remainder);
  1309. *this = remainder;
  1310. }
  1311. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1312. {
  1313. while (! m->isEmpty())
  1314. {
  1315. if (n->compareAbsolute (*m) > 0)
  1316. swapVariables (m, n);
  1317. m->subtract (*n);
  1318. }
  1319. return *n;
  1320. }
  1321. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1322. {
  1323. BitArray m (*this);
  1324. while (! n.isEmpty())
  1325. {
  1326. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1327. return simpleGCD (&m, &n);
  1328. BitArray temp1 (m), temp2;
  1329. temp1.divideBy (n, temp2);
  1330. m = n;
  1331. n = temp2;
  1332. }
  1333. return m;
  1334. }
  1335. void BitArray::exponentModulo (const BitArray& exponent,
  1336. const BitArray& modulus) throw()
  1337. {
  1338. BitArray exp (exponent);
  1339. exp.modulo (modulus);
  1340. BitArray value (*this);
  1341. value.modulo (modulus);
  1342. clear();
  1343. setBit (0);
  1344. while (! exp.isEmpty())
  1345. {
  1346. if (exp [0])
  1347. {
  1348. multiplyBy (value);
  1349. this->modulo (modulus);
  1350. }
  1351. value.multiplyBy (value);
  1352. value.modulo (modulus);
  1353. exp.shiftBits (-1);
  1354. }
  1355. }
  1356. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1357. {
  1358. const BitArray one (1);
  1359. if (modulus == one || modulus.isNegative())
  1360. {
  1361. clear();
  1362. return;
  1363. }
  1364. if (isNegative() || compareAbsolute (modulus) >= 0)
  1365. this->modulo (modulus);
  1366. if (*this == one)
  1367. return;
  1368. if (! (*this)[0])
  1369. {
  1370. // not invertible
  1371. clear();
  1372. return;
  1373. }
  1374. BitArray a1 (modulus);
  1375. BitArray a2 (*this);
  1376. BitArray b1 (modulus);
  1377. BitArray b2 (1);
  1378. while (a2 != one)
  1379. {
  1380. BitArray temp1, temp2, multiplier (a1);
  1381. multiplier.divideBy (a2, temp1);
  1382. temp1 = a2;
  1383. temp1.multiplyBy (multiplier);
  1384. temp2 = a1;
  1385. temp2.subtract (temp1);
  1386. a1 = a2;
  1387. a2 = temp2;
  1388. temp1 = b2;
  1389. temp1.multiplyBy (multiplier);
  1390. temp2 = b1;
  1391. temp2.subtract (temp1);
  1392. b1 = b2;
  1393. b2 = temp2;
  1394. }
  1395. while (b2.isNegative())
  1396. b2.add (modulus);
  1397. b2.modulo (modulus);
  1398. *this = b2;
  1399. }
  1400. void BitArray::shiftBits (int bits, const int startBit) throw()
  1401. {
  1402. if (highestBit < 0)
  1403. return;
  1404. if (startBit > 0)
  1405. {
  1406. if (bits < 0)
  1407. {
  1408. // right shift
  1409. for (int i = startBit; i <= highestBit; ++i)
  1410. setBit (i, operator[] (i - bits));
  1411. highestBit = getHighestBit();
  1412. }
  1413. else if (bits > 0)
  1414. {
  1415. // left shift
  1416. for (int i = highestBit + 1; --i >= startBit;)
  1417. setBit (i + bits, operator[] (i));
  1418. while (--bits >= 0)
  1419. clearBit (bits + startBit);
  1420. }
  1421. }
  1422. else
  1423. {
  1424. if (bits < 0)
  1425. {
  1426. // right shift
  1427. bits = -bits;
  1428. if (bits > highestBit)
  1429. {
  1430. clear();
  1431. }
  1432. else
  1433. {
  1434. const int wordsToMove = bits >> 5;
  1435. int top = 1 + (highestBit >> 5) - wordsToMove;
  1436. highestBit -= bits;
  1437. if (wordsToMove > 0)
  1438. {
  1439. int i;
  1440. for (i = 0; i < top; ++i)
  1441. values [i] = values [i + wordsToMove];
  1442. for (i = 0; i < wordsToMove; ++i)
  1443. values [top + i] = 0;
  1444. bits &= 31;
  1445. }
  1446. if (bits != 0)
  1447. {
  1448. const int invBits = 32 - bits;
  1449. --top;
  1450. for (int i = 0; i < top; ++i)
  1451. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  1452. values[top] = (values[top] >> bits);
  1453. }
  1454. highestBit = getHighestBit();
  1455. }
  1456. }
  1457. else if (bits > 0)
  1458. {
  1459. // left shift
  1460. ensureSize (((highestBit + bits) >> 5) + 1);
  1461. const int wordsToMove = bits >> 5;
  1462. int top = 1 + (highestBit >> 5);
  1463. highestBit += bits;
  1464. if (wordsToMove > 0)
  1465. {
  1466. int i;
  1467. for (i = top; --i >= 0;)
  1468. values [i + wordsToMove] = values [i];
  1469. for (i = 0; i < wordsToMove; ++i)
  1470. values [i] = 0;
  1471. bits &= 31;
  1472. }
  1473. if (bits != 0)
  1474. {
  1475. const int invBits = 32 - bits;
  1476. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  1477. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  1478. values [wordsToMove] = values [wordsToMove] << bits;
  1479. }
  1480. highestBit = getHighestBit();
  1481. }
  1482. }
  1483. }
  1484. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  1485. {
  1486. if (numBits > 32)
  1487. {
  1488. jassertfalse
  1489. numBits = 32;
  1490. }
  1491. if (startBit == 0)
  1492. {
  1493. if (numBits < 32)
  1494. return values[0] & ((1 << numBits) - 1);
  1495. return values[0];
  1496. }
  1497. int n = 0;
  1498. for (int i = numBits; --i >= 0;)
  1499. {
  1500. n <<= 1;
  1501. if (operator[] (startBit + i))
  1502. n |= 1;
  1503. }
  1504. return n;
  1505. }
  1506. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  1507. {
  1508. if (numBits > 32)
  1509. {
  1510. jassertfalse
  1511. numBits = 32;
  1512. }
  1513. for (int i = 0; i < numBits; ++i)
  1514. {
  1515. setBit (startBit + i, (valueToSet & 1) != 0);
  1516. valueToSet >>= 1;
  1517. }
  1518. }
  1519. void BitArray::fillBitsRandomly (int startBit, int numBits) throw()
  1520. {
  1521. highestBit = jmax (highestBit, startBit + numBits);
  1522. ensureSize (((startBit + numBits) >> 5) + 1);
  1523. while ((startBit & 31) != 0 && numBits > 0)
  1524. {
  1525. setBit (startBit++, Random::getSystemRandom().nextBool());
  1526. --numBits;
  1527. }
  1528. while (numBits >= 32)
  1529. {
  1530. values [startBit >> 5] = (unsigned int) Random::getSystemRandom().nextInt();
  1531. startBit += 32;
  1532. numBits -= 32;
  1533. }
  1534. while (--numBits >= 0)
  1535. {
  1536. setBit (startBit + numBits, Random::getSystemRandom().nextBool());
  1537. }
  1538. highestBit = getHighestBit();
  1539. }
  1540. void BitArray::createRandomNumber (const BitArray& maximumValue) throw()
  1541. {
  1542. clear();
  1543. do
  1544. {
  1545. fillBitsRandomly (0, maximumValue.getHighestBit() + 1);
  1546. }
  1547. while (compare (maximumValue) >= 0);
  1548. }
  1549. bool BitArray::isNegative() const throw()
  1550. {
  1551. return negative && ! isEmpty();
  1552. }
  1553. void BitArray::setNegative (const bool neg) throw()
  1554. {
  1555. negative = neg;
  1556. }
  1557. void BitArray::negate() throw()
  1558. {
  1559. negative = (! negative) && ! isEmpty();
  1560. }
  1561. int BitArray::countNumberOfSetBits() const throw()
  1562. {
  1563. int total = 0;
  1564. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  1565. {
  1566. unsigned int n = values[i];
  1567. if (n == 0xffffffff)
  1568. {
  1569. total += 32;
  1570. }
  1571. else
  1572. {
  1573. while (n != 0)
  1574. {
  1575. total += (n & 1);
  1576. n >>= 1;
  1577. }
  1578. }
  1579. }
  1580. return total;
  1581. }
  1582. int BitArray::getHighestBit() const throw()
  1583. {
  1584. for (int i = highestBit + 1; --i >= 0;)
  1585. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1586. return i;
  1587. return -1;
  1588. }
  1589. int BitArray::findNextSetBit (int i) const throw()
  1590. {
  1591. for (; i <= highestBit; ++i)
  1592. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1593. return i;
  1594. return -1;
  1595. }
  1596. int BitArray::findNextClearBit (int i) const throw()
  1597. {
  1598. for (; i <= highestBit; ++i)
  1599. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  1600. break;
  1601. return i;
  1602. }
  1603. void BitArray::ensureSize (const int numVals) throw()
  1604. {
  1605. if (numVals + 2 >= numValues)
  1606. {
  1607. int oldSize = numValues;
  1608. numValues = ((numVals + 2) * 3) / 2;
  1609. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  1610. while (oldSize < numValues)
  1611. values [oldSize++] = 0;
  1612. }
  1613. }
  1614. const String BitArray::toString (const int base) const throw()
  1615. {
  1616. String s;
  1617. BitArray v (*this);
  1618. if (base == 2 || base == 8 || base == 16)
  1619. {
  1620. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1621. static const tchar* const hexDigits = T("0123456789abcdef");
  1622. for (;;)
  1623. {
  1624. const int remainder = v.getBitRangeAsInt (0, bits);
  1625. v.shiftBits (-bits);
  1626. if (remainder == 0 && v.isEmpty())
  1627. break;
  1628. s = String::charToString (hexDigits [remainder]) + s;
  1629. }
  1630. }
  1631. else if (base == 10)
  1632. {
  1633. const BitArray ten (10);
  1634. BitArray remainder;
  1635. for (;;)
  1636. {
  1637. v.divideBy (ten, remainder);
  1638. if (remainder.isEmpty() && v.isEmpty())
  1639. break;
  1640. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  1641. }
  1642. }
  1643. else
  1644. {
  1645. jassertfalse // can't do the specified base
  1646. return String::empty;
  1647. }
  1648. if (s.isEmpty())
  1649. return T("0");
  1650. return isNegative() ? T("-") + s : s;
  1651. }
  1652. void BitArray::parseString (const String& text,
  1653. const int base) throw()
  1654. {
  1655. clear();
  1656. const tchar* t = (const tchar*) text;
  1657. if (base == 2 || base == 8 || base == 16)
  1658. {
  1659. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1660. for (;;)
  1661. {
  1662. const tchar c = *t++;
  1663. const int digit = CharacterFunctions::getHexDigitValue (c);
  1664. if (((unsigned int) digit) < (unsigned int) base)
  1665. {
  1666. shiftBits (bits);
  1667. add (digit);
  1668. }
  1669. else if (c == 0)
  1670. {
  1671. break;
  1672. }
  1673. }
  1674. }
  1675. else if (base == 10)
  1676. {
  1677. const BitArray ten ((unsigned int) 10);
  1678. for (;;)
  1679. {
  1680. const tchar c = *t++;
  1681. if (c >= T('0') && c <= T('9'))
  1682. {
  1683. multiplyBy (ten);
  1684. add ((int) (c - T('0')));
  1685. }
  1686. else if (c == 0)
  1687. {
  1688. break;
  1689. }
  1690. }
  1691. }
  1692. setNegative (text.trimStart().startsWithChar (T('-')));
  1693. }
  1694. const MemoryBlock BitArray::toMemoryBlock() const throw()
  1695. {
  1696. const int numBytes = (getHighestBit() + 7) >> 3;
  1697. MemoryBlock mb (numBytes);
  1698. for (int i = 0; i < numBytes; ++i)
  1699. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  1700. return mb;
  1701. }
  1702. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  1703. {
  1704. clear();
  1705. for (int i = data.getSize(); --i >= 0;)
  1706. this->setBitRangeAsInt (i << 3, 8, data [i]);
  1707. }
  1708. END_JUCE_NAMESPACE
  1709. /********* End of inlined file: juce_BitArray.cpp *********/
  1710. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  1711. BEGIN_JUCE_NAMESPACE
  1712. MemoryBlock::MemoryBlock() throw()
  1713. : data (0),
  1714. size (0)
  1715. {
  1716. }
  1717. MemoryBlock::MemoryBlock (const int initialSize,
  1718. const bool initialiseToZero) throw()
  1719. {
  1720. if (initialSize > 0)
  1721. {
  1722. size = initialSize;
  1723. if (initialiseToZero)
  1724. data = (char*) juce_calloc (initialSize);
  1725. else
  1726. data = (char*) juce_malloc (initialSize);
  1727. }
  1728. else
  1729. {
  1730. data = 0;
  1731. size = 0;
  1732. }
  1733. }
  1734. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  1735. : data (0),
  1736. size (other.size)
  1737. {
  1738. if (size > 0)
  1739. {
  1740. jassert (other.data != 0);
  1741. data = (char*) juce_malloc (size);
  1742. memcpy (data, other.data, size);
  1743. }
  1744. }
  1745. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  1746. const int sizeInBytes) throw()
  1747. : data (0),
  1748. size (jmax (0, sizeInBytes))
  1749. {
  1750. jassert (sizeInBytes >= 0);
  1751. if (size > 0)
  1752. {
  1753. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  1754. data = (char*) juce_malloc (size);
  1755. if (dataToInitialiseFrom != 0)
  1756. memcpy (data, dataToInitialiseFrom, size);
  1757. }
  1758. }
  1759. MemoryBlock::~MemoryBlock() throw()
  1760. {
  1761. jassert (size >= 0); // should never happen
  1762. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  1763. juce_free (data);
  1764. }
  1765. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  1766. {
  1767. if (this != &other)
  1768. {
  1769. setSize (other.size, false);
  1770. memcpy (data, other.data, size);
  1771. }
  1772. return *this;
  1773. }
  1774. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  1775. {
  1776. return (size == other.size)
  1777. && (memcmp (data, other.data, size) == 0);
  1778. }
  1779. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  1780. {
  1781. return ! operator== (other);
  1782. }
  1783. // this will resize the block to this size
  1784. void MemoryBlock::setSize (const int newSize,
  1785. const bool initialiseToZero) throw()
  1786. {
  1787. if (size != newSize)
  1788. {
  1789. if (newSize <= 0)
  1790. {
  1791. juce_free (data);
  1792. data = 0;
  1793. size = 0;
  1794. }
  1795. else
  1796. {
  1797. if (data != 0)
  1798. {
  1799. data = (char*) juce_realloc (data, newSize);
  1800. if (initialiseToZero && (newSize > size))
  1801. zeromem (data + size, newSize - size);
  1802. }
  1803. else
  1804. {
  1805. if (initialiseToZero)
  1806. data = (char*) juce_calloc (newSize);
  1807. else
  1808. data = (char*) juce_malloc (newSize);
  1809. }
  1810. size = newSize;
  1811. }
  1812. }
  1813. }
  1814. void MemoryBlock::ensureSize (const int minimumSize,
  1815. const bool initialiseToZero) throw()
  1816. {
  1817. if (size < minimumSize)
  1818. setSize (minimumSize, initialiseToZero);
  1819. }
  1820. void MemoryBlock::fillWith (const uint8 value) throw()
  1821. {
  1822. memset (data, (int) value, size);
  1823. }
  1824. void MemoryBlock::append (const void* const srcData,
  1825. const int numBytes) throw()
  1826. {
  1827. if (numBytes > 0)
  1828. {
  1829. const int oldSize = size;
  1830. setSize (size + numBytes);
  1831. memcpy (data + oldSize, srcData, numBytes);
  1832. }
  1833. }
  1834. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  1835. {
  1836. const char* d = (const char*) src;
  1837. if (offset < 0)
  1838. {
  1839. d -= offset;
  1840. num -= offset;
  1841. offset = 0;
  1842. }
  1843. if (offset + num > size)
  1844. num = size - offset;
  1845. if (num > 0)
  1846. memcpy (data + offset, d, num);
  1847. }
  1848. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  1849. {
  1850. char* d = (char*) dst;
  1851. if (offset < 0)
  1852. {
  1853. zeromem (d, -offset);
  1854. d -= offset;
  1855. num += offset;
  1856. offset = 0;
  1857. }
  1858. if (offset + num > size)
  1859. {
  1860. const int newNum = size - offset;
  1861. zeromem (d + newNum, num - newNum);
  1862. num = newNum;
  1863. }
  1864. if (num > 0)
  1865. memcpy (d, data + offset, num);
  1866. }
  1867. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  1868. {
  1869. if (startByte < 0)
  1870. {
  1871. numBytesToRemove += startByte;
  1872. startByte = 0;
  1873. }
  1874. if (startByte + numBytesToRemove >= size)
  1875. {
  1876. setSize (startByte);
  1877. }
  1878. else if (numBytesToRemove > 0)
  1879. {
  1880. memmove (data + startByte,
  1881. data + startByte + numBytesToRemove,
  1882. size - (startByte + numBytesToRemove));
  1883. setSize (size - numBytesToRemove);
  1884. }
  1885. }
  1886. const String MemoryBlock::toString() const throw()
  1887. {
  1888. return String (data, size);
  1889. }
  1890. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  1891. {
  1892. int res = 0;
  1893. int byte = bitRangeStart >> 3;
  1894. int offsetInByte = bitRangeStart & 7;
  1895. int bitsSoFar = 0;
  1896. while (numBits > 0 && byte < size)
  1897. {
  1898. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1899. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  1900. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  1901. bitsSoFar += bitsThisTime;
  1902. numBits -= bitsThisTime;
  1903. ++byte;
  1904. offsetInByte = 0;
  1905. }
  1906. return res;
  1907. }
  1908. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  1909. {
  1910. int byte = bitRangeStart >> 3;
  1911. int offsetInByte = bitRangeStart & 7;
  1912. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  1913. while (numBits > 0 && byte < size)
  1914. {
  1915. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1916. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  1917. const unsigned int tempBits = bitsToSet << offsetInByte;
  1918. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  1919. ++byte;
  1920. numBits -= bitsThisTime;
  1921. bitsToSet >>= bitsThisTime;
  1922. mask >>= bitsThisTime;
  1923. offsetInByte = 0;
  1924. }
  1925. }
  1926. void MemoryBlock::loadFromHexString (const String& hex) throw()
  1927. {
  1928. ensureSize (hex.length() >> 1);
  1929. char* dest = data;
  1930. int i = 0;
  1931. for (;;)
  1932. {
  1933. int byte = 0;
  1934. for (int loop = 2; --loop >= 0;)
  1935. {
  1936. byte <<= 4;
  1937. for (;;)
  1938. {
  1939. const tchar c = hex [i++];
  1940. if (c >= T('0') && c <= T('9'))
  1941. {
  1942. byte |= c - T('0');
  1943. break;
  1944. }
  1945. else if (c >= T('a') && c <= T('z'))
  1946. {
  1947. byte |= c - (T('a') - 10);
  1948. break;
  1949. }
  1950. else if (c >= T('A') && c <= T('Z'))
  1951. {
  1952. byte |= c - (T('A') - 10);
  1953. break;
  1954. }
  1955. else if (c == 0)
  1956. {
  1957. setSize ((int) (dest - data));
  1958. return;
  1959. }
  1960. }
  1961. }
  1962. *dest++ = (char) byte;
  1963. }
  1964. }
  1965. static const char* const encodingTable
  1966. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  1967. const String MemoryBlock::toBase64Encoding() const throw()
  1968. {
  1969. const int numChars = ((size << 3) + 5) / 6;
  1970. String destString (size); // store the length, followed by a '.', and then the data.
  1971. const int initialLen = destString.length();
  1972. destString.preallocateStorage (initialLen + 2 + numChars);
  1973. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  1974. *d++ = T('.');
  1975. for (int i = 0; i < numChars; ++i)
  1976. *d++ = encodingTable [getBitRange (i * 6, 6)];
  1977. *d++ = 0;
  1978. return destString;
  1979. }
  1980. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  1981. {
  1982. const int startPos = s.indexOfChar (T('.')) + 1;
  1983. if (startPos <= 0)
  1984. return false;
  1985. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  1986. setSize (numBytesNeeded, true);
  1987. const int numChars = s.length() - startPos;
  1988. const tchar* const srcChars = ((const tchar*) s) + startPos;
  1989. for (int i = 0; i < numChars; ++i)
  1990. {
  1991. const char c = (char) srcChars[i];
  1992. for (int j = 0; j < 64; ++j)
  1993. {
  1994. if (encodingTable[j] == c)
  1995. {
  1996. setBitRange (i * 6, 6, j);
  1997. break;
  1998. }
  1999. }
  2000. }
  2001. return true;
  2002. }
  2003. END_JUCE_NAMESPACE
  2004. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2005. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2006. BEGIN_JUCE_NAMESPACE
  2007. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2008. : properties (ignoreCaseOfKeyNames),
  2009. fallbackProperties (0),
  2010. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2011. {
  2012. }
  2013. PropertySet::PropertySet (const PropertySet& other) throw()
  2014. : properties (other.properties),
  2015. fallbackProperties (other.fallbackProperties),
  2016. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2017. {
  2018. }
  2019. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2020. {
  2021. properties = other.properties;
  2022. fallbackProperties = other.fallbackProperties;
  2023. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2024. propertyChanged();
  2025. return *this;
  2026. }
  2027. PropertySet::~PropertySet()
  2028. {
  2029. }
  2030. void PropertySet::clear()
  2031. {
  2032. const ScopedLock sl (lock);
  2033. if (properties.size() > 0)
  2034. {
  2035. properties.clear();
  2036. propertyChanged();
  2037. }
  2038. }
  2039. const String PropertySet::getValue (const String& keyName,
  2040. const String& defaultValue) const throw()
  2041. {
  2042. const ScopedLock sl (lock);
  2043. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2044. if (index >= 0)
  2045. return properties.getAllValues() [index];
  2046. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2047. : defaultValue;
  2048. }
  2049. int PropertySet::getIntValue (const String& keyName,
  2050. const int defaultValue) const throw()
  2051. {
  2052. const ScopedLock sl (lock);
  2053. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2054. if (index >= 0)
  2055. return properties.getAllValues() [index].getIntValue();
  2056. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2057. : defaultValue;
  2058. }
  2059. double PropertySet::getDoubleValue (const String& keyName,
  2060. const double defaultValue) const throw()
  2061. {
  2062. const ScopedLock sl (lock);
  2063. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2064. if (index >= 0)
  2065. return properties.getAllValues()[index].getDoubleValue();
  2066. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2067. : defaultValue;
  2068. }
  2069. bool PropertySet::getBoolValue (const String& keyName,
  2070. const bool defaultValue) const throw()
  2071. {
  2072. const ScopedLock sl (lock);
  2073. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2074. if (index >= 0)
  2075. return properties.getAllValues() [index].getIntValue() != 0;
  2076. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2077. : defaultValue;
  2078. }
  2079. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2080. {
  2081. XmlDocument doc (getValue (keyName));
  2082. return doc.getDocumentElement();
  2083. }
  2084. void PropertySet::setValue (const String& keyName,
  2085. const String& value) throw()
  2086. {
  2087. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2088. if (keyName.isNotEmpty())
  2089. {
  2090. const ScopedLock sl (lock);
  2091. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2092. if (index < 0 || properties.getAllValues() [index] != value)
  2093. {
  2094. properties.set (keyName, value);
  2095. propertyChanged();
  2096. }
  2097. }
  2098. }
  2099. void PropertySet::removeValue (const String& keyName) throw()
  2100. {
  2101. if (keyName.isNotEmpty())
  2102. {
  2103. const ScopedLock sl (lock);
  2104. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2105. if (index >= 0)
  2106. {
  2107. properties.remove (keyName);
  2108. propertyChanged();
  2109. }
  2110. }
  2111. }
  2112. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2113. {
  2114. setValue (keyName, String (value));
  2115. }
  2116. void PropertySet::setValue (const String& keyName, const int value) throw()
  2117. {
  2118. setValue (keyName, String (value));
  2119. }
  2120. void PropertySet::setValue (const String& keyName, const double value) throw()
  2121. {
  2122. setValue (keyName, String (value));
  2123. }
  2124. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2125. {
  2126. setValue (keyName, String ((value) ? T("1") : T("0")));
  2127. }
  2128. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2129. {
  2130. setValue (keyName, (xml == 0) ? String::empty
  2131. : xml->createDocument (String::empty, true));
  2132. }
  2133. bool PropertySet::containsKey (const String& keyName) const throw()
  2134. {
  2135. const ScopedLock sl (lock);
  2136. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2137. }
  2138. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2139. {
  2140. const ScopedLock sl (lock);
  2141. fallbackProperties = fallbackProperties_;
  2142. }
  2143. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2144. {
  2145. const ScopedLock sl (lock);
  2146. XmlElement* const xml = new XmlElement (nodeName);
  2147. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2148. {
  2149. XmlElement* const e = new XmlElement (T("VALUE"));
  2150. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2151. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2152. xml->addChildElement (e);
  2153. }
  2154. return xml;
  2155. }
  2156. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2157. {
  2158. const ScopedLock sl (lock);
  2159. clear();
  2160. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2161. {
  2162. if (e->hasAttribute (T("name"))
  2163. && e->hasAttribute (T("val")))
  2164. {
  2165. properties.set (e->getStringAttribute (T("name")),
  2166. e->getStringAttribute (T("val")));
  2167. }
  2168. }
  2169. if (properties.size() > 0)
  2170. propertyChanged();
  2171. }
  2172. void PropertySet::propertyChanged()
  2173. {
  2174. }
  2175. END_JUCE_NAMESPACE
  2176. /********* End of inlined file: juce_PropertySet.cpp *********/
  2177. /********* Start of inlined file: juce_BlowFish.cpp *********/
  2178. BEGIN_JUCE_NAMESPACE
  2179. static const uint32 initialPValues [18] =
  2180. {
  2181. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  2182. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  2183. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  2184. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  2185. 0x9216d5d9, 0x8979fb1b
  2186. };
  2187. static const uint32 initialSValues [4 * 256] =
  2188. {
  2189. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  2190. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  2191. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  2192. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  2193. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  2194. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  2195. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  2196. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  2197. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  2198. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  2199. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  2200. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  2201. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  2202. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  2203. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  2204. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  2205. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  2206. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  2207. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  2208. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  2209. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  2210. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  2211. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  2212. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  2213. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  2214. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  2215. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  2216. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  2217. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  2218. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  2219. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  2220. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  2221. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  2222. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  2223. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  2224. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  2225. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  2226. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  2227. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  2228. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  2229. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  2230. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  2231. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  2232. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  2233. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  2234. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  2235. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  2236. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  2237. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  2238. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  2239. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  2240. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  2241. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  2242. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  2243. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  2244. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  2245. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  2246. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  2247. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  2248. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  2249. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  2250. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  2251. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  2252. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  2253. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  2254. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  2255. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  2256. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  2257. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  2258. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  2259. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  2260. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  2261. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  2262. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  2263. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  2264. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  2265. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  2266. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  2267. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  2268. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  2269. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  2270. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  2271. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  2272. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  2273. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  2274. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  2275. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  2276. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  2277. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  2278. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  2279. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  2280. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  2281. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  2282. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  2283. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  2284. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  2285. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  2286. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  2287. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  2288. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  2289. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  2290. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  2291. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  2292. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  2293. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  2294. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  2295. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  2296. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  2297. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  2298. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  2299. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  2300. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  2301. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  2302. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  2303. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  2304. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  2305. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  2306. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  2307. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  2308. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  2309. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  2310. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  2311. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  2312. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  2313. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  2314. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  2315. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  2316. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  2317. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  2318. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  2319. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  2320. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  2321. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  2322. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  2323. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  2324. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  2325. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  2326. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  2327. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  2328. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  2329. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  2330. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  2331. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  2332. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  2333. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  2334. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  2335. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  2336. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  2337. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  2338. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  2339. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  2340. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  2341. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  2342. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  2343. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  2344. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  2345. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  2346. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  2347. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  2348. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  2349. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  2350. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  2351. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  2352. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  2353. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  2354. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  2355. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  2356. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  2357. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  2358. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  2359. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  2360. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  2361. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  2362. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  2363. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  2364. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  2365. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  2366. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  2367. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  2368. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  2369. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  2370. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  2371. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  2372. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  2373. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  2374. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  2375. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  2376. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  2377. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  2378. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  2379. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  2380. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  2381. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  2382. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  2383. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  2384. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  2385. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  2386. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  2387. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  2388. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  2389. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  2390. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  2391. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  2392. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  2393. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  2394. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  2395. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  2396. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  2397. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  2398. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  2399. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  2400. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  2401. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  2402. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  2403. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  2404. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  2405. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  2406. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  2407. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  2408. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  2409. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  2410. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  2411. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  2412. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  2413. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  2414. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  2415. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  2416. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  2417. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  2418. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  2419. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  2420. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  2421. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  2422. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  2423. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  2424. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  2425. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  2426. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  2427. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  2428. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  2429. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  2430. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  2431. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  2432. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  2433. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  2434. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  2435. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  2436. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  2437. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  2438. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  2439. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  2440. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  2441. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  2442. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  2443. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  2444. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  2445. };
  2446. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  2447. {
  2448. memcpy (p, initialPValues, sizeof (p));
  2449. int i, j;
  2450. for (i = 4; --i >= 0;)
  2451. {
  2452. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2453. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  2454. }
  2455. j = 0;
  2456. for (i = 0; i < 18; ++i)
  2457. {
  2458. uint32 d = 0;
  2459. for (int k = 0; k < 4; ++k)
  2460. {
  2461. d = (d << 8) | keyData[j];
  2462. if (++j >= keyBytes)
  2463. j = 0;
  2464. }
  2465. p[i] = initialPValues[i] ^ d;
  2466. }
  2467. uint32 l = 0, r = 0;
  2468. for (i = 0; i < 18; i += 2)
  2469. {
  2470. encrypt (l, r);
  2471. p[i] = l;
  2472. p[i + 1] = r;
  2473. }
  2474. for (i = 0; i < 4; ++i)
  2475. {
  2476. for (j = 0; j < 256; j += 2)
  2477. {
  2478. encrypt (l, r);
  2479. s[i][j] = l;
  2480. s[i][j + 1] = r;
  2481. }
  2482. }
  2483. }
  2484. BlowFish::BlowFish (const BlowFish& other)
  2485. {
  2486. for (int i = 4; --i >= 0;)
  2487. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2488. operator= (other);
  2489. }
  2490. const BlowFish& BlowFish::operator= (const BlowFish& other)
  2491. {
  2492. memcpy (p, other.p, sizeof (p));
  2493. for (int i = 4; --i >= 0;)
  2494. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  2495. return *this;
  2496. }
  2497. BlowFish::~BlowFish()
  2498. {
  2499. for (int i = 4; --i >= 0;)
  2500. juce_free (s[i]);
  2501. }
  2502. uint32 BlowFish::F (uint32 x) const
  2503. {
  2504. uint16 a, b, c, d;
  2505. uint32 y;
  2506. d = (uint16) (x & 0xff);
  2507. x >>= 8;
  2508. c = (uint16) (x & 0xff);
  2509. x >>= 8;
  2510. b = (uint16) (x & 0xff);
  2511. x >>= 8;
  2512. a = (uint16) (x & 0xff);
  2513. y = s[0][a] + s[1][b];
  2514. y = y ^ s[2][c];
  2515. y = y + s[3][d];
  2516. return y;
  2517. }
  2518. void BlowFish::encrypt (uint32& data1,
  2519. uint32& data2) const
  2520. {
  2521. uint32 l = data1;
  2522. uint32 r = data2;
  2523. for (int i = 0; i < 16; ++i)
  2524. {
  2525. l = l ^ p[i];
  2526. r = F (l) ^ r;
  2527. const uint32 temp = l;
  2528. l = r;
  2529. r = temp;
  2530. }
  2531. const uint32 temp = l;
  2532. l = r;
  2533. r = temp;
  2534. r = r ^ p[16];
  2535. l = l ^ p[17];
  2536. data1 = l;
  2537. data2 = r;
  2538. }
  2539. void BlowFish::decrypt (uint32& data1,
  2540. uint32& data2) const
  2541. {
  2542. uint32 l = data1;
  2543. uint32 r = data2;
  2544. for (int i = 17; i > 1; --i)
  2545. {
  2546. l =l ^ p[i];
  2547. r = F (l) ^ r;
  2548. const uint32 temp = l;
  2549. l = r;
  2550. r = temp;
  2551. }
  2552. const uint32 temp = l;
  2553. l = r;
  2554. r = temp;
  2555. r = r ^ p[1];
  2556. l = l ^ p[0];
  2557. data1 = l;
  2558. data2 = r;
  2559. }
  2560. END_JUCE_NAMESPACE
  2561. /********* End of inlined file: juce_BlowFish.cpp *********/
  2562. /********* Start of inlined file: juce_MD5.cpp *********/
  2563. BEGIN_JUCE_NAMESPACE
  2564. MD5::MD5()
  2565. {
  2566. zeromem (result, sizeof (result));
  2567. }
  2568. MD5::MD5 (const MD5& other)
  2569. {
  2570. memcpy (result, other.result, sizeof (result));
  2571. }
  2572. const MD5& MD5::operator= (const MD5& other)
  2573. {
  2574. memcpy (result, other.result, sizeof (result));
  2575. return *this;
  2576. }
  2577. MD5::MD5 (const MemoryBlock& data)
  2578. {
  2579. ProcessContext context;
  2580. context.processBlock ((const uint8*) data.getData(), data.getSize());
  2581. context.finish (result);
  2582. }
  2583. MD5::MD5 (const char* data, const int numBytes)
  2584. {
  2585. ProcessContext context;
  2586. context.processBlock ((const uint8*) data, numBytes);
  2587. context.finish (result);
  2588. }
  2589. MD5::MD5 (const String& text)
  2590. {
  2591. ProcessContext context;
  2592. const int len = text.length();
  2593. const juce_wchar* const t = text;
  2594. for (int i = 0; i < len; ++i)
  2595. {
  2596. // force the string into integer-sized unicode characters, to try to make it
  2597. // get the same results on all platforms + compilers.
  2598. uint32 unicodeChar = (uint32) t[i];
  2599. swapIfBigEndian (unicodeChar);
  2600. context.processBlock ((const uint8*) &unicodeChar,
  2601. sizeof (unicodeChar));
  2602. }
  2603. context.finish (result);
  2604. }
  2605. void MD5::processStream (InputStream& input, int numBytesToRead)
  2606. {
  2607. ProcessContext context;
  2608. if (numBytesToRead < 0)
  2609. numBytesToRead = INT_MAX;
  2610. while (numBytesToRead > 0)
  2611. {
  2612. char tempBuffer [512];
  2613. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  2614. if (bytesRead <= 0)
  2615. break;
  2616. numBytesToRead -= bytesRead;
  2617. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  2618. }
  2619. context.finish (result);
  2620. }
  2621. MD5::MD5 (InputStream& input, int numBytesToRead)
  2622. {
  2623. processStream (input, numBytesToRead);
  2624. }
  2625. MD5::MD5 (const File& file)
  2626. {
  2627. FileInputStream* const fin = file.createInputStream();
  2628. if (fin != 0)
  2629. {
  2630. processStream (*fin, -1);
  2631. delete fin;
  2632. }
  2633. else
  2634. {
  2635. zeromem (result, sizeof (result));
  2636. }
  2637. }
  2638. MD5::~MD5()
  2639. {
  2640. }
  2641. MD5::ProcessContext::ProcessContext()
  2642. {
  2643. state[0] = 0x67452301;
  2644. state[1] = 0xefcdab89;
  2645. state[2] = 0x98badcfe;
  2646. state[3] = 0x10325476;
  2647. count[0] = 0;
  2648. count[1] = 0;
  2649. }
  2650. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  2651. {
  2652. int bufferPos = ((count[0] >> 3) & 0x3F);
  2653. count[0] += (dataSize << 3);
  2654. if (count[0] < ((uint32) dataSize << 3))
  2655. count[1]++;
  2656. count[1] += (dataSize >> 29);
  2657. const int spaceLeft = 64 - bufferPos;
  2658. int i = 0;
  2659. if (dataSize >= spaceLeft)
  2660. {
  2661. memcpy (buffer + bufferPos, data, spaceLeft);
  2662. transform (buffer);
  2663. i = spaceLeft;
  2664. while (i < dataSize - 63)
  2665. {
  2666. transform (data + i);
  2667. i += 64;
  2668. }
  2669. bufferPos = 0;
  2670. }
  2671. memcpy (buffer + bufferPos, data + i, dataSize - i);
  2672. }
  2673. static void encode (uint8* const output,
  2674. const uint32* const input,
  2675. const int numBytes)
  2676. {
  2677. uint32* const o = (uint32*) output;
  2678. for (int i = 0; i < (numBytes >> 2); ++i)
  2679. o[i] = swapIfBigEndian (input [i]);
  2680. }
  2681. static void decode (uint32* const output,
  2682. const uint8* const input,
  2683. const int numBytes)
  2684. {
  2685. for (int i = 0; i < (numBytes >> 2); ++i)
  2686. output[i] = littleEndianInt ((const char*) input + (i << 2));
  2687. }
  2688. void MD5::ProcessContext::finish (uint8* const result)
  2689. {
  2690. unsigned char encodedLength[8];
  2691. encode (encodedLength, count, 8);
  2692. // Pad out to 56 mod 64.
  2693. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  2694. const int paddingLength = (index < 56) ? (56 - index)
  2695. : (120 - index);
  2696. uint8 paddingBuffer [64];
  2697. zeromem (paddingBuffer, paddingLength);
  2698. paddingBuffer [0] = 0x80;
  2699. processBlock (paddingBuffer, paddingLength);
  2700. processBlock (encodedLength, 8);
  2701. encode (result, state, 16);
  2702. zeromem (buffer, sizeof (buffer));
  2703. }
  2704. #define S11 7
  2705. #define S12 12
  2706. #define S13 17
  2707. #define S14 22
  2708. #define S21 5
  2709. #define S22 9
  2710. #define S23 14
  2711. #define S24 20
  2712. #define S31 4
  2713. #define S32 11
  2714. #define S33 16
  2715. #define S34 23
  2716. #define S41 6
  2717. #define S42 10
  2718. #define S43 15
  2719. #define S44 21
  2720. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  2721. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  2722. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  2723. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  2724. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  2725. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2726. {
  2727. a += F (b, c, d) + x + ac;
  2728. a = rotateLeft (a, s) + b;
  2729. }
  2730. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2731. {
  2732. a += G (b, c, d) + x + ac;
  2733. a = rotateLeft (a, s) + b;
  2734. }
  2735. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2736. {
  2737. a += H (b, c, d) + x + ac;
  2738. a = rotateLeft (a, s) + b;
  2739. }
  2740. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2741. {
  2742. a += I (b, c, d) + x + ac;
  2743. a = rotateLeft (a, s) + b;
  2744. }
  2745. void MD5::ProcessContext::transform (const uint8* const buffer)
  2746. {
  2747. uint32 a = state[0];
  2748. uint32 b = state[1];
  2749. uint32 c = state[2];
  2750. uint32 d = state[3];
  2751. uint32 x[16];
  2752. decode (x, buffer, 64);
  2753. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  2754. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  2755. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  2756. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  2757. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  2758. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  2759. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  2760. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  2761. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  2762. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  2763. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  2764. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  2765. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  2766. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  2767. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  2768. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  2769. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  2770. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  2771. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  2772. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  2773. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  2774. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  2775. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  2776. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  2777. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  2778. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  2779. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  2780. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  2781. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  2782. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  2783. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  2784. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  2785. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  2786. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  2787. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  2788. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  2789. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  2790. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  2791. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  2792. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  2793. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  2794. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  2795. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  2796. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  2797. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  2798. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  2799. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  2800. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  2801. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  2802. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  2803. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  2804. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  2805. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  2806. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  2807. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  2808. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  2809. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  2810. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  2811. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  2812. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  2813. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  2814. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  2815. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  2816. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  2817. state[0] += a;
  2818. state[1] += b;
  2819. state[2] += c;
  2820. state[3] += d;
  2821. zeromem (x, sizeof (x));
  2822. }
  2823. const MemoryBlock MD5::getRawChecksumData() const
  2824. {
  2825. return MemoryBlock (result, 16);
  2826. }
  2827. const String MD5::toHexString() const
  2828. {
  2829. return String::toHexString (result, 16, 0);
  2830. }
  2831. bool MD5::operator== (const MD5& other) const
  2832. {
  2833. return memcmp (result, other.result, 16) == 0;
  2834. }
  2835. bool MD5::operator!= (const MD5& other) const
  2836. {
  2837. return ! operator== (other);
  2838. }
  2839. END_JUCE_NAMESPACE
  2840. /********* End of inlined file: juce_MD5.cpp *********/
  2841. /********* Start of inlined file: juce_Primes.cpp *********/
  2842. BEGIN_JUCE_NAMESPACE
  2843. static void createSmallSieve (const int numBits, BitArray& result) throw()
  2844. {
  2845. result.setBit (numBits);
  2846. result.clearBit (numBits); // to enlarge the array
  2847. result.setBit (0);
  2848. int n = 2;
  2849. do
  2850. {
  2851. for (int i = n + n; i < numBits; i += n)
  2852. result.setBit (i);
  2853. n = result.findNextClearBit (n + 1);
  2854. }
  2855. while (n <= (numBits >> 1));
  2856. }
  2857. static void bigSieve (const BitArray& base,
  2858. const int numBits,
  2859. BitArray& result,
  2860. const BitArray& smallSieve,
  2861. const int smallSieveSize) throw()
  2862. {
  2863. jassert (! base[0]); // must be even!
  2864. result.setBit (numBits);
  2865. result.clearBit (numBits); // to enlarge the array
  2866. int index = smallSieve.findNextClearBit (0);
  2867. do
  2868. {
  2869. const int prime = (index << 1) + 1;
  2870. BitArray r (base);
  2871. BitArray remainder;
  2872. r.divideBy (prime, remainder);
  2873. int i = prime - remainder.getBitRangeAsInt (0, 32);
  2874. if (r.isEmpty())
  2875. i += prime;
  2876. if ((i & 1) == 0)
  2877. i += prime;
  2878. i = (i - 1) >> 1;
  2879. while (i < numBits)
  2880. {
  2881. result.setBit (i);
  2882. i += prime;
  2883. }
  2884. index = smallSieve.findNextClearBit (index + 1);
  2885. }
  2886. while (index < smallSieveSize);
  2887. }
  2888. static bool findCandidate (const BitArray& base,
  2889. const BitArray& sieve,
  2890. const int numBits,
  2891. BitArray& result,
  2892. const int certainty) throw()
  2893. {
  2894. for (int i = 0; i < numBits; ++i)
  2895. {
  2896. if (! sieve[i])
  2897. {
  2898. result = base;
  2899. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  2900. if (Primes::isProbablyPrime (result, certainty))
  2901. return true;
  2902. }
  2903. }
  2904. return false;
  2905. }
  2906. const BitArray Primes::createProbablePrime (const int bitLength,
  2907. const int certainty) throw()
  2908. {
  2909. BitArray smallSieve;
  2910. const int smallSieveSize = 15000;
  2911. createSmallSieve (smallSieveSize, smallSieve);
  2912. BitArray p;
  2913. p.fillBitsRandomly (0, bitLength);
  2914. p.setBit (bitLength - 1);
  2915. p.clearBit (0);
  2916. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  2917. while (p.getHighestBit() < bitLength)
  2918. {
  2919. p.add (2 * searchLen);
  2920. BitArray sieve;
  2921. bigSieve (p, searchLen, sieve,
  2922. smallSieve, smallSieveSize);
  2923. BitArray candidate;
  2924. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  2925. return candidate;
  2926. }
  2927. jassertfalse
  2928. return BitArray();
  2929. }
  2930. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  2931. {
  2932. const BitArray one (1);
  2933. const BitArray two (2);
  2934. BitArray nMinusOne (n);
  2935. nMinusOne.subtract (one);
  2936. BitArray d (nMinusOne);
  2937. const int s = d.findNextSetBit (0);
  2938. d.shiftBits (-s);
  2939. BitArray smallPrimes;
  2940. int numBitsInSmallPrimes = 0;
  2941. for (;;)
  2942. {
  2943. numBitsInSmallPrimes += 256;
  2944. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  2945. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  2946. if (numPrimesFound > iterations + 1)
  2947. break;
  2948. }
  2949. int smallPrime = 2;
  2950. while (--iterations >= 0)
  2951. {
  2952. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  2953. BitArray r (smallPrime);
  2954. //r.createRandomNumber (nMinusOne);
  2955. r.exponentModulo (d, n);
  2956. if (! (r == one || r == nMinusOne))
  2957. {
  2958. for (int j = 0; j < s; ++j)
  2959. {
  2960. r.exponentModulo (two, n);
  2961. if (r == nMinusOne)
  2962. break;
  2963. }
  2964. if (r != nMinusOne)
  2965. return false;
  2966. }
  2967. }
  2968. return true;
  2969. }
  2970. bool Primes::isProbablyPrime (const BitArray& number,
  2971. const int certainty) throw()
  2972. {
  2973. if (! number[0])
  2974. return false;
  2975. if (number.getHighestBit() <= 10)
  2976. {
  2977. const int num = number.getBitRangeAsInt (0, 10);
  2978. for (int i = num / 2; --i > 1;)
  2979. if (num % i == 0)
  2980. return false;
  2981. return true;
  2982. }
  2983. else
  2984. {
  2985. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  2986. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  2987. return false;
  2988. return passesMillerRabin (number, certainty);
  2989. }
  2990. }
  2991. END_JUCE_NAMESPACE
  2992. /********* End of inlined file: juce_Primes.cpp *********/
  2993. /********* Start of inlined file: juce_RSAKey.cpp *********/
  2994. BEGIN_JUCE_NAMESPACE
  2995. RSAKey::RSAKey() throw()
  2996. {
  2997. }
  2998. RSAKey::RSAKey (const String& s) throw()
  2999. {
  3000. if (s.containsChar (T(',')))
  3001. {
  3002. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3003. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3004. }
  3005. else
  3006. {
  3007. // the string needs to be two hex numbers, comma-separated..
  3008. jassertfalse;
  3009. }
  3010. }
  3011. RSAKey::~RSAKey() throw()
  3012. {
  3013. }
  3014. const String RSAKey::toString() const throw()
  3015. {
  3016. return part1.toString (16) + T(",") + part2.toString (16);
  3017. }
  3018. bool RSAKey::applyToValue (BitArray& value) const throw()
  3019. {
  3020. if (part1.isEmpty() || part2.isEmpty()
  3021. || value.compare (0) <= 0)
  3022. {
  3023. jassertfalse // using an uninitialised key
  3024. value.clear();
  3025. return false;
  3026. }
  3027. BitArray result;
  3028. while (! value.isEmpty())
  3029. {
  3030. result.multiplyBy (part2);
  3031. BitArray remainder;
  3032. value.divideBy (part2, remainder);
  3033. remainder.exponentModulo (part1, part2);
  3034. result.add (remainder);
  3035. }
  3036. value = result;
  3037. return true;
  3038. }
  3039. static const BitArray findBestCommonDivisor (const BitArray& p,
  3040. const BitArray& q) throw()
  3041. {
  3042. const BitArray one (1);
  3043. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  3044. // are fast to divide + multiply
  3045. for (int i = 2; i <= 65536; i *= 2)
  3046. {
  3047. const BitArray e (1 + i);
  3048. if (e.findGreatestCommonDivisor (p) == one
  3049. && e.findGreatestCommonDivisor (q) == one)
  3050. {
  3051. return e;
  3052. }
  3053. }
  3054. BitArray e (4);
  3055. while (! (e.findGreatestCommonDivisor (p) == one
  3056. && e.findGreatestCommonDivisor (q) == one))
  3057. {
  3058. e.add (one);
  3059. }
  3060. return e;
  3061. }
  3062. void RSAKey::createKeyPair (RSAKey& publicKey,
  3063. RSAKey& privateKey,
  3064. const int numBits) throw()
  3065. {
  3066. jassert (numBits > 16); // not much point using less than this..
  3067. BitArray p (Primes::createProbablePrime (numBits / 2, 30));
  3068. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30));
  3069. BitArray n (p);
  3070. n.multiplyBy (q); // n = pq
  3071. const BitArray one (1);
  3072. p.subtract (one);
  3073. q.subtract (one);
  3074. BitArray m (p);
  3075. m.multiplyBy (q); // m = (p - 1)(q - 1)
  3076. const BitArray e (findBestCommonDivisor (p, q));
  3077. BitArray d (e);
  3078. d.inverseModulo (m);
  3079. publicKey.part1 = e;
  3080. publicKey.part2 = n;
  3081. privateKey.part1 = d;
  3082. privateKey.part2 = n;
  3083. }
  3084. END_JUCE_NAMESPACE
  3085. /********* End of inlined file: juce_RSAKey.cpp *********/
  3086. /********* Start of inlined file: juce_InputStream.cpp *********/
  3087. BEGIN_JUCE_NAMESPACE
  3088. char InputStream::readByte()
  3089. {
  3090. char temp = 0;
  3091. read (&temp, 1);
  3092. return temp;
  3093. }
  3094. bool InputStream::readBool()
  3095. {
  3096. return readByte() != 0;
  3097. }
  3098. short InputStream::readShort()
  3099. {
  3100. char temp [2];
  3101. if (read (temp, 2) == 2)
  3102. return (short) littleEndianShort (temp);
  3103. else
  3104. return 0;
  3105. }
  3106. short InputStream::readShortBigEndian()
  3107. {
  3108. char temp [2];
  3109. if (read (temp, 2) == 2)
  3110. return (short) bigEndianShort (temp);
  3111. else
  3112. return 0;
  3113. }
  3114. int InputStream::readInt()
  3115. {
  3116. char temp [4];
  3117. if (read (temp, 4) == 4)
  3118. return (int) littleEndianInt (temp);
  3119. else
  3120. return 0;
  3121. }
  3122. int InputStream::readIntBigEndian()
  3123. {
  3124. char temp [4];
  3125. if (read (temp, 4) == 4)
  3126. return (int) bigEndianInt (temp);
  3127. else
  3128. return 0;
  3129. }
  3130. int InputStream::readCompressedInt()
  3131. {
  3132. int num = 0;
  3133. if (! isExhausted())
  3134. {
  3135. unsigned char numBytes = readByte();
  3136. const bool negative = (numBytes & 0x80) != 0;
  3137. numBytes &= 0x7f;
  3138. if (numBytes <= 4)
  3139. {
  3140. if (read (&num, numBytes) != numBytes)
  3141. return 0;
  3142. if (negative)
  3143. num = -num;
  3144. }
  3145. }
  3146. return num;
  3147. }
  3148. int64 InputStream::readInt64()
  3149. {
  3150. char temp [8];
  3151. if (read (temp, 8) == 8)
  3152. return (int64) swapIfBigEndian (*(uint64*)temp);
  3153. else
  3154. return 0;
  3155. }
  3156. int64 InputStream::readInt64BigEndian()
  3157. {
  3158. char temp [8];
  3159. if (read (temp, 8) == 8)
  3160. return (int64) swapIfLittleEndian (*(uint64*)temp);
  3161. else
  3162. return 0;
  3163. }
  3164. float InputStream::readFloat()
  3165. {
  3166. union { int asInt; float asFloat; } n;
  3167. n.asInt = readInt();
  3168. return n.asFloat;
  3169. }
  3170. float InputStream::readFloatBigEndian()
  3171. {
  3172. union { int asInt; float asFloat; } n;
  3173. n.asInt = readIntBigEndian();
  3174. return n.asFloat;
  3175. }
  3176. double InputStream::readDouble()
  3177. {
  3178. union { int64 asInt; double asDouble; } n;
  3179. n.asInt = readInt64();
  3180. return n.asDouble;
  3181. }
  3182. double InputStream::readDoubleBigEndian()
  3183. {
  3184. union { int64 asInt; double asDouble; } n;
  3185. n.asInt = readInt64BigEndian();
  3186. return n.asDouble;
  3187. }
  3188. const String InputStream::readString()
  3189. {
  3190. const int tempBufferSize = 256;
  3191. uint8 temp [tempBufferSize];
  3192. int i = 0;
  3193. while ((temp [i++] = readByte()) != 0)
  3194. {
  3195. if (i == tempBufferSize)
  3196. {
  3197. // too big for our quick buffer, so read it in blocks..
  3198. String result (String::fromUTF8 (temp, i));
  3199. i = 0;
  3200. for (;;)
  3201. {
  3202. if ((temp [i++] = readByte()) == 0)
  3203. {
  3204. result += String::fromUTF8 (temp, i - 1);
  3205. break;
  3206. }
  3207. else if (i == tempBufferSize)
  3208. {
  3209. result += String::fromUTF8 (temp, i);
  3210. i = 0;
  3211. }
  3212. }
  3213. return result;
  3214. }
  3215. }
  3216. return String::fromUTF8 (temp, i - 1);
  3217. }
  3218. const String InputStream::readNextLine()
  3219. {
  3220. String s;
  3221. const int maxChars = 256;
  3222. tchar buffer [maxChars];
  3223. int charsInBuffer = 0;
  3224. while (! isExhausted())
  3225. {
  3226. const uint8 c = readByte();
  3227. const int64 lastPos = getPosition();
  3228. if (c == '\n')
  3229. {
  3230. break;
  3231. }
  3232. else if (c == '\r')
  3233. {
  3234. if (readByte() != '\n')
  3235. setPosition (lastPos);
  3236. break;
  3237. }
  3238. buffer [charsInBuffer++] = c;
  3239. if (charsInBuffer == maxChars)
  3240. {
  3241. s.append (buffer, maxChars);
  3242. charsInBuffer = 0;
  3243. }
  3244. }
  3245. if (charsInBuffer > 0)
  3246. s.append (buffer, charsInBuffer);
  3247. return s;
  3248. }
  3249. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  3250. int numBytes)
  3251. {
  3252. const int64 totalLength = getTotalLength();
  3253. if (totalLength >= 0)
  3254. {
  3255. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  3256. totalLength - getPosition());
  3257. if (numBytes < 0)
  3258. numBytes = totalBytesRemaining;
  3259. else if (numBytes > 0)
  3260. numBytes = jmin (numBytes, totalBytesRemaining);
  3261. else
  3262. return 0;
  3263. }
  3264. const int originalBlockSize = block.getSize();
  3265. int totalBytesRead = 0;
  3266. if (numBytes > 0)
  3267. {
  3268. // know how many bytes we want, so we can resize the block first..
  3269. block.setSize (originalBlockSize + numBytes, false);
  3270. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  3271. }
  3272. else
  3273. {
  3274. // read until end of stram..
  3275. const int chunkSize = 32768;
  3276. for (;;)
  3277. {
  3278. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  3279. const int bytesJustIn = read (((char*) block.getData())
  3280. + originalBlockSize
  3281. + totalBytesRead,
  3282. chunkSize);
  3283. if (bytesJustIn == 0)
  3284. break;
  3285. totalBytesRead += bytesJustIn;
  3286. }
  3287. }
  3288. // trim off any excess left at the end
  3289. block.setSize (originalBlockSize + totalBytesRead, false);
  3290. return totalBytesRead;
  3291. }
  3292. const String InputStream::readEntireStreamAsString()
  3293. {
  3294. MemoryBlock mb;
  3295. const int size = readIntoMemoryBlock (mb);
  3296. return String::createStringFromData ((const char*) mb.getData(), size);
  3297. }
  3298. void InputStream::skipNextBytes (int64 numBytesToSkip)
  3299. {
  3300. if (numBytesToSkip > 0)
  3301. {
  3302. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  3303. MemoryBlock temp (skipBufferSize);
  3304. while ((numBytesToSkip > 0) && ! isExhausted())
  3305. {
  3306. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  3307. }
  3308. }
  3309. }
  3310. END_JUCE_NAMESPACE
  3311. /********* End of inlined file: juce_InputStream.cpp *********/
  3312. /********* Start of inlined file: juce_OutputStream.cpp *********/
  3313. BEGIN_JUCE_NAMESPACE
  3314. #if JUCE_DEBUG
  3315. static CriticalSection activeStreamLock;
  3316. static VoidArray activeStreams;
  3317. void juce_CheckForDanglingStreams()
  3318. {
  3319. /*
  3320. It's always a bad idea to leak any object, but if you're leaking output
  3321. streams, then there's a good chance that you're failing to flush a file
  3322. to disk properly, which could result in corrupted data and other similar
  3323. nastiness..
  3324. */
  3325. jassert (activeStreams.size() == 0);
  3326. };
  3327. #endif
  3328. OutputStream::OutputStream() throw()
  3329. {
  3330. #if JUCE_DEBUG
  3331. activeStreamLock.enter();
  3332. activeStreams.add (this);
  3333. activeStreamLock.exit();
  3334. #endif
  3335. }
  3336. OutputStream::~OutputStream()
  3337. {
  3338. #if JUCE_DEBUG
  3339. activeStreamLock.enter();
  3340. activeStreams.removeValue (this);
  3341. activeStreamLock.exit();
  3342. #endif
  3343. }
  3344. void OutputStream::writeBool (bool b)
  3345. {
  3346. writeByte ((b) ? (char) 1
  3347. : (char) 0);
  3348. }
  3349. void OutputStream::writeByte (char byte)
  3350. {
  3351. write (&byte, 1);
  3352. }
  3353. void OutputStream::writeShort (short value)
  3354. {
  3355. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  3356. write (&v, 2);
  3357. }
  3358. void OutputStream::writeShortBigEndian (short value)
  3359. {
  3360. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  3361. write (&v, 2);
  3362. }
  3363. void OutputStream::writeInt (int value)
  3364. {
  3365. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  3366. write (&v, 4);
  3367. }
  3368. void OutputStream::writeIntBigEndian (int value)
  3369. {
  3370. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  3371. write (&v, 4);
  3372. }
  3373. void OutputStream::writeCompressedInt (int value)
  3374. {
  3375. unsigned int un = (value < 0) ? (unsigned int) -value
  3376. : (unsigned int) value;
  3377. unsigned int tn = un;
  3378. int numSigBytes = 0;
  3379. do
  3380. {
  3381. tn >>= 8;
  3382. numSigBytes++;
  3383. } while (tn & 0xff);
  3384. if (value < 0)
  3385. numSigBytes |= 0x80;
  3386. writeByte ((char) numSigBytes);
  3387. write (&un, numSigBytes);
  3388. }
  3389. void OutputStream::writeInt64 (int64 value)
  3390. {
  3391. const uint64 v = swapIfBigEndian ((uint64) value);
  3392. write (&v, 8);
  3393. }
  3394. void OutputStream::writeInt64BigEndian (int64 value)
  3395. {
  3396. const uint64 v = swapIfLittleEndian ((uint64) value);
  3397. write (&v, 8);
  3398. }
  3399. void OutputStream::writeFloat (float value)
  3400. {
  3401. union { int asInt; float asFloat; } n;
  3402. n.asFloat = value;
  3403. writeInt (n.asInt);
  3404. }
  3405. void OutputStream::writeFloatBigEndian (float value)
  3406. {
  3407. union { int asInt; float asFloat; } n;
  3408. n.asFloat = value;
  3409. writeIntBigEndian (n.asInt);
  3410. }
  3411. void OutputStream::writeDouble (double value)
  3412. {
  3413. union { int64 asInt; double asDouble; } n;
  3414. n.asDouble = value;
  3415. writeInt64 (n.asInt);
  3416. }
  3417. void OutputStream::writeDoubleBigEndian (double value)
  3418. {
  3419. union { int64 asInt; double asDouble; } n;
  3420. n.asDouble = value;
  3421. writeInt64BigEndian (n.asInt);
  3422. }
  3423. void OutputStream::writeString (const String& text)
  3424. {
  3425. const int numBytes = text.copyToUTF8 (0);
  3426. uint8* const temp = (uint8*) juce_malloc (numBytes);
  3427. text.copyToUTF8 (temp);
  3428. write (temp, numBytes); // (numBytes includes the terminating null).
  3429. juce_free (temp);
  3430. }
  3431. void OutputStream::printf (const char* pf, ...)
  3432. {
  3433. unsigned int bufSize = 256;
  3434. char* buf = (char*) juce_malloc (bufSize);
  3435. for (;;)
  3436. {
  3437. va_list list;
  3438. va_start (list, pf);
  3439. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  3440. if (num > 0)
  3441. {
  3442. write (buf, num);
  3443. break;
  3444. }
  3445. else if (num == 0)
  3446. {
  3447. break;
  3448. }
  3449. juce_free (buf);
  3450. bufSize += 256;
  3451. buf = (char*) juce_malloc (bufSize);
  3452. }
  3453. juce_free (buf);
  3454. }
  3455. OutputStream& OutputStream::operator<< (const int number)
  3456. {
  3457. const String s (number);
  3458. write ((const char*) s, s.length());
  3459. return *this;
  3460. }
  3461. OutputStream& OutputStream::operator<< (const double number)
  3462. {
  3463. const String s (number);
  3464. write ((const char*) s, s.length());
  3465. return *this;
  3466. }
  3467. OutputStream& OutputStream::operator<< (const char character)
  3468. {
  3469. writeByte (character);
  3470. return *this;
  3471. }
  3472. OutputStream& OutputStream::operator<< (const char* const text)
  3473. {
  3474. write (text, (int) strlen (text));
  3475. return *this;
  3476. }
  3477. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  3478. {
  3479. const String s (text);
  3480. write ((const char*) s, s.length());
  3481. return *this;
  3482. }
  3483. OutputStream& OutputStream::operator<< (const String& text)
  3484. {
  3485. write ((const char*) text,
  3486. text.length());
  3487. return *this;
  3488. }
  3489. void OutputStream::writeText (const String& text,
  3490. const bool asUnicode,
  3491. const bool writeUnicodeHeaderBytes)
  3492. {
  3493. if (asUnicode)
  3494. {
  3495. if (writeUnicodeHeaderBytes)
  3496. write ("\x0ff\x0fe", 2);
  3497. const juce_wchar* src = (const juce_wchar*) text;
  3498. bool lastCharWasReturn = false;
  3499. while (*src != 0)
  3500. {
  3501. if (*src == L'\n' && ! lastCharWasReturn)
  3502. writeShort ((short) L'\r');
  3503. lastCharWasReturn = (*src == L'\r');
  3504. writeShort ((short) *src++);
  3505. }
  3506. }
  3507. else
  3508. {
  3509. const char* src = (const char*) text;
  3510. const char* t = src;
  3511. for (;;)
  3512. {
  3513. if (*t == '\n')
  3514. {
  3515. if (t > src)
  3516. write (src, (int) (t - src));
  3517. write ("\r\n", 2);
  3518. src = t + 1;
  3519. }
  3520. else if (*t == '\r')
  3521. {
  3522. if (t[1] == '\n')
  3523. ++t;
  3524. }
  3525. else if (*t == 0)
  3526. {
  3527. if (t > src)
  3528. write (src, (int) (t - src));
  3529. break;
  3530. }
  3531. ++t;
  3532. }
  3533. }
  3534. }
  3535. int OutputStream::writeFromInputStream (InputStream& source,
  3536. int numBytesToWrite)
  3537. {
  3538. if (numBytesToWrite < 0)
  3539. numBytesToWrite = 0x7fffffff;
  3540. int numWritten = 0;
  3541. while (numBytesToWrite > 0 && ! source.isExhausted())
  3542. {
  3543. char buffer [8192];
  3544. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  3545. if (num == 0)
  3546. break;
  3547. write (buffer, num);
  3548. numBytesToWrite -= num;
  3549. numWritten += num;
  3550. }
  3551. return numWritten;
  3552. }
  3553. END_JUCE_NAMESPACE
  3554. /********* End of inlined file: juce_OutputStream.cpp *********/
  3555. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  3556. BEGIN_JUCE_NAMESPACE
  3557. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3558. bool* isDirectory, bool* isHidden, int64* fileSize,
  3559. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3560. bool juce_findFileNext (void* handle, String& resultFile,
  3561. bool* isDirectory, bool* isHidden, int64* fileSize,
  3562. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3563. void juce_findFileClose (void* handle) throw();
  3564. DirectoryIterator::DirectoryIterator (const File& directory,
  3565. bool isRecursive,
  3566. const String& wc,
  3567. const int whatToLookFor_) throw()
  3568. : wildCard (wc),
  3569. index (-1),
  3570. whatToLookFor (whatToLookFor_),
  3571. subIterator (0)
  3572. {
  3573. // you have to specify the type of files you're looking for!
  3574. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  3575. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  3576. String path (directory.getFullPathName());
  3577. if (! path.endsWithChar (File::separator))
  3578. path += File::separator;
  3579. String filename;
  3580. bool isDirectory, isHidden;
  3581. void* const handle = juce_findFileStart (path,
  3582. isRecursive ? T("*") : wc,
  3583. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  3584. if (handle != 0)
  3585. {
  3586. do
  3587. {
  3588. if (! filename.containsOnly (T(".")))
  3589. {
  3590. bool addToList = false;
  3591. if (isDirectory)
  3592. {
  3593. if (isRecursive
  3594. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  3595. || ! isHidden))
  3596. {
  3597. dirsFound.add (new File (path + filename, 0));
  3598. }
  3599. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  3600. }
  3601. else
  3602. {
  3603. addToList = (whatToLookFor_ & File::findFiles) != 0;
  3604. }
  3605. // if it's recursive, we're not relying on the OS iterator
  3606. // to do the wildcard match, so do it now..
  3607. if (isRecursive && addToList)
  3608. addToList = filename.matchesWildcard (wc, true);
  3609. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  3610. addToList = ! isHidden;
  3611. if (addToList)
  3612. filesFound.add (new File (path + filename, 0));
  3613. }
  3614. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  3615. juce_findFileClose (handle);
  3616. }
  3617. }
  3618. DirectoryIterator::~DirectoryIterator() throw()
  3619. {
  3620. if (subIterator != 0)
  3621. delete subIterator;
  3622. }
  3623. bool DirectoryIterator::next() throw()
  3624. {
  3625. if (subIterator != 0)
  3626. {
  3627. if (subIterator->next())
  3628. return true;
  3629. deleteAndZero (subIterator);
  3630. }
  3631. if (index >= filesFound.size() + dirsFound.size() - 1)
  3632. return false;
  3633. ++index;
  3634. if (index >= filesFound.size())
  3635. {
  3636. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  3637. true, wildCard, whatToLookFor);
  3638. return next();
  3639. }
  3640. return true;
  3641. }
  3642. const File DirectoryIterator::getFile() const throw()
  3643. {
  3644. if (subIterator != 0)
  3645. return subIterator->getFile();
  3646. const File* const f = filesFound [index];
  3647. return (f != 0) ? *f
  3648. : File::nonexistent;
  3649. }
  3650. float DirectoryIterator::getEstimatedProgress() const throw()
  3651. {
  3652. if (filesFound.size() + dirsFound.size() == 0)
  3653. {
  3654. return 0.0f;
  3655. }
  3656. else
  3657. {
  3658. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  3659. : (float) index;
  3660. return detailedIndex / (filesFound.size() + dirsFound.size());
  3661. }
  3662. }
  3663. END_JUCE_NAMESPACE
  3664. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  3665. /********* Start of inlined file: juce_File.cpp *********/
  3666. #ifdef _MSC_VER
  3667. #pragma warning (disable: 4514)
  3668. #pragma warning (push)
  3669. #endif
  3670. #ifndef JUCE_WIN32
  3671. #include <pwd.h>
  3672. #endif
  3673. BEGIN_JUCE_NAMESPACE
  3674. #ifdef _MSC_VER
  3675. #pragma warning (pop)
  3676. #endif
  3677. void* juce_fileOpen (const String& path, bool forWriting) throw();
  3678. void juce_fileClose (void* handle) throw();
  3679. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  3680. int64 juce_fileGetPosition (void* handle) throw();
  3681. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  3682. void juce_fileFlush (void* handle) throw();
  3683. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  3684. bool juce_isDirectory (const String& fileName) throw();
  3685. int64 juce_getFileSize (const String& fileName) throw();
  3686. bool juce_canWriteToFile (const String& fileName) throw();
  3687. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  3688. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  3689. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  3690. bool juce_deleteFile (const String& fileName) throw();
  3691. bool juce_copyFile (const String& source, const String& dest) throw();
  3692. bool juce_moveFile (const String& source, const String& dest) throw();
  3693. // this must also create all paths involved in the directory.
  3694. void juce_createDirectory (const String& fileName) throw();
  3695. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  3696. const StringArray juce_getFileSystemRoots() throw();
  3697. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  3698. // starts a directory search operation with a wildcard, returning a handle for
  3699. // use in calls to juce_findFileNext.
  3700. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  3701. // the other pointers, if non-null, are set based on the properties of the file.
  3702. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3703. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  3704. Time* creationTime, bool* isReadOnly) throw();
  3705. // returns false when no more files are found
  3706. bool juce_findFileNext (void* handle, String& resultFile,
  3707. bool* isDirectory, bool* isHidden, int64* fileSize,
  3708. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3709. void juce_findFileClose (void* handle) throw();
  3710. static const String parseAbsolutePath (String path) throw()
  3711. {
  3712. if (path.isEmpty())
  3713. return String::empty;
  3714. #if JUCE_WIN32
  3715. // Windows..
  3716. path = path.replaceCharacter (T('/'), T('\\')).unquoted();
  3717. if (path.startsWithChar (File::separator))
  3718. {
  3719. if (path[1] != File::separator)
  3720. {
  3721. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  3722. // Windows, because it needs a drive letter, which in this case
  3723. // we'll take from the CWD.. but this is a bit of an assumption that
  3724. // could be wrong..
  3725. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  3726. }
  3727. }
  3728. else if (path.indexOfChar (T(':')) < 0)
  3729. {
  3730. if (path.isEmpty())
  3731. return String::empty;
  3732. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3733. // we don't know what directory to put it in.
  3734. // Here we'll assume it's in the CWD, but this might not be what was
  3735. // intended..
  3736. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3737. }
  3738. #else
  3739. // Mac or Linux..
  3740. path = path.replaceCharacter (T('\\'), T('/')).unquoted();
  3741. if (path.startsWithChar (T('~')))
  3742. {
  3743. const char* homeDir = 0;
  3744. if (path[1] == File::separator || path[1] == 0)
  3745. {
  3746. // expand a name of the form "~/abc"
  3747. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  3748. + path.substring (1);
  3749. }
  3750. else
  3751. {
  3752. // expand a name of type "~dave/abc"
  3753. const String userName (path.substring (1)
  3754. .upToFirstOccurrenceOf (T("/"), false, false));
  3755. struct passwd* const pw = getpwnam (userName);
  3756. if (pw != 0)
  3757. {
  3758. String home (homeDir);
  3759. if (home.endsWithChar (File::separator))
  3760. home [home.length() - 1] = 0;
  3761. path = String (pw->pw_dir)
  3762. + path.substring (userName.length());
  3763. }
  3764. }
  3765. }
  3766. else if (! path.startsWithChar (File::separator))
  3767. {
  3768. while (path.startsWith (T("./")))
  3769. path = path.substring (2);
  3770. if (path.isEmpty())
  3771. return String::empty;
  3772. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3773. // we don't know what directory to put it in.
  3774. // Here we'll assume it's in the CWD, but this might not be what was
  3775. // intended..
  3776. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3777. }
  3778. #endif
  3779. int len = path.length();
  3780. while (--len > 0 && path [len] == File::separator)
  3781. path [len] = 0;
  3782. return path;
  3783. }
  3784. const File File::nonexistent;
  3785. File::File (const String& fullPathName) throw()
  3786. : fullPath (parseAbsolutePath (fullPathName))
  3787. {
  3788. }
  3789. File::File (const String& path, int) throw()
  3790. : fullPath (path)
  3791. {
  3792. }
  3793. File::File (const File& other) throw()
  3794. : fullPath (other.fullPath)
  3795. {
  3796. }
  3797. const File& File::operator= (const String& newPath) throw()
  3798. {
  3799. fullPath = parseAbsolutePath (newPath);
  3800. return *this;
  3801. }
  3802. const File& File::operator= (const File& other) throw()
  3803. {
  3804. fullPath = other.fullPath;
  3805. return *this;
  3806. }
  3807. #if JUCE_LINUX
  3808. #define NAMES_ARE_CASE_SENSITIVE 1
  3809. #endif
  3810. bool File::areFileNamesCaseSensitive()
  3811. {
  3812. #if NAMES_ARE_CASE_SENSITIVE
  3813. return true;
  3814. #else
  3815. return false;
  3816. #endif
  3817. }
  3818. bool File::operator== (const File& other) const throw()
  3819. {
  3820. // case-insensitive on Windows, but not on linux.
  3821. #if NAMES_ARE_CASE_SENSITIVE
  3822. return fullPath == other.fullPath;
  3823. #else
  3824. return fullPath.equalsIgnoreCase (other.fullPath);
  3825. #endif
  3826. }
  3827. bool File::operator!= (const File& other) const throw()
  3828. {
  3829. return ! operator== (other);
  3830. }
  3831. bool File::exists() const throw()
  3832. {
  3833. return juce_fileExists (fullPath, false);
  3834. }
  3835. bool File::existsAsFile() const throw()
  3836. {
  3837. return juce_fileExists (fullPath, true);
  3838. }
  3839. bool File::isDirectory() const throw()
  3840. {
  3841. return juce_isDirectory (fullPath);
  3842. }
  3843. bool File::hasWriteAccess() const throw()
  3844. {
  3845. if (exists())
  3846. return juce_canWriteToFile (fullPath);
  3847. #ifndef JUCE_WIN32
  3848. else if ((! isDirectory()) && fullPath.containsChar (separator))
  3849. return getParentDirectory().hasWriteAccess();
  3850. else
  3851. return false;
  3852. #else
  3853. // on windows, it seems that even read-only directories can still be written into,
  3854. // so checking the parent directory's permissions would return the wrong result..
  3855. else
  3856. return true;
  3857. #endif
  3858. }
  3859. bool File::setReadOnly (const bool shouldBeReadOnly,
  3860. const bool applyRecursively) const throw()
  3861. {
  3862. bool worked = true;
  3863. if (applyRecursively && isDirectory())
  3864. {
  3865. OwnedArray <File> subFiles;
  3866. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3867. for (int i = subFiles.size(); --i >= 0;)
  3868. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  3869. }
  3870. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  3871. }
  3872. bool File::deleteFile() const throw()
  3873. {
  3874. return (! exists())
  3875. || juce_deleteFile (fullPath);
  3876. }
  3877. bool File::deleteRecursively() const throw()
  3878. {
  3879. bool worked = true;
  3880. if (isDirectory())
  3881. {
  3882. OwnedArray<File> subFiles;
  3883. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3884. for (int i = subFiles.size(); --i >= 0;)
  3885. worked = subFiles[i]->deleteRecursively() && worked;
  3886. }
  3887. return deleteFile() && worked;
  3888. }
  3889. bool File::moveFileTo (const File& newFile) const throw()
  3890. {
  3891. if (newFile.fullPath == fullPath)
  3892. return true;
  3893. #if ! NAMES_ARE_CASE_SENSITIVE
  3894. if (*this != newFile)
  3895. #endif
  3896. if (! newFile.deleteFile())
  3897. return false;
  3898. return juce_moveFile (fullPath, newFile.fullPath);
  3899. }
  3900. bool File::copyFileTo (const File& newFile) const throw()
  3901. {
  3902. if (*this == newFile)
  3903. return true;
  3904. if (! newFile.deleteFile())
  3905. return false;
  3906. return juce_copyFile (fullPath, newFile.fullPath);
  3907. }
  3908. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  3909. {
  3910. if (isDirectory() && newDirectory.createDirectory())
  3911. {
  3912. OwnedArray<File> subFiles;
  3913. findChildFiles (subFiles, File::findFiles, false);
  3914. int i;
  3915. for (i = 0; i < subFiles.size(); ++i)
  3916. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3917. return false;
  3918. subFiles.clear();
  3919. findChildFiles (subFiles, File::findDirectories, false);
  3920. for (i = 0; i < subFiles.size(); ++i)
  3921. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3922. return false;
  3923. return true;
  3924. }
  3925. return false;
  3926. }
  3927. const String File::getPathUpToLastSlash() const throw()
  3928. {
  3929. const int lastSlash = fullPath.lastIndexOfChar (separator);
  3930. if (lastSlash > 0)
  3931. return fullPath.substring (0, lastSlash);
  3932. else if (lastSlash == 0)
  3933. return separatorString;
  3934. else
  3935. return fullPath;
  3936. }
  3937. const File File::getParentDirectory() const throw()
  3938. {
  3939. return File (getPathUpToLastSlash());
  3940. }
  3941. const String File::getFileName() const throw()
  3942. {
  3943. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  3944. }
  3945. int File::hashCode() const throw()
  3946. {
  3947. return fullPath.hashCode();
  3948. }
  3949. int64 File::hashCode64() const throw()
  3950. {
  3951. return fullPath.hashCode64();
  3952. }
  3953. const String File::getFileNameWithoutExtension() const throw()
  3954. {
  3955. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  3956. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  3957. if (lastDot > lastSlash)
  3958. return fullPath.substring (lastSlash, lastDot);
  3959. else
  3960. return fullPath.substring (lastSlash);
  3961. }
  3962. bool File::isAChildOf (const File& potentialParent) const throw()
  3963. {
  3964. const String ourPath (getPathUpToLastSlash());
  3965. #if NAMES_ARE_CASE_SENSITIVE
  3966. if (potentialParent.fullPath == ourPath)
  3967. #else
  3968. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  3969. #endif
  3970. {
  3971. return true;
  3972. }
  3973. else if (potentialParent.fullPath.length() >= ourPath.length())
  3974. {
  3975. return false;
  3976. }
  3977. else
  3978. {
  3979. return getParentDirectory().isAChildOf (potentialParent);
  3980. }
  3981. }
  3982. bool File::isAbsolutePath (const String& path) throw()
  3983. {
  3984. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  3985. #if JUCE_WIN32
  3986. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  3987. #else
  3988. || path.startsWithChar (T('~'));
  3989. #endif
  3990. }
  3991. const File File::getChildFile (String relativePath) const throw()
  3992. {
  3993. if (isAbsolutePath (relativePath))
  3994. {
  3995. // the path is really absolute..
  3996. return File (relativePath);
  3997. }
  3998. else
  3999. {
  4000. // it's relative, so remove any ../ or ./ bits at the start.
  4001. String path (fullPath);
  4002. if (relativePath[0] == T('.'))
  4003. {
  4004. #if JUCE_WIN32
  4005. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4006. #else
  4007. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4008. #endif
  4009. while (relativePath[0] == T('.'))
  4010. {
  4011. if (relativePath[1] == T('.'))
  4012. {
  4013. if (relativePath [2] == 0 || relativePath[2] == separator)
  4014. {
  4015. const int lastSlash = path.lastIndexOfChar (separator);
  4016. if (lastSlash > 0)
  4017. path = path.substring (0, lastSlash);
  4018. relativePath = relativePath.substring (3);
  4019. }
  4020. else
  4021. {
  4022. break;
  4023. }
  4024. }
  4025. else if (relativePath[1] == separator)
  4026. {
  4027. relativePath = relativePath.substring (2);
  4028. }
  4029. else
  4030. {
  4031. break;
  4032. }
  4033. }
  4034. }
  4035. if (! path.endsWithChar (separator))
  4036. path += separator;
  4037. return File (path + relativePath);
  4038. }
  4039. }
  4040. const File File::getSiblingFile (const String& fileName) const throw()
  4041. {
  4042. return getParentDirectory().getChildFile (fileName);
  4043. }
  4044. int64 File::getSize() const throw()
  4045. {
  4046. return juce_getFileSize (fullPath);
  4047. }
  4048. const String File::descriptionOfSizeInBytes (const int64 bytes)
  4049. {
  4050. if (bytes == 1)
  4051. {
  4052. return "1 byte";
  4053. }
  4054. else if (bytes < 1024)
  4055. {
  4056. return String ((int) bytes) + " bytes";
  4057. }
  4058. else if (bytes < 1024 * 1024)
  4059. {
  4060. return String (bytes / 1024.0, 1) + " KB";
  4061. }
  4062. else if (bytes < 1024 * 1024 * 1024)
  4063. {
  4064. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  4065. }
  4066. else
  4067. {
  4068. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  4069. }
  4070. }
  4071. bool File::create() const throw()
  4072. {
  4073. if (! exists())
  4074. {
  4075. const File parentDir (getParentDirectory());
  4076. if (parentDir == *this || ! parentDir.createDirectory())
  4077. return false;
  4078. void* const fh = juce_fileOpen (fullPath, true);
  4079. if (fh == 0)
  4080. return false;
  4081. juce_fileClose (fh);
  4082. }
  4083. return true;
  4084. }
  4085. bool File::createDirectory() const throw()
  4086. {
  4087. if (! isDirectory())
  4088. {
  4089. const File parentDir (getParentDirectory());
  4090. if (parentDir == *this || ! parentDir.createDirectory())
  4091. return false;
  4092. String dir (fullPath);
  4093. while (dir.endsWithChar (separator))
  4094. dir [dir.length() - 1] = 0;
  4095. juce_createDirectory (dir);
  4096. return isDirectory();
  4097. }
  4098. return true;
  4099. }
  4100. const Time File::getCreationTime() const throw()
  4101. {
  4102. int64 m, a, c;
  4103. juce_getFileTimes (fullPath, m, a, c);
  4104. return Time (c);
  4105. }
  4106. bool File::setCreationTime (const Time& t) const throw()
  4107. {
  4108. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  4109. }
  4110. const Time File::getLastModificationTime() const throw()
  4111. {
  4112. int64 m, a, c;
  4113. juce_getFileTimes (fullPath, m, a, c);
  4114. return Time (m);
  4115. }
  4116. bool File::setLastModificationTime (const Time& t) const throw()
  4117. {
  4118. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  4119. }
  4120. const Time File::getLastAccessTime() const throw()
  4121. {
  4122. int64 m, a, c;
  4123. juce_getFileTimes (fullPath, m, a, c);
  4124. return Time (a);
  4125. }
  4126. bool File::setLastAccessTime (const Time& t) const throw()
  4127. {
  4128. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  4129. }
  4130. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  4131. {
  4132. if (! existsAsFile())
  4133. return false;
  4134. FileInputStream in (*this);
  4135. return getSize() == in.readIntoMemoryBlock (destBlock);
  4136. }
  4137. const String File::loadFileAsString() const throw()
  4138. {
  4139. if (! existsAsFile())
  4140. return String::empty;
  4141. FileInputStream in (*this);
  4142. return in.readEntireStreamAsString();
  4143. }
  4144. static inline bool fileTypeMatches (const int whatToLookFor,
  4145. const bool isDir,
  4146. const bool isHidden)
  4147. {
  4148. return (whatToLookFor & (isDir ? File::findDirectories
  4149. : File::findFiles)) != 0
  4150. && ((! isHidden)
  4151. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  4152. }
  4153. int File::findChildFiles (OwnedArray<File>& results,
  4154. const int whatToLookFor,
  4155. const bool searchRecursively,
  4156. const String& wildCardPattern) const throw()
  4157. {
  4158. // you have to specify the type of files you're looking for!
  4159. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  4160. int total = 0;
  4161. // find child files or directories in this directory first..
  4162. if (isDirectory())
  4163. {
  4164. String path (fullPath);
  4165. if (! path.endsWithChar (separator))
  4166. path += separator;
  4167. String filename;
  4168. bool isDirectory, isHidden;
  4169. void* const handle = juce_findFileStart (path,
  4170. wildCardPattern,
  4171. filename,
  4172. &isDirectory, &isHidden,
  4173. 0, 0, 0, 0);
  4174. if (handle != 0)
  4175. {
  4176. do
  4177. {
  4178. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4179. && ! filename.containsOnly (T(".")))
  4180. {
  4181. results.add (new File (path + filename, 0));
  4182. ++total;
  4183. }
  4184. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4185. juce_findFileClose (handle);
  4186. }
  4187. }
  4188. else
  4189. {
  4190. // trying to search for files inside a non-directory?
  4191. //jassertfalse
  4192. }
  4193. // and recurse down if required.
  4194. if (searchRecursively)
  4195. {
  4196. OwnedArray <File> subDirectories;
  4197. findChildFiles (subDirectories, File::findDirectories, false);
  4198. for (int i = 0; i < subDirectories.size(); ++i)
  4199. {
  4200. total += subDirectories.getUnchecked(i)
  4201. ->findChildFiles (results,
  4202. whatToLookFor,
  4203. true,
  4204. wildCardPattern);
  4205. }
  4206. }
  4207. return total;
  4208. }
  4209. int File::getNumberOfChildFiles (const int whatToLookFor,
  4210. const String& wildCardPattern) const throw()
  4211. {
  4212. // you have to specify the type of files you're looking for!
  4213. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  4214. int count = 0;
  4215. if (isDirectory())
  4216. {
  4217. String filename;
  4218. bool isDirectory, isHidden;
  4219. void* const handle = juce_findFileStart (fullPath,
  4220. wildCardPattern,
  4221. filename,
  4222. &isDirectory, &isHidden,
  4223. 0, 0, 0, 0);
  4224. if (handle != 0)
  4225. {
  4226. do
  4227. {
  4228. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4229. && ! filename.containsOnly (T(".")))
  4230. {
  4231. ++count;
  4232. }
  4233. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4234. juce_findFileClose (handle);
  4235. }
  4236. }
  4237. else
  4238. {
  4239. // trying to search for files inside a non-directory?
  4240. jassertfalse
  4241. }
  4242. return count;
  4243. }
  4244. const File File::getNonexistentChildFile (const String& prefix_,
  4245. const String& suffix,
  4246. bool putNumbersInBrackets) const throw()
  4247. {
  4248. File f (getChildFile (prefix_ + suffix));
  4249. if (f.exists())
  4250. {
  4251. int num = 2;
  4252. String prefix (prefix_);
  4253. // remove any bracketed numbers that may already be on the end..
  4254. if (prefix.trim().endsWithChar (T(')')))
  4255. {
  4256. putNumbersInBrackets = true;
  4257. const int openBracks = prefix.lastIndexOfChar (T('('));
  4258. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  4259. if (openBracks > 0
  4260. && closeBracks > openBracks
  4261. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  4262. {
  4263. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  4264. prefix = prefix.substring (0, openBracks);
  4265. }
  4266. }
  4267. // also use brackets if it ends in a digit.
  4268. putNumbersInBrackets = putNumbersInBrackets
  4269. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  4270. do
  4271. {
  4272. if (putNumbersInBrackets)
  4273. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  4274. else
  4275. f = getChildFile (prefix + String (num++) + suffix);
  4276. } while (f.exists());
  4277. }
  4278. return f;
  4279. }
  4280. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  4281. {
  4282. if (exists())
  4283. {
  4284. return getParentDirectory()
  4285. .getNonexistentChildFile (getFileNameWithoutExtension(),
  4286. getFileExtension(),
  4287. putNumbersInBrackets);
  4288. }
  4289. else
  4290. {
  4291. return *this;
  4292. }
  4293. }
  4294. const String File::getFileExtension() const throw()
  4295. {
  4296. String ext;
  4297. if (! isDirectory())
  4298. {
  4299. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  4300. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  4301. ext = fullPath.substring (indexOfDot);
  4302. }
  4303. return ext;
  4304. }
  4305. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  4306. {
  4307. if (possibleSuffix.isEmpty())
  4308. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  4309. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  4310. {
  4311. if (possibleSuffix.startsWithChar (T('.')))
  4312. return true;
  4313. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  4314. if (dotPos >= 0)
  4315. return fullPath [dotPos] == T('.');
  4316. }
  4317. return false;
  4318. }
  4319. const File File::withFileExtension (const String& newExtension) const throw()
  4320. {
  4321. if (fullPath.isEmpty())
  4322. return File::nonexistent;
  4323. String filePart (getFileName());
  4324. int i = filePart.lastIndexOfChar (T('.'));
  4325. if (i < 0)
  4326. i = filePart.length();
  4327. String newExt (newExtension);
  4328. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  4329. newExt = T(".") + newExt;
  4330. return getSiblingFile (filePart.substring (0, i) + newExt);
  4331. }
  4332. bool File::startAsProcess (const String& parameters) const throw()
  4333. {
  4334. return exists()
  4335. && juce_launchFile (fullPath, parameters);
  4336. }
  4337. FileInputStream* File::createInputStream() const throw()
  4338. {
  4339. if (existsAsFile())
  4340. return new FileInputStream (*this);
  4341. else
  4342. return 0;
  4343. }
  4344. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  4345. {
  4346. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  4347. if (out->failedToOpen())
  4348. {
  4349. delete out;
  4350. return 0;
  4351. }
  4352. else
  4353. {
  4354. return out;
  4355. }
  4356. }
  4357. bool File::appendData (const void* const dataToAppend,
  4358. const int numberOfBytes) const throw()
  4359. {
  4360. if (numberOfBytes > 0)
  4361. {
  4362. FileOutputStream* const out = createOutputStream();
  4363. if (out == 0)
  4364. return false;
  4365. out->write (dataToAppend, numberOfBytes);
  4366. delete out;
  4367. }
  4368. return true;
  4369. }
  4370. bool File::replaceWithData (const void* const dataToWrite,
  4371. const int numberOfBytes) const throw()
  4372. {
  4373. jassert (numberOfBytes >= 0); // a negative number of bytes??
  4374. if (numberOfBytes <= 0)
  4375. return deleteFile();
  4376. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4377. if (tempFile.appendData (dataToWrite, numberOfBytes)
  4378. && tempFile.moveFileTo (*this))
  4379. {
  4380. return true;
  4381. }
  4382. tempFile.deleteFile();
  4383. return false;
  4384. }
  4385. bool File::appendText (const String& text,
  4386. const bool asUnicode,
  4387. const bool writeUnicodeHeaderBytes) const throw()
  4388. {
  4389. FileOutputStream* const out = createOutputStream();
  4390. if (out != 0)
  4391. {
  4392. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  4393. delete out;
  4394. return true;
  4395. }
  4396. return false;
  4397. }
  4398. bool File::printf (const tchar* pf, ...) const throw()
  4399. {
  4400. va_list list;
  4401. va_start (list, pf);
  4402. String text;
  4403. text.vprintf (pf, list);
  4404. return appendData ((const char*) text, text.length());
  4405. }
  4406. bool File::replaceWithText (const String& textToWrite,
  4407. const bool asUnicode,
  4408. const bool writeUnicodeHeaderBytes) const throw()
  4409. {
  4410. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4411. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  4412. && tempFile.moveFileTo (*this))
  4413. {
  4414. return true;
  4415. }
  4416. tempFile.deleteFile();
  4417. return false;
  4418. }
  4419. const String File::createLegalPathName (const String& original) throw()
  4420. {
  4421. String s (original);
  4422. String start;
  4423. if (s[1] == T(':'))
  4424. {
  4425. start = s.substring (0, 2);
  4426. s = s.substring (2);
  4427. }
  4428. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  4429. .substring (0, 1024);
  4430. }
  4431. const String File::createLegalFileName (const String& original) throw()
  4432. {
  4433. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  4434. const int maxLength = 128; // only the length of the filename, not the whole path
  4435. const int len = s.length();
  4436. if (len > maxLength)
  4437. {
  4438. const int lastDot = s.lastIndexOfChar (T('.'));
  4439. if (lastDot > jmax (0, len - 12))
  4440. {
  4441. s = s.substring (0, maxLength - (len - lastDot))
  4442. + s.substring (lastDot);
  4443. }
  4444. else
  4445. {
  4446. s = s.substring (0, maxLength);
  4447. }
  4448. }
  4449. return s;
  4450. }
  4451. const String File::getRelativePathFrom (const File& dir) const throw()
  4452. {
  4453. String thisPath (fullPath);
  4454. {
  4455. int len = thisPath.length();
  4456. while (--len >= 0 && thisPath [len] == File::separator)
  4457. thisPath [len] = 0;
  4458. }
  4459. String dirPath ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  4460. : dir.fullPath);
  4461. if (! dirPath.endsWithChar (separator))
  4462. dirPath += separator;
  4463. const int len = jmin (thisPath.length(), dirPath.length());
  4464. int commonBitLength = 0;
  4465. for (int i = 0; i < len; ++i)
  4466. {
  4467. #if NAMES_ARE_CASE_SENSITIVE
  4468. if (thisPath[i] != dirPath[i])
  4469. #else
  4470. if (CharacterFunctions::toLowerCase (thisPath[i])
  4471. != CharacterFunctions::toLowerCase (dirPath[i]))
  4472. #endif
  4473. {
  4474. break;
  4475. }
  4476. ++commonBitLength;
  4477. }
  4478. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  4479. --commonBitLength;
  4480. // if the only common bit is the root, then just return the full path..
  4481. #if JUCE_WIN32
  4482. if (commonBitLength <= 0
  4483. || (commonBitLength == 1 && thisPath [1] == File::separator)
  4484. || (commonBitLength <= 3 && thisPath [1] == T(':')))
  4485. #else
  4486. if (commonBitLength <= 0
  4487. || (commonBitLength == 1 && thisPath [1] == File::separator))
  4488. #endif
  4489. return fullPath;
  4490. thisPath = thisPath.substring (commonBitLength);
  4491. dirPath = dirPath.substring (commonBitLength);
  4492. while (dirPath.isNotEmpty())
  4493. {
  4494. #if JUCE_WIN32
  4495. thisPath = T("..\\") + thisPath;
  4496. #else
  4497. thisPath = T("../") + thisPath;
  4498. #endif
  4499. const int sep = dirPath.indexOfChar (separator);
  4500. if (sep >= 0)
  4501. dirPath = dirPath.substring (sep + 1);
  4502. else
  4503. dirPath = String::empty;
  4504. }
  4505. return thisPath;
  4506. }
  4507. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  4508. {
  4509. const StringArray roots (juce_getFileSystemRoots());
  4510. for (int i = 0; i < roots.size(); ++i)
  4511. destArray.add (new File (roots[i]));
  4512. }
  4513. const String File::getVolumeLabel() const throw()
  4514. {
  4515. int serialNum;
  4516. return juce_getVolumeLabel (fullPath, serialNum);
  4517. }
  4518. int File::getVolumeSerialNumber() const throw()
  4519. {
  4520. int serialNum;
  4521. juce_getVolumeLabel (fullPath, serialNum);
  4522. return serialNum;
  4523. }
  4524. const File File::createTempFile (const String& fileNameEnding) throw()
  4525. {
  4526. String tempName (T("temp"));
  4527. static int tempNum = 0;
  4528. tempName << tempNum++ << fileNameEnding;
  4529. const File tempFile (getSpecialLocation (tempDirectory)
  4530. .getChildFile (tempName));
  4531. if (tempFile.exists())
  4532. return createTempFile (fileNameEnding);
  4533. else
  4534. return tempFile;
  4535. }
  4536. END_JUCE_NAMESPACE
  4537. /********* End of inlined file: juce_File.cpp *********/
  4538. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  4539. BEGIN_JUCE_NAMESPACE
  4540. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4541. void juce_fileClose (void* handle) throw();
  4542. int juce_fileRead (void* handle, void* buffer, int size) throw();
  4543. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4544. FileInputStream::FileInputStream (const File& f)
  4545. : file (f),
  4546. currentPosition (0),
  4547. needToSeek (true)
  4548. {
  4549. totalSize = f.getSize();
  4550. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  4551. }
  4552. FileInputStream::~FileInputStream()
  4553. {
  4554. juce_fileClose (fileHandle);
  4555. }
  4556. int64 FileInputStream::getTotalLength()
  4557. {
  4558. return totalSize;
  4559. }
  4560. int FileInputStream::read (void* buffer, int bytesToRead)
  4561. {
  4562. int num = 0;
  4563. if (needToSeek)
  4564. {
  4565. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  4566. return 0;
  4567. needToSeek = false;
  4568. }
  4569. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  4570. currentPosition += num;
  4571. return num;
  4572. }
  4573. bool FileInputStream::isExhausted()
  4574. {
  4575. return currentPosition >= totalSize;
  4576. }
  4577. int64 FileInputStream::getPosition()
  4578. {
  4579. return currentPosition;
  4580. }
  4581. bool FileInputStream::setPosition (int64 pos)
  4582. {
  4583. pos = jlimit ((int64) 0, totalSize, pos);
  4584. needToSeek |= (currentPosition != pos);
  4585. currentPosition = pos;
  4586. return true;
  4587. }
  4588. END_JUCE_NAMESPACE
  4589. /********* End of inlined file: juce_FileInputStream.cpp *********/
  4590. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  4591. BEGIN_JUCE_NAMESPACE
  4592. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4593. void juce_fileClose (void* handle) throw();
  4594. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4595. void juce_fileFlush (void* handle) throw();
  4596. int64 juce_fileGetPosition (void* handle) throw();
  4597. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4598. FileOutputStream::FileOutputStream (const File& f,
  4599. const int bufferSize_)
  4600. : file (f),
  4601. bufferSize (bufferSize_),
  4602. bytesInBuffer (0)
  4603. {
  4604. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  4605. if (fileHandle != 0)
  4606. {
  4607. currentPosition = juce_fileGetPosition (fileHandle);
  4608. if (currentPosition < 0)
  4609. {
  4610. jassertfalse
  4611. juce_fileClose (fileHandle);
  4612. fileHandle = 0;
  4613. }
  4614. }
  4615. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  4616. }
  4617. FileOutputStream::~FileOutputStream()
  4618. {
  4619. flush();
  4620. juce_fileClose (fileHandle);
  4621. juce_free (buffer);
  4622. }
  4623. int64 FileOutputStream::getPosition()
  4624. {
  4625. return currentPosition;
  4626. }
  4627. bool FileOutputStream::setPosition (int64 newPosition)
  4628. {
  4629. if (newPosition != currentPosition)
  4630. {
  4631. flush();
  4632. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  4633. }
  4634. return newPosition == currentPosition;
  4635. }
  4636. void FileOutputStream::flush()
  4637. {
  4638. if (bytesInBuffer > 0)
  4639. {
  4640. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  4641. bytesInBuffer = 0;
  4642. }
  4643. juce_fileFlush (fileHandle);
  4644. }
  4645. bool FileOutputStream::write (const void* const src, const int numBytes)
  4646. {
  4647. if (bytesInBuffer + numBytes < bufferSize)
  4648. {
  4649. memcpy (buffer + bytesInBuffer, src, numBytes);
  4650. bytesInBuffer += numBytes;
  4651. currentPosition += numBytes;
  4652. }
  4653. else
  4654. {
  4655. if (bytesInBuffer > 0)
  4656. {
  4657. // flush the reservoir
  4658. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  4659. bytesInBuffer = 0;
  4660. if (! wroteOk)
  4661. return false;
  4662. }
  4663. if (numBytes < bufferSize)
  4664. {
  4665. memcpy (buffer + bytesInBuffer, src, numBytes);
  4666. bytesInBuffer += numBytes;
  4667. currentPosition += numBytes;
  4668. }
  4669. else
  4670. {
  4671. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  4672. currentPosition += bytesWritten;
  4673. return bytesWritten == numBytes;
  4674. }
  4675. }
  4676. return true;
  4677. }
  4678. END_JUCE_NAMESPACE
  4679. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  4680. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  4681. BEGIN_JUCE_NAMESPACE
  4682. FileSearchPath::FileSearchPath()
  4683. {
  4684. }
  4685. FileSearchPath::FileSearchPath (const String& path)
  4686. {
  4687. init (path);
  4688. }
  4689. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  4690. : directories (other.directories)
  4691. {
  4692. }
  4693. FileSearchPath::~FileSearchPath()
  4694. {
  4695. }
  4696. const FileSearchPath& FileSearchPath::operator= (const String& path)
  4697. {
  4698. init (path);
  4699. return *this;
  4700. }
  4701. void FileSearchPath::init (const String& path)
  4702. {
  4703. directories.clear();
  4704. directories.addTokens (path, T(";"), T("\""));
  4705. directories.trim();
  4706. directories.removeEmptyStrings();
  4707. for (int i = directories.size(); --i >= 0;)
  4708. directories.set (i, directories[i].unquoted());
  4709. }
  4710. int FileSearchPath::getNumPaths() const
  4711. {
  4712. return directories.size();
  4713. }
  4714. const File FileSearchPath::operator[] (const int index) const
  4715. {
  4716. return File (directories [index]);
  4717. }
  4718. const String FileSearchPath::toString() const
  4719. {
  4720. StringArray directories2 (directories);
  4721. for (int i = directories2.size(); --i >= 0;)
  4722. if (directories2[i].containsChar (T(';')))
  4723. directories2.set (i, directories2[i].quoted());
  4724. return directories2.joinIntoString (T(";"));
  4725. }
  4726. void FileSearchPath::add (const File& dir, const int insertIndex)
  4727. {
  4728. directories.insert (insertIndex, dir.getFullPathName());
  4729. }
  4730. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  4731. {
  4732. for (int i = 0; i < directories.size(); ++i)
  4733. if (File (directories[i]) == dir)
  4734. return;
  4735. add (dir);
  4736. }
  4737. void FileSearchPath::remove (const int index)
  4738. {
  4739. directories.remove (index);
  4740. }
  4741. void FileSearchPath::addPath (const FileSearchPath& other)
  4742. {
  4743. for (int i = 0; i < other.getNumPaths(); ++i)
  4744. addIfNotAlreadyThere (other[i]);
  4745. }
  4746. void FileSearchPath::removeRedundantPaths()
  4747. {
  4748. for (int i = directories.size(); --i >= 0;)
  4749. {
  4750. const File d1 (directories[i]);
  4751. for (int j = directories.size(); --j >= 0;)
  4752. {
  4753. const File d2 (directories[j]);
  4754. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  4755. {
  4756. directories.remove (i);
  4757. break;
  4758. }
  4759. }
  4760. }
  4761. }
  4762. void FileSearchPath::removeNonExistentPaths()
  4763. {
  4764. for (int i = directories.size(); --i >= 0;)
  4765. if (! File (directories[i]).isDirectory())
  4766. directories.remove (i);
  4767. }
  4768. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  4769. const int whatToLookFor,
  4770. const bool searchRecursively,
  4771. const String& wildCardPattern) const
  4772. {
  4773. int total = 0;
  4774. for (int i = 0; i < directories.size(); ++i)
  4775. total += operator[] (i).findChildFiles (results,
  4776. whatToLookFor,
  4777. searchRecursively,
  4778. wildCardPattern);
  4779. return total;
  4780. }
  4781. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  4782. const bool checkRecursively) const
  4783. {
  4784. for (int i = directories.size(); --i >= 0;)
  4785. {
  4786. const File d (directories[i]);
  4787. if (checkRecursively)
  4788. {
  4789. if (fileToCheck.isAChildOf (d))
  4790. return true;
  4791. }
  4792. else
  4793. {
  4794. if (fileToCheck.getParentDirectory() == d)
  4795. return true;
  4796. }
  4797. }
  4798. return false;
  4799. }
  4800. END_JUCE_NAMESPACE
  4801. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  4802. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  4803. BEGIN_JUCE_NAMESPACE
  4804. NamedPipe::NamedPipe()
  4805. : internal (0)
  4806. {
  4807. }
  4808. NamedPipe::~NamedPipe()
  4809. {
  4810. close();
  4811. }
  4812. bool NamedPipe::openExisting (const String& pipeName)
  4813. {
  4814. currentPipeName = pipeName;
  4815. return openInternal (pipeName, false);
  4816. }
  4817. bool NamedPipe::createNewPipe (const String& pipeName)
  4818. {
  4819. currentPipeName = pipeName;
  4820. return openInternal (pipeName, true);
  4821. }
  4822. bool NamedPipe::isOpen() const throw()
  4823. {
  4824. return internal != 0;
  4825. }
  4826. const String NamedPipe::getName() const throw()
  4827. {
  4828. return currentPipeName;
  4829. }
  4830. // other methods for this class are implemented in the platform-specific files
  4831. END_JUCE_NAMESPACE
  4832. /********* End of inlined file: juce_NamedPipe.cpp *********/
  4833. /********* Start of inlined file: juce_Socket.cpp *********/
  4834. #ifdef _WIN32
  4835. #include <winsock2.h>
  4836. #ifdef _MSC_VER
  4837. #pragma warning (disable : 4127 4389 4018)
  4838. #endif
  4839. #else
  4840. #ifndef LINUX
  4841. #include <Carbon/Carbon.h>
  4842. #endif
  4843. #include <sys/types.h>
  4844. #include <netdb.h>
  4845. #include <sys/socket.h>
  4846. #include <arpa/inet.h>
  4847. #include <sys/errno.h>
  4848. #include <netinet/tcp.h>
  4849. #include <netinet/in.h>
  4850. #include <fcntl.h>
  4851. #include <unistd.h>
  4852. #endif
  4853. BEGIN_JUCE_NAMESPACE
  4854. #if JUCE_WIN32
  4855. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  4856. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  4857. static void initWin32Sockets()
  4858. {
  4859. static CriticalSection lock;
  4860. const ScopedLock sl (lock);
  4861. if (juce_CloseWin32SocketLib == 0)
  4862. {
  4863. WSADATA wsaData;
  4864. const WORD wVersionRequested = MAKEWORD (1, 1);
  4865. WSAStartup (wVersionRequested, &wsaData);
  4866. juce_CloseWin32SocketLib = &WSACleanup;
  4867. }
  4868. }
  4869. #endif
  4870. static bool resetSocketOptions (const int handle, const bool isDatagram) throw()
  4871. {
  4872. if (handle <= 0)
  4873. return false;
  4874. const int sndBufSize = 65536;
  4875. const int rcvBufSize = 65536;
  4876. const int one = 1;
  4877. return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0
  4878. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0
  4879. && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));
  4880. }
  4881. static bool bindSocketToPort (const int handle, const int port) throw()
  4882. {
  4883. if (handle == 0 || port <= 0)
  4884. return false;
  4885. struct sockaddr_in servTmpAddr;
  4886. zerostruct (servTmpAddr);
  4887. servTmpAddr.sin_family = PF_INET;
  4888. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  4889. servTmpAddr.sin_port = htons ((uint16) port);
  4890. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  4891. }
  4892. static int readSocket (const int handle,
  4893. void* const destBuffer, const int maxBytesToRead,
  4894. bool volatile& connected) throw()
  4895. {
  4896. int bytesRead = 0;
  4897. while (bytesRead < maxBytesToRead)
  4898. {
  4899. int bytesThisTime;
  4900. #if JUCE_WIN32
  4901. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  4902. #else
  4903. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  4904. && errno == EINTR
  4905. && connected)
  4906. {
  4907. }
  4908. #endif
  4909. if (bytesThisTime <= 0 || ! connected)
  4910. {
  4911. if (bytesRead == 0)
  4912. bytesRead = -1;
  4913. break;
  4914. }
  4915. bytesRead += bytesThisTime;
  4916. }
  4917. return bytesRead;
  4918. }
  4919. static int waitForReadiness (const int handle, const bool forReading,
  4920. const int timeoutMsecs) throw()
  4921. {
  4922. struct timeval timeout;
  4923. struct timeval* timeoutp;
  4924. if (timeoutMsecs >= 0)
  4925. {
  4926. timeout.tv_sec = timeoutMsecs / 1000;
  4927. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  4928. timeoutp = &timeout;
  4929. }
  4930. else
  4931. {
  4932. timeoutp = 0;
  4933. }
  4934. fd_set rset, wset;
  4935. FD_ZERO (&rset);
  4936. FD_SET (handle, &rset);
  4937. FD_ZERO (&wset);
  4938. FD_SET (handle, &wset);
  4939. fd_set* const prset = forReading ? &rset : 0;
  4940. fd_set* const pwset = forReading ? 0 : &wset;
  4941. #if JUCE_WIN32
  4942. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  4943. return -1;
  4944. #else
  4945. {
  4946. int result;
  4947. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  4948. && errno == EINTR)
  4949. {
  4950. }
  4951. if (result < 0)
  4952. return -1;
  4953. }
  4954. #endif
  4955. {
  4956. int opt;
  4957. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  4958. socklen_t len = sizeof (opt);
  4959. #else
  4960. int len = sizeof (opt);
  4961. #endif
  4962. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  4963. || opt != 0)
  4964. return -1;
  4965. }
  4966. if ((forReading && FD_ISSET (handle, &rset))
  4967. || ((! forReading) && FD_ISSET (handle, &wset)))
  4968. return 1;
  4969. return 0;
  4970. }
  4971. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  4972. {
  4973. #if JUCE_WIN32
  4974. u_long nonBlocking = shouldBlock ? 0 : 1;
  4975. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  4976. return false;
  4977. #else
  4978. int socketFlags = fcntl (handle, F_GETFL, 0);
  4979. if (socketFlags == -1)
  4980. return false;
  4981. if (shouldBlock)
  4982. socketFlags &= ~O_NONBLOCK;
  4983. else
  4984. socketFlags |= O_NONBLOCK;
  4985. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  4986. return false;
  4987. #endif
  4988. return true;
  4989. }
  4990. static bool connectSocket (int volatile& handle,
  4991. const bool isDatagram,
  4992. void** serverAddress,
  4993. const String& hostName,
  4994. const int portNumber,
  4995. const int timeOutMillisecs) throw()
  4996. {
  4997. struct hostent* const hostEnt = gethostbyname (hostName);
  4998. if (hostEnt == 0)
  4999. return false;
  5000. struct in_addr targetAddress;
  5001. memcpy (&targetAddress.s_addr,
  5002. *(hostEnt->h_addr_list),
  5003. sizeof (targetAddress.s_addr));
  5004. struct sockaddr_in servTmpAddr;
  5005. zerostruct (servTmpAddr);
  5006. servTmpAddr.sin_family = PF_INET;
  5007. servTmpAddr.sin_addr = targetAddress;
  5008. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5009. if (handle < 0)
  5010. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5011. if (handle < 0)
  5012. return false;
  5013. if (isDatagram)
  5014. {
  5015. *serverAddress = new struct sockaddr_in();
  5016. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5017. return true;
  5018. }
  5019. setSocketBlockingState (handle, false);
  5020. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  5021. if (result < 0)
  5022. {
  5023. #if JUCE_WIN32
  5024. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  5025. #else
  5026. if (errno == EINPROGRESS)
  5027. #endif
  5028. {
  5029. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  5030. {
  5031. setSocketBlockingState (handle, true);
  5032. return false;
  5033. }
  5034. }
  5035. }
  5036. setSocketBlockingState (handle, true);
  5037. resetSocketOptions (handle, false);
  5038. return true;
  5039. }
  5040. StreamingSocket::StreamingSocket()
  5041. : portNumber (0),
  5042. handle (-1),
  5043. connected (false),
  5044. isListener (false)
  5045. {
  5046. #if JUCE_WIN32
  5047. initWin32Sockets();
  5048. #endif
  5049. }
  5050. StreamingSocket::StreamingSocket (const String& hostName_,
  5051. const int portNumber_,
  5052. const int handle_)
  5053. : hostName (hostName_),
  5054. portNumber (portNumber_),
  5055. handle (handle_),
  5056. connected (true),
  5057. isListener (false)
  5058. {
  5059. #if JUCE_WIN32
  5060. initWin32Sockets();
  5061. #endif
  5062. resetSocketOptions (handle_, false);
  5063. }
  5064. StreamingSocket::~StreamingSocket()
  5065. {
  5066. close();
  5067. }
  5068. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead)
  5069. {
  5070. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5071. : -1;
  5072. }
  5073. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5074. {
  5075. if (isListener || ! connected)
  5076. return -1;
  5077. #if JUCE_WIN32
  5078. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  5079. #else
  5080. int result;
  5081. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  5082. && errno == EINTR)
  5083. {
  5084. }
  5085. return result;
  5086. #endif
  5087. }
  5088. int StreamingSocket::waitUntilReady (const bool readyForReading,
  5089. const int timeoutMsecs) const
  5090. {
  5091. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5092. : -1;
  5093. }
  5094. bool StreamingSocket::bindToPort (const int port)
  5095. {
  5096. return bindSocketToPort (handle, port);
  5097. }
  5098. bool StreamingSocket::connect (const String& remoteHostName,
  5099. const int remotePortNumber,
  5100. const int timeOutMillisecs)
  5101. {
  5102. if (isListener)
  5103. {
  5104. jassertfalse // a listener socket can't connect to another one!
  5105. return false;
  5106. }
  5107. if (connected)
  5108. close();
  5109. hostName = remoteHostName;
  5110. portNumber = remotePortNumber;
  5111. isListener = false;
  5112. connected = connectSocket (handle, false, 0, remoteHostName,
  5113. remotePortNumber, timeOutMillisecs);
  5114. if (! (connected && resetSocketOptions (handle, false)))
  5115. {
  5116. close();
  5117. return false;
  5118. }
  5119. return true;
  5120. }
  5121. void StreamingSocket::close()
  5122. {
  5123. #if JUCE_WIN32
  5124. closesocket (handle);
  5125. connected = false;
  5126. #else
  5127. if (connected)
  5128. {
  5129. connected = false;
  5130. if (isListener)
  5131. {
  5132. // need to do this to interrupt the accept() function..
  5133. StreamingSocket temp;
  5134. temp.connect ("localhost", portNumber, 1000);
  5135. }
  5136. }
  5137. ::close (handle);
  5138. #endif
  5139. hostName = String::empty;
  5140. portNumber = 0;
  5141. handle = -1;
  5142. isListener = false;
  5143. }
  5144. bool StreamingSocket::createListener (const int newPortNumber)
  5145. {
  5146. if (connected)
  5147. close();
  5148. hostName = "listener";
  5149. portNumber = newPortNumber;
  5150. isListener = true;
  5151. struct sockaddr_in servTmpAddr;
  5152. zerostruct (servTmpAddr);
  5153. servTmpAddr.sin_family = PF_INET;
  5154. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5155. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5156. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  5157. if (handle < 0)
  5158. return false;
  5159. const int reuse = 1;
  5160. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  5161. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  5162. || listen (handle, SOMAXCONN) < 0)
  5163. {
  5164. close();
  5165. return false;
  5166. }
  5167. connected = true;
  5168. return true;
  5169. }
  5170. StreamingSocket* StreamingSocket::waitForNextConnection() const
  5171. {
  5172. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  5173. // prepare this socket as a listener.
  5174. if (connected && isListener)
  5175. {
  5176. struct sockaddr address;
  5177. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5178. socklen_t len = sizeof (sockaddr);
  5179. #else
  5180. int len = sizeof (sockaddr);
  5181. #endif
  5182. const int newSocket = (int) accept (handle, &address, &len);
  5183. if (newSocket >= 0 && connected)
  5184. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5185. portNumber, newSocket);
  5186. }
  5187. return 0;
  5188. }
  5189. bool StreamingSocket::isLocal() const throw()
  5190. {
  5191. return hostName == T("127.0.0.1");
  5192. }
  5193. DatagramSocket::DatagramSocket (const int localPortNumber)
  5194. : portNumber (0),
  5195. handle (-1),
  5196. connected (false),
  5197. serverAddress (0)
  5198. {
  5199. #if JUCE_WIN32
  5200. initWin32Sockets();
  5201. #endif
  5202. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  5203. bindToPort (localPortNumber);
  5204. }
  5205. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  5206. const int handle_, const int localPortNumber)
  5207. : hostName (hostName_),
  5208. portNumber (portNumber_),
  5209. handle (handle_),
  5210. connected (true),
  5211. serverAddress (0)
  5212. {
  5213. #if JUCE_WIN32
  5214. initWin32Sockets();
  5215. #endif
  5216. resetSocketOptions (handle_, true);
  5217. bindToPort (localPortNumber);
  5218. }
  5219. DatagramSocket::~DatagramSocket()
  5220. {
  5221. close();
  5222. delete ((struct sockaddr_in*) serverAddress);
  5223. serverAddress = 0;
  5224. }
  5225. void DatagramSocket::close()
  5226. {
  5227. #if JUCE_WIN32
  5228. closesocket (handle);
  5229. connected = false;
  5230. #else
  5231. connected = false;
  5232. ::close (handle);
  5233. #endif
  5234. hostName = String::empty;
  5235. portNumber = 0;
  5236. handle = -1;
  5237. }
  5238. bool DatagramSocket::bindToPort (const int port)
  5239. {
  5240. return bindSocketToPort (handle, port);
  5241. }
  5242. bool DatagramSocket::connect (const String& remoteHostName,
  5243. const int remotePortNumber,
  5244. const int timeOutMillisecs)
  5245. {
  5246. if (connected)
  5247. close();
  5248. hostName = remoteHostName;
  5249. portNumber = remotePortNumber;
  5250. connected = connectSocket (handle, true, &serverAddress,
  5251. remoteHostName, remotePortNumber,
  5252. timeOutMillisecs);
  5253. if (! (connected && resetSocketOptions (handle, true)))
  5254. {
  5255. close();
  5256. return false;
  5257. }
  5258. return true;
  5259. }
  5260. DatagramSocket* DatagramSocket::waitForNextConnection() const
  5261. {
  5262. struct sockaddr address;
  5263. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5264. socklen_t len = sizeof (sockaddr);
  5265. #else
  5266. int len = sizeof (sockaddr);
  5267. #endif
  5268. while (waitUntilReady (true, -1) == 1)
  5269. {
  5270. char buf[1];
  5271. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  5272. {
  5273. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5274. ntohs (((struct sockaddr_in*) &address)->sin_port),
  5275. -1, -1);
  5276. }
  5277. }
  5278. return 0;
  5279. }
  5280. int DatagramSocket::waitUntilReady (const bool readyForReading,
  5281. const int timeoutMsecs) const
  5282. {
  5283. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5284. : -1;
  5285. }
  5286. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead)
  5287. {
  5288. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5289. : -1;
  5290. }
  5291. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5292. {
  5293. // You need to call connect() first to set the server address..
  5294. jassert (serverAddress != 0 && connected);
  5295. return connected ? sendto (handle, (const char*) sourceBuffer,
  5296. numBytesToWrite, 0,
  5297. (const struct sockaddr*) serverAddress,
  5298. sizeof (struct sockaddr_in))
  5299. : -1;
  5300. }
  5301. bool DatagramSocket::isLocal() const throw()
  5302. {
  5303. return hostName == T("127.0.0.1");
  5304. }
  5305. END_JUCE_NAMESPACE
  5306. /********* End of inlined file: juce_Socket.cpp *********/
  5307. /********* Start of inlined file: juce_URL.cpp *********/
  5308. BEGIN_JUCE_NAMESPACE
  5309. URL::URL() throw()
  5310. {
  5311. }
  5312. URL::URL (const String& url_)
  5313. : url (url_)
  5314. {
  5315. int i = url.indexOfChar (T('?'));
  5316. if (i >= 0)
  5317. {
  5318. do
  5319. {
  5320. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  5321. const int equalsPos = url.indexOfChar (i + 1, T('='));
  5322. if (equalsPos > i + 1)
  5323. {
  5324. if (nextAmp < 0)
  5325. {
  5326. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5327. removeEscapeChars (url.substring (equalsPos + 1)));
  5328. }
  5329. else if (nextAmp > 0 && equalsPos < nextAmp)
  5330. {
  5331. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5332. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  5333. }
  5334. }
  5335. i = nextAmp;
  5336. }
  5337. while (i >= 0);
  5338. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  5339. }
  5340. }
  5341. URL::URL (const URL& other)
  5342. : url (other.url),
  5343. parameters (other.parameters),
  5344. filesToUpload (other.filesToUpload),
  5345. mimeTypes (other.mimeTypes)
  5346. {
  5347. }
  5348. const URL& URL::operator= (const URL& other)
  5349. {
  5350. url = other.url;
  5351. parameters = other.parameters;
  5352. filesToUpload = other.filesToUpload;
  5353. mimeTypes = other.mimeTypes;
  5354. return *this;
  5355. }
  5356. URL::~URL() throw()
  5357. {
  5358. }
  5359. static const String getMangledParameters (const StringPairArray& parameters)
  5360. {
  5361. String p;
  5362. for (int i = 0; i < parameters.size(); ++i)
  5363. {
  5364. if (i > 0)
  5365. p += T("&");
  5366. p << URL::addEscapeChars (parameters.getAllKeys() [i])
  5367. << T("=")
  5368. << URL::addEscapeChars (parameters.getAllValues() [i]);
  5369. }
  5370. return p;
  5371. }
  5372. const String URL::toString (const bool includeGetParameters) const
  5373. {
  5374. if (includeGetParameters && parameters.size() > 0)
  5375. return url + T("?") + getMangledParameters (parameters);
  5376. else
  5377. return url;
  5378. }
  5379. bool URL::isWellFormed() const
  5380. {
  5381. //xxx TODO
  5382. return url.isNotEmpty();
  5383. }
  5384. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  5385. {
  5386. return (possibleURL.containsChar (T('.'))
  5387. && (! possibleURL.containsChar (T('@')))
  5388. && (! possibleURL.endsWithChar (T('.')))
  5389. && (possibleURL.startsWithIgnoreCase (T("www."))
  5390. || possibleURL.startsWithIgnoreCase (T("http:"))
  5391. || possibleURL.startsWithIgnoreCase (T("ftp:"))
  5392. || possibleURL.endsWithIgnoreCase (T(".com"))
  5393. || possibleURL.endsWithIgnoreCase (T(".net"))
  5394. || possibleURL.endsWithIgnoreCase (T(".org"))
  5395. || possibleURL.endsWithIgnoreCase (T(".co.uk")))
  5396. || possibleURL.startsWithIgnoreCase (T("file:")));
  5397. }
  5398. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  5399. {
  5400. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  5401. return atSign > 0
  5402. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  5403. && (! possibleEmailAddress.endsWithChar (T('.')));
  5404. }
  5405. void* juce_openInternetFile (const String& url,
  5406. const String& headers,
  5407. const MemoryBlock& optionalPostData,
  5408. const bool isPost,
  5409. URL::OpenStreamProgressCallback* callback,
  5410. void* callbackContext);
  5411. void juce_closeInternetFile (void* handle);
  5412. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  5413. int juce_seekInInternetFile (void* handle, int newPosition);
  5414. class WebInputStream : public InputStream
  5415. {
  5416. public:
  5417. WebInputStream (const URL& url,
  5418. const bool isPost_,
  5419. URL::OpenStreamProgressCallback* const progressCallback_,
  5420. void* const progressCallbackContext_)
  5421. : position (0),
  5422. finished (false),
  5423. isPost (isPost_),
  5424. progressCallback (progressCallback_),
  5425. progressCallbackContext (progressCallbackContext_)
  5426. {
  5427. server = url.toString (! isPost);
  5428. if (isPost_)
  5429. createHeadersAndPostData (url);
  5430. handle = juce_openInternetFile (server, headers, postData, isPost,
  5431. progressCallback_, progressCallbackContext_);
  5432. }
  5433. ~WebInputStream()
  5434. {
  5435. juce_closeInternetFile (handle);
  5436. }
  5437. bool isError() const throw()
  5438. {
  5439. return handle == 0;
  5440. }
  5441. int64 getTotalLength()
  5442. {
  5443. return -1;
  5444. }
  5445. bool isExhausted()
  5446. {
  5447. return finished;
  5448. }
  5449. int read (void* dest, int bytes)
  5450. {
  5451. if (finished || isError())
  5452. {
  5453. return 0;
  5454. }
  5455. else
  5456. {
  5457. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5458. position += bytesRead;
  5459. if (bytesRead == 0)
  5460. finished = true;
  5461. return bytesRead;
  5462. }
  5463. }
  5464. int64 getPosition()
  5465. {
  5466. return position;
  5467. }
  5468. bool setPosition (int64 wantedPos)
  5469. {
  5470. if (wantedPos != position)
  5471. {
  5472. finished = false;
  5473. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5474. if (actualPos == wantedPos)
  5475. {
  5476. position = wantedPos;
  5477. }
  5478. else
  5479. {
  5480. if (wantedPos < position)
  5481. {
  5482. juce_closeInternetFile (handle);
  5483. position = 0;
  5484. finished = false;
  5485. handle = juce_openInternetFile (server, headers, postData, isPost,
  5486. progressCallback, progressCallbackContext);
  5487. }
  5488. skipNextBytes (wantedPos - position);
  5489. }
  5490. }
  5491. return true;
  5492. }
  5493. juce_UseDebuggingNewOperator
  5494. private:
  5495. String server, headers;
  5496. MemoryBlock postData;
  5497. int64 position;
  5498. bool finished;
  5499. const bool isPost;
  5500. void* handle;
  5501. URL::OpenStreamProgressCallback* const progressCallback;
  5502. void* const progressCallbackContext;
  5503. void createHeadersAndPostData (const URL& url)
  5504. {
  5505. if (url.getFilesToUpload().size() > 0)
  5506. {
  5507. // need to upload some files, so do it as multi-part...
  5508. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5509. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5510. appendUTF8ToPostData ("--" + boundary);
  5511. int i;
  5512. for (i = 0; i < url.getParameters().size(); ++i)
  5513. {
  5514. String s;
  5515. s << "\r\nContent-Disposition: form-data; name=\""
  5516. << url.getParameters().getAllKeys() [i]
  5517. << "\"\r\n\r\n"
  5518. << url.getParameters().getAllValues() [i]
  5519. << "\r\n--"
  5520. << boundary;
  5521. appendUTF8ToPostData (s);
  5522. }
  5523. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5524. {
  5525. const File f (url.getFilesToUpload().getAllValues() [i]);
  5526. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5527. String s;
  5528. s << "\r\nContent-Disposition: form-data; name=\""
  5529. << paramName
  5530. << "\"; filename=\""
  5531. << f.getFileName()
  5532. << "\"\r\n";
  5533. const String mimeType (url.getMimeTypesOfUploadFiles()
  5534. .getValue (paramName, String::empty));
  5535. if (mimeType.isNotEmpty())
  5536. s << "Content-Type: " << mimeType << "\r\n";
  5537. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5538. appendUTF8ToPostData (s);
  5539. f.loadFileAsData (postData);
  5540. s = "\r\n--" + boundary;
  5541. appendUTF8ToPostData (s);
  5542. }
  5543. appendUTF8ToPostData ("--\r\n");
  5544. }
  5545. else
  5546. {
  5547. // just a short text attachment, so use simple url encoding..
  5548. const String params (getMangledParameters (url.getParameters()));
  5549. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5550. + String ((int) strlen (params.toUTF8()))
  5551. + "\r\n";
  5552. appendUTF8ToPostData (params);
  5553. }
  5554. }
  5555. void appendUTF8ToPostData (const String& text) throw()
  5556. {
  5557. postData.append (text.toUTF8(),
  5558. (int) strlen (text.toUTF8()));
  5559. }
  5560. WebInputStream (const WebInputStream&);
  5561. const WebInputStream& operator= (const WebInputStream&);
  5562. };
  5563. InputStream* URL::createInputStream (const bool usePostCommand,
  5564. OpenStreamProgressCallback* const progressCallback,
  5565. void* const progressCallbackContext) const
  5566. {
  5567. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5568. progressCallback, progressCallbackContext);
  5569. if (wi->isError())
  5570. {
  5571. delete wi;
  5572. wi = 0;
  5573. }
  5574. return wi;
  5575. }
  5576. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5577. const bool usePostCommand) const
  5578. {
  5579. InputStream* const in = createInputStream (usePostCommand);
  5580. if (in != 0)
  5581. {
  5582. in->readIntoMemoryBlock (destData, -1);
  5583. delete in;
  5584. return true;
  5585. }
  5586. return false;
  5587. }
  5588. const String URL::readEntireTextStream (const bool usePostCommand) const
  5589. {
  5590. String result;
  5591. InputStream* const in = createInputStream (usePostCommand);
  5592. if (in != 0)
  5593. {
  5594. result = in->readEntireStreamAsString();
  5595. delete in;
  5596. }
  5597. return result;
  5598. }
  5599. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  5600. {
  5601. XmlDocument doc (readEntireTextStream (usePostCommand));
  5602. return doc.getDocumentElement();
  5603. }
  5604. const URL URL::withParameter (const String& parameterName,
  5605. const String& parameterValue) const
  5606. {
  5607. URL u (*this);
  5608. u.parameters.set (parameterName, parameterValue);
  5609. return u;
  5610. }
  5611. const URL URL::withFileToUpload (const String& parameterName,
  5612. const File& fileToUpload,
  5613. const String& mimeType) const
  5614. {
  5615. URL u (*this);
  5616. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  5617. u.mimeTypes.set (parameterName, mimeType);
  5618. return u;
  5619. }
  5620. const StringPairArray& URL::getParameters() const throw()
  5621. {
  5622. return parameters;
  5623. }
  5624. const StringPairArray& URL::getFilesToUpload() const throw()
  5625. {
  5626. return filesToUpload;
  5627. }
  5628. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  5629. {
  5630. return mimeTypes;
  5631. }
  5632. const String URL::removeEscapeChars (const String& s)
  5633. {
  5634. const int len = s.length();
  5635. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  5636. uint8* r = resultUTF8;
  5637. for (int i = 0; i < len; ++i)
  5638. {
  5639. char c = (char) s[i];
  5640. if (c == 0)
  5641. break;
  5642. if (c == '+')
  5643. {
  5644. c = ' ';
  5645. }
  5646. else if (c == '%')
  5647. {
  5648. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  5649. i += 2;
  5650. }
  5651. *r++ = c;
  5652. }
  5653. const String stringResult (String::fromUTF8 (resultUTF8));
  5654. juce_free (resultUTF8);
  5655. return stringResult;
  5656. }
  5657. const String URL::addEscapeChars (const String& s)
  5658. {
  5659. String result;
  5660. result.preallocateStorage (s.length() + 8);
  5661. const char* utf8 = s.toUTF8();
  5662. while (*utf8 != 0)
  5663. {
  5664. const char c = *utf8++;
  5665. if (c == ' ')
  5666. {
  5667. result += T('+');
  5668. }
  5669. else if (CharacterFunctions::isLetterOrDigit (c)
  5670. || CharacterFunctions::indexOfChar ("_-$.*!'(),", c, false) >= 0)
  5671. {
  5672. result << c;
  5673. }
  5674. else
  5675. {
  5676. const int v = (int) (uint8) c;
  5677. if (v < 0x10)
  5678. result << T("%0");
  5679. else
  5680. result << T('%');
  5681. result << String::toHexString (v);
  5682. }
  5683. }
  5684. return result;
  5685. }
  5686. extern bool juce_launchFile (const String& fileName,
  5687. const String& parameters) throw();
  5688. bool URL::launchInDefaultBrowser() const
  5689. {
  5690. String u (toString (true));
  5691. if (u.contains (T("@")) && ! u.contains (T(":")))
  5692. u = "mailto:" + u;
  5693. return juce_launchFile (u, String::empty);
  5694. }
  5695. END_JUCE_NAMESPACE
  5696. /********* End of inlined file: juce_URL.cpp *********/
  5697. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  5698. BEGIN_JUCE_NAMESPACE
  5699. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  5700. const int bufferSize_,
  5701. const bool deleteSourceWhenDestroyed_) throw()
  5702. : source (source_),
  5703. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5704. bufferSize (jmax (256, bufferSize_)),
  5705. position (source_->getPosition()),
  5706. lastReadPos (0),
  5707. bufferOverlap (128)
  5708. {
  5709. const int sourceSize = (int) source_->getTotalLength();
  5710. if (sourceSize >= 0)
  5711. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  5712. bufferStart = position;
  5713. buffer = (char*) juce_malloc (bufferSize);
  5714. }
  5715. BufferedInputStream::~BufferedInputStream() throw()
  5716. {
  5717. if (deleteSourceWhenDestroyed)
  5718. delete source;
  5719. juce_free (buffer);
  5720. }
  5721. int64 BufferedInputStream::getTotalLength()
  5722. {
  5723. return source->getTotalLength();
  5724. }
  5725. int64 BufferedInputStream::getPosition()
  5726. {
  5727. return position;
  5728. }
  5729. bool BufferedInputStream::setPosition (int64 newPosition)
  5730. {
  5731. position = jmax ((int64) 0, newPosition);
  5732. return true;
  5733. }
  5734. bool BufferedInputStream::isExhausted()
  5735. {
  5736. return (position >= lastReadPos)
  5737. && source->isExhausted();
  5738. }
  5739. void BufferedInputStream::ensureBuffered()
  5740. {
  5741. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  5742. if (position < bufferStart || position >= bufferEndOverlap)
  5743. {
  5744. int bytesRead;
  5745. if (position < lastReadPos
  5746. && position >= bufferEndOverlap
  5747. && position >= bufferStart)
  5748. {
  5749. const int bytesToKeep = (int) (lastReadPos - position);
  5750. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  5751. bufferStart = position;
  5752. bytesRead = source->read (buffer + bytesToKeep,
  5753. bufferSize - bytesToKeep);
  5754. lastReadPos += bytesRead;
  5755. bytesRead += bytesToKeep;
  5756. }
  5757. else
  5758. {
  5759. bufferStart = position;
  5760. source->setPosition (bufferStart);
  5761. bytesRead = source->read (buffer, bufferSize);
  5762. lastReadPos = bufferStart + bytesRead;
  5763. }
  5764. while (bytesRead < bufferSize)
  5765. buffer [bytesRead++] = 0;
  5766. }
  5767. }
  5768. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  5769. {
  5770. if (position >= bufferStart
  5771. && position + maxBytesToRead < lastReadPos)
  5772. {
  5773. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  5774. position += maxBytesToRead;
  5775. return maxBytesToRead;
  5776. }
  5777. else
  5778. {
  5779. int bytesRead = 0;
  5780. while (maxBytesToRead > 0)
  5781. {
  5782. ensureBuffered();
  5783. if (isExhausted())
  5784. break;
  5785. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  5786. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  5787. maxBytesToRead -= bytesAvailable;
  5788. bytesRead += bytesAvailable;
  5789. position += bytesAvailable;
  5790. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  5791. }
  5792. return bytesRead;
  5793. }
  5794. }
  5795. const String BufferedInputStream::readString()
  5796. {
  5797. if (position >= bufferStart
  5798. && position < lastReadPos)
  5799. {
  5800. const int maxChars = (int) (lastReadPos - position);
  5801. const char* const src = buffer + (position - bufferStart);
  5802. for (int i = 0; i < maxChars; ++i)
  5803. {
  5804. if (src[i] == 0)
  5805. {
  5806. position += i + 1;
  5807. return String::fromUTF8 ((const uint8*) src, i);
  5808. }
  5809. }
  5810. }
  5811. return InputStream::readString();
  5812. }
  5813. END_JUCE_NAMESPACE
  5814. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  5815. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  5816. BEGIN_JUCE_NAMESPACE
  5817. FileInputSource::FileInputSource (const File& file_) throw()
  5818. : file (file_)
  5819. {
  5820. }
  5821. FileInputSource::~FileInputSource()
  5822. {
  5823. }
  5824. InputStream* FileInputSource::createInputStream()
  5825. {
  5826. return file.createInputStream();
  5827. }
  5828. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  5829. {
  5830. return file.getSiblingFile (relatedItemPath).createInputStream();
  5831. }
  5832. int64 FileInputSource::hashCode() const
  5833. {
  5834. return file.hashCode();
  5835. }
  5836. END_JUCE_NAMESPACE
  5837. /********* End of inlined file: juce_FileInputSource.cpp *********/
  5838. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  5839. BEGIN_JUCE_NAMESPACE
  5840. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  5841. const int sourceDataSize,
  5842. const bool keepInternalCopy) throw()
  5843. : data ((const char*) sourceData),
  5844. dataSize (sourceDataSize),
  5845. position (0)
  5846. {
  5847. if (keepInternalCopy)
  5848. {
  5849. internalCopy.append (data, sourceDataSize);
  5850. data = (const char*) internalCopy.getData();
  5851. }
  5852. }
  5853. MemoryInputStream::~MemoryInputStream() throw()
  5854. {
  5855. }
  5856. int64 MemoryInputStream::getTotalLength()
  5857. {
  5858. return dataSize;
  5859. }
  5860. int MemoryInputStream::read (void* buffer, int howMany)
  5861. {
  5862. const int num = jmin (howMany, dataSize - position);
  5863. memcpy (buffer, data + position, num);
  5864. position += num;
  5865. return num;
  5866. }
  5867. bool MemoryInputStream::isExhausted()
  5868. {
  5869. return (position >= dataSize);
  5870. }
  5871. bool MemoryInputStream::setPosition (int64 pos)
  5872. {
  5873. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  5874. return true;
  5875. }
  5876. int64 MemoryInputStream::getPosition()
  5877. {
  5878. return position;
  5879. }
  5880. END_JUCE_NAMESPACE
  5881. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  5882. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  5883. BEGIN_JUCE_NAMESPACE
  5884. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  5885. const int blockSizeToIncreaseBy,
  5886. MemoryBlock* const memoryBlockToWriteTo) throw()
  5887. : data (memoryBlockToWriteTo),
  5888. position (0),
  5889. size (0),
  5890. blockSize (jmax (16, blockSizeToIncreaseBy)),
  5891. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  5892. {
  5893. if (memoryBlockToWriteTo == 0)
  5894. data = new MemoryBlock (initialSize);
  5895. else
  5896. memoryBlockToWriteTo->setSize (initialSize, false);
  5897. }
  5898. MemoryOutputStream::~MemoryOutputStream() throw()
  5899. {
  5900. if (ownsMemoryBlock)
  5901. delete data;
  5902. else
  5903. flush();
  5904. }
  5905. void MemoryOutputStream::flush()
  5906. {
  5907. if (! ownsMemoryBlock)
  5908. data->setSize (size, false);
  5909. }
  5910. void MemoryOutputStream::reset() throw()
  5911. {
  5912. position = 0;
  5913. size = 0;
  5914. }
  5915. bool MemoryOutputStream::write (const void* buffer, int howMany)
  5916. {
  5917. int storageNeeded = position + howMany + 1;
  5918. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  5919. data->ensureSize (storageNeeded);
  5920. data->copyFrom (buffer, position, howMany);
  5921. position += howMany;
  5922. size = jmax (size, position);
  5923. return true;
  5924. }
  5925. const char* MemoryOutputStream::getData() throw()
  5926. {
  5927. if (data->getSize() > size)
  5928. ((char*) data->getData()) [size] = 0;
  5929. return (const char*) data->getData();
  5930. }
  5931. int MemoryOutputStream::getDataSize() const throw()
  5932. {
  5933. return size;
  5934. }
  5935. int64 MemoryOutputStream::getPosition()
  5936. {
  5937. return position;
  5938. }
  5939. bool MemoryOutputStream::setPosition (int64 newPosition)
  5940. {
  5941. if (newPosition <= size)
  5942. {
  5943. // ok to seek backwards
  5944. position = jlimit (0, size, (int) newPosition);
  5945. return true;
  5946. }
  5947. else
  5948. {
  5949. // trying to make it bigger isn't a good thing to do..
  5950. return false;
  5951. }
  5952. }
  5953. END_JUCE_NAMESPACE
  5954. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  5955. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  5956. BEGIN_JUCE_NAMESPACE
  5957. SubregionStream::SubregionStream (InputStream* const sourceStream,
  5958. const int64 startPositionInSourceStream_,
  5959. const int64 lengthOfSourceStream_,
  5960. const bool deleteSourceWhenDestroyed_) throw()
  5961. : source (sourceStream),
  5962. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5963. startPositionInSourceStream (startPositionInSourceStream_),
  5964. lengthOfSourceStream (lengthOfSourceStream_)
  5965. {
  5966. setPosition (0);
  5967. }
  5968. SubregionStream::~SubregionStream() throw()
  5969. {
  5970. if (deleteSourceWhenDestroyed)
  5971. delete source;
  5972. }
  5973. int64 SubregionStream::getTotalLength()
  5974. {
  5975. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  5976. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  5977. : srcLen;
  5978. }
  5979. int64 SubregionStream::getPosition()
  5980. {
  5981. return source->getPosition() - startPositionInSourceStream;
  5982. }
  5983. bool SubregionStream::setPosition (int64 newPosition)
  5984. {
  5985. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  5986. }
  5987. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  5988. {
  5989. if (lengthOfSourceStream < 0)
  5990. {
  5991. return source->read (destBuffer, maxBytesToRead);
  5992. }
  5993. else
  5994. {
  5995. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  5996. if (maxBytesToRead <= 0)
  5997. return 0;
  5998. return source->read (destBuffer, maxBytesToRead);
  5999. }
  6000. }
  6001. bool SubregionStream::isExhausted()
  6002. {
  6003. if (lengthOfSourceStream >= 0)
  6004. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6005. else
  6006. return source->isExhausted();
  6007. }
  6008. END_JUCE_NAMESPACE
  6009. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6010. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6011. BEGIN_JUCE_NAMESPACE
  6012. PerformanceCounter::PerformanceCounter (const String& name_,
  6013. int runsPerPrintout,
  6014. const File& loggingFile)
  6015. : name (name_),
  6016. numRuns (0),
  6017. runsPerPrint (runsPerPrintout),
  6018. totalTime (0),
  6019. outputFile (loggingFile)
  6020. {
  6021. if (outputFile != File::nonexistent)
  6022. {
  6023. String s ("**** Counter for \"");
  6024. s << name_ << "\" started at: "
  6025. << Time::getCurrentTime().toString (true, true)
  6026. << "\r\n";
  6027. outputFile.appendText (s, false, false);
  6028. }
  6029. }
  6030. PerformanceCounter::~PerformanceCounter()
  6031. {
  6032. printStatistics();
  6033. }
  6034. void PerformanceCounter::start()
  6035. {
  6036. started = Time::getHighResolutionTicks();
  6037. }
  6038. void PerformanceCounter::stop()
  6039. {
  6040. const int64 now = Time::getHighResolutionTicks();
  6041. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6042. if (++numRuns == runsPerPrint)
  6043. printStatistics();
  6044. }
  6045. void PerformanceCounter::printStatistics()
  6046. {
  6047. if (numRuns > 0)
  6048. {
  6049. String s ("Performance count for \"");
  6050. s << name << "\" - average over " << numRuns << " run(s) = ";
  6051. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6052. if (micros > 10000)
  6053. s << (micros/1000) << " millisecs";
  6054. else
  6055. s << micros << " microsecs";
  6056. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6057. Logger::outputDebugString (s);
  6058. s << "\r\n";
  6059. if (outputFile != File::nonexistent)
  6060. outputFile.appendText (s, false, false);
  6061. numRuns = 0;
  6062. totalTime = 0;
  6063. }
  6064. }
  6065. END_JUCE_NAMESPACE
  6066. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6067. /********* Start of inlined file: juce_Uuid.cpp *********/
  6068. BEGIN_JUCE_NAMESPACE
  6069. Uuid::Uuid()
  6070. {
  6071. // do some serious mixing up of our MAC addresses and different types of time info,
  6072. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6073. SystemStats::getMACAddresses (value.asInt64, 2);
  6074. int i;
  6075. for (i = 16; --i >= 0;)
  6076. {
  6077. Random r (Time::getHighResolutionTicks()
  6078. + Random::getSystemRandom().nextInt()
  6079. + value.asInt [i & 3]);
  6080. value.asBytes[i] ^= (uint8) r.nextInt();
  6081. }
  6082. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6083. value.asInt64 [1] ^= Time::currentTimeMillis();
  6084. for (i = 4; --i >= 0;)
  6085. {
  6086. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6087. value.asInt[i] ^= r.nextInt();
  6088. }
  6089. }
  6090. Uuid::~Uuid() throw()
  6091. {
  6092. }
  6093. Uuid::Uuid (const Uuid& other)
  6094. : value (other.value)
  6095. {
  6096. }
  6097. Uuid& Uuid::operator= (const Uuid& other)
  6098. {
  6099. if (this != &other)
  6100. value = other.value;
  6101. return *this;
  6102. }
  6103. bool Uuid::operator== (const Uuid& other) const
  6104. {
  6105. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6106. }
  6107. bool Uuid::operator!= (const Uuid& other) const
  6108. {
  6109. return ! operator== (other);
  6110. }
  6111. bool Uuid::isNull() const throw()
  6112. {
  6113. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6114. }
  6115. const String Uuid::toString() const
  6116. {
  6117. return String::toHexString (value.asBytes, 16, 0);
  6118. }
  6119. Uuid::Uuid (const String& uuidString)
  6120. {
  6121. operator= (uuidString);
  6122. }
  6123. Uuid& Uuid::operator= (const String& uuidString)
  6124. {
  6125. int destIndex = 0;
  6126. int i = 0;
  6127. for (;;)
  6128. {
  6129. int byte = 0;
  6130. for (int loop = 2; --loop >= 0;)
  6131. {
  6132. byte <<= 4;
  6133. for (;;)
  6134. {
  6135. const tchar c = uuidString [i++];
  6136. if (c >= T('0') && c <= T('9'))
  6137. {
  6138. byte |= c - T('0');
  6139. break;
  6140. }
  6141. else if (c >= T('a') && c <= T('z'))
  6142. {
  6143. byte |= c - (T('a') - 10);
  6144. break;
  6145. }
  6146. else if (c >= T('A') && c <= T('Z'))
  6147. {
  6148. byte |= c - (T('A') - 10);
  6149. break;
  6150. }
  6151. else if (c == 0)
  6152. {
  6153. while (destIndex < 16)
  6154. value.asBytes [destIndex++] = 0;
  6155. return *this;
  6156. }
  6157. }
  6158. }
  6159. value.asBytes [destIndex++] = (uint8) byte;
  6160. }
  6161. }
  6162. Uuid::Uuid (const uint8* const rawData)
  6163. {
  6164. operator= (rawData);
  6165. }
  6166. Uuid& Uuid::operator= (const uint8* const rawData)
  6167. {
  6168. if (rawData != 0)
  6169. memcpy (value.asBytes, rawData, 16);
  6170. else
  6171. zeromem (value.asBytes, 16);
  6172. return *this;
  6173. }
  6174. END_JUCE_NAMESPACE
  6175. /********* End of inlined file: juce_Uuid.cpp *********/
  6176. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6177. BEGIN_JUCE_NAMESPACE
  6178. struct ZipEntryInfo
  6179. {
  6180. ZipFile::ZipEntry entry;
  6181. int streamOffset;
  6182. int compressedSize;
  6183. bool compressed;
  6184. };
  6185. class ZipInputStream : public InputStream
  6186. {
  6187. public:
  6188. ZipInputStream (ZipFile& file_,
  6189. ZipEntryInfo& zei) throw()
  6190. : file (file_),
  6191. zipEntryInfo (zei),
  6192. pos (0),
  6193. headerSize (0),
  6194. inputStream (0)
  6195. {
  6196. inputStream = file_.inputStream;
  6197. if (file_.inputSource != 0)
  6198. {
  6199. inputStream = file.inputSource->createInputStream();
  6200. }
  6201. else
  6202. {
  6203. #ifdef JUCE_DEBUG
  6204. file_.numOpenStreams++;
  6205. #endif
  6206. }
  6207. char buffer [30];
  6208. if (inputStream != 0
  6209. && inputStream->setPosition (zei.streamOffset)
  6210. && inputStream->read (buffer, 30) == 30
  6211. && littleEndianInt (buffer) == 0x04034b50)
  6212. {
  6213. headerSize = 30 + littleEndianShort (buffer + 26)
  6214. + littleEndianShort (buffer + 28);
  6215. }
  6216. }
  6217. ~ZipInputStream() throw()
  6218. {
  6219. #ifdef JUCE_DEBUG
  6220. if (inputStream != 0 && inputStream == file.inputStream)
  6221. file.numOpenStreams--;
  6222. #endif
  6223. if (inputStream != file.inputStream)
  6224. delete inputStream;
  6225. }
  6226. int64 getTotalLength() throw()
  6227. {
  6228. return zipEntryInfo.compressedSize;
  6229. }
  6230. int read (void* buffer, int howMany) throw()
  6231. {
  6232. if (headerSize <= 0)
  6233. return 0;
  6234. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6235. if (inputStream == 0)
  6236. return 0;
  6237. int num;
  6238. if (inputStream == file.inputStream)
  6239. {
  6240. const ScopedLock sl (file.lock);
  6241. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6242. num = inputStream->read (buffer, howMany);
  6243. }
  6244. else
  6245. {
  6246. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6247. num = inputStream->read (buffer, howMany);
  6248. }
  6249. pos += num;
  6250. return num;
  6251. }
  6252. bool isExhausted() throw()
  6253. {
  6254. return pos >= zipEntryInfo.compressedSize;
  6255. }
  6256. int64 getPosition() throw()
  6257. {
  6258. return pos;
  6259. }
  6260. bool setPosition (int64 newPos) throw()
  6261. {
  6262. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6263. return true;
  6264. }
  6265. private:
  6266. ZipFile& file;
  6267. ZipEntryInfo zipEntryInfo;
  6268. int64 pos;
  6269. int headerSize;
  6270. InputStream* inputStream;
  6271. ZipInputStream (const ZipInputStream&);
  6272. const ZipInputStream& operator= (const ZipInputStream&);
  6273. };
  6274. ZipFile::ZipFile (InputStream* const source_,
  6275. const bool deleteStreamWhenDestroyed_) throw()
  6276. : inputStream (source_),
  6277. inputSource (0),
  6278. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6279. #ifdef JUCE_DEBUG
  6280. , numOpenStreams (0)
  6281. #endif
  6282. {
  6283. init();
  6284. }
  6285. ZipFile::ZipFile (const File& file)
  6286. : inputStream (0),
  6287. deleteStreamWhenDestroyed (false)
  6288. #ifdef JUCE_DEBUG
  6289. , numOpenStreams (0)
  6290. #endif
  6291. {
  6292. inputSource = new FileInputSource (file);
  6293. init();
  6294. }
  6295. ZipFile::ZipFile (InputSource* const inputSource_)
  6296. : inputStream (0),
  6297. inputSource (inputSource_),
  6298. deleteStreamWhenDestroyed (false)
  6299. #ifdef JUCE_DEBUG
  6300. , numOpenStreams (0)
  6301. #endif
  6302. {
  6303. init();
  6304. }
  6305. ZipFile::~ZipFile() throw()
  6306. {
  6307. for (int i = entries.size(); --i >= 0;)
  6308. {
  6309. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6310. delete zei;
  6311. }
  6312. if (deleteStreamWhenDestroyed)
  6313. delete inputStream;
  6314. delete inputSource;
  6315. #ifdef JUCE_DEBUG
  6316. // If you hit this assertion, it means you've created a stream to read
  6317. // one of the items in the zipfile, but you've forgotten to delete that
  6318. // stream object before deleting the file.. Streams can't be kept open
  6319. // after the file is deleted because they need to share the input
  6320. // stream that the file uses to read itself.
  6321. jassert (numOpenStreams == 0);
  6322. #endif
  6323. }
  6324. int ZipFile::getNumEntries() const throw()
  6325. {
  6326. return entries.size();
  6327. }
  6328. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6329. {
  6330. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6331. return (zei != 0) ? &(zei->entry)
  6332. : 0;
  6333. }
  6334. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6335. {
  6336. for (int i = 0; i < entries.size(); ++i)
  6337. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6338. return i;
  6339. return -1;
  6340. }
  6341. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6342. {
  6343. return getEntry (getIndexOfFileName (fileName));
  6344. }
  6345. InputStream* ZipFile::createStreamForEntry (const int index)
  6346. {
  6347. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6348. InputStream* stream = 0;
  6349. if (zei != 0)
  6350. {
  6351. stream = new ZipInputStream (*this, *zei);
  6352. if (zei->compressed)
  6353. {
  6354. stream = new GZIPDecompressorInputStream (stream, true, true,
  6355. zei->entry.uncompressedSize);
  6356. // (much faster to unzip in big blocks using a buffer..)
  6357. stream = new BufferedInputStream (stream, 32768, true);
  6358. }
  6359. }
  6360. return stream;
  6361. }
  6362. class ZipFilenameComparator
  6363. {
  6364. public:
  6365. static int compareElements (const void* const first, const void* const second) throw()
  6366. {
  6367. return ((const ZipEntryInfo*) first)->entry.filename
  6368. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6369. }
  6370. };
  6371. void ZipFile::sortEntriesByFilename()
  6372. {
  6373. ZipFilenameComparator sorter;
  6374. entries.sort (sorter);
  6375. }
  6376. void ZipFile::init()
  6377. {
  6378. InputStream* in = inputStream;
  6379. bool deleteInput = false;
  6380. if (inputSource != 0)
  6381. {
  6382. deleteInput = true;
  6383. in = inputSource->createInputStream();
  6384. }
  6385. if (in != 0)
  6386. {
  6387. numEntries = 0;
  6388. int pos = findEndOfZipEntryTable (in);
  6389. const int size = (int) (in->getTotalLength() - pos);
  6390. in->setPosition (pos);
  6391. MemoryBlock headerData;
  6392. if (in->readIntoMemoryBlock (headerData, size) == size)
  6393. {
  6394. pos = 0;
  6395. for (int i = 0; i < numEntries; ++i)
  6396. {
  6397. if (pos + 46 > size)
  6398. break;
  6399. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6400. const int fileNameLen = littleEndianShort (buffer + 28);
  6401. if (pos + 46 + fileNameLen > size)
  6402. break;
  6403. ZipEntryInfo* const zei = new ZipEntryInfo();
  6404. zei->entry.filename = String (buffer + 46, fileNameLen);
  6405. const int time = littleEndianShort (buffer + 12);
  6406. const int date = littleEndianShort (buffer + 14);
  6407. const int year = 1980 + (date >> 9);
  6408. const int month = ((date >> 5) & 15) - 1;
  6409. const int day = date & 31;
  6410. const int hours = time >> 11;
  6411. const int minutes = (time >> 5) & 63;
  6412. const int seconds = (time & 31) << 1;
  6413. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6414. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6415. zei->compressedSize = littleEndianInt (buffer + 20);
  6416. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6417. zei->streamOffset = littleEndianInt (buffer + 42);
  6418. entries.add (zei);
  6419. pos += 46 + fileNameLen
  6420. + littleEndianShort (buffer + 30)
  6421. + littleEndianShort (buffer + 32);
  6422. }
  6423. }
  6424. if (deleteInput)
  6425. delete in;
  6426. }
  6427. }
  6428. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6429. {
  6430. BufferedInputStream in (input, 8192, false);
  6431. in.setPosition (in.getTotalLength());
  6432. int64 pos = in.getPosition();
  6433. char buffer [32];
  6434. zeromem (buffer, sizeof (buffer));
  6435. while (pos > 0)
  6436. {
  6437. in.setPosition (pos - 22);
  6438. pos = in.getPosition();
  6439. memcpy (buffer + 22, buffer, 4);
  6440. if (in.read (buffer, 22) != 22)
  6441. return 0;
  6442. for (int i = 0; i < 22; ++i)
  6443. {
  6444. if (littleEndianInt (buffer + i) == 0x06054b50)
  6445. {
  6446. in.setPosition (pos + i);
  6447. in.read (buffer, 22);
  6448. numEntries = littleEndianShort (buffer + 10);
  6449. return littleEndianInt (buffer + 16);
  6450. }
  6451. }
  6452. }
  6453. return 0;
  6454. }
  6455. void ZipFile::uncompressTo (const File& targetDirectory,
  6456. const bool shouldOverwriteFiles)
  6457. {
  6458. for (int i = 0; i < entries.size(); ++i)
  6459. {
  6460. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6461. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6462. if (zei.entry.filename.endsWithChar (T('/')))
  6463. {
  6464. targetFile.createDirectory(); // (entry is a directory, not a file)
  6465. }
  6466. else
  6467. {
  6468. InputStream* const in = createStreamForEntry (i);
  6469. if (in != 0)
  6470. {
  6471. if (shouldOverwriteFiles)
  6472. targetFile.deleteFile();
  6473. if ((! targetFile.exists())
  6474. && targetFile.getParentDirectory().createDirectory())
  6475. {
  6476. FileOutputStream* const out = targetFile.createOutputStream();
  6477. if (out != 0)
  6478. {
  6479. out->writeFromInputStream (*in, -1);
  6480. delete out;
  6481. targetFile.setCreationTime (zei.entry.fileTime);
  6482. targetFile.setLastModificationTime (zei.entry.fileTime);
  6483. targetFile.setLastAccessTime (zei.entry.fileTime);
  6484. }
  6485. }
  6486. delete in;
  6487. }
  6488. }
  6489. }
  6490. }
  6491. END_JUCE_NAMESPACE
  6492. /********* End of inlined file: juce_ZipFile.cpp *********/
  6493. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6494. #ifdef _MSC_VER
  6495. #pragma warning (disable: 4514 4996)
  6496. #pragma warning (push)
  6497. #endif
  6498. #include <cwctype>
  6499. #include <cctype>
  6500. #include <ctime>
  6501. #ifdef _MSC_VER
  6502. #pragma warning (pop)
  6503. #endif
  6504. BEGIN_JUCE_NAMESPACE
  6505. int CharacterFunctions::length (const char* const s) throw()
  6506. {
  6507. return (int) strlen (s);
  6508. }
  6509. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6510. {
  6511. #if MACOS_10_2_OR_EARLIER
  6512. int n = 0;
  6513. while (s[n] != 0)
  6514. ++n;
  6515. return n;
  6516. #else
  6517. return (int) wcslen (s);
  6518. #endif
  6519. }
  6520. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6521. {
  6522. strncpy (dest, src, maxChars);
  6523. }
  6524. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6525. {
  6526. #if MACOS_10_2_OR_EARLIER
  6527. while (--maxChars >= 0 && *src != 0)
  6528. *dest++ = *src++;
  6529. *dest = 0;
  6530. #else
  6531. wcsncpy (dest, src, maxChars);
  6532. #endif
  6533. }
  6534. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6535. {
  6536. mbstowcs (dest, src, maxChars);
  6537. }
  6538. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6539. {
  6540. wcstombs (dest, src, maxChars);
  6541. }
  6542. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6543. {
  6544. return (int) wcstombs (0, src, 0);
  6545. }
  6546. void CharacterFunctions::append (char* dest, const char* src) throw()
  6547. {
  6548. strcat (dest, src);
  6549. }
  6550. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6551. {
  6552. #if MACOS_10_2_OR_EARLIER
  6553. while (*dest != 0)
  6554. ++dest;
  6555. while (*src != 0)
  6556. *dest++ = *src++;
  6557. *dest = 0;
  6558. #else
  6559. wcscat (dest, src);
  6560. #endif
  6561. }
  6562. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6563. {
  6564. return strcmp (s1, s2);
  6565. }
  6566. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6567. {
  6568. jassert (s1 != 0 && s2 != 0);
  6569. #if MACOS_10_2_OR_EARLIER
  6570. for (;;)
  6571. {
  6572. if (*s1 != *s2)
  6573. {
  6574. const int diff = *s1 - *s2;
  6575. if (diff != 0)
  6576. return diff < 0 ? -1 : 1;
  6577. }
  6578. else if (*s1 == 0)
  6579. break;
  6580. ++s1;
  6581. ++s2;
  6582. }
  6583. return 0;
  6584. #else
  6585. return wcscmp (s1, s2);
  6586. #endif
  6587. }
  6588. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  6589. {
  6590. jassert (s1 != 0 && s2 != 0);
  6591. return strncmp (s1, s2, maxChars);
  6592. }
  6593. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6594. {
  6595. jassert (s1 != 0 && s2 != 0);
  6596. #if MACOS_10_2_OR_EARLIER
  6597. while (--maxChars >= 0)
  6598. {
  6599. if (*s1 != *s2)
  6600. return (*s1 < *s2) ? -1 : 1;
  6601. else if (*s1 == 0)
  6602. break;
  6603. ++s1;
  6604. ++s2;
  6605. }
  6606. return 0;
  6607. #else
  6608. return wcsncmp (s1, s2, maxChars);
  6609. #endif
  6610. }
  6611. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  6612. {
  6613. jassert (s1 != 0 && s2 != 0);
  6614. #if JUCE_WIN32
  6615. return stricmp (s1, s2);
  6616. #else
  6617. return strcasecmp (s1, s2);
  6618. #endif
  6619. }
  6620. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  6621. {
  6622. jassert (s1 != 0 && s2 != 0);
  6623. #if JUCE_WIN32
  6624. return _wcsicmp (s1, s2);
  6625. #else
  6626. for (;;)
  6627. {
  6628. if (*s1 != *s2)
  6629. {
  6630. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6631. if (diff != 0)
  6632. return diff < 0 ? -1 : 1;
  6633. }
  6634. else if (*s1 == 0)
  6635. break;
  6636. ++s1;
  6637. ++s2;
  6638. }
  6639. return 0;
  6640. #endif
  6641. }
  6642. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  6643. {
  6644. jassert (s1 != 0 && s2 != 0);
  6645. #if JUCE_WIN32
  6646. return strnicmp (s1, s2, maxChars);
  6647. #else
  6648. return strncasecmp (s1, s2, maxChars);
  6649. #endif
  6650. }
  6651. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6652. {
  6653. jassert (s1 != 0 && s2 != 0);
  6654. #if JUCE_WIN32
  6655. return _wcsnicmp (s1, s2, maxChars);
  6656. #else
  6657. while (--maxChars >= 0)
  6658. {
  6659. if (*s1 != *s2)
  6660. {
  6661. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6662. if (diff != 0)
  6663. return diff < 0 ? -1 : 1;
  6664. }
  6665. else if (*s1 == 0)
  6666. break;
  6667. ++s1;
  6668. ++s2;
  6669. }
  6670. return 0;
  6671. #endif
  6672. }
  6673. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  6674. {
  6675. return strstr (haystack, needle);
  6676. }
  6677. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  6678. {
  6679. #if MACOS_10_2_OR_EARLIER
  6680. while (*haystack != 0)
  6681. {
  6682. const juce_wchar* s1 = haystack;
  6683. const juce_wchar* s2 = needle;
  6684. for (;;)
  6685. {
  6686. if (*s2 == 0)
  6687. return haystack;
  6688. if (*s1 != *s2 || *s2 == 0)
  6689. break;
  6690. ++s1;
  6691. ++s2;
  6692. }
  6693. ++haystack;
  6694. }
  6695. return 0;
  6696. #else
  6697. return wcsstr (haystack, needle);
  6698. #endif
  6699. }
  6700. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  6701. {
  6702. if (haystack != 0)
  6703. {
  6704. int i = 0;
  6705. if (ignoreCase)
  6706. {
  6707. const char n1 = toLowerCase (needle);
  6708. const char n2 = toUpperCase (needle);
  6709. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6710. {
  6711. while (haystack[i] != 0)
  6712. {
  6713. if (haystack[i] == n1 || haystack[i] == n2)
  6714. return i;
  6715. ++i;
  6716. }
  6717. return -1;
  6718. }
  6719. jassert (n1 == needle);
  6720. }
  6721. while (haystack[i] != 0)
  6722. {
  6723. if (haystack[i] == needle)
  6724. return i;
  6725. ++i;
  6726. }
  6727. }
  6728. return -1;
  6729. }
  6730. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  6731. {
  6732. if (haystack != 0)
  6733. {
  6734. int i = 0;
  6735. if (ignoreCase)
  6736. {
  6737. const juce_wchar n1 = toLowerCase (needle);
  6738. const juce_wchar n2 = toUpperCase (needle);
  6739. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6740. {
  6741. while (haystack[i] != 0)
  6742. {
  6743. if (haystack[i] == n1 || haystack[i] == n2)
  6744. return i;
  6745. ++i;
  6746. }
  6747. return -1;
  6748. }
  6749. jassert (n1 == needle);
  6750. }
  6751. while (haystack[i] != 0)
  6752. {
  6753. if (haystack[i] == needle)
  6754. return i;
  6755. ++i;
  6756. }
  6757. }
  6758. return -1;
  6759. }
  6760. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  6761. {
  6762. jassert (haystack != 0);
  6763. int i = 0;
  6764. while (haystack[i] != 0)
  6765. {
  6766. if (haystack[i] == needle)
  6767. return i;
  6768. ++i;
  6769. }
  6770. return -1;
  6771. }
  6772. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  6773. {
  6774. jassert (haystack != 0);
  6775. int i = 0;
  6776. while (haystack[i] != 0)
  6777. {
  6778. if (haystack[i] == needle)
  6779. return i;
  6780. ++i;
  6781. }
  6782. return -1;
  6783. }
  6784. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  6785. {
  6786. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  6787. }
  6788. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  6789. {
  6790. if (allowedChars == 0)
  6791. return 0;
  6792. int i = 0;
  6793. for (;;)
  6794. {
  6795. if (indexOfCharFast (allowedChars, text[i]) < 0)
  6796. break;
  6797. ++i;
  6798. }
  6799. return i;
  6800. }
  6801. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  6802. {
  6803. return (int) strftime (dest, maxChars, format, tm);
  6804. }
  6805. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  6806. {
  6807. #if MACOS_10_2_OR_EARLIER
  6808. const String formatTemp (format);
  6809. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  6810. String temp ((char*) dest);
  6811. temp.copyToBuffer (dest, num);
  6812. dest [num] = 0;
  6813. return (int) num;
  6814. #else
  6815. return (int) wcsftime (dest, maxChars, format, tm);
  6816. #endif
  6817. }
  6818. int CharacterFunctions::getIntValue (const char* const s) throw()
  6819. {
  6820. return atoi (s);
  6821. }
  6822. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  6823. {
  6824. #if JUCE_WIN32
  6825. return _wtoi (s);
  6826. #else
  6827. int v = 0;
  6828. while (isWhitespace (*s))
  6829. ++s;
  6830. const bool isNeg = *s == T('-');
  6831. if (isNeg)
  6832. ++s;
  6833. for (;;)
  6834. {
  6835. const wchar_t c = *s++;
  6836. if (c >= T('0') && c <= T('9'))
  6837. v = v * 10 + (int) (c - T('0'));
  6838. else
  6839. break;
  6840. }
  6841. return isNeg ? -v : v;
  6842. #endif
  6843. }
  6844. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  6845. {
  6846. #if JUCE_LINUX
  6847. return atoll (s);
  6848. #elif defined (JUCE_WIN32)
  6849. return _atoi64 (s);
  6850. #else
  6851. int64 v = 0;
  6852. while (isWhitespace (*s))
  6853. ++s;
  6854. const bool isNeg = *s == T('-');
  6855. if (isNeg)
  6856. ++s;
  6857. for (;;)
  6858. {
  6859. const char c = *s++;
  6860. if (c >= '0' && c <= '9')
  6861. v = v * 10 + (int64) (c - '0');
  6862. else
  6863. break;
  6864. }
  6865. return isNeg ? -v : v;
  6866. #endif
  6867. }
  6868. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  6869. {
  6870. #if JUCE_WIN32
  6871. return _wtoi64 (s);
  6872. #else
  6873. int64 v = 0;
  6874. while (isWhitespace (*s))
  6875. ++s;
  6876. const bool isNeg = *s == T('-');
  6877. if (isNeg)
  6878. ++s;
  6879. for (;;)
  6880. {
  6881. const juce_wchar c = *s++;
  6882. if (c >= T('0') && c <= T('9'))
  6883. v = v * 10 + (int64) (c - T('0'));
  6884. else
  6885. break;
  6886. }
  6887. return isNeg ? -v : v;
  6888. #endif
  6889. }
  6890. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  6891. {
  6892. return atof (s);
  6893. }
  6894. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  6895. {
  6896. #if MACOS_10_2_OR_EARLIER
  6897. String temp (s);
  6898. return atof ((const char*) temp);
  6899. #else
  6900. wchar_t* endChar;
  6901. return wcstod (s, &endChar);
  6902. #endif
  6903. }
  6904. char CharacterFunctions::toUpperCase (const char character) throw()
  6905. {
  6906. return (char) toupper (character);
  6907. }
  6908. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  6909. {
  6910. #if MACOS_10_2_OR_EARLIER
  6911. return toupper ((char) character);
  6912. #else
  6913. return towupper (character);
  6914. #endif
  6915. }
  6916. void CharacterFunctions::toUpperCase (char* s) throw()
  6917. {
  6918. #if JUCE_WIN32
  6919. strupr (s);
  6920. #else
  6921. while (*s != 0)
  6922. {
  6923. *s = toUpperCase (*s);
  6924. ++s;
  6925. }
  6926. #endif
  6927. }
  6928. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  6929. {
  6930. #if JUCE_WIN32
  6931. _wcsupr (s);
  6932. #else
  6933. while (*s != 0)
  6934. {
  6935. *s = toUpperCase (*s);
  6936. ++s;
  6937. }
  6938. #endif
  6939. }
  6940. bool CharacterFunctions::isUpperCase (const char character) throw()
  6941. {
  6942. return isupper (character) != 0;
  6943. }
  6944. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  6945. {
  6946. #if JUCE_WIN32
  6947. return iswupper (character) != 0;
  6948. #else
  6949. return toLowerCase (character) != character;
  6950. #endif
  6951. }
  6952. char CharacterFunctions::toLowerCase (const char character) throw()
  6953. {
  6954. return (char) tolower (character);
  6955. }
  6956. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  6957. {
  6958. #if MACOS_10_2_OR_EARLIER
  6959. return tolower ((char) character);
  6960. #else
  6961. return towlower (character);
  6962. #endif
  6963. }
  6964. void CharacterFunctions::toLowerCase (char* s) throw()
  6965. {
  6966. #if JUCE_WIN32
  6967. strlwr (s);
  6968. #else
  6969. while (*s != 0)
  6970. {
  6971. *s = toLowerCase (*s);
  6972. ++s;
  6973. }
  6974. #endif
  6975. }
  6976. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  6977. {
  6978. #if JUCE_WIN32
  6979. _wcslwr (s);
  6980. #else
  6981. while (*s != 0)
  6982. {
  6983. *s = toLowerCase (*s);
  6984. ++s;
  6985. }
  6986. #endif
  6987. }
  6988. bool CharacterFunctions::isLowerCase (const char character) throw()
  6989. {
  6990. return islower (character) != 0;
  6991. }
  6992. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  6993. {
  6994. #if JUCE_WIN32
  6995. return iswlower (character) != 0;
  6996. #else
  6997. return toUpperCase (character) != character;
  6998. #endif
  6999. }
  7000. bool CharacterFunctions::isWhitespace (const char character) throw()
  7001. {
  7002. return character == T(' ') || (character <= 13 && character >= 9);
  7003. }
  7004. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7005. {
  7006. #if MACOS_10_2_OR_EARLIER
  7007. return isWhitespace ((char) character);
  7008. #else
  7009. return iswspace (character) != 0;
  7010. #endif
  7011. }
  7012. bool CharacterFunctions::isDigit (const char character) throw()
  7013. {
  7014. return (character >= '0' && character <= '9');
  7015. }
  7016. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7017. {
  7018. #if MACOS_10_2_OR_EARLIER
  7019. return isdigit ((char) character) != 0;
  7020. #else
  7021. return iswdigit (character) != 0;
  7022. #endif
  7023. }
  7024. bool CharacterFunctions::isLetter (const char character) throw()
  7025. {
  7026. return (character >= 'a' && character <= 'z')
  7027. || (character >= 'A' && character <= 'Z');
  7028. }
  7029. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7030. {
  7031. #if MACOS_10_2_OR_EARLIER
  7032. return isLetter ((char) character);
  7033. #else
  7034. return iswalpha (character) != 0;
  7035. #endif
  7036. }
  7037. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7038. {
  7039. return (character >= 'a' && character <= 'z')
  7040. || (character >= 'A' && character <= 'Z')
  7041. || (character >= '0' && character <= '9');
  7042. }
  7043. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7044. {
  7045. #if MACOS_10_2_OR_EARLIER
  7046. return isLetterOrDigit ((char) character);
  7047. #else
  7048. return iswalnum (character) != 0;
  7049. #endif
  7050. }
  7051. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7052. {
  7053. if (digit >= T('0') && digit <= T('9'))
  7054. return digit - T('0');
  7055. else if (digit >= T('a') && digit <= T('f'))
  7056. return digit - (T('a') - 10);
  7057. else if (digit >= T('A') && digit <= T('F'))
  7058. return digit - (T('A') - 10);
  7059. return -1;
  7060. }
  7061. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7062. {
  7063. va_list list;
  7064. va_start (list, format);
  7065. return vprintf (dest, maxLength, format, list);
  7066. }
  7067. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7068. {
  7069. va_list list;
  7070. va_start (list, format);
  7071. return vprintf (dest, maxLength, format, list);
  7072. }
  7073. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7074. {
  7075. #if JUCE_WIN32
  7076. return (int) _vsnprintf (dest, maxLength, format, args);
  7077. #else
  7078. return (int) vsnprintf (dest, maxLength, format, args);
  7079. #endif
  7080. }
  7081. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7082. {
  7083. #if MACOS_10_3_OR_EARLIER
  7084. const String formatTemp (format);
  7085. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7086. String temp ((char*) dest);
  7087. temp.copyToBuffer (dest, num);
  7088. dest [num] = 0;
  7089. return (int) num;
  7090. #elif defined (JUCE_WIN32)
  7091. return (int) _vsnwprintf (dest, maxLength, format, args);
  7092. #else
  7093. return (int) vswprintf (dest, maxLength, format, args);
  7094. #endif
  7095. }
  7096. END_JUCE_NAMESPACE
  7097. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7098. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7099. BEGIN_JUCE_NAMESPACE
  7100. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7101. {
  7102. loadFromText (fileContents);
  7103. }
  7104. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7105. {
  7106. loadFromText (fileToLoad.loadFileAsString());
  7107. }
  7108. LocalisedStrings::~LocalisedStrings() throw()
  7109. {
  7110. }
  7111. const String LocalisedStrings::translate (const String& text) const throw()
  7112. {
  7113. return translations.getValue (text, text);
  7114. }
  7115. static int findCloseQuote (const String& text, int startPos) throw()
  7116. {
  7117. tchar lastChar = 0;
  7118. for (;;)
  7119. {
  7120. const tchar c = text [startPos];
  7121. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7122. break;
  7123. lastChar = c;
  7124. ++startPos;
  7125. }
  7126. return startPos;
  7127. }
  7128. static const String unescapeString (const String& s) throw()
  7129. {
  7130. return s.replace (T("\\\""), T("\""))
  7131. .replace (T("\\\'"), T("\'"))
  7132. .replace (T("\\t"), T("\t"))
  7133. .replace (T("\\r"), T("\r"))
  7134. .replace (T("\\n"), T("\n"));
  7135. }
  7136. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7137. {
  7138. StringArray lines;
  7139. lines.addLines (fileContents);
  7140. for (int i = 0; i < lines.size(); ++i)
  7141. {
  7142. String line (lines[i].trim());
  7143. if (line.startsWithChar (T('"')))
  7144. {
  7145. int closeQuote = findCloseQuote (line, 1);
  7146. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7147. if (originalText.isNotEmpty())
  7148. {
  7149. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7150. closeQuote = findCloseQuote (line, openingQuote + 1);
  7151. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7152. if (newText.isNotEmpty())
  7153. translations.set (originalText, newText);
  7154. }
  7155. }
  7156. else if (line.startsWithIgnoreCase (T("language:")))
  7157. {
  7158. languageName = line.substring (9).trim();
  7159. }
  7160. else if (line.startsWithIgnoreCase (T("countries:")))
  7161. {
  7162. countryCodes.addTokens (line.substring (10).trim(), true);
  7163. countryCodes.trim();
  7164. countryCodes.removeEmptyStrings();
  7165. }
  7166. }
  7167. }
  7168. static CriticalSection currentMappingsLock;
  7169. static LocalisedStrings* currentMappings = 0;
  7170. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7171. {
  7172. const ScopedLock sl (currentMappingsLock);
  7173. delete currentMappings;
  7174. currentMappings = newTranslations;
  7175. }
  7176. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7177. {
  7178. return currentMappings;
  7179. }
  7180. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7181. {
  7182. const ScopedLock sl (currentMappingsLock);
  7183. if (currentMappings != 0)
  7184. return currentMappings->translate (text);
  7185. return text;
  7186. }
  7187. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7188. {
  7189. return translateWithCurrentMappings (String (text));
  7190. }
  7191. END_JUCE_NAMESPACE
  7192. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7193. /********* Start of inlined file: juce_String.cpp *********/
  7194. #ifdef _MSC_VER
  7195. #pragma warning (disable: 4514)
  7196. #pragma warning (push)
  7197. #endif
  7198. #include <locale>
  7199. #if JUCE_MSVC
  7200. #include <float.h>
  7201. #endif
  7202. BEGIN_JUCE_NAMESPACE
  7203. #ifdef _MSC_VER
  7204. #pragma warning (pop)
  7205. #endif
  7206. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7207. static const int safeEmptyStringRefCount = 0x3fffffff;
  7208. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7209. static tchar decimalPoint = T('.');
  7210. void juce_initialiseStrings()
  7211. {
  7212. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7213. }
  7214. void String::deleteInternal() throw()
  7215. {
  7216. if (atomicDecrementAndReturn (text->refCount) == 0)
  7217. juce_free (text);
  7218. }
  7219. void String::createInternal (const int numChars) throw()
  7220. {
  7221. jassert (numChars > 0);
  7222. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7223. + numChars * sizeof (tchar));
  7224. text->refCount = 1;
  7225. text->allocatedNumChars = numChars;
  7226. text->text[0] = 0;
  7227. }
  7228. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7229. {
  7230. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7231. const int numChars = (int) (textEnd - t);
  7232. createInternal (numChars - 1);
  7233. memcpy (text->text, t, numChars * sizeof (tchar));
  7234. }
  7235. void String::appendInternal (const tchar* const newText,
  7236. const int numExtraChars) throw()
  7237. {
  7238. if (numExtraChars > 0)
  7239. {
  7240. const int oldLen = CharacterFunctions::length (text->text);
  7241. const int newTotalLen = oldLen + numExtraChars;
  7242. if (text->refCount > 1)
  7243. {
  7244. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7245. InternalRefCountedStringHolder* const newTextHolder
  7246. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7247. + newTotalLen * sizeof (tchar));
  7248. newTextHolder->refCount = 1;
  7249. newTextHolder->allocatedNumChars = newTotalLen;
  7250. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7251. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7252. InternalRefCountedStringHolder* const old = text;
  7253. text = newTextHolder;
  7254. if (atomicDecrementAndReturn (old->refCount) == 0)
  7255. juce_free (old);
  7256. }
  7257. else
  7258. {
  7259. // no other strings using it, so just expand it if needed..
  7260. if (newTotalLen > text->allocatedNumChars)
  7261. {
  7262. text = (InternalRefCountedStringHolder*)
  7263. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7264. + newTotalLen * sizeof (tchar));
  7265. text->allocatedNumChars = newTotalLen;
  7266. }
  7267. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7268. }
  7269. text->text [newTotalLen] = 0;
  7270. }
  7271. }
  7272. void String::dupeInternalIfMultiplyReferenced() throw()
  7273. {
  7274. if (text->refCount > 1)
  7275. {
  7276. InternalRefCountedStringHolder* const old = text;
  7277. const int len = old->allocatedNumChars;
  7278. InternalRefCountedStringHolder* const newTextHolder
  7279. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7280. + len * sizeof (tchar));
  7281. newTextHolder->refCount = 1;
  7282. newTextHolder->allocatedNumChars = len;
  7283. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7284. text = newTextHolder;
  7285. if (atomicDecrementAndReturn (old->refCount) == 0)
  7286. juce_free (old);
  7287. }
  7288. }
  7289. const String String::empty;
  7290. String::String() throw()
  7291. : text (&emptyString)
  7292. {
  7293. }
  7294. String::String (const String& other) throw()
  7295. : text (other.text)
  7296. {
  7297. atomicIncrement (text->refCount);
  7298. }
  7299. String::String (const int numChars,
  7300. const int /*dummyVariable*/) throw()
  7301. {
  7302. createInternal (numChars);
  7303. }
  7304. String::String (const char* const t) throw()
  7305. {
  7306. if (t != 0 && *t != 0)
  7307. {
  7308. const int len = CharacterFunctions::length (t);
  7309. createInternal (len);
  7310. #if JUCE_STRINGS_ARE_UNICODE
  7311. CharacterFunctions::copy (text->text, t, len + 1);
  7312. #else
  7313. memcpy (text->text, t, len + 1);
  7314. #endif
  7315. }
  7316. else
  7317. {
  7318. text = &emptyString;
  7319. emptyString.refCount = safeEmptyStringRefCount;
  7320. }
  7321. }
  7322. String::String (const juce_wchar* const t) throw()
  7323. {
  7324. if (t != 0 && *t != 0)
  7325. {
  7326. #if JUCE_STRINGS_ARE_UNICODE
  7327. const int len = CharacterFunctions::length (t);
  7328. createInternal (len);
  7329. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7330. #else
  7331. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7332. createInternal (len);
  7333. CharacterFunctions::copy (text->text, t, len + 1);
  7334. #endif
  7335. }
  7336. else
  7337. {
  7338. text = &emptyString;
  7339. emptyString.refCount = safeEmptyStringRefCount;
  7340. }
  7341. }
  7342. String::String (const char* const t,
  7343. const int maxChars) throw()
  7344. {
  7345. int i;
  7346. for (i = 0; i < maxChars; ++i)
  7347. if (t[i] == 0)
  7348. break;
  7349. if (i > 0)
  7350. {
  7351. createInternal (i);
  7352. #if JUCE_STRINGS_ARE_UNICODE
  7353. CharacterFunctions::copy (text->text, t, i);
  7354. #else
  7355. memcpy (text->text, t, i);
  7356. #endif
  7357. text->text [i] = 0;
  7358. }
  7359. else
  7360. {
  7361. text = &emptyString;
  7362. emptyString.refCount = safeEmptyStringRefCount;
  7363. }
  7364. }
  7365. String::String (const juce_wchar* const t,
  7366. const int maxChars) throw()
  7367. {
  7368. int i;
  7369. for (i = 0; i < maxChars; ++i)
  7370. if (t[i] == 0)
  7371. break;
  7372. if (i > 0)
  7373. {
  7374. createInternal (i);
  7375. #if JUCE_STRINGS_ARE_UNICODE
  7376. memcpy (text->text, t, i * sizeof (tchar));
  7377. #else
  7378. CharacterFunctions::copy (text->text, t, i);
  7379. #endif
  7380. text->text [i] = 0;
  7381. }
  7382. else
  7383. {
  7384. text = &emptyString;
  7385. emptyString.refCount = safeEmptyStringRefCount;
  7386. }
  7387. }
  7388. const String String::charToString (const tchar character) throw()
  7389. {
  7390. tchar temp[2];
  7391. temp[0] = character;
  7392. temp[1] = 0;
  7393. return String (temp);
  7394. }
  7395. // pass in a pointer to the END of a buffer..
  7396. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7397. {
  7398. *--t = 0;
  7399. int64 v = (n >= 0) ? n : -n;
  7400. do
  7401. {
  7402. *--t = (tchar) (T('0') + (int) (v % 10));
  7403. v /= 10;
  7404. } while (v > 0);
  7405. if (n < 0)
  7406. *--t = T('-');
  7407. return t;
  7408. }
  7409. static tchar* intToCharString (tchar* t, const int n) throw()
  7410. {
  7411. if (n == (int) 0x80000000) // (would cause an overflow)
  7412. return int64ToCharString (t, n);
  7413. *--t = 0;
  7414. int v = abs (n);
  7415. do
  7416. {
  7417. *--t = (tchar) (T('0') + (v % 10));
  7418. v /= 10;
  7419. } while (v > 0);
  7420. if (n < 0)
  7421. *--t = T('-');
  7422. return t;
  7423. }
  7424. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7425. {
  7426. *--t = 0;
  7427. do
  7428. {
  7429. *--t = (tchar) (T('0') + (v % 10));
  7430. v /= 10;
  7431. } while (v > 0);
  7432. return t;
  7433. }
  7434. String::String (const int number) throw()
  7435. {
  7436. tchar buffer [16];
  7437. tchar* const end = buffer + 16;
  7438. createInternal (intToCharString (end, number), end);
  7439. }
  7440. String::String (const unsigned int number) throw()
  7441. {
  7442. tchar buffer [16];
  7443. tchar* const end = buffer + 16;
  7444. createInternal (uintToCharString (end, number), end);
  7445. }
  7446. String::String (const short number) throw()
  7447. {
  7448. tchar buffer [16];
  7449. tchar* const end = buffer + 16;
  7450. createInternal (intToCharString (end, (int) number), end);
  7451. }
  7452. String::String (const unsigned short number) throw()
  7453. {
  7454. tchar buffer [16];
  7455. tchar* const end = buffer + 16;
  7456. createInternal (uintToCharString (end, (unsigned int) number), end);
  7457. }
  7458. String::String (const int64 number) throw()
  7459. {
  7460. tchar buffer [32];
  7461. tchar* const end = buffer + 32;
  7462. createInternal (int64ToCharString (end, number), end);
  7463. }
  7464. String::String (const uint64 number) throw()
  7465. {
  7466. tchar buffer [32];
  7467. tchar* const end = buffer + 32;
  7468. tchar* t = end;
  7469. *--t = 0;
  7470. int64 v = number;
  7471. do
  7472. {
  7473. *--t = (tchar) (T('0') + (int) (v % 10));
  7474. v /= 10;
  7475. } while (v > 0);
  7476. createInternal (t, end);
  7477. }
  7478. // a double-to-string routine that actually uses the number of dec. places you asked for
  7479. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7480. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7481. {
  7482. const int bufSize = 80;
  7483. tchar buffer [bufSize];
  7484. int len;
  7485. tchar* t;
  7486. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7487. {
  7488. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7489. t = buffer + bufSize;
  7490. *--t = (tchar) 0;
  7491. while (numDecPlaces >= 0 || v > 0)
  7492. {
  7493. if (numDecPlaces == 0)
  7494. *--t = decimalPoint;
  7495. *--t = (tchar) (T('0') + (v % 10));
  7496. v /= 10;
  7497. --numDecPlaces;
  7498. }
  7499. if (n < 0)
  7500. *--t = T('-');
  7501. len = (int) ((buffer + bufSize) - t);
  7502. }
  7503. else
  7504. {
  7505. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7506. t = buffer;
  7507. }
  7508. if (len > 1)
  7509. {
  7510. jassert (len < numElementsInArray (buffer));
  7511. createInternal (len - 1);
  7512. memcpy (text->text, t, len * sizeof (tchar));
  7513. }
  7514. else
  7515. {
  7516. jassert (*t == 0);
  7517. text = &emptyString;
  7518. emptyString.refCount = safeEmptyStringRefCount;
  7519. }
  7520. }
  7521. String::String (const float number,
  7522. const int numberOfDecimalPlaces) throw()
  7523. {
  7524. doubleToStringWithDecPlaces ((double) number,
  7525. numberOfDecimalPlaces);
  7526. }
  7527. String::String (const double number,
  7528. const int numberOfDecimalPlaces) throw()
  7529. {
  7530. doubleToStringWithDecPlaces (number,
  7531. numberOfDecimalPlaces);
  7532. }
  7533. String::~String() throw()
  7534. {
  7535. if (atomicDecrementAndReturn (text->refCount) == 0)
  7536. juce_free (text);
  7537. }
  7538. void String::preallocateStorage (const int numChars) throw()
  7539. {
  7540. if (numChars > text->allocatedNumChars)
  7541. {
  7542. dupeInternalIfMultiplyReferenced();
  7543. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7544. + numChars * sizeof (tchar));
  7545. text->allocatedNumChars = numChars;
  7546. }
  7547. }
  7548. #if JUCE_STRINGS_ARE_UNICODE
  7549. String::operator const char*() const throw()
  7550. {
  7551. if (isEmpty())
  7552. {
  7553. return (const char*) emptyCharString;
  7554. }
  7555. else
  7556. {
  7557. String* const mutableThis = const_cast <String*> (this);
  7558. mutableThis->dupeInternalIfMultiplyReferenced();
  7559. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7560. mutableThis->text = (InternalRefCountedStringHolder*)
  7561. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7562. + (len * sizeof (juce_wchar) + len));
  7563. char* otherCopy = (char*) (text->text + len);
  7564. --len;
  7565. CharacterFunctions::copy (otherCopy, text->text, len);
  7566. otherCopy [len] = 0;
  7567. return otherCopy;
  7568. }
  7569. }
  7570. #else
  7571. String::operator const juce_wchar*() const throw()
  7572. {
  7573. if (isEmpty())
  7574. {
  7575. return (const juce_wchar*) emptyCharString;
  7576. }
  7577. else
  7578. {
  7579. String* const mutableThis = const_cast <String*> (this);
  7580. mutableThis->dupeInternalIfMultiplyReferenced();
  7581. int len = CharacterFunctions::length (text->text) + 1;
  7582. mutableThis->text = (InternalRefCountedStringHolder*)
  7583. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7584. + (len * sizeof (juce_wchar) + len));
  7585. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  7586. --len;
  7587. CharacterFunctions::copy (otherCopy, text->text, len);
  7588. otherCopy [len] = 0;
  7589. return otherCopy;
  7590. }
  7591. }
  7592. #endif
  7593. void String::copyToBuffer (char* const destBuffer,
  7594. const int bufferSizeBytes) const throw()
  7595. {
  7596. #if JUCE_STRINGS_ARE_UNICODE
  7597. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  7598. CharacterFunctions::copy (destBuffer, text->text, len);
  7599. #else
  7600. const int len = jmin (bufferSizeBytes, length());
  7601. memcpy (destBuffer, text->text, len * sizeof (tchar));
  7602. #endif
  7603. destBuffer [len] = 0;
  7604. }
  7605. void String::copyToBuffer (juce_wchar* const destBuffer,
  7606. const int maxCharsToCopy) const throw()
  7607. {
  7608. const int len = jmin (maxCharsToCopy, length());
  7609. #if JUCE_STRINGS_ARE_UNICODE
  7610. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  7611. #else
  7612. CharacterFunctions::copy (destBuffer, text->text, len);
  7613. #endif
  7614. destBuffer [len] = 0;
  7615. }
  7616. int String::length() const throw()
  7617. {
  7618. return CharacterFunctions::length (text->text);
  7619. }
  7620. int String::hashCode() const throw()
  7621. {
  7622. const tchar* t = text->text;
  7623. int result = 0;
  7624. while (*t != (tchar) 0)
  7625. result = 31 * result + *t++;
  7626. return result;
  7627. }
  7628. int64 String::hashCode64() const throw()
  7629. {
  7630. const tchar* t = text->text;
  7631. int64 result = 0;
  7632. while (*t != (tchar) 0)
  7633. result = 101 * result + *t++;
  7634. return result;
  7635. }
  7636. const String& String::operator= (const tchar* const otherText) throw()
  7637. {
  7638. if (otherText != 0 && *otherText != 0)
  7639. {
  7640. const int otherLen = CharacterFunctions::length (otherText);
  7641. if (otherLen > 0)
  7642. {
  7643. // avoid resizing the memory block if the string is
  7644. // shrinking..
  7645. if (text->refCount > 1
  7646. || otherLen > text->allocatedNumChars
  7647. || otherLen <= (text->allocatedNumChars >> 1))
  7648. {
  7649. deleteInternal();
  7650. createInternal (otherLen);
  7651. }
  7652. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  7653. return *this;
  7654. }
  7655. }
  7656. deleteInternal();
  7657. text = &emptyString;
  7658. emptyString.refCount = safeEmptyStringRefCount;
  7659. return *this;
  7660. }
  7661. const String& String::operator= (const String& other) throw()
  7662. {
  7663. if (this != &other)
  7664. {
  7665. atomicIncrement (other.text->refCount);
  7666. if (atomicDecrementAndReturn (text->refCount) == 0)
  7667. juce_free (text);
  7668. text = other.text;
  7669. }
  7670. return *this;
  7671. }
  7672. bool String::operator== (const String& other) const throw()
  7673. {
  7674. return text == other.text
  7675. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  7676. }
  7677. bool String::operator== (const tchar* const t) const throw()
  7678. {
  7679. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  7680. : isEmpty();
  7681. }
  7682. bool String::equalsIgnoreCase (const tchar* t) const throw()
  7683. {
  7684. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  7685. : isEmpty();
  7686. }
  7687. bool String::equalsIgnoreCase (const String& other) const throw()
  7688. {
  7689. return text == other.text
  7690. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  7691. }
  7692. bool String::operator!= (const String& other) const throw()
  7693. {
  7694. return text != other.text
  7695. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  7696. }
  7697. bool String::operator!= (const tchar* const t) const throw()
  7698. {
  7699. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  7700. : isNotEmpty();
  7701. }
  7702. bool String::operator> (const String& other) const throw()
  7703. {
  7704. return compare (other) > 0;
  7705. }
  7706. bool String::operator< (const tchar* const other) const throw()
  7707. {
  7708. return compare (other) < 0;
  7709. }
  7710. bool String::operator>= (const String& other) const throw()
  7711. {
  7712. return compare (other) >= 0;
  7713. }
  7714. bool String::operator<= (const tchar* const other) const throw()
  7715. {
  7716. return compare (other) <= 0;
  7717. }
  7718. int String::compare (const tchar* const other) const throw()
  7719. {
  7720. return other != 0 ? CharacterFunctions::compare (text->text, other)
  7721. : isEmpty();
  7722. }
  7723. int String::compareIgnoreCase (const tchar* const other) const throw()
  7724. {
  7725. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  7726. : isEmpty();
  7727. }
  7728. int String::compareLexicographically (const tchar* other) const throw()
  7729. {
  7730. if (other == 0)
  7731. return isEmpty();
  7732. const tchar* s1 = text->text;
  7733. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  7734. ++s1;
  7735. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  7736. ++other;
  7737. return CharacterFunctions::compareIgnoreCase (s1, other);
  7738. }
  7739. const String String::operator+ (const String& other) const throw()
  7740. {
  7741. if (*(other.text->text) == 0)
  7742. return *this;
  7743. if (isEmpty())
  7744. return other;
  7745. const int len = CharacterFunctions::length (text->text);
  7746. const int otherLen = CharacterFunctions::length (other.text->text);
  7747. String result (len + otherLen, (int) 0);
  7748. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7749. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  7750. result.text->text [len + otherLen] = 0;
  7751. return result;
  7752. }
  7753. const String String::operator+ (const tchar* const textToAppend) const throw()
  7754. {
  7755. if (textToAppend == 0 || *textToAppend == 0)
  7756. return *this;
  7757. const int len = CharacterFunctions::length (text->text);
  7758. const int otherLen = CharacterFunctions::length (textToAppend);
  7759. String result (len + otherLen, (int) 0);
  7760. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7761. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  7762. result.text->text [len + otherLen] = 0;
  7763. return result;
  7764. }
  7765. const String String::operator+ (const tchar characterToAppend) const throw()
  7766. {
  7767. if (characterToAppend == 0)
  7768. return *this;
  7769. const int len = CharacterFunctions::length (text->text);
  7770. String result ((int) (len + 1), (int) 0);
  7771. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7772. result.text->text[len] = characterToAppend;
  7773. result.text->text[len + 1] = 0;
  7774. return result;
  7775. }
  7776. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  7777. const String& string2) throw()
  7778. {
  7779. String s (string1);
  7780. s += string2;
  7781. return s;
  7782. }
  7783. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  7784. const String& string2) throw()
  7785. {
  7786. String s (string1);
  7787. s += string2;
  7788. return s;
  7789. }
  7790. const String& String::operator+= (const tchar* const t) throw()
  7791. {
  7792. if (t != 0)
  7793. appendInternal (t, CharacterFunctions::length (t));
  7794. return *this;
  7795. }
  7796. const String& String::operator+= (const String& other) throw()
  7797. {
  7798. if (isEmpty())
  7799. operator= (other);
  7800. else
  7801. appendInternal (other.text->text,
  7802. CharacterFunctions::length (other.text->text));
  7803. return *this;
  7804. }
  7805. const String& String::operator+= (const char ch) throw()
  7806. {
  7807. char asString[2];
  7808. asString[0] = ch;
  7809. asString[1] = 0;
  7810. #if JUCE_STRINGS_ARE_UNICODE
  7811. operator+= (String (asString));
  7812. #else
  7813. appendInternal (asString, 1);
  7814. #endif
  7815. return *this;
  7816. }
  7817. const String& String::operator+= (const juce_wchar ch) throw()
  7818. {
  7819. juce_wchar asString[2];
  7820. asString[0] = ch;
  7821. asString[1] = 0;
  7822. #if JUCE_STRINGS_ARE_UNICODE
  7823. appendInternal (asString, 1);
  7824. #else
  7825. operator+= (String (asString));
  7826. #endif
  7827. return *this;
  7828. }
  7829. void String::append (const tchar* const other,
  7830. const int howMany) throw()
  7831. {
  7832. if (howMany > 0)
  7833. {
  7834. int i;
  7835. for (i = 0; i < howMany; ++i)
  7836. if (other[i] == 0)
  7837. break;
  7838. appendInternal (other, i);
  7839. }
  7840. }
  7841. String& String::operator<< (const int number) throw()
  7842. {
  7843. tchar buffer [64];
  7844. tchar* const end = buffer + 64;
  7845. const tchar* const t = intToCharString (end, number);
  7846. appendInternal (t, (int) (end - t) - 1);
  7847. return *this;
  7848. }
  7849. String& String::operator<< (const unsigned int number) throw()
  7850. {
  7851. tchar buffer [64];
  7852. tchar* const end = buffer + 64;
  7853. const tchar* const t = uintToCharString (end, number);
  7854. appendInternal (t, (int) (end - t) - 1);
  7855. return *this;
  7856. }
  7857. String& String::operator<< (const short number) throw()
  7858. {
  7859. tchar buffer [64];
  7860. tchar* const end = buffer + 64;
  7861. const tchar* const t = intToCharString (end, (int) number);
  7862. appendInternal (t, (int) (end - t) - 1);
  7863. return *this;
  7864. }
  7865. String& String::operator<< (const double number) throw()
  7866. {
  7867. operator+= (String (number));
  7868. return *this;
  7869. }
  7870. String& String::operator<< (const float number) throw()
  7871. {
  7872. operator+= (String (number));
  7873. return *this;
  7874. }
  7875. String& String::operator<< (const char character) throw()
  7876. {
  7877. operator+= (character);
  7878. return *this;
  7879. }
  7880. String& String::operator<< (const juce_wchar character) throw()
  7881. {
  7882. operator+= (character);
  7883. return *this;
  7884. }
  7885. String& String::operator<< (const char* const t) throw()
  7886. {
  7887. #if JUCE_STRINGS_ARE_UNICODE
  7888. operator+= (String (t));
  7889. #else
  7890. operator+= (t);
  7891. #endif
  7892. return *this;
  7893. }
  7894. String& String::operator<< (const juce_wchar* const t) throw()
  7895. {
  7896. #if JUCE_STRINGS_ARE_UNICODE
  7897. operator+= (t);
  7898. #else
  7899. operator+= (String (t));
  7900. #endif
  7901. return *this;
  7902. }
  7903. String& String::operator<< (const String& t) throw()
  7904. {
  7905. operator+= (t);
  7906. return *this;
  7907. }
  7908. int String::indexOfChar (const tchar character) const throw()
  7909. {
  7910. const tchar* t = text->text;
  7911. for (;;)
  7912. {
  7913. if (*t == character)
  7914. return (int) (t - text->text);
  7915. if (*t++ == 0)
  7916. return -1;
  7917. }
  7918. }
  7919. int String::lastIndexOfChar (const tchar character) const throw()
  7920. {
  7921. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  7922. if (text->text[i] == character)
  7923. return i;
  7924. return -1;
  7925. }
  7926. int String::indexOf (const tchar* const t) const throw()
  7927. {
  7928. const tchar* const r = CharacterFunctions::find (text->text, t);
  7929. return (r == 0) ? -1
  7930. : (int) (r - text->text);
  7931. }
  7932. int String::indexOfChar (const int startIndex,
  7933. const tchar character) const throw()
  7934. {
  7935. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  7936. return -1;
  7937. const tchar* t = text->text + jmax (0, startIndex);
  7938. for (;;)
  7939. {
  7940. if (*t == character)
  7941. return (int) (t - text->text);
  7942. if (*t++ == 0)
  7943. return -1;
  7944. }
  7945. }
  7946. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  7947. const int startIndex,
  7948. const bool ignoreCase) const throw()
  7949. {
  7950. if (charactersToLookFor == 0
  7951. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  7952. return -1;
  7953. const tchar* t = text->text + jmax (0, startIndex);
  7954. while (*t != 0)
  7955. {
  7956. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  7957. return (int) (t - text->text);
  7958. ++t;
  7959. }
  7960. return -1;
  7961. }
  7962. int String::indexOf (const int startIndex,
  7963. const tchar* const other) const throw()
  7964. {
  7965. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  7966. return -1;
  7967. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  7968. other);
  7969. return (found == 0) ? -1
  7970. : (int) (found - text->text);
  7971. }
  7972. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  7973. {
  7974. if (other != 0 && *other != 0)
  7975. {
  7976. const int len = CharacterFunctions::length (other);
  7977. const int end = CharacterFunctions::length (text->text) - len;
  7978. for (int i = 0; i <= end; ++i)
  7979. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  7980. return i;
  7981. }
  7982. return -1;
  7983. }
  7984. int String::indexOfIgnoreCase (const int startIndex,
  7985. const tchar* const other) const throw()
  7986. {
  7987. if (other != 0 && *other != 0)
  7988. {
  7989. const int len = CharacterFunctions::length (other);
  7990. const int end = length() - len;
  7991. for (int i = jmax (0, startIndex); i <= end; ++i)
  7992. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  7993. return i;
  7994. }
  7995. return -1;
  7996. }
  7997. int String::lastIndexOf (const tchar* const other) const throw()
  7998. {
  7999. if (other != 0 && *other != 0)
  8000. {
  8001. const int len = CharacterFunctions::length (other);
  8002. int i = length() - len;
  8003. if (i >= 0)
  8004. {
  8005. const tchar* n = text->text + i;
  8006. while (i >= 0)
  8007. {
  8008. if (CharacterFunctions::compare (n--, other, len) == 0)
  8009. return i;
  8010. --i;
  8011. }
  8012. }
  8013. }
  8014. return -1;
  8015. }
  8016. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8017. {
  8018. if (other != 0 && *other != 0)
  8019. {
  8020. const int len = CharacterFunctions::length (other);
  8021. int i = length() - len;
  8022. if (i >= 0)
  8023. {
  8024. const tchar* n = text->text + i;
  8025. while (i >= 0)
  8026. {
  8027. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8028. return i;
  8029. --i;
  8030. }
  8031. }
  8032. }
  8033. return -1;
  8034. }
  8035. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8036. const bool ignoreCase) const throw()
  8037. {
  8038. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8039. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8040. return i;
  8041. return -1;
  8042. }
  8043. bool String::contains (const tchar* const other) const throw()
  8044. {
  8045. return indexOf (other) >= 0;
  8046. }
  8047. bool String::containsChar (const tchar character) const throw()
  8048. {
  8049. return indexOfChar (character) >= 0;
  8050. }
  8051. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8052. {
  8053. return indexOfIgnoreCase (t) >= 0;
  8054. }
  8055. int String::indexOfWholeWord (const tchar* const word) const throw()
  8056. {
  8057. if (word != 0 && *word != 0)
  8058. {
  8059. const int wordLen = CharacterFunctions::length (word);
  8060. const int end = length() - wordLen;
  8061. const tchar* t = text->text;
  8062. for (int i = 0; i <= end; ++i)
  8063. {
  8064. if (CharacterFunctions::compare (t, word, wordLen) == 0
  8065. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8066. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8067. {
  8068. return i;
  8069. }
  8070. ++t;
  8071. }
  8072. }
  8073. return -1;
  8074. }
  8075. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8076. {
  8077. if (word != 0 && *word != 0)
  8078. {
  8079. const int wordLen = CharacterFunctions::length (word);
  8080. const int end = length() - wordLen;
  8081. const tchar* t = text->text;
  8082. for (int i = 0; i <= end; ++i)
  8083. {
  8084. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8085. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8086. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8087. {
  8088. return i;
  8089. }
  8090. ++t;
  8091. }
  8092. }
  8093. return -1;
  8094. }
  8095. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8096. {
  8097. return indexOfWholeWord (wordToLookFor) >= 0;
  8098. }
  8099. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8100. {
  8101. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8102. }
  8103. static int indexOfMatch (const tchar* const wildcard,
  8104. const tchar* const test,
  8105. const bool ignoreCase) throw()
  8106. {
  8107. int start = 0;
  8108. while (test [start] != 0)
  8109. {
  8110. int i = 0;
  8111. for (;;)
  8112. {
  8113. const tchar wc = wildcard [i];
  8114. const tchar c = test [i + start];
  8115. if (wc == c
  8116. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8117. || (wc == T('?') && c != 0))
  8118. {
  8119. if (wc == 0)
  8120. return start;
  8121. ++i;
  8122. }
  8123. else
  8124. {
  8125. if (wc == T('*') && (wildcard [i + 1] == 0
  8126. || indexOfMatch (wildcard + i + 1,
  8127. test + start + i,
  8128. ignoreCase) >= 0))
  8129. {
  8130. return start;
  8131. }
  8132. break;
  8133. }
  8134. }
  8135. ++start;
  8136. }
  8137. return -1;
  8138. }
  8139. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8140. {
  8141. int i = 0;
  8142. for (;;)
  8143. {
  8144. const tchar wc = wildcard [i];
  8145. const tchar c = text->text [i];
  8146. if (wc == c
  8147. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8148. || (wc == T('?') && c != 0))
  8149. {
  8150. if (wc == 0)
  8151. return true;
  8152. ++i;
  8153. }
  8154. else
  8155. {
  8156. return wc == T('*') && (wildcard [i + 1] == 0
  8157. || indexOfMatch (wildcard + i + 1,
  8158. text->text + i,
  8159. ignoreCase) >= 0);
  8160. }
  8161. }
  8162. }
  8163. void String::printf (const tchar* const pf, ...) throw()
  8164. {
  8165. va_list list;
  8166. va_start (list, pf);
  8167. vprintf (pf, list);
  8168. }
  8169. const String String::formatted (const tchar* const pf, ...) throw()
  8170. {
  8171. va_list list;
  8172. va_start (list, pf);
  8173. String result;
  8174. result.vprintf (pf, list);
  8175. return result;
  8176. }
  8177. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8178. {
  8179. tchar stackBuf [256];
  8180. unsigned int bufSize = 256;
  8181. tchar* buf = stackBuf;
  8182. deleteInternal();
  8183. do
  8184. {
  8185. #if JUCE_LINUX && JUCE_64BIT
  8186. va_list tempArgs;
  8187. va_copy (tempArgs, args);
  8188. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8189. va_end (tempArgs);
  8190. #else
  8191. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8192. #endif
  8193. if (num > 0)
  8194. {
  8195. createInternal (num);
  8196. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8197. break;
  8198. }
  8199. else if (num == 0)
  8200. {
  8201. text = &emptyString;
  8202. emptyString.refCount = safeEmptyStringRefCount;
  8203. break;
  8204. }
  8205. if (buf != stackBuf)
  8206. juce_free (buf);
  8207. bufSize += 256;
  8208. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8209. }
  8210. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8211. // returns -1 because of an error rather than because it needs more space.
  8212. if (buf != stackBuf)
  8213. juce_free (buf);
  8214. }
  8215. const String String::repeatedString (const tchar* const stringToRepeat,
  8216. int numberOfTimesToRepeat) throw()
  8217. {
  8218. const int len = CharacterFunctions::length (stringToRepeat);
  8219. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8220. tchar* n = result.text->text;
  8221. n[0] = 0;
  8222. while (--numberOfTimesToRepeat >= 0)
  8223. {
  8224. CharacterFunctions::append (n, stringToRepeat);
  8225. n += len;
  8226. }
  8227. return result;
  8228. }
  8229. const String String::replaceSection (int index,
  8230. int numCharsToReplace,
  8231. const tchar* const stringToInsert) const throw()
  8232. {
  8233. if (index < 0)
  8234. {
  8235. // a negative index to replace from?
  8236. jassertfalse
  8237. index = 0;
  8238. }
  8239. if (numCharsToReplace < 0)
  8240. {
  8241. // replacing a negative number of characters?
  8242. numCharsToReplace = 0;
  8243. jassertfalse;
  8244. }
  8245. const int len = length();
  8246. if (index + numCharsToReplace > len)
  8247. {
  8248. if (index > len)
  8249. {
  8250. // replacing beyond the end of the string?
  8251. index = len;
  8252. jassertfalse
  8253. }
  8254. numCharsToReplace = len - index;
  8255. }
  8256. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8257. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8258. String result (newTotalLen, (int) 0);
  8259. memcpy (result.text->text,
  8260. text->text,
  8261. index * sizeof (tchar));
  8262. if (newStringLen > 0)
  8263. memcpy (result.text->text + index,
  8264. stringToInsert,
  8265. newStringLen * sizeof (tchar));
  8266. const int endStringLen = newTotalLen - (index + newStringLen);
  8267. if (endStringLen > 0)
  8268. memcpy (result.text->text + (index + newStringLen),
  8269. text->text + (index + numCharsToReplace),
  8270. endStringLen * sizeof (tchar));
  8271. result.text->text [newTotalLen] = 0;
  8272. return result;
  8273. }
  8274. const String String::replace (const tchar* const stringToReplace,
  8275. const tchar* const stringToInsert,
  8276. const bool ignoreCase) const throw()
  8277. {
  8278. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8279. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8280. int i = 0;
  8281. String result (*this);
  8282. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8283. : result.indexOf (i, stringToReplace))) >= 0)
  8284. {
  8285. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8286. i += stringToInsertLen;
  8287. }
  8288. return result;
  8289. }
  8290. const String String::replaceCharacter (const tchar charToReplace,
  8291. const tchar charToInsert) const throw()
  8292. {
  8293. const int index = indexOfChar (charToReplace);
  8294. if (index < 0)
  8295. return *this;
  8296. String result (*this);
  8297. result.dupeInternalIfMultiplyReferenced();
  8298. tchar* t = result.text->text + index;
  8299. while (*t != 0)
  8300. {
  8301. if (*t == charToReplace)
  8302. *t = charToInsert;
  8303. ++t;
  8304. }
  8305. return result;
  8306. }
  8307. const String String::replaceCharacters (const String& charactersToReplace,
  8308. const tchar* const charactersToInsertInstead) const throw()
  8309. {
  8310. String result (*this);
  8311. result.dupeInternalIfMultiplyReferenced();
  8312. tchar* t = result.text->text;
  8313. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8314. // the two strings passed in are supposed to be the same length!
  8315. jassert (len2 == charactersToReplace.length());
  8316. while (*t != 0)
  8317. {
  8318. const int index = charactersToReplace.indexOfChar (*t);
  8319. if (((unsigned int) index) < (unsigned int) len2)
  8320. *t = charactersToInsertInstead [index];
  8321. ++t;
  8322. }
  8323. return result;
  8324. }
  8325. bool String::startsWith (const tchar* const other) const throw()
  8326. {
  8327. return other != 0
  8328. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8329. }
  8330. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8331. {
  8332. return other != 0
  8333. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8334. }
  8335. bool String::startsWithChar (const tchar character) const throw()
  8336. {
  8337. return text->text[0] == character;
  8338. }
  8339. bool String::endsWithChar (const tchar character) const throw()
  8340. {
  8341. return text->text[0] != 0
  8342. && text->text [length() - 1] == character;
  8343. }
  8344. bool String::endsWith (const tchar* const other) const throw()
  8345. {
  8346. if (other == 0)
  8347. return false;
  8348. const int thisLen = length();
  8349. const int otherLen = CharacterFunctions::length (other);
  8350. return thisLen >= otherLen
  8351. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8352. }
  8353. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8354. {
  8355. if (other == 0)
  8356. return false;
  8357. const int thisLen = length();
  8358. const int otherLen = CharacterFunctions::length (other);
  8359. return thisLen >= otherLen
  8360. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8361. }
  8362. const String String::toUpperCase() const throw()
  8363. {
  8364. String result (*this);
  8365. result.dupeInternalIfMultiplyReferenced();
  8366. CharacterFunctions::toUpperCase (result.text->text);
  8367. return result;
  8368. }
  8369. const String String::toLowerCase() const throw()
  8370. {
  8371. String result (*this);
  8372. result.dupeInternalIfMultiplyReferenced();
  8373. CharacterFunctions::toLowerCase (result.text->text);
  8374. return result;
  8375. }
  8376. tchar& String::operator[] (const int index) throw()
  8377. {
  8378. jassert (((unsigned int) index) <= (unsigned int) length());
  8379. dupeInternalIfMultiplyReferenced();
  8380. return text->text [index];
  8381. }
  8382. tchar String::getLastCharacter() const throw()
  8383. {
  8384. return (isEmpty()) ? ((tchar) 0)
  8385. : text->text [CharacterFunctions::length (text->text) - 1];
  8386. }
  8387. const String String::substring (int start, int end) const throw()
  8388. {
  8389. if (start < 0)
  8390. start = 0;
  8391. else if (end <= start)
  8392. return empty;
  8393. int len = 0;
  8394. const tchar* const t = text->text;
  8395. while (len <= end && t [len] != 0)
  8396. ++len;
  8397. if (end >= len)
  8398. {
  8399. if (start == 0)
  8400. return *this;
  8401. end = len;
  8402. }
  8403. return String (text->text + start,
  8404. end - start);
  8405. }
  8406. const String String::substring (const int start) const throw()
  8407. {
  8408. if (start <= 0)
  8409. return *this;
  8410. const int len = CharacterFunctions::length (text->text);
  8411. if (start >= len)
  8412. return empty;
  8413. else
  8414. return String (text->text + start,
  8415. len - start);
  8416. }
  8417. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8418. {
  8419. return String (text->text,
  8420. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8421. }
  8422. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8423. const bool includeSubString,
  8424. const bool ignoreCase) const throw()
  8425. {
  8426. const int i = ignoreCase ? indexOf (sub)
  8427. : indexOfIgnoreCase (sub);
  8428. if (i < 0)
  8429. return empty;
  8430. else
  8431. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8432. }
  8433. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8434. const bool includeSubString,
  8435. const bool ignoreCase) const throw()
  8436. {
  8437. const int i = ignoreCase ? lastIndexOf (sub)
  8438. : lastIndexOfIgnoreCase (sub);
  8439. if (i < 0)
  8440. return *this;
  8441. else
  8442. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8443. }
  8444. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8445. const bool includeSubString,
  8446. const bool ignoreCase) const throw()
  8447. {
  8448. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8449. : indexOf (sub);
  8450. if (i < 0)
  8451. return *this;
  8452. else
  8453. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8454. }
  8455. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8456. const bool includeSubString,
  8457. const bool ignoreCase) const throw()
  8458. {
  8459. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8460. : lastIndexOf (sub);
  8461. if (i < 0)
  8462. return *this;
  8463. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8464. }
  8465. bool String::isQuotedString() const throw()
  8466. {
  8467. const String trimmed (trimStart());
  8468. return trimmed[0] == T('"')
  8469. || trimmed[0] == T('\'');
  8470. }
  8471. const String String::unquoted() const throw()
  8472. {
  8473. String s (*this);
  8474. if (s[0] == T('"') || s[0] == T('\''))
  8475. s = s.substring (1);
  8476. const int lastCharIndex = s.length() - 1;
  8477. if (lastCharIndex >= 0
  8478. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8479. s [lastCharIndex] = 0;
  8480. return s;
  8481. }
  8482. const String String::quoted (const tchar quoteCharacter) const throw()
  8483. {
  8484. if (isEmpty())
  8485. return charToString (quoteCharacter) + quoteCharacter;
  8486. String t (*this);
  8487. if (! t.startsWithChar (quoteCharacter))
  8488. t = charToString (quoteCharacter) + t;
  8489. if (! t.endsWithChar (quoteCharacter))
  8490. t += quoteCharacter;
  8491. return t;
  8492. }
  8493. const String String::trim() const throw()
  8494. {
  8495. if (isEmpty())
  8496. return empty;
  8497. int start = 0;
  8498. while (CharacterFunctions::isWhitespace (text->text [start]))
  8499. ++start;
  8500. const int len = CharacterFunctions::length (text->text);
  8501. int end = len - 1;
  8502. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8503. --end;
  8504. ++end;
  8505. if (end <= start)
  8506. return empty;
  8507. else if (start > 0 || end < len)
  8508. return String (text->text + start, end - start);
  8509. else
  8510. return *this;
  8511. }
  8512. const String String::trimStart() const throw()
  8513. {
  8514. if (isEmpty())
  8515. return empty;
  8516. const tchar* t = text->text;
  8517. while (CharacterFunctions::isWhitespace (*t))
  8518. ++t;
  8519. if (t == text->text)
  8520. return *this;
  8521. else
  8522. return String (t);
  8523. }
  8524. const String String::trimEnd() const throw()
  8525. {
  8526. if (isEmpty())
  8527. return empty;
  8528. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8529. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8530. --endT;
  8531. return String (text->text, (int) (++endT - text->text));
  8532. }
  8533. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8534. {
  8535. jassert (charactersToRetain != 0);
  8536. if (isEmpty())
  8537. return empty;
  8538. String result (text->allocatedNumChars, (int) 0);
  8539. tchar* dst = result.text->text;
  8540. const tchar* src = text->text;
  8541. while (*src != 0)
  8542. {
  8543. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8544. *dst++ = *src;
  8545. ++src;
  8546. }
  8547. *dst = 0;
  8548. return result;
  8549. }
  8550. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8551. {
  8552. jassert (charactersToRemove != 0);
  8553. if (isEmpty())
  8554. return empty;
  8555. String result (text->allocatedNumChars, (int) 0);
  8556. tchar* dst = result.text->text;
  8557. const tchar* src = text->text;
  8558. while (*src != 0)
  8559. {
  8560. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8561. *dst++ = *src;
  8562. ++src;
  8563. }
  8564. *dst = 0;
  8565. return result;
  8566. }
  8567. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8568. {
  8569. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  8570. }
  8571. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  8572. {
  8573. jassert (charactersToStopAt != 0);
  8574. const tchar* const t = text->text;
  8575. int i = 0;
  8576. while (t[i] != 0)
  8577. {
  8578. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  8579. return String (text->text, i);
  8580. ++i;
  8581. }
  8582. return empty;
  8583. }
  8584. bool String::containsOnly (const tchar* const chars) const throw()
  8585. {
  8586. jassert (chars != 0);
  8587. const tchar* t = text->text;
  8588. while (*t != 0)
  8589. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  8590. return false;
  8591. return true;
  8592. }
  8593. bool String::containsAnyOf (const tchar* const chars) const throw()
  8594. {
  8595. jassert (chars != 0);
  8596. const tchar* t = text->text;
  8597. while (*t != 0)
  8598. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  8599. return true;
  8600. return false;
  8601. }
  8602. int String::getIntValue() const throw()
  8603. {
  8604. return CharacterFunctions::getIntValue (text->text);
  8605. }
  8606. int String::getTrailingIntValue() const throw()
  8607. {
  8608. int n = 0;
  8609. int mult = 1;
  8610. const tchar* t = text->text + length();
  8611. while (--t >= text->text)
  8612. {
  8613. const tchar c = *t;
  8614. if (! CharacterFunctions::isDigit (c))
  8615. {
  8616. if (c == T('-'))
  8617. n = -n;
  8618. break;
  8619. }
  8620. n += mult * (c - T('0'));
  8621. mult *= 10;
  8622. }
  8623. return n;
  8624. }
  8625. int64 String::getLargeIntValue() const throw()
  8626. {
  8627. return CharacterFunctions::getInt64Value (text->text);
  8628. }
  8629. float String::getFloatValue() const throw()
  8630. {
  8631. return (float) CharacterFunctions::getDoubleValue (text->text);
  8632. }
  8633. double String::getDoubleValue() const throw()
  8634. {
  8635. return CharacterFunctions::getDoubleValue (text->text);
  8636. }
  8637. static const tchar* const hexDigits = T("0123456789abcdef");
  8638. const String String::toHexString (const int number) throw()
  8639. {
  8640. tchar buffer[32];
  8641. tchar* const end = buffer + 32;
  8642. tchar* t = end;
  8643. *--t = 0;
  8644. unsigned int v = (unsigned int) number;
  8645. do
  8646. {
  8647. *--t = hexDigits [v & 15];
  8648. v >>= 4;
  8649. } while (v != 0);
  8650. return String (t, (int) (((char*) end) - (char*) t) - 1);
  8651. }
  8652. const String String::toHexString (const int64 number) throw()
  8653. {
  8654. tchar buffer[32];
  8655. tchar* const end = buffer + 32;
  8656. tchar* t = end;
  8657. *--t = 0;
  8658. uint64 v = (uint64) number;
  8659. do
  8660. {
  8661. *--t = hexDigits [(int) (v & 15)];
  8662. v >>= 4;
  8663. } while (v != 0);
  8664. return String (t, (int) (((char*) end) - (char*) t));
  8665. }
  8666. const String String::toHexString (const short number) throw()
  8667. {
  8668. return toHexString ((int) (unsigned short) number);
  8669. }
  8670. const String String::toHexString (const unsigned char* data,
  8671. const int size,
  8672. const int groupSize) throw()
  8673. {
  8674. if (size <= 0)
  8675. return empty;
  8676. int numChars = (size * 2) + 2;
  8677. if (groupSize > 0)
  8678. numChars += size / groupSize;
  8679. String s (numChars, (int) 0);
  8680. tchar* d = s.text->text;
  8681. for (int i = 0; i < size; ++i)
  8682. {
  8683. *d++ = hexDigits [(*data) >> 4];
  8684. *d++ = hexDigits [(*data) & 0xf];
  8685. ++data;
  8686. if (groupSize > 0 && (i % groupSize) == 0)
  8687. *d++ = T(' ');
  8688. }
  8689. if (groupSize > 0)
  8690. --d;
  8691. *d = 0;
  8692. return s;
  8693. }
  8694. int String::getHexValue32() const throw()
  8695. {
  8696. int result = 0;
  8697. const tchar* c = text->text;
  8698. for (;;)
  8699. {
  8700. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8701. if (hexValue >= 0)
  8702. result = (result << 4) | hexValue;
  8703. else if (*c == 0)
  8704. break;
  8705. ++c;
  8706. }
  8707. return result;
  8708. }
  8709. int64 String::getHexValue64() const throw()
  8710. {
  8711. int64 result = 0;
  8712. const tchar* c = text->text;
  8713. for (;;)
  8714. {
  8715. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8716. if (hexValue >= 0)
  8717. result = (result << 4) | hexValue;
  8718. else if (*c == 0)
  8719. break;
  8720. ++c;
  8721. }
  8722. return result;
  8723. }
  8724. const String String::createStringFromData (const void* const data_,
  8725. const int size) throw()
  8726. {
  8727. const char* const data = (const char*) data_;
  8728. if (size <= 0 || data == 0)
  8729. {
  8730. return empty;
  8731. }
  8732. else if (size < 2)
  8733. {
  8734. return charToString (data[0]);
  8735. }
  8736. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  8737. || (data[0] == (char)-1 && data[1] == (char)-2))
  8738. {
  8739. // assume it's 16-bit unicode
  8740. const bool bigEndian = (data[0] == (char)-2);
  8741. const int numChars = size / 2 - 1;
  8742. String result;
  8743. result.preallocateStorage (numChars + 2);
  8744. const uint16* const src = (const uint16*) (data + 2);
  8745. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8746. if (bigEndian)
  8747. {
  8748. for (int i = 0; i < numChars; ++i)
  8749. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  8750. }
  8751. else
  8752. {
  8753. for (int i = 0; i < numChars; ++i)
  8754. dst[i] = (tchar) swapIfBigEndian (src[i]);
  8755. }
  8756. dst [numChars] = 0;
  8757. return result;
  8758. }
  8759. else
  8760. {
  8761. #if JUCE_STRINGS_ARE_UNICODE && JUCE_LINUX
  8762. // (workaround for strange behaviour of mbstowcs)
  8763. int i;
  8764. for (i = 0; i < size; ++i)
  8765. if (data[i] == 0)
  8766. break;
  8767. String result;
  8768. result.preallocateStorage (i + 1);
  8769. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8770. for (int j = 0; j < i; ++j)
  8771. dst[j] = (juce_wchar) (unsigned char) data[j];
  8772. dst[i] = 0;
  8773. return result;
  8774. #else
  8775. return String (data, size);
  8776. #endif
  8777. }
  8778. }
  8779. const char* String::toUTF8() const throw()
  8780. {
  8781. if (isEmpty())
  8782. {
  8783. return (const char*) emptyCharString;
  8784. }
  8785. else
  8786. {
  8787. String* const mutableThis = const_cast <String*> (this);
  8788. mutableThis->dupeInternalIfMultiplyReferenced();
  8789. const int currentLen = CharacterFunctions::length (text->text) + 1;
  8790. const int utf8BytesNeeded = copyToUTF8 (0);
  8791. mutableThis->text = (InternalRefCountedStringHolder*)
  8792. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8793. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  8794. char* const otherCopy = (char*) (text->text + currentLen);
  8795. copyToUTF8 ((uint8*) otherCopy);
  8796. return otherCopy;
  8797. }
  8798. }
  8799. int String::copyToUTF8 (uint8* const buffer) const throw()
  8800. {
  8801. #if JUCE_STRINGS_ARE_UNICODE
  8802. int num = 0, index = 0;
  8803. for (;;)
  8804. {
  8805. const uint32 c = (uint32) text->text [index++];
  8806. if (c >= 0x80)
  8807. {
  8808. int numExtraBytes = 1;
  8809. if (c >= 0x800)
  8810. {
  8811. ++numExtraBytes;
  8812. if (c >= 0x10000)
  8813. {
  8814. ++numExtraBytes;
  8815. if (c >= 0x200000)
  8816. {
  8817. ++numExtraBytes;
  8818. if (c >= 0x4000000)
  8819. ++numExtraBytes;
  8820. }
  8821. }
  8822. }
  8823. if (buffer != 0)
  8824. {
  8825. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  8826. while (--numExtraBytes >= 0)
  8827. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  8828. }
  8829. else
  8830. {
  8831. num += numExtraBytes + 1;
  8832. }
  8833. }
  8834. else
  8835. {
  8836. if (buffer != 0)
  8837. buffer [num] = (uint8) c;
  8838. ++num;
  8839. }
  8840. if (c == 0)
  8841. break;
  8842. }
  8843. return num;
  8844. #else
  8845. const int numBytes = length() + 1;
  8846. if (buffer != 0)
  8847. copyToBuffer ((char*) buffer, numBytes);
  8848. return numBytes;
  8849. #endif
  8850. }
  8851. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  8852. {
  8853. if (buffer == 0)
  8854. return empty;
  8855. if (bufferSizeBytes < 0)
  8856. bufferSizeBytes = INT_MAX;
  8857. int numBytes;
  8858. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  8859. if (buffer [numBytes] == 0)
  8860. break;
  8861. String result (numBytes + 1, 0);
  8862. tchar* dest = result.text->text;
  8863. int i = 0;
  8864. while (i < numBytes)
  8865. {
  8866. const uint8 c = buffer [i++];
  8867. if ((c & 0x80) != 0)
  8868. {
  8869. int mask = 0x7f;
  8870. int bit = 0x40;
  8871. int numExtraValues = 0;
  8872. while (bit != 0 && (c & bit) != 0)
  8873. {
  8874. bit >>= 1;
  8875. mask >>= 1;
  8876. ++numExtraValues;
  8877. }
  8878. int n = (c & mask);
  8879. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  8880. {
  8881. const uint8 c = buffer[i];
  8882. if ((c & 0xc0) != 0x80)
  8883. break;
  8884. n <<= 6;
  8885. n |= (c & 0x3f);
  8886. ++i;
  8887. }
  8888. *dest++ = (tchar) n;
  8889. }
  8890. else
  8891. {
  8892. *dest++ = (tchar) c;
  8893. }
  8894. }
  8895. *dest = 0;
  8896. return result;
  8897. }
  8898. END_JUCE_NAMESPACE
  8899. /********* End of inlined file: juce_String.cpp *********/
  8900. /********* Start of inlined file: juce_StringArray.cpp *********/
  8901. BEGIN_JUCE_NAMESPACE
  8902. StringArray::StringArray() throw()
  8903. {
  8904. }
  8905. StringArray::StringArray (const StringArray& other) throw()
  8906. {
  8907. addArray (other);
  8908. }
  8909. StringArray::StringArray (const juce_wchar** const strings,
  8910. const int numberOfStrings) throw()
  8911. {
  8912. for (int i = 0; i < numberOfStrings; ++i)
  8913. add (strings [i]);
  8914. }
  8915. StringArray::StringArray (const char** const strings,
  8916. const int numberOfStrings) throw()
  8917. {
  8918. for (int i = 0; i < numberOfStrings; ++i)
  8919. add (strings [i]);
  8920. }
  8921. StringArray::StringArray (const juce_wchar** const strings) throw()
  8922. {
  8923. int i = 0;
  8924. while (strings[i] != 0)
  8925. add (strings [i++]);
  8926. }
  8927. StringArray::StringArray (const char** const strings) throw()
  8928. {
  8929. int i = 0;
  8930. while (strings[i] != 0)
  8931. add (strings [i++]);
  8932. }
  8933. const StringArray& StringArray::operator= (const StringArray& other) throw()
  8934. {
  8935. if (this != &other)
  8936. {
  8937. clear();
  8938. addArray (other);
  8939. }
  8940. return *this;
  8941. }
  8942. StringArray::~StringArray() throw()
  8943. {
  8944. clear();
  8945. }
  8946. bool StringArray::operator== (const StringArray& other) const throw()
  8947. {
  8948. if (other.size() != size())
  8949. return false;
  8950. for (int i = size(); --i >= 0;)
  8951. {
  8952. if (*(String*) other.strings.getUnchecked(i)
  8953. != *(String*) strings.getUnchecked(i))
  8954. {
  8955. return false;
  8956. }
  8957. }
  8958. return true;
  8959. }
  8960. bool StringArray::operator!= (const StringArray& other) const throw()
  8961. {
  8962. return ! operator== (other);
  8963. }
  8964. void StringArray::clear() throw()
  8965. {
  8966. for (int i = size(); --i >= 0;)
  8967. {
  8968. String* const s = (String*) strings.getUnchecked(i);
  8969. delete s;
  8970. }
  8971. strings.clear();
  8972. }
  8973. const String& StringArray::operator[] (const int index) const throw()
  8974. {
  8975. if (((unsigned int) index) < (unsigned int) strings.size())
  8976. return *(const String*) (strings.getUnchecked (index));
  8977. return String::empty;
  8978. }
  8979. void StringArray::add (const String& newString) throw()
  8980. {
  8981. strings.add (new String (newString));
  8982. }
  8983. void StringArray::insert (const int index,
  8984. const String& newString) throw()
  8985. {
  8986. strings.insert (index, new String (newString));
  8987. }
  8988. void StringArray::addIfNotAlreadyThere (const String& newString,
  8989. const bool ignoreCase) throw()
  8990. {
  8991. if (! contains (newString, ignoreCase))
  8992. add (newString);
  8993. }
  8994. void StringArray::addArray (const StringArray& otherArray,
  8995. int startIndex,
  8996. int numElementsToAdd) throw()
  8997. {
  8998. if (startIndex < 0)
  8999. {
  9000. jassertfalse
  9001. startIndex = 0;
  9002. }
  9003. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9004. numElementsToAdd = otherArray.size() - startIndex;
  9005. while (--numElementsToAdd >= 0)
  9006. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9007. }
  9008. void StringArray::set (const int index,
  9009. const String& newString) throw()
  9010. {
  9011. String* const s = (String*) strings [index];
  9012. if (s != 0)
  9013. {
  9014. *s = newString;
  9015. }
  9016. else if (index >= 0)
  9017. {
  9018. add (newString);
  9019. }
  9020. }
  9021. bool StringArray::contains (const String& stringToLookFor,
  9022. const bool ignoreCase) const throw()
  9023. {
  9024. if (ignoreCase)
  9025. {
  9026. for (int i = size(); --i >= 0;)
  9027. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9028. return true;
  9029. }
  9030. else
  9031. {
  9032. for (int i = size(); --i >= 0;)
  9033. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9034. return true;
  9035. }
  9036. return false;
  9037. }
  9038. int StringArray::indexOf (const String& stringToLookFor,
  9039. const bool ignoreCase,
  9040. int i) const throw()
  9041. {
  9042. if (i < 0)
  9043. i = 0;
  9044. const int numElements = size();
  9045. if (ignoreCase)
  9046. {
  9047. while (i < numElements)
  9048. {
  9049. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9050. return i;
  9051. ++i;
  9052. }
  9053. }
  9054. else
  9055. {
  9056. while (i < numElements)
  9057. {
  9058. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9059. return i;
  9060. ++i;
  9061. }
  9062. }
  9063. return -1;
  9064. }
  9065. void StringArray::remove (const int index) throw()
  9066. {
  9067. String* const s = (String*) strings [index];
  9068. if (s != 0)
  9069. {
  9070. strings.remove (index);
  9071. delete s;
  9072. }
  9073. }
  9074. void StringArray::removeString (const String& stringToRemove,
  9075. const bool ignoreCase) throw()
  9076. {
  9077. if (ignoreCase)
  9078. {
  9079. for (int i = size(); --i >= 0;)
  9080. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9081. remove (i);
  9082. }
  9083. else
  9084. {
  9085. for (int i = size(); --i >= 0;)
  9086. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9087. remove (i);
  9088. }
  9089. }
  9090. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9091. {
  9092. if (removeWhitespaceStrings)
  9093. {
  9094. for (int i = size(); --i >= 0;)
  9095. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9096. remove (i);
  9097. }
  9098. else
  9099. {
  9100. for (int i = size(); --i >= 0;)
  9101. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9102. remove (i);
  9103. }
  9104. }
  9105. void StringArray::trim() throw()
  9106. {
  9107. for (int i = size(); --i >= 0;)
  9108. {
  9109. String& s = *(String*) strings.getUnchecked(i);
  9110. s = s.trim();
  9111. }
  9112. }
  9113. class InternalStringArrayComparator
  9114. {
  9115. public:
  9116. static int compareElements (void* const first, void* const second) throw()
  9117. {
  9118. return ((const String*) first)->compare (*(const String*) second);
  9119. }
  9120. };
  9121. class InsensitiveInternalStringArrayComparator
  9122. {
  9123. public:
  9124. static int compareElements (void* const first, void* const second) throw()
  9125. {
  9126. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9127. }
  9128. };
  9129. void StringArray::sort (const bool ignoreCase) throw()
  9130. {
  9131. if (ignoreCase)
  9132. {
  9133. InsensitiveInternalStringArrayComparator comp;
  9134. strings.sort (comp);
  9135. }
  9136. else
  9137. {
  9138. InternalStringArrayComparator comp;
  9139. strings.sort (comp);
  9140. }
  9141. }
  9142. void StringArray::move (const int currentIndex, int newIndex) throw()
  9143. {
  9144. strings.move (currentIndex, newIndex);
  9145. }
  9146. const String StringArray::joinIntoString (const String& separator,
  9147. int start,
  9148. int numberToJoin) const throw()
  9149. {
  9150. const int last = (numberToJoin < 0) ? size()
  9151. : jmin (size(), start + numberToJoin);
  9152. if (start < 0)
  9153. start = 0;
  9154. if (start >= last)
  9155. return String::empty;
  9156. if (start == last - 1)
  9157. return *(const String*) strings.getUnchecked (start);
  9158. const int separatorLen = separator.length();
  9159. int charsNeeded = separatorLen * (last - start - 1);
  9160. for (int i = start; i < last; ++i)
  9161. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9162. String result;
  9163. result.preallocateStorage (charsNeeded);
  9164. tchar* dest = (tchar*) (const tchar*) result;
  9165. while (start < last)
  9166. {
  9167. const String& s = *(const String*) strings.getUnchecked (start);
  9168. const int len = s.length();
  9169. if (len > 0)
  9170. {
  9171. s.copyToBuffer (dest, len);
  9172. dest += len;
  9173. }
  9174. if (++start < last && separatorLen > 0)
  9175. {
  9176. separator.copyToBuffer (dest, separatorLen);
  9177. dest += separatorLen;
  9178. }
  9179. }
  9180. *dest = 0;
  9181. return result;
  9182. }
  9183. int StringArray::addTokens (const tchar* const text,
  9184. const bool preserveQuotedStrings) throw()
  9185. {
  9186. return addTokens (text,
  9187. T(" \n\r\t"),
  9188. preserveQuotedStrings ? T("\"") : 0);
  9189. }
  9190. int StringArray::addTokens (const tchar* const text,
  9191. const tchar* breakCharacters,
  9192. const tchar* quoteCharacters) throw()
  9193. {
  9194. int num = 0;
  9195. if (text != 0 && *text != 0)
  9196. {
  9197. if (breakCharacters == 0)
  9198. breakCharacters = T("");
  9199. if (quoteCharacters == 0)
  9200. quoteCharacters = T("");
  9201. bool insideQuotes = false;
  9202. tchar currentQuoteChar = 0;
  9203. int i = 0;
  9204. int tokenStart = 0;
  9205. for (;;)
  9206. {
  9207. const tchar c = text[i];
  9208. bool isBreak = (c == 0);
  9209. if (! (insideQuotes || isBreak))
  9210. {
  9211. const tchar* b = breakCharacters;
  9212. while (*b != 0)
  9213. {
  9214. if (*b++ == c)
  9215. {
  9216. isBreak = true;
  9217. break;
  9218. }
  9219. }
  9220. }
  9221. if (! isBreak)
  9222. {
  9223. bool isQuote = false;
  9224. const tchar* q = quoteCharacters;
  9225. while (*q != 0)
  9226. {
  9227. if (*q++ == c)
  9228. {
  9229. isQuote = true;
  9230. break;
  9231. }
  9232. }
  9233. if (isQuote)
  9234. {
  9235. if (insideQuotes)
  9236. {
  9237. // only break out of quotes-mode if we find a matching quote to the
  9238. // one that we opened with..
  9239. if (currentQuoteChar == c)
  9240. insideQuotes = false;
  9241. }
  9242. else
  9243. {
  9244. insideQuotes = true;
  9245. currentQuoteChar = c;
  9246. }
  9247. }
  9248. }
  9249. else
  9250. {
  9251. add (String (text + tokenStart, i - tokenStart));
  9252. ++num;
  9253. tokenStart = i + 1;
  9254. }
  9255. if (c == 0)
  9256. break;
  9257. ++i;
  9258. }
  9259. }
  9260. return num;
  9261. }
  9262. int StringArray::addLines (const tchar* text) throw()
  9263. {
  9264. int numLines = 0;
  9265. if (text != 0)
  9266. {
  9267. while (*text != 0)
  9268. {
  9269. const tchar* const startOfLine = text;
  9270. while (*text != 0)
  9271. {
  9272. if (*text == T('\r'))
  9273. {
  9274. ++text;
  9275. if (*text == T('\n'))
  9276. ++text;
  9277. break;
  9278. }
  9279. if (*text == T('\n'))
  9280. {
  9281. ++text;
  9282. break;
  9283. }
  9284. ++text;
  9285. }
  9286. const tchar* endOfLine = text;
  9287. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9288. --endOfLine;
  9289. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9290. --endOfLine;
  9291. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9292. ++numLines;
  9293. }
  9294. }
  9295. return numLines;
  9296. }
  9297. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9298. {
  9299. for (int i = 0; i < size() - 1; ++i)
  9300. {
  9301. const String& s = *(String*) strings.getUnchecked(i);
  9302. int nextIndex = i + 1;
  9303. for (;;)
  9304. {
  9305. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9306. if (nextIndex < 0)
  9307. break;
  9308. remove (nextIndex);
  9309. }
  9310. }
  9311. }
  9312. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9313. const bool appendNumberToFirstInstance,
  9314. const tchar* const preNumberString,
  9315. const tchar* const postNumberString) throw()
  9316. {
  9317. for (int i = 0; i < size() - 1; ++i)
  9318. {
  9319. String& s = *(String*) strings.getUnchecked(i);
  9320. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9321. if (nextIndex >= 0)
  9322. {
  9323. const String original (s);
  9324. int number = 0;
  9325. if (appendNumberToFirstInstance)
  9326. s = original + preNumberString + String (++number) + postNumberString;
  9327. else
  9328. ++number;
  9329. while (nextIndex >= 0)
  9330. {
  9331. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9332. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9333. }
  9334. }
  9335. }
  9336. }
  9337. void StringArray::minimiseStorageOverheads() throw()
  9338. {
  9339. strings.minimiseStorageOverheads();
  9340. }
  9341. END_JUCE_NAMESPACE
  9342. /********* End of inlined file: juce_StringArray.cpp *********/
  9343. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9344. BEGIN_JUCE_NAMESPACE
  9345. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9346. : ignoreCase (ignoreCase_)
  9347. {
  9348. }
  9349. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9350. : keys (other.keys),
  9351. values (other.values),
  9352. ignoreCase (other.ignoreCase)
  9353. {
  9354. }
  9355. StringPairArray::~StringPairArray() throw()
  9356. {
  9357. }
  9358. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9359. {
  9360. keys = other.keys;
  9361. values = other.values;
  9362. return *this;
  9363. }
  9364. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9365. {
  9366. for (int i = keys.size(); --i >= 0;)
  9367. if (other [keys[i]] != values[i])
  9368. return false;
  9369. return true;
  9370. }
  9371. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9372. {
  9373. return ! operator== (other);
  9374. }
  9375. const String& StringPairArray::operator[] (const String& key) const throw()
  9376. {
  9377. return values [keys.indexOf (key, ignoreCase)];
  9378. }
  9379. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9380. {
  9381. const int i = keys.indexOf (key, ignoreCase);
  9382. if (i >= 0)
  9383. return values[i];
  9384. return defaultReturnValue;
  9385. }
  9386. void StringPairArray::set (const String& key,
  9387. const String& value) throw()
  9388. {
  9389. const int i = keys.indexOf (key, ignoreCase);
  9390. if (i >= 0)
  9391. {
  9392. values.set (i, value);
  9393. }
  9394. else
  9395. {
  9396. keys.add (key);
  9397. values.add (value);
  9398. }
  9399. }
  9400. void StringPairArray::addArray (const StringPairArray& other)
  9401. {
  9402. for (int i = 0; i < other.size(); ++i)
  9403. set (other.keys[i], other.values[i]);
  9404. }
  9405. void StringPairArray::clear() throw()
  9406. {
  9407. keys.clear();
  9408. values.clear();
  9409. }
  9410. void StringPairArray::remove (const String& key) throw()
  9411. {
  9412. remove (keys.indexOf (key, ignoreCase));
  9413. }
  9414. void StringPairArray::remove (const int index) throw()
  9415. {
  9416. keys.remove (index);
  9417. values.remove (index);
  9418. }
  9419. void StringPairArray::minimiseStorageOverheads() throw()
  9420. {
  9421. keys.minimiseStorageOverheads();
  9422. values.minimiseStorageOverheads();
  9423. }
  9424. END_JUCE_NAMESPACE
  9425. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9426. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9427. BEGIN_JUCE_NAMESPACE
  9428. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9429. {
  9430. return CharacterFunctions::isLetterOrDigit (c)
  9431. || c == T('_')
  9432. || c == T('-')
  9433. || c == T(':')
  9434. || c == T('.');
  9435. }
  9436. #define isXmlIdentifierChar(c) \
  9437. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9438. XmlDocument::XmlDocument (const String& documentText) throw()
  9439. : originalText (documentText),
  9440. inputSource (0)
  9441. {
  9442. }
  9443. XmlDocument::XmlDocument (const File& file)
  9444. {
  9445. inputSource = new FileInputSource (file);
  9446. }
  9447. XmlDocument::~XmlDocument() throw()
  9448. {
  9449. delete inputSource;
  9450. }
  9451. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9452. {
  9453. if (inputSource != newSource)
  9454. {
  9455. delete inputSource;
  9456. inputSource = newSource;
  9457. }
  9458. }
  9459. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9460. {
  9461. String textToParse (originalText);
  9462. if (textToParse.isEmpty() && inputSource != 0)
  9463. {
  9464. InputStream* const in = inputSource->createInputStream();
  9465. if (in != 0)
  9466. {
  9467. MemoryBlock data;
  9468. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9469. delete in;
  9470. if (data.getSize() >= 2
  9471. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9472. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9473. {
  9474. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9475. }
  9476. else
  9477. {
  9478. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9479. }
  9480. if (! onlyReadOuterDocumentElement)
  9481. originalText = textToParse;
  9482. }
  9483. }
  9484. input = textToParse;
  9485. lastError = String::empty;
  9486. errorOccurred = false;
  9487. outOfData = false;
  9488. needToLoadDTD = true;
  9489. for (int i = 0; i < 128; ++i)
  9490. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9491. if (textToParse.isEmpty())
  9492. {
  9493. lastError = "not enough input";
  9494. }
  9495. else
  9496. {
  9497. skipHeader();
  9498. if (input != 0)
  9499. {
  9500. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9501. if (errorOccurred)
  9502. delete result;
  9503. else
  9504. return result;
  9505. }
  9506. else
  9507. {
  9508. lastError = "incorrect xml header";
  9509. }
  9510. }
  9511. return 0;
  9512. }
  9513. const String& XmlDocument::getLastParseError() const throw()
  9514. {
  9515. return lastError;
  9516. }
  9517. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9518. {
  9519. lastError = desc;
  9520. errorOccurred = ! carryOn;
  9521. }
  9522. const String XmlDocument::getFileContents (const String& filename) const
  9523. {
  9524. String result;
  9525. if (inputSource != 0)
  9526. {
  9527. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9528. if (in != 0)
  9529. {
  9530. result = in->readEntireStreamAsString();
  9531. delete in;
  9532. }
  9533. }
  9534. return result;
  9535. }
  9536. tchar XmlDocument::readNextChar() throw()
  9537. {
  9538. if (*input != 0)
  9539. {
  9540. return *input++;
  9541. }
  9542. else
  9543. {
  9544. outOfData = true;
  9545. return 0;
  9546. }
  9547. }
  9548. int XmlDocument::findNextTokenLength() throw()
  9549. {
  9550. int len = 0;
  9551. tchar c = *input;
  9552. while (isXmlIdentifierChar (c))
  9553. c = input [++len];
  9554. return len;
  9555. }
  9556. void XmlDocument::skipHeader() throw()
  9557. {
  9558. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9559. if (found != 0)
  9560. {
  9561. input = found;
  9562. input = CharacterFunctions::find (input, T("?>"));
  9563. if (input == 0)
  9564. return;
  9565. input += 2;
  9566. }
  9567. skipNextWhiteSpace();
  9568. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9569. if (docType == 0)
  9570. return;
  9571. input = docType + 9;
  9572. int n = 1;
  9573. while (n > 0)
  9574. {
  9575. const tchar c = readNextChar();
  9576. if (outOfData)
  9577. return;
  9578. if (c == T('<'))
  9579. ++n;
  9580. else if (c == T('>'))
  9581. --n;
  9582. }
  9583. docType += 9;
  9584. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9585. }
  9586. void XmlDocument::skipNextWhiteSpace() throw()
  9587. {
  9588. for (;;)
  9589. {
  9590. tchar c = *input;
  9591. while (CharacterFunctions::isWhitespace (c))
  9592. c = *++input;
  9593. if (c == 0)
  9594. {
  9595. outOfData = true;
  9596. break;
  9597. }
  9598. else if (c == T('<'))
  9599. {
  9600. if (input[1] == T('!')
  9601. && input[2] == T('-')
  9602. && input[3] == T('-'))
  9603. {
  9604. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  9605. if (closeComment == 0)
  9606. {
  9607. outOfData = true;
  9608. break;
  9609. }
  9610. input = closeComment + 3;
  9611. continue;
  9612. }
  9613. else if (input[1] == T('?'))
  9614. {
  9615. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  9616. if (closeBracket == 0)
  9617. {
  9618. outOfData = true;
  9619. break;
  9620. }
  9621. input = closeBracket + 2;
  9622. continue;
  9623. }
  9624. }
  9625. break;
  9626. }
  9627. }
  9628. void XmlDocument::readQuotedString (String& result) throw()
  9629. {
  9630. const tchar quote = readNextChar();
  9631. while (! outOfData)
  9632. {
  9633. const tchar character = readNextChar();
  9634. if (character == quote)
  9635. break;
  9636. if (character == T('&'))
  9637. {
  9638. --input;
  9639. readEntity (result);
  9640. }
  9641. else
  9642. {
  9643. --input;
  9644. const tchar* const start = input;
  9645. for (;;)
  9646. {
  9647. const tchar character = *input;
  9648. if (character == quote)
  9649. {
  9650. result.append (start, (int) (input - start));
  9651. ++input;
  9652. return;
  9653. }
  9654. else if (character == T('&'))
  9655. {
  9656. result.append (start, (int) (input - start));
  9657. break;
  9658. }
  9659. else if (character == 0)
  9660. {
  9661. outOfData = true;
  9662. setLastError ("unmatched quotes", false);
  9663. break;
  9664. }
  9665. ++input;
  9666. }
  9667. }
  9668. }
  9669. }
  9670. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  9671. {
  9672. XmlElement* node = 0;
  9673. skipNextWhiteSpace();
  9674. if (outOfData)
  9675. return 0;
  9676. input = CharacterFunctions::find (input, T("<"));
  9677. if (input != 0)
  9678. {
  9679. ++input;
  9680. int tagLen = findNextTokenLength();
  9681. if (tagLen == 0)
  9682. {
  9683. // no tag name - but allow for a gap after the '<' before giving an error
  9684. skipNextWhiteSpace();
  9685. tagLen = findNextTokenLength();
  9686. if (tagLen == 0)
  9687. {
  9688. setLastError ("tag name missing", false);
  9689. return node;
  9690. }
  9691. }
  9692. node = new XmlElement (input, tagLen);
  9693. input += tagLen;
  9694. XmlElement::XmlAttributeNode* lastAttribute = 0;
  9695. // look for attributes
  9696. for (;;)
  9697. {
  9698. skipNextWhiteSpace();
  9699. const tchar c = *input;
  9700. // empty tag..
  9701. if (c == T('/') && input[1] == T('>'))
  9702. {
  9703. input += 2;
  9704. break;
  9705. }
  9706. // parse the guts of the element..
  9707. if (c == T('>'))
  9708. {
  9709. ++input;
  9710. skipNextWhiteSpace();
  9711. if (alsoParseSubElements)
  9712. readChildElements (node);
  9713. break;
  9714. }
  9715. // get an attribute..
  9716. if (isXmlIdentifierChar (c))
  9717. {
  9718. const int attNameLen = findNextTokenLength();
  9719. if (attNameLen > 0)
  9720. {
  9721. const tchar* attNameStart = input;
  9722. input += attNameLen;
  9723. skipNextWhiteSpace();
  9724. if (readNextChar() == T('='))
  9725. {
  9726. skipNextWhiteSpace();
  9727. const tchar c = *input;
  9728. if (c == T('"') || c == T('\''))
  9729. {
  9730. XmlElement::XmlAttributeNode* const newAtt
  9731. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  9732. String::empty);
  9733. readQuotedString (newAtt->value);
  9734. if (lastAttribute == 0)
  9735. node->attributes = newAtt;
  9736. else
  9737. lastAttribute->next = newAtt;
  9738. lastAttribute = newAtt;
  9739. continue;
  9740. }
  9741. }
  9742. }
  9743. }
  9744. else
  9745. {
  9746. if (! outOfData)
  9747. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  9748. }
  9749. break;
  9750. }
  9751. }
  9752. return node;
  9753. }
  9754. void XmlDocument::readChildElements (XmlElement* parent) throw()
  9755. {
  9756. XmlElement* lastChildNode = 0;
  9757. for (;;)
  9758. {
  9759. skipNextWhiteSpace();
  9760. if (outOfData)
  9761. {
  9762. setLastError ("unmatched tags", false);
  9763. break;
  9764. }
  9765. if (*input == T('<'))
  9766. {
  9767. if (input[1] == T('/'))
  9768. {
  9769. // our close tag..
  9770. input = CharacterFunctions::find (input, T(">"));
  9771. ++input;
  9772. break;
  9773. }
  9774. else if (input[1] == T('!')
  9775. && input[2] == T('[')
  9776. && input[3] == T('C')
  9777. && input[4] == T('D')
  9778. && input[5] == T('A')
  9779. && input[6] == T('T')
  9780. && input[7] == T('A')
  9781. && input[8] == T('['))
  9782. {
  9783. input += 9;
  9784. const tchar* const inputStart = input;
  9785. int len = 0;
  9786. for (;;)
  9787. {
  9788. if (*input == 0)
  9789. {
  9790. setLastError ("unterminated CDATA section", false);
  9791. outOfData = true;
  9792. break;
  9793. }
  9794. else if (input[0] == T(']')
  9795. && input[1] == T(']')
  9796. && input[2] == T('>'))
  9797. {
  9798. input += 3;
  9799. break;
  9800. }
  9801. ++input;
  9802. ++len;
  9803. }
  9804. XmlElement* const e = new XmlElement ((int) 0);
  9805. e->setText (String (inputStart, len));
  9806. if (lastChildNode != 0)
  9807. lastChildNode->nextElement = e;
  9808. else
  9809. parent->addChildElement (e);
  9810. lastChildNode = e;
  9811. }
  9812. else
  9813. {
  9814. // this is some other element, so parse and add it..
  9815. XmlElement* const n = readNextElement (true);
  9816. if (n != 0)
  9817. {
  9818. if (lastChildNode == 0)
  9819. parent->addChildElement (n);
  9820. else
  9821. lastChildNode->nextElement = n;
  9822. lastChildNode = n;
  9823. }
  9824. else
  9825. {
  9826. return;
  9827. }
  9828. }
  9829. }
  9830. else
  9831. {
  9832. // read character block..
  9833. XmlElement* const e = new XmlElement ((int)0);
  9834. if (lastChildNode != 0)
  9835. lastChildNode->nextElement = e;
  9836. else
  9837. parent->addChildElement (e);
  9838. lastChildNode = e;
  9839. String textElementContent;
  9840. for (;;)
  9841. {
  9842. const tchar c = *input;
  9843. if (c == T('<'))
  9844. break;
  9845. if (c == 0)
  9846. {
  9847. setLastError ("unmatched tags", false);
  9848. outOfData = true;
  9849. return;
  9850. }
  9851. if (c == T('&'))
  9852. {
  9853. String entity;
  9854. readEntity (entity);
  9855. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  9856. {
  9857. const tchar* const oldInput = input;
  9858. const bool oldOutOfData = outOfData;
  9859. input = (const tchar*) entity;
  9860. outOfData = false;
  9861. for (;;)
  9862. {
  9863. XmlElement* const n = readNextElement (true);
  9864. if (n == 0)
  9865. break;
  9866. if (lastChildNode == 0)
  9867. parent->addChildElement (n);
  9868. else
  9869. lastChildNode->nextElement = n;
  9870. lastChildNode = n;
  9871. }
  9872. input = oldInput;
  9873. outOfData = oldOutOfData;
  9874. }
  9875. else
  9876. {
  9877. textElementContent += entity;
  9878. }
  9879. }
  9880. else
  9881. {
  9882. const tchar* start = input;
  9883. int len = 0;
  9884. for (;;)
  9885. {
  9886. const tchar c = *input;
  9887. if (c == T('<') || c == T('&'))
  9888. {
  9889. break;
  9890. }
  9891. else if (c == 0)
  9892. {
  9893. setLastError ("unmatched tags", false);
  9894. outOfData = true;
  9895. return;
  9896. }
  9897. ++input;
  9898. ++len;
  9899. }
  9900. textElementContent.append (start, len);
  9901. }
  9902. }
  9903. textElementContent = textElementContent.trim();
  9904. if (textElementContent.isNotEmpty())
  9905. e->setText (textElementContent);
  9906. }
  9907. }
  9908. }
  9909. void XmlDocument::readEntity (String& result) throw()
  9910. {
  9911. // skip over the ampersand
  9912. ++input;
  9913. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  9914. {
  9915. input += 4;
  9916. result += T("&");
  9917. }
  9918. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  9919. {
  9920. input += 5;
  9921. result += T("\"");
  9922. }
  9923. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  9924. {
  9925. input += 5;
  9926. result += T("\'");
  9927. }
  9928. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  9929. {
  9930. input += 3;
  9931. result += T("<");
  9932. }
  9933. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  9934. {
  9935. input += 3;
  9936. result += T(">");
  9937. }
  9938. else if (*input == T('#'))
  9939. {
  9940. int charCode = 0;
  9941. ++input;
  9942. if (*input == T('x') || *input == T('X'))
  9943. {
  9944. ++input;
  9945. int numChars = 0;
  9946. while (input[0] != T(';'))
  9947. {
  9948. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  9949. if (hexValue < 0 || ++numChars > 8)
  9950. {
  9951. setLastError ("illegal escape sequence", true);
  9952. break;
  9953. }
  9954. charCode = (charCode << 4) | hexValue;
  9955. ++input;
  9956. }
  9957. ++input;
  9958. }
  9959. else if (input[0] >= T('0') && input[0] <= T('9'))
  9960. {
  9961. int numChars = 0;
  9962. while (input[0] != T(';'))
  9963. {
  9964. if (++numChars > 12)
  9965. {
  9966. setLastError ("illegal escape sequence", true);
  9967. break;
  9968. }
  9969. charCode = charCode * 10 + (input[0] - T('0'));
  9970. ++input;
  9971. }
  9972. ++input;
  9973. }
  9974. else
  9975. {
  9976. setLastError ("illegal escape sequence", true);
  9977. result += T("&");
  9978. return;
  9979. }
  9980. result << (tchar) charCode;
  9981. }
  9982. else
  9983. {
  9984. const tchar* const entityNameStart = input;
  9985. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  9986. if (closingSemiColon == 0)
  9987. {
  9988. outOfData = true;
  9989. result += T("&");
  9990. }
  9991. else
  9992. {
  9993. input = closingSemiColon + 1;
  9994. result += expandExternalEntity (String (entityNameStart,
  9995. (int) (closingSemiColon - entityNameStart)));
  9996. }
  9997. }
  9998. }
  9999. const String XmlDocument::expandEntity (const String& ent)
  10000. {
  10001. if (ent.equalsIgnoreCase (T("amp")))
  10002. {
  10003. return T("&");
  10004. }
  10005. else if (ent.equalsIgnoreCase (T("quot")))
  10006. {
  10007. return T("\"");
  10008. }
  10009. else if (ent.equalsIgnoreCase (T("apos")))
  10010. {
  10011. return T("\'");
  10012. }
  10013. else if (ent.equalsIgnoreCase (T("lt")))
  10014. {
  10015. return T("<");
  10016. }
  10017. else if (ent.equalsIgnoreCase (T("gt")))
  10018. {
  10019. return T(">");
  10020. }
  10021. else if (ent[0] == T('#'))
  10022. {
  10023. if (ent[1] == T('x') || ent[1] == T('X'))
  10024. {
  10025. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10026. }
  10027. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10028. {
  10029. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10030. }
  10031. setLastError ("illegal escape sequence", false);
  10032. return T("&");
  10033. }
  10034. else
  10035. {
  10036. return expandExternalEntity (ent);
  10037. }
  10038. }
  10039. const String XmlDocument::expandExternalEntity (const String& entity)
  10040. {
  10041. if (needToLoadDTD)
  10042. {
  10043. if (dtdText.isNotEmpty())
  10044. {
  10045. while (dtdText.endsWithChar (T('>')))
  10046. dtdText = dtdText.dropLastCharacters (1);
  10047. tokenisedDTD.addTokens (dtdText, true);
  10048. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10049. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10050. {
  10051. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10052. tokenisedDTD.clear();
  10053. tokenisedDTD.addTokens (getFileContents (fn), true);
  10054. }
  10055. else
  10056. {
  10057. tokenisedDTD.clear();
  10058. const int openBracket = dtdText.indexOfChar (T('['));
  10059. if (openBracket > 0)
  10060. {
  10061. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10062. if (closeBracket > openBracket)
  10063. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10064. closeBracket), true);
  10065. }
  10066. }
  10067. for (int i = tokenisedDTD.size(); --i >= 0;)
  10068. {
  10069. if (tokenisedDTD[i].startsWithChar (T('%'))
  10070. && tokenisedDTD[i].endsWithChar (T(';')))
  10071. {
  10072. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10073. StringArray newToks;
  10074. newToks.addTokens (parsed, true);
  10075. tokenisedDTD.remove (i);
  10076. for (int j = newToks.size(); --j >= 0;)
  10077. tokenisedDTD.insert (i, newToks[j]);
  10078. }
  10079. }
  10080. }
  10081. needToLoadDTD = false;
  10082. }
  10083. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10084. {
  10085. if (tokenisedDTD[i] == entity)
  10086. {
  10087. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10088. {
  10089. String ent (tokenisedDTD [i + 1]);
  10090. while (ent.endsWithChar (T('>')))
  10091. ent = ent.dropLastCharacters (1);
  10092. ent = ent.trim().unquoted();
  10093. // check for sub-entities..
  10094. int ampersand = ent.indexOfChar (T('&'));
  10095. while (ampersand >= 0)
  10096. {
  10097. const int semiColon = ent.indexOf (i + 1, T(";"));
  10098. if (semiColon < 0)
  10099. {
  10100. setLastError ("entity without terminating semi-colon", false);
  10101. break;
  10102. }
  10103. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10104. ent = ent.substring (0, ampersand)
  10105. + resolved
  10106. + ent.substring (semiColon + 1);
  10107. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10108. }
  10109. return ent;
  10110. }
  10111. }
  10112. }
  10113. setLastError ("unknown entity", true);
  10114. return entity;
  10115. }
  10116. const String XmlDocument::getParameterEntity (const String& entity)
  10117. {
  10118. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10119. {
  10120. if (tokenisedDTD[i] == entity)
  10121. {
  10122. if (tokenisedDTD [i - 1] == T("%")
  10123. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10124. {
  10125. String ent (tokenisedDTD [i + 1]);
  10126. while (ent.endsWithChar (T('>')))
  10127. ent = ent.dropLastCharacters (1);
  10128. if (ent.equalsIgnoreCase (T("system")))
  10129. {
  10130. String filename (tokenisedDTD [i + 2]);
  10131. while (filename.endsWithChar (T('>')))
  10132. filename = filename.dropLastCharacters (1);
  10133. return getFileContents (filename);
  10134. }
  10135. else
  10136. {
  10137. return ent.trim().unquoted();
  10138. }
  10139. }
  10140. }
  10141. }
  10142. return entity;
  10143. }
  10144. END_JUCE_NAMESPACE
  10145. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10146. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10147. BEGIN_JUCE_NAMESPACE
  10148. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10149. : name (other.name),
  10150. value (other.value),
  10151. next (0)
  10152. {
  10153. }
  10154. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10155. const String& value_) throw()
  10156. : name (name_),
  10157. value (value_),
  10158. next (0)
  10159. {
  10160. }
  10161. XmlElement::XmlElement (const String& tagName_) throw()
  10162. : tagName (tagName_),
  10163. firstChildElement (0),
  10164. nextElement (0),
  10165. attributes (0)
  10166. {
  10167. // the tag name mustn't be empty, or it'll look like a text element!
  10168. jassert (tagName_.trim().isNotEmpty())
  10169. }
  10170. XmlElement::XmlElement (int /*dummy*/) throw()
  10171. : firstChildElement (0),
  10172. nextElement (0),
  10173. attributes (0)
  10174. {
  10175. }
  10176. XmlElement::XmlElement (const tchar* const tagName_,
  10177. const int nameLen) throw()
  10178. : tagName (tagName_, nameLen),
  10179. firstChildElement (0),
  10180. nextElement (0),
  10181. attributes (0)
  10182. {
  10183. }
  10184. XmlElement::XmlElement (const XmlElement& other) throw()
  10185. : tagName (other.tagName),
  10186. firstChildElement (0),
  10187. nextElement (0),
  10188. attributes (0)
  10189. {
  10190. copyChildrenAndAttributesFrom (other);
  10191. }
  10192. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10193. {
  10194. if (this != &other)
  10195. {
  10196. removeAllAttributes();
  10197. deleteAllChildElements();
  10198. tagName = other.tagName;
  10199. copyChildrenAndAttributesFrom (other);
  10200. }
  10201. return *this;
  10202. }
  10203. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10204. {
  10205. XmlElement* child = other.firstChildElement;
  10206. XmlElement* lastChild = 0;
  10207. while (child != 0)
  10208. {
  10209. XmlElement* const copiedChild = new XmlElement (*child);
  10210. if (lastChild != 0)
  10211. lastChild->nextElement = copiedChild;
  10212. else
  10213. firstChildElement = copiedChild;
  10214. lastChild = copiedChild;
  10215. child = child->nextElement;
  10216. }
  10217. const XmlAttributeNode* att = other.attributes;
  10218. XmlAttributeNode* lastAtt = 0;
  10219. while (att != 0)
  10220. {
  10221. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10222. if (lastAtt != 0)
  10223. lastAtt->next = newAtt;
  10224. else
  10225. attributes = newAtt;
  10226. lastAtt = newAtt;
  10227. att = att->next;
  10228. }
  10229. }
  10230. XmlElement::~XmlElement() throw()
  10231. {
  10232. XmlElement* child = firstChildElement;
  10233. while (child != 0)
  10234. {
  10235. XmlElement* const nextChild = child->nextElement;
  10236. delete child;
  10237. child = nextChild;
  10238. }
  10239. XmlAttributeNode* att = attributes;
  10240. while (att != 0)
  10241. {
  10242. XmlAttributeNode* const nextAtt = att->next;
  10243. delete att;
  10244. att = nextAtt;
  10245. }
  10246. }
  10247. static bool isLegalXmlChar (const juce_wchar character)
  10248. {
  10249. if ((character >= 'a' && character <= 'z')
  10250. || (character >= 'A' && character <= 'Z')
  10251. || (character >= '0' && character <= '9'))
  10252. return true;
  10253. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10254. do
  10255. {
  10256. if (((juce_wchar) (uint8) *t) == character)
  10257. return true;
  10258. }
  10259. while (*++t != 0);
  10260. return false;
  10261. }
  10262. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10263. const String& text,
  10264. const bool changeNewLines) throw()
  10265. {
  10266. const juce_wchar* t = (const juce_wchar*) text;
  10267. for (;;)
  10268. {
  10269. const juce_wchar character = *t++;
  10270. if (character == 0)
  10271. {
  10272. break;
  10273. }
  10274. else if (isLegalXmlChar (character))
  10275. {
  10276. outputStream.writeByte ((char) character);
  10277. }
  10278. else
  10279. {
  10280. switch (character)
  10281. {
  10282. case '&':
  10283. outputStream.write ("&amp;", 5);
  10284. break;
  10285. case '"':
  10286. outputStream.write ("&quot;", 6);
  10287. break;
  10288. case '>':
  10289. outputStream.write ("&gt;", 4);
  10290. break;
  10291. case '<':
  10292. outputStream.write ("&lt;", 4);
  10293. break;
  10294. case '\n':
  10295. if (changeNewLines)
  10296. outputStream.write ("&#10;", 5);
  10297. else
  10298. outputStream.writeByte ((char) character);
  10299. break;
  10300. case '\r':
  10301. if (changeNewLines)
  10302. outputStream.write ("&#13;", 5);
  10303. else
  10304. outputStream.writeByte ((char) character);
  10305. break;
  10306. default:
  10307. {
  10308. String encoded (T("&#"));
  10309. encoded << String ((int) (unsigned int) character).trim()
  10310. << T(';');
  10311. outputStream.write ((const char*) encoded, encoded.length());
  10312. }
  10313. }
  10314. }
  10315. }
  10316. }
  10317. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10318. {
  10319. if (numSpaces > 0)
  10320. {
  10321. const char* const blanks = " ";
  10322. const int blankSize = (int) sizeof (blanks) - 1;
  10323. while (numSpaces > blankSize)
  10324. {
  10325. out.write (blanks, blankSize);
  10326. numSpaces -= blankSize;
  10327. }
  10328. out.write (blanks, numSpaces);
  10329. }
  10330. }
  10331. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10332. const int indentationLevel) const throw()
  10333. {
  10334. writeSpaces (outputStream, indentationLevel);
  10335. if (! isTextElement())
  10336. {
  10337. outputStream.writeByte ('<');
  10338. const int nameLen = tagName.length();
  10339. outputStream.write ((const char*) tagName, nameLen);
  10340. const int attIndent = indentationLevel + nameLen + 1;
  10341. int lineLen = 0;
  10342. const XmlAttributeNode* att = attributes;
  10343. while (att != 0)
  10344. {
  10345. if (lineLen > 60 && indentationLevel >= 0)
  10346. {
  10347. outputStream.write ("\r\n", 2);
  10348. writeSpaces (outputStream, attIndent);
  10349. lineLen = 0;
  10350. }
  10351. const int attNameLen = att->name.length();
  10352. outputStream.writeByte (' ');
  10353. outputStream.write ((const char*) (att->name), attNameLen);
  10354. outputStream.write ("=\"", 2);
  10355. escapeIllegalXmlChars (outputStream, att->value, true);
  10356. outputStream.writeByte ('"');
  10357. lineLen += 4 + attNameLen + att->value.length();
  10358. att = att->next;
  10359. }
  10360. if (firstChildElement != 0)
  10361. {
  10362. XmlElement* child = firstChildElement;
  10363. if (child->nextElement == 0 && child->isTextElement())
  10364. {
  10365. outputStream.writeByte ('>');
  10366. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10367. }
  10368. else
  10369. {
  10370. if (indentationLevel >= 0)
  10371. outputStream.write (">\r\n", 3);
  10372. else
  10373. outputStream.writeByte ('>');
  10374. bool lastWasTextNode = false;
  10375. while (child != 0)
  10376. {
  10377. if (child->isTextElement())
  10378. {
  10379. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10380. writeSpaces (outputStream, indentationLevel + 2);
  10381. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10382. lastWasTextNode = true;
  10383. }
  10384. else
  10385. {
  10386. if (indentationLevel >= 0)
  10387. {
  10388. if (lastWasTextNode)
  10389. outputStream.write ("\r\n", 2);
  10390. child->writeElementAsText (outputStream, indentationLevel + 2);
  10391. }
  10392. else
  10393. {
  10394. child->writeElementAsText (outputStream, indentationLevel);
  10395. }
  10396. lastWasTextNode = false;
  10397. }
  10398. child = child->nextElement;
  10399. }
  10400. if (indentationLevel >= 0)
  10401. {
  10402. if (lastWasTextNode)
  10403. outputStream.write ("\r\n", 2);
  10404. writeSpaces (outputStream, indentationLevel);
  10405. }
  10406. }
  10407. outputStream.write ("</", 2);
  10408. outputStream.write ((const char*) tagName, nameLen);
  10409. if (indentationLevel >= 0)
  10410. outputStream.write (">\r\n", 3);
  10411. else
  10412. outputStream.writeByte ('>');
  10413. }
  10414. else
  10415. {
  10416. if (indentationLevel >= 0)
  10417. outputStream.write ("/>\r\n", 4);
  10418. else
  10419. outputStream.write ("/>", 2);
  10420. }
  10421. }
  10422. else
  10423. {
  10424. if (indentationLevel >= 0)
  10425. writeSpaces (outputStream, indentationLevel + 2);
  10426. escapeIllegalXmlChars (outputStream, getText(), false);
  10427. }
  10428. }
  10429. const String XmlElement::createDocument (const String& dtd,
  10430. const bool allOnOneLine,
  10431. const bool includeXmlHeader,
  10432. const tchar* const encoding) const throw()
  10433. {
  10434. String doc;
  10435. doc.preallocateStorage (1024);
  10436. if (includeXmlHeader)
  10437. {
  10438. doc << "<?xml version=\"1.0\" encoding=\""
  10439. << encoding;
  10440. if (allOnOneLine)
  10441. doc += "\"?> ";
  10442. else
  10443. doc += "\"?>\n\n";
  10444. }
  10445. if (dtd.isNotEmpty())
  10446. {
  10447. if (allOnOneLine)
  10448. doc << dtd << " ";
  10449. else
  10450. doc << dtd << "\r\n";
  10451. }
  10452. MemoryOutputStream mem (2048, 4096);
  10453. writeElementAsText (mem, allOnOneLine ? -1 : 0);
  10454. return doc + String (mem.getData(),
  10455. mem.getDataSize());
  10456. }
  10457. bool XmlElement::writeToFile (const File& f,
  10458. const String& dtd,
  10459. const tchar* const encoding) const throw()
  10460. {
  10461. if (f.hasWriteAccess())
  10462. {
  10463. const File tempFile (f.getNonexistentSibling());
  10464. FileOutputStream* const out = tempFile.createOutputStream();
  10465. if (out != 0)
  10466. {
  10467. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10468. << dtd << "\r\n";
  10469. writeElementAsText (*out, 0);
  10470. delete out;
  10471. if (tempFile.moveFileTo (f))
  10472. return true;
  10473. tempFile.deleteFile();
  10474. }
  10475. }
  10476. return false;
  10477. }
  10478. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10479. {
  10480. #ifdef JUCE_DEBUG
  10481. // if debugging, check that the case is actually the same, because
  10482. // valid xml is case-sensitive, and although this lets it pass, it's
  10483. // better not to..
  10484. if (tagName.equalsIgnoreCase (tagNameWanted))
  10485. {
  10486. jassert (tagName == tagNameWanted);
  10487. return true;
  10488. }
  10489. else
  10490. {
  10491. return false;
  10492. }
  10493. #else
  10494. return tagName.equalsIgnoreCase (tagNameWanted);
  10495. #endif
  10496. }
  10497. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10498. {
  10499. XmlElement* e = nextElement;
  10500. while (e != 0 && ! e->hasTagName (requiredTagName))
  10501. e = e->nextElement;
  10502. return e;
  10503. }
  10504. int XmlElement::getNumAttributes() const throw()
  10505. {
  10506. const XmlAttributeNode* att = attributes;
  10507. int count = 0;
  10508. while (att != 0)
  10509. {
  10510. att = att->next;
  10511. ++count;
  10512. }
  10513. return count;
  10514. }
  10515. const String& XmlElement::getAttributeName (const int index) const throw()
  10516. {
  10517. const XmlAttributeNode* att = attributes;
  10518. int count = 0;
  10519. while (att != 0)
  10520. {
  10521. if (count == index)
  10522. return att->name;
  10523. att = att->next;
  10524. ++count;
  10525. }
  10526. return String::empty;
  10527. }
  10528. const String& XmlElement::getAttributeValue (const int index) const throw()
  10529. {
  10530. const XmlAttributeNode* att = attributes;
  10531. int count = 0;
  10532. while (att != 0)
  10533. {
  10534. if (count == index)
  10535. return att->value;
  10536. att = att->next;
  10537. ++count;
  10538. }
  10539. return String::empty;
  10540. }
  10541. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10542. {
  10543. const XmlAttributeNode* att = attributes;
  10544. while (att != 0)
  10545. {
  10546. if (att->name.equalsIgnoreCase (attributeName))
  10547. return true;
  10548. att = att->next;
  10549. }
  10550. return false;
  10551. }
  10552. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10553. const tchar* const defaultReturnValue) const throw()
  10554. {
  10555. const XmlAttributeNode* att = attributes;
  10556. while (att != 0)
  10557. {
  10558. if (att->name.equalsIgnoreCase (attributeName))
  10559. return att->value;
  10560. att = att->next;
  10561. }
  10562. return defaultReturnValue;
  10563. }
  10564. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10565. const int defaultReturnValue) const throw()
  10566. {
  10567. const XmlAttributeNode* att = attributes;
  10568. while (att != 0)
  10569. {
  10570. if (att->name.equalsIgnoreCase (attributeName))
  10571. return att->value.getIntValue();
  10572. att = att->next;
  10573. }
  10574. return defaultReturnValue;
  10575. }
  10576. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10577. const double defaultReturnValue) const throw()
  10578. {
  10579. const XmlAttributeNode* att = attributes;
  10580. while (att != 0)
  10581. {
  10582. if (att->name.equalsIgnoreCase (attributeName))
  10583. return att->value.getDoubleValue();
  10584. att = att->next;
  10585. }
  10586. return defaultReturnValue;
  10587. }
  10588. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  10589. const bool defaultReturnValue) const throw()
  10590. {
  10591. const XmlAttributeNode* att = attributes;
  10592. while (att != 0)
  10593. {
  10594. if (att->name.equalsIgnoreCase (attributeName))
  10595. {
  10596. tchar firstChar = att->value[0];
  10597. if (CharacterFunctions::isWhitespace (firstChar))
  10598. firstChar = att->value.trimStart() [0];
  10599. return firstChar == T('1')
  10600. || firstChar == T('t')
  10601. || firstChar == T('y')
  10602. || firstChar == T('T')
  10603. || firstChar == T('Y');
  10604. }
  10605. att = att->next;
  10606. }
  10607. return defaultReturnValue;
  10608. }
  10609. bool XmlElement::compareAttribute (const tchar* const attributeName,
  10610. const tchar* const stringToCompareAgainst,
  10611. const bool ignoreCase) const throw()
  10612. {
  10613. const XmlAttributeNode* att = attributes;
  10614. while (att != 0)
  10615. {
  10616. if (att->name.equalsIgnoreCase (attributeName))
  10617. {
  10618. if (ignoreCase)
  10619. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  10620. else
  10621. return att->value == stringToCompareAgainst;
  10622. }
  10623. att = att->next;
  10624. }
  10625. return false;
  10626. }
  10627. void XmlElement::setAttribute (const tchar* const attributeName,
  10628. const String& value) throw()
  10629. {
  10630. #ifdef JUCE_DEBUG
  10631. // check the identifier being passed in is legal..
  10632. const tchar* t = attributeName;
  10633. while (*t != 0)
  10634. {
  10635. jassert (CharacterFunctions::isLetterOrDigit (*t)
  10636. || *t == T('_')
  10637. || *t == T('-')
  10638. || *t == T(':'));
  10639. ++t;
  10640. }
  10641. #endif
  10642. if (attributes == 0)
  10643. {
  10644. attributes = new XmlAttributeNode (attributeName, value);
  10645. }
  10646. else
  10647. {
  10648. XmlAttributeNode* att = attributes;
  10649. for (;;)
  10650. {
  10651. if (att->name.equalsIgnoreCase (attributeName))
  10652. {
  10653. att->value = value;
  10654. break;
  10655. }
  10656. else if (att->next == 0)
  10657. {
  10658. att->next = new XmlAttributeNode (attributeName, value);
  10659. break;
  10660. }
  10661. att = att->next;
  10662. }
  10663. }
  10664. }
  10665. void XmlElement::setAttribute (const tchar* const attributeName,
  10666. const tchar* const text) throw()
  10667. {
  10668. setAttribute (attributeName, String (text));
  10669. }
  10670. void XmlElement::setAttribute (const tchar* const attributeName,
  10671. const int number) throw()
  10672. {
  10673. setAttribute (attributeName, String (number));
  10674. }
  10675. void XmlElement::setAttribute (const tchar* const attributeName,
  10676. const double number) throw()
  10677. {
  10678. tchar buffer [40];
  10679. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  10680. setAttribute (attributeName, buffer);
  10681. }
  10682. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  10683. {
  10684. XmlAttributeNode* att = attributes;
  10685. XmlAttributeNode* lastAtt = 0;
  10686. while (att != 0)
  10687. {
  10688. if (att->name.equalsIgnoreCase (attributeName))
  10689. {
  10690. if (lastAtt == 0)
  10691. attributes = att->next;
  10692. else
  10693. lastAtt->next = att->next;
  10694. delete att;
  10695. break;
  10696. }
  10697. lastAtt = att;
  10698. att = att->next;
  10699. }
  10700. }
  10701. void XmlElement::removeAllAttributes() throw()
  10702. {
  10703. while (attributes != 0)
  10704. {
  10705. XmlAttributeNode* const nextAtt = attributes->next;
  10706. delete attributes;
  10707. attributes = nextAtt;
  10708. }
  10709. }
  10710. int XmlElement::getNumChildElements() const throw()
  10711. {
  10712. int count = 0;
  10713. const XmlElement* child = firstChildElement;
  10714. while (child != 0)
  10715. {
  10716. ++count;
  10717. child = child->nextElement;
  10718. }
  10719. return count;
  10720. }
  10721. XmlElement* XmlElement::getChildElement (const int index) const throw()
  10722. {
  10723. int count = 0;
  10724. XmlElement* child = firstChildElement;
  10725. while (child != 0 && count < index)
  10726. {
  10727. child = child->nextElement;
  10728. ++count;
  10729. }
  10730. return child;
  10731. }
  10732. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  10733. {
  10734. XmlElement* child = firstChildElement;
  10735. while (child != 0)
  10736. {
  10737. if (child->hasTagName (childName))
  10738. break;
  10739. child = child->nextElement;
  10740. }
  10741. return child;
  10742. }
  10743. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  10744. {
  10745. if (newNode != 0)
  10746. {
  10747. if (firstChildElement == 0)
  10748. {
  10749. firstChildElement = newNode;
  10750. }
  10751. else
  10752. {
  10753. XmlElement* child = firstChildElement;
  10754. while (child->nextElement != 0)
  10755. child = child->nextElement;
  10756. child->nextElement = newNode;
  10757. // if this is non-zero, then something's probably
  10758. // gone wrong..
  10759. jassert (newNode->nextElement == 0);
  10760. }
  10761. }
  10762. }
  10763. void XmlElement::insertChildElement (XmlElement* const newNode,
  10764. int indexToInsertAt) throw()
  10765. {
  10766. if (newNode != 0)
  10767. {
  10768. removeChildElement (newNode, false);
  10769. if (indexToInsertAt == 0)
  10770. {
  10771. newNode->nextElement = firstChildElement;
  10772. firstChildElement = newNode;
  10773. }
  10774. else
  10775. {
  10776. if (firstChildElement == 0)
  10777. {
  10778. firstChildElement = newNode;
  10779. }
  10780. else
  10781. {
  10782. if (indexToInsertAt < 0)
  10783. indexToInsertAt = INT_MAX;
  10784. XmlElement* child = firstChildElement;
  10785. while (child->nextElement != 0 && --indexToInsertAt > 0)
  10786. child = child->nextElement;
  10787. newNode->nextElement = child->nextElement;
  10788. child->nextElement = newNode;
  10789. }
  10790. }
  10791. }
  10792. }
  10793. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  10794. XmlElement* const newNode) throw()
  10795. {
  10796. if (newNode != 0)
  10797. {
  10798. XmlElement* child = firstChildElement;
  10799. XmlElement* previousNode = 0;
  10800. while (child != 0)
  10801. {
  10802. if (child == currentChildElement)
  10803. {
  10804. if (child != newNode)
  10805. {
  10806. if (previousNode == 0)
  10807. firstChildElement = newNode;
  10808. else
  10809. previousNode->nextElement = newNode;
  10810. newNode->nextElement = child->nextElement;
  10811. delete child;
  10812. }
  10813. return true;
  10814. }
  10815. previousNode = child;
  10816. child = child->nextElement;
  10817. }
  10818. }
  10819. return false;
  10820. }
  10821. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  10822. const bool shouldDeleteTheChild) throw()
  10823. {
  10824. if (childToRemove != 0)
  10825. {
  10826. if (firstChildElement == childToRemove)
  10827. {
  10828. firstChildElement = childToRemove->nextElement;
  10829. childToRemove->nextElement = 0;
  10830. }
  10831. else
  10832. {
  10833. XmlElement* child = firstChildElement;
  10834. XmlElement* last = 0;
  10835. while (child != 0)
  10836. {
  10837. if (child == childToRemove)
  10838. {
  10839. if (last == 0)
  10840. firstChildElement = child->nextElement;
  10841. else
  10842. last->nextElement = child->nextElement;
  10843. childToRemove->nextElement = 0;
  10844. break;
  10845. }
  10846. last = child;
  10847. child = child->nextElement;
  10848. }
  10849. }
  10850. if (shouldDeleteTheChild)
  10851. delete childToRemove;
  10852. }
  10853. }
  10854. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  10855. const bool ignoreOrderOfAttributes) const throw()
  10856. {
  10857. if (this != other)
  10858. {
  10859. if (other == 0 || tagName != other->tagName)
  10860. {
  10861. return false;
  10862. }
  10863. if (ignoreOrderOfAttributes)
  10864. {
  10865. int totalAtts = 0;
  10866. const XmlAttributeNode* att = attributes;
  10867. while (att != 0)
  10868. {
  10869. if (! other->compareAttribute (att->name, att->value))
  10870. return false;
  10871. att = att->next;
  10872. ++totalAtts;
  10873. }
  10874. if (totalAtts != other->getNumAttributes())
  10875. return false;
  10876. }
  10877. else
  10878. {
  10879. const XmlAttributeNode* thisAtt = attributes;
  10880. const XmlAttributeNode* otherAtt = other->attributes;
  10881. for (;;)
  10882. {
  10883. if (thisAtt == 0 || otherAtt == 0)
  10884. {
  10885. if (thisAtt == otherAtt) // both 0, so it's a match
  10886. break;
  10887. return false;
  10888. }
  10889. if (thisAtt->name != otherAtt->name
  10890. || thisAtt->value != otherAtt->value)
  10891. {
  10892. return false;
  10893. }
  10894. thisAtt = thisAtt->next;
  10895. otherAtt = otherAtt->next;
  10896. }
  10897. }
  10898. const XmlElement* thisChild = firstChildElement;
  10899. const XmlElement* otherChild = other->firstChildElement;
  10900. for (;;)
  10901. {
  10902. if (thisChild == 0 || otherChild == 0)
  10903. {
  10904. if (thisChild == otherChild) // both 0, so it's a match
  10905. break;
  10906. return false;
  10907. }
  10908. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  10909. return false;
  10910. thisChild = thisChild->nextElement;
  10911. otherChild = otherChild->nextElement;
  10912. }
  10913. }
  10914. return true;
  10915. }
  10916. void XmlElement::deleteAllChildElements() throw()
  10917. {
  10918. while (firstChildElement != 0)
  10919. {
  10920. XmlElement* const nextChild = firstChildElement->nextElement;
  10921. delete firstChildElement;
  10922. firstChildElement = nextChild;
  10923. }
  10924. }
  10925. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  10926. {
  10927. XmlElement* child = firstChildElement;
  10928. while (child != 0)
  10929. {
  10930. if (child->hasTagName (name))
  10931. {
  10932. XmlElement* const nextChild = child->nextElement;
  10933. removeChildElement (child, true);
  10934. child = nextChild;
  10935. }
  10936. else
  10937. {
  10938. child = child->nextElement;
  10939. }
  10940. }
  10941. }
  10942. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  10943. {
  10944. const XmlElement* child = firstChildElement;
  10945. while (child != 0)
  10946. {
  10947. if (child == possibleChild)
  10948. return true;
  10949. child = child->nextElement;
  10950. }
  10951. return false;
  10952. }
  10953. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  10954. {
  10955. if (this == elementToLookFor || elementToLookFor == 0)
  10956. return 0;
  10957. XmlElement* child = firstChildElement;
  10958. while (child != 0)
  10959. {
  10960. if (elementToLookFor == child)
  10961. return this;
  10962. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  10963. if (found != 0)
  10964. return found;
  10965. child = child->nextElement;
  10966. }
  10967. return 0;
  10968. }
  10969. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  10970. {
  10971. XmlElement** const elems = new XmlElement* [num];
  10972. XmlElement* e = firstChildElement;
  10973. int i = 0;
  10974. while (e != 0)
  10975. {
  10976. elems [i++] = e;
  10977. e = e->nextElement;
  10978. }
  10979. return elems;
  10980. }
  10981. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  10982. {
  10983. XmlElement* e = firstChildElement = elems[0];
  10984. for (int i = 1; i < num; ++i)
  10985. {
  10986. e->nextElement = elems[i];
  10987. e = e->nextElement;
  10988. }
  10989. e->nextElement = 0;
  10990. }
  10991. bool XmlElement::isTextElement() const throw()
  10992. {
  10993. return tagName.isEmpty();
  10994. }
  10995. static const tchar* const juce_xmltextContentAttributeName = T("text");
  10996. const String XmlElement::getText() const throw()
  10997. {
  10998. jassert (isTextElement()); // you're trying to get the text from an element that
  10999. // isn't actually a text element.. If this contains text sub-nodes, you
  11000. // can use getAllSubText instead to
  11001. return getStringAttribute (juce_xmltextContentAttributeName);
  11002. }
  11003. void XmlElement::setText (const String& newText) throw()
  11004. {
  11005. if (isTextElement())
  11006. {
  11007. setAttribute (juce_xmltextContentAttributeName, newText);
  11008. }
  11009. else
  11010. {
  11011. jassertfalse // you can only change the text in a text element, not a normal one.
  11012. }
  11013. }
  11014. const String XmlElement::getAllSubText() const throw()
  11015. {
  11016. String result;
  11017. const XmlElement* child = firstChildElement;
  11018. while (child != 0)
  11019. {
  11020. if (child->isTextElement())
  11021. result += child->getText();
  11022. child = child->nextElement;
  11023. }
  11024. return result;
  11025. }
  11026. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11027. const String& defaultReturnValue) const throw()
  11028. {
  11029. const XmlElement* const child = getChildByName (childTagName);
  11030. if (child != 0)
  11031. return child->getAllSubText();
  11032. return defaultReturnValue;
  11033. }
  11034. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11035. {
  11036. XmlElement* const e = new XmlElement ((int) 0);
  11037. e->setAttribute (juce_xmltextContentAttributeName, text);
  11038. return e;
  11039. }
  11040. void XmlElement::addTextElement (const String& text) throw()
  11041. {
  11042. addChildElement (createTextElement (text));
  11043. }
  11044. void XmlElement::deleteAllTextElements() throw()
  11045. {
  11046. XmlElement* child = firstChildElement;
  11047. while (child != 0)
  11048. {
  11049. XmlElement* const next = child->nextElement;
  11050. if (child->isTextElement())
  11051. removeChildElement (child, true);
  11052. child = next;
  11053. }
  11054. }
  11055. END_JUCE_NAMESPACE
  11056. /********* End of inlined file: juce_XmlElement.cpp *********/
  11057. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11058. BEGIN_JUCE_NAMESPACE
  11059. // (implemented in the platform-specific code files)
  11060. END_JUCE_NAMESPACE
  11061. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11062. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11063. BEGIN_JUCE_NAMESPACE
  11064. ReadWriteLock::ReadWriteLock() throw()
  11065. : numWaitingWriters (0),
  11066. numWriters (0),
  11067. writerThreadId (0)
  11068. {
  11069. }
  11070. ReadWriteLock::~ReadWriteLock() throw()
  11071. {
  11072. jassert (readerThreads.size() == 0);
  11073. jassert (numWriters == 0);
  11074. }
  11075. void ReadWriteLock::enterRead() const throw()
  11076. {
  11077. const int threadId = Thread::getCurrentThreadId();
  11078. const ScopedLock sl (accessLock);
  11079. for (;;)
  11080. {
  11081. jassert (readerThreads.size() % 2 == 0);
  11082. int i;
  11083. for (i = 0; i < readerThreads.size(); i += 2)
  11084. if (readerThreads.getUnchecked(i) == threadId)
  11085. break;
  11086. if (i < readerThreads.size()
  11087. || numWriters + numWaitingWriters == 0
  11088. || (threadId == writerThreadId && numWriters > 0))
  11089. {
  11090. if (i < readerThreads.size())
  11091. {
  11092. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11093. }
  11094. else
  11095. {
  11096. readerThreads.add (threadId);
  11097. readerThreads.add (1);
  11098. }
  11099. return;
  11100. }
  11101. const ScopedUnlock ul (accessLock);
  11102. waitEvent.wait (100);
  11103. }
  11104. }
  11105. void ReadWriteLock::exitRead() const throw()
  11106. {
  11107. const int threadId = Thread::getCurrentThreadId();
  11108. const ScopedLock sl (accessLock);
  11109. for (int i = 0; i < readerThreads.size(); i += 2)
  11110. {
  11111. if (readerThreads.getUnchecked(i) == threadId)
  11112. {
  11113. const int newCount = readerThreads.getUnchecked (i + 1) - 1;
  11114. if (newCount == 0)
  11115. {
  11116. readerThreads.removeRange (i, 2);
  11117. waitEvent.signal();
  11118. }
  11119. else
  11120. {
  11121. readerThreads.set (i + 1, newCount);
  11122. }
  11123. return;
  11124. }
  11125. }
  11126. jassertfalse // unlocking a lock that wasn't locked..
  11127. }
  11128. void ReadWriteLock::enterWrite() const throw()
  11129. {
  11130. const int threadId = Thread::getCurrentThreadId();
  11131. const ScopedLock sl (accessLock);
  11132. for (;;)
  11133. {
  11134. if (readerThreads.size() + numWriters == 0
  11135. || threadId == writerThreadId
  11136. || (readerThreads.size() == 2
  11137. && readerThreads.getUnchecked(0) == threadId))
  11138. {
  11139. writerThreadId = threadId;
  11140. ++numWriters;
  11141. break;
  11142. }
  11143. ++numWaitingWriters;
  11144. accessLock.exit();
  11145. waitEvent.wait (100);
  11146. accessLock.enter();
  11147. --numWaitingWriters;
  11148. }
  11149. }
  11150. void ReadWriteLock::exitWrite() const throw()
  11151. {
  11152. const ScopedLock sl (accessLock);
  11153. // check this thread actually had the lock..
  11154. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11155. if (--numWriters == 0)
  11156. {
  11157. writerThreadId = 0;
  11158. waitEvent.signal();
  11159. }
  11160. }
  11161. END_JUCE_NAMESPACE
  11162. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11163. /********* Start of inlined file: juce_Thread.cpp *********/
  11164. BEGIN_JUCE_NAMESPACE
  11165. // these functions are implemented in the platform-specific code.
  11166. void* juce_createThread (void* userData) throw();
  11167. void juce_killThread (void* handle) throw();
  11168. void juce_setThreadPriority (void* handle, int priority) throw();
  11169. void juce_setCurrentThreadName (const String& name) throw();
  11170. #if JUCE_WIN32
  11171. void juce_CloseThreadHandle (void* handle) throw();
  11172. #endif
  11173. static VoidArray runningThreads (4);
  11174. static CriticalSection runningThreadsLock;
  11175. void Thread::threadEntryPoint (Thread* const thread) throw()
  11176. {
  11177. runningThreadsLock.enter();
  11178. runningThreads.add (thread);
  11179. runningThreadsLock.exit();
  11180. JUCE_TRY
  11181. {
  11182. thread->threadId_ = Thread::getCurrentThreadId();
  11183. if (thread->threadName_.isNotEmpty())
  11184. juce_setCurrentThreadName (thread->threadName_);
  11185. if (thread->startSuspensionEvent_.wait (10000))
  11186. {
  11187. if (thread->affinityMask_ != 0)
  11188. setCurrentThreadAffinityMask (thread->affinityMask_);
  11189. thread->run();
  11190. }
  11191. }
  11192. JUCE_CATCH_ALL_ASSERT
  11193. runningThreadsLock.enter();
  11194. jassert (runningThreads.contains (thread));
  11195. runningThreads.removeValue (thread);
  11196. runningThreadsLock.exit();
  11197. #if JUCE_WIN32
  11198. juce_CloseThreadHandle (thread->threadHandle_);
  11199. #endif
  11200. thread->threadHandle_ = 0;
  11201. thread->threadId_ = 0;
  11202. }
  11203. // used to wrap the incoming call from the platform-specific code
  11204. void JUCE_API juce_threadEntryPoint (void* userData)
  11205. {
  11206. Thread::threadEntryPoint ((Thread*) userData);
  11207. }
  11208. Thread::Thread (const String& threadName)
  11209. : threadName_ (threadName),
  11210. threadHandle_ (0),
  11211. threadPriority_ (5),
  11212. threadId_ (0),
  11213. affinityMask_ (0),
  11214. threadShouldExit_ (false)
  11215. {
  11216. }
  11217. Thread::~Thread()
  11218. {
  11219. stopThread (100);
  11220. }
  11221. void Thread::startThread() throw()
  11222. {
  11223. const ScopedLock sl (startStopLock);
  11224. threadShouldExit_ = false;
  11225. if (threadHandle_ == 0)
  11226. {
  11227. threadHandle_ = juce_createThread ((void*) this);
  11228. juce_setThreadPriority (threadHandle_, threadPriority_);
  11229. startSuspensionEvent_.signal();
  11230. }
  11231. }
  11232. void Thread::startThread (const int priority) throw()
  11233. {
  11234. const ScopedLock sl (startStopLock);
  11235. if (threadHandle_ == 0)
  11236. {
  11237. threadPriority_ = priority;
  11238. startThread();
  11239. }
  11240. else
  11241. {
  11242. setPriority (priority);
  11243. }
  11244. }
  11245. bool Thread::isThreadRunning() const throw()
  11246. {
  11247. return threadHandle_ != 0;
  11248. }
  11249. void Thread::signalThreadShouldExit() throw()
  11250. {
  11251. threadShouldExit_ = true;
  11252. }
  11253. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11254. {
  11255. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11256. jassert (getThreadId() != getCurrentThreadId());
  11257. const int sleepMsPerIteration = 5;
  11258. int count = timeOutMilliseconds / sleepMsPerIteration;
  11259. while (isThreadRunning())
  11260. {
  11261. if (timeOutMilliseconds > 0 && --count < 0)
  11262. return false;
  11263. sleep (sleepMsPerIteration);
  11264. }
  11265. return true;
  11266. }
  11267. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11268. {
  11269. // agh! You can't stop the thread that's calling this method! How on earth
  11270. // would that work??
  11271. jassert (getCurrentThreadId() != getThreadId());
  11272. const ScopedLock sl (startStopLock);
  11273. if (isThreadRunning())
  11274. {
  11275. signalThreadShouldExit();
  11276. notify();
  11277. if (timeOutMilliseconds != 0)
  11278. waitForThreadToExit (timeOutMilliseconds);
  11279. if (isThreadRunning())
  11280. {
  11281. // very bad karma if this point is reached, as
  11282. // there are bound to be locks and events left in
  11283. // silly states when a thread is killed by force..
  11284. jassertfalse
  11285. Logger::writeToLog ("!! killing thread by force !!");
  11286. juce_killThread (threadHandle_);
  11287. threadHandle_ = 0;
  11288. threadId_ = 0;
  11289. const ScopedLock sl (runningThreadsLock);
  11290. runningThreads.removeValue (this);
  11291. }
  11292. }
  11293. }
  11294. void Thread::setPriority (const int priority) throw()
  11295. {
  11296. const ScopedLock sl (startStopLock);
  11297. threadPriority_ = priority;
  11298. juce_setThreadPriority (threadHandle_, priority);
  11299. }
  11300. void Thread::setCurrentThreadPriority (const int priority) throw()
  11301. {
  11302. juce_setThreadPriority (0, priority);
  11303. }
  11304. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11305. {
  11306. affinityMask_ = affinityMask;
  11307. }
  11308. int Thread::getThreadId() const throw()
  11309. {
  11310. return threadId_;
  11311. }
  11312. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11313. {
  11314. return defaultEvent_.wait (timeOutMilliseconds);
  11315. }
  11316. void Thread::notify() const throw()
  11317. {
  11318. defaultEvent_.signal();
  11319. }
  11320. int Thread::getNumRunningThreads() throw()
  11321. {
  11322. return runningThreads.size();
  11323. }
  11324. Thread* Thread::getCurrentThread() throw()
  11325. {
  11326. const int thisId = getCurrentThreadId();
  11327. Thread* result = 0;
  11328. runningThreadsLock.enter();
  11329. for (int i = runningThreads.size(); --i >= 0;)
  11330. {
  11331. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11332. if (t->threadId_ == thisId)
  11333. {
  11334. result = t;
  11335. break;
  11336. }
  11337. }
  11338. runningThreadsLock.exit();
  11339. return result;
  11340. }
  11341. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11342. {
  11343. runningThreadsLock.enter();
  11344. for (int i = runningThreads.size(); --i >= 0;)
  11345. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11346. runningThreadsLock.exit();
  11347. for (;;)
  11348. {
  11349. runningThreadsLock.enter();
  11350. Thread* const t = (Thread*) runningThreads[0];
  11351. runningThreadsLock.exit();
  11352. if (t == 0)
  11353. break;
  11354. t->stopThread (timeOutMilliseconds);
  11355. }
  11356. }
  11357. END_JUCE_NAMESPACE
  11358. /********* End of inlined file: juce_Thread.cpp *********/
  11359. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11360. BEGIN_JUCE_NAMESPACE
  11361. ThreadPoolJob::ThreadPoolJob (const String& name)
  11362. : jobName (name),
  11363. pool (0),
  11364. shouldStop (false),
  11365. isActive (false),
  11366. shouldBeDeleted (false)
  11367. {
  11368. }
  11369. ThreadPoolJob::~ThreadPoolJob()
  11370. {
  11371. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11372. // to remove it first!
  11373. jassert (pool == 0 || ! pool->contains (this));
  11374. }
  11375. const String ThreadPoolJob::getJobName() const
  11376. {
  11377. return jobName;
  11378. }
  11379. void ThreadPoolJob::setJobName (const String& newName)
  11380. {
  11381. jobName = newName;
  11382. }
  11383. void ThreadPoolJob::signalJobShouldExit()
  11384. {
  11385. shouldStop = true;
  11386. }
  11387. class ThreadPoolThread : public Thread
  11388. {
  11389. ThreadPool& pool;
  11390. bool volatile busy;
  11391. ThreadPoolThread (const ThreadPoolThread&);
  11392. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11393. public:
  11394. ThreadPoolThread (ThreadPool& pool_)
  11395. : Thread (T("Pool")),
  11396. pool (pool_),
  11397. busy (false)
  11398. {
  11399. }
  11400. ~ThreadPoolThread()
  11401. {
  11402. }
  11403. void run()
  11404. {
  11405. while (! threadShouldExit())
  11406. {
  11407. if (! pool.runNextJob())
  11408. wait (500);
  11409. }
  11410. }
  11411. };
  11412. ThreadPool::ThreadPool (const int numThreads_,
  11413. const bool startThreadsOnlyWhenNeeded,
  11414. const int stopThreadsWhenNotUsedTimeoutMs)
  11415. : numThreads (jmax (1, numThreads_)),
  11416. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11417. priority (5)
  11418. {
  11419. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11420. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11421. for (int i = numThreads; --i >= 0;)
  11422. {
  11423. threads[i] = new ThreadPoolThread (*this);
  11424. if (! startThreadsOnlyWhenNeeded)
  11425. threads[i]->startThread();
  11426. }
  11427. }
  11428. ThreadPool::~ThreadPool()
  11429. {
  11430. removeAllJobs (true, 4000);
  11431. int i;
  11432. for (i = numThreads; --i >= 0;)
  11433. threads[i]->signalThreadShouldExit();
  11434. for (i = numThreads; --i >= 0;)
  11435. {
  11436. threads[i]->stopThread (500);
  11437. delete threads[i];
  11438. }
  11439. juce_free (threads);
  11440. }
  11441. void ThreadPool::addJob (ThreadPoolJob* const job)
  11442. {
  11443. jassert (job->pool == 0);
  11444. if (job->pool == 0)
  11445. {
  11446. job->pool = this;
  11447. job->shouldStop = false;
  11448. job->isActive = false;
  11449. lock.enter();
  11450. jobs.add (job);
  11451. int numRunning = 0;
  11452. int i;
  11453. for (i = numThreads; --i >= 0;)
  11454. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11455. ++numRunning;
  11456. if (numRunning < numThreads)
  11457. {
  11458. bool startedOne = false;
  11459. int n = 1000;
  11460. while (--n >= 0 && ! startedOne)
  11461. {
  11462. for (int i = numThreads; --i >= 0;)
  11463. {
  11464. if (! threads[i]->isThreadRunning())
  11465. {
  11466. threads[i]->startThread();
  11467. startedOne = true;
  11468. }
  11469. }
  11470. if (! startedOne)
  11471. Thread::sleep (5);
  11472. }
  11473. }
  11474. lock.exit();
  11475. for (i = numThreads; --i >= 0;)
  11476. threads[i]->notify();
  11477. }
  11478. }
  11479. int ThreadPool::getNumJobs() const throw()
  11480. {
  11481. return jobs.size();
  11482. }
  11483. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11484. {
  11485. const ScopedLock sl (lock);
  11486. return (ThreadPoolJob*) jobs [index];
  11487. }
  11488. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11489. {
  11490. const ScopedLock sl (lock);
  11491. return jobs.contains ((void*) job);
  11492. }
  11493. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11494. {
  11495. const ScopedLock sl (lock);
  11496. return jobs.contains ((void*) job) && job->isActive;
  11497. }
  11498. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11499. const int timeOutMs) const
  11500. {
  11501. if (job != 0)
  11502. {
  11503. const uint32 start = Time::getMillisecondCounter();
  11504. while (contains (job))
  11505. {
  11506. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11507. return false;
  11508. Thread::sleep (2);
  11509. }
  11510. }
  11511. return true;
  11512. }
  11513. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11514. const bool interruptIfRunning,
  11515. const int timeOutMs)
  11516. {
  11517. if (job != 0)
  11518. {
  11519. lock.enter();
  11520. if (jobs.contains (job))
  11521. {
  11522. if (job->isActive)
  11523. {
  11524. if (interruptIfRunning)
  11525. job->signalJobShouldExit();
  11526. lock.exit();
  11527. return waitForJobToFinish (job, timeOutMs);
  11528. }
  11529. else
  11530. {
  11531. jobs.removeValue (job);
  11532. }
  11533. }
  11534. lock.exit();
  11535. }
  11536. return true;
  11537. }
  11538. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11539. const int timeOutMs)
  11540. {
  11541. lock.enter();
  11542. for (int i = jobs.size(); --i >= 0;)
  11543. {
  11544. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11545. if (job->isActive)
  11546. {
  11547. if (interruptRunningJobs)
  11548. job->signalJobShouldExit();
  11549. }
  11550. else
  11551. {
  11552. jobs.remove (i);
  11553. }
  11554. }
  11555. lock.exit();
  11556. const uint32 start = Time::getMillisecondCounter();
  11557. while (jobs.size() > 0)
  11558. {
  11559. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11560. return false;
  11561. Thread::sleep (2);
  11562. }
  11563. return true;
  11564. }
  11565. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11566. {
  11567. StringArray s;
  11568. const ScopedLock sl (lock);
  11569. for (int i = 0; i < jobs.size(); ++i)
  11570. {
  11571. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  11572. if (job->isActive || ! onlyReturnActiveJobs)
  11573. s.add (job->getJobName());
  11574. }
  11575. return s;
  11576. }
  11577. void ThreadPool::setThreadPriorities (const int newPriority)
  11578. {
  11579. if (priority != newPriority)
  11580. {
  11581. priority = newPriority;
  11582. for (int i = numThreads; --i >= 0;)
  11583. threads[i]->setPriority (newPriority);
  11584. }
  11585. }
  11586. bool ThreadPool::runNextJob()
  11587. {
  11588. lock.enter();
  11589. ThreadPoolJob* job = 0;
  11590. for (int i = 0; i < jobs.size(); ++i)
  11591. {
  11592. job = (ThreadPoolJob*) jobs [i];
  11593. if (job != 0 && ! (job->isActive || job->shouldStop))
  11594. break;
  11595. job = 0;
  11596. }
  11597. if (job != 0)
  11598. {
  11599. job->isActive = true;
  11600. lock.exit();
  11601. JUCE_TRY
  11602. {
  11603. ThreadPoolJob::JobStatus result = job->runJob();
  11604. lastJobEndTime = Time::getApproximateMillisecondCounter();
  11605. const ScopedLock sl (lock);
  11606. if (jobs.contains (job))
  11607. {
  11608. job->isActive = false;
  11609. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  11610. {
  11611. job->pool = 0;
  11612. job->shouldStop = true;
  11613. jobs.removeValue (job);
  11614. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  11615. delete job;
  11616. }
  11617. else
  11618. {
  11619. // move the job to the end of the queue if it wants another go
  11620. jobs.move (jobs.indexOf (job), -1);
  11621. }
  11622. }
  11623. }
  11624. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11625. catch (...)
  11626. {
  11627. lock.enter();
  11628. jobs.removeValue (job);
  11629. lock.exit();
  11630. }
  11631. #endif
  11632. }
  11633. else
  11634. {
  11635. lock.exit();
  11636. if (threadStopTimeout > 0
  11637. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  11638. {
  11639. lock.enter();
  11640. if (jobs.size() == 0)
  11641. {
  11642. for (int i = numThreads; --i >= 0;)
  11643. threads[i]->signalThreadShouldExit();
  11644. }
  11645. lock.exit();
  11646. }
  11647. else
  11648. {
  11649. return false;
  11650. }
  11651. }
  11652. return true;
  11653. }
  11654. END_JUCE_NAMESPACE
  11655. /********* End of inlined file: juce_ThreadPool.cpp *********/
  11656. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  11657. BEGIN_JUCE_NAMESPACE
  11658. TimeSliceThread::TimeSliceThread (const String& threadName)
  11659. : Thread (threadName),
  11660. index (0),
  11661. clientBeingCalled (0),
  11662. clientsChanged (false)
  11663. {
  11664. }
  11665. TimeSliceThread::~TimeSliceThread()
  11666. {
  11667. stopThread (2000);
  11668. }
  11669. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  11670. {
  11671. const ScopedLock sl (listLock);
  11672. clients.addIfNotAlreadyThere (client);
  11673. clientsChanged = true;
  11674. notify();
  11675. }
  11676. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  11677. {
  11678. const ScopedLock sl1 (listLock);
  11679. clientsChanged = true;
  11680. // if there's a chance we're in the middle of calling this client, we need to
  11681. // also lock the outer lock..
  11682. if (clientBeingCalled == client)
  11683. {
  11684. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  11685. const ScopedLock sl1 (callbackLock);
  11686. const ScopedLock sl2 (listLock);
  11687. clients.removeValue (client);
  11688. }
  11689. else
  11690. {
  11691. clients.removeValue (client);
  11692. }
  11693. }
  11694. int TimeSliceThread::getNumClients() const throw()
  11695. {
  11696. return clients.size();
  11697. }
  11698. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  11699. {
  11700. const ScopedLock sl (listLock);
  11701. return clients [index];
  11702. }
  11703. void TimeSliceThread::run()
  11704. {
  11705. int numCallsSinceBusy = 0;
  11706. while (! threadShouldExit())
  11707. {
  11708. int timeToWait = 500;
  11709. {
  11710. const ScopedLock sl (callbackLock);
  11711. {
  11712. const ScopedLock sl (listLock);
  11713. if (clients.size() > 0)
  11714. {
  11715. index = (index + 1) % clients.size();
  11716. clientBeingCalled = clients [index];
  11717. }
  11718. else
  11719. {
  11720. index = 0;
  11721. clientBeingCalled = 0;
  11722. }
  11723. if (clientsChanged)
  11724. {
  11725. clientsChanged = false;
  11726. numCallsSinceBusy = 0;
  11727. }
  11728. }
  11729. if (clientBeingCalled != 0)
  11730. {
  11731. if (clientBeingCalled->useTimeSlice())
  11732. numCallsSinceBusy = 0;
  11733. else
  11734. ++numCallsSinceBusy;
  11735. if (numCallsSinceBusy >= clients.size())
  11736. timeToWait = 500;
  11737. else if (index == 0)
  11738. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  11739. else
  11740. timeToWait = 0;
  11741. }
  11742. }
  11743. if (timeToWait > 0)
  11744. wait (timeToWait);
  11745. }
  11746. }
  11747. END_JUCE_NAMESPACE
  11748. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  11749. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11750. /********* Start of inlined file: juce_Application.cpp *********/
  11751. #if JUCE_MSVC
  11752. #pragma warning (push)
  11753. #pragma warning (disable: 4245 4514 4100)
  11754. #include <crtdbg.h>
  11755. #pragma warning (pop)
  11756. #endif
  11757. BEGIN_JUCE_NAMESPACE
  11758. void juce_setCurrentExecutableFileName (const String& filename) throw();
  11759. void juce_setCurrentThreadName (const String& name) throw();
  11760. static JUCEApplication* appInstance = 0;
  11761. JUCEApplication::JUCEApplication()
  11762. : appReturnValue (0),
  11763. stillInitialising (true)
  11764. {
  11765. }
  11766. JUCEApplication::~JUCEApplication()
  11767. {
  11768. }
  11769. JUCEApplication* JUCEApplication::getInstance() throw()
  11770. {
  11771. return appInstance;
  11772. }
  11773. bool JUCEApplication::isInitialising() const throw()
  11774. {
  11775. return stillInitialising;
  11776. }
  11777. const String JUCEApplication::getApplicationVersion()
  11778. {
  11779. return String::empty;
  11780. }
  11781. bool JUCEApplication::moreThanOneInstanceAllowed()
  11782. {
  11783. return true;
  11784. }
  11785. void JUCEApplication::anotherInstanceStarted (const String&)
  11786. {
  11787. }
  11788. void JUCEApplication::systemRequestedQuit()
  11789. {
  11790. quit();
  11791. }
  11792. void JUCEApplication::quit (const bool useMaximumForce)
  11793. {
  11794. MessageManager::getInstance()->postQuitMessage (useMaximumForce);
  11795. }
  11796. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  11797. {
  11798. appReturnValue = newReturnValue;
  11799. }
  11800. void JUCEApplication::unhandledException (const std::exception*,
  11801. const String&,
  11802. const int)
  11803. {
  11804. jassertfalse
  11805. }
  11806. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  11807. const char* const sourceFile,
  11808. const int lineNumber)
  11809. {
  11810. if (appInstance != 0)
  11811. appInstance->unhandledException (e, sourceFile, lineNumber);
  11812. }
  11813. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  11814. {
  11815. return 0;
  11816. }
  11817. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  11818. {
  11819. commands.add (StandardApplicationCommandIDs::quit);
  11820. }
  11821. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  11822. {
  11823. if (commandID == StandardApplicationCommandIDs::quit)
  11824. {
  11825. result.setInfo ("Quit",
  11826. "Quits the application",
  11827. "Application",
  11828. 0);
  11829. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  11830. }
  11831. }
  11832. bool JUCEApplication::perform (const InvocationInfo& info)
  11833. {
  11834. if (info.commandID == StandardApplicationCommandIDs::quit)
  11835. {
  11836. systemRequestedQuit();
  11837. return true;
  11838. }
  11839. return false;
  11840. }
  11841. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  11842. {
  11843. jassert (appInstance == 0);
  11844. appInstance = app;
  11845. bool useForce = true;
  11846. initialiseJuce_GUI();
  11847. InterProcessLock* appLock = 0;
  11848. if (! app->moreThanOneInstanceAllowed())
  11849. {
  11850. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  11851. if (! appLock->enter(0))
  11852. {
  11853. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  11854. delete appInstance;
  11855. appInstance = 0;
  11856. commandLine = String::empty;
  11857. DBG ("Another instance is running - quitting...");
  11858. return 0;
  11859. }
  11860. }
  11861. JUCE_TRY
  11862. {
  11863. juce_setCurrentThreadName ("Juce Message Thread");
  11864. // let the app do its setting-up..
  11865. app->initialise (commandLine.trim());
  11866. commandLine = String::empty;
  11867. // register for broadcast new app messages
  11868. MessageManager::getInstance()->registerBroadcastListener (app);
  11869. app->stillInitialising = false;
  11870. // now loop until a quit message is received..
  11871. useForce = MessageManager::getInstance()->runDispatchLoop();
  11872. MessageManager::getInstance()->deregisterBroadcastListener (app);
  11873. if (appLock != 0)
  11874. {
  11875. appLock->exit();
  11876. delete appLock;
  11877. }
  11878. }
  11879. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11880. catch (const std::exception& e)
  11881. {
  11882. app->unhandledException (&e, __FILE__, __LINE__);
  11883. }
  11884. catch (...)
  11885. {
  11886. app->unhandledException (0, __FILE__, __LINE__);
  11887. }
  11888. #endif
  11889. return shutdownAppAndClearUp (useForce);
  11890. }
  11891. int JUCEApplication::shutdownAppAndClearUp (const bool useMaximumForce)
  11892. {
  11893. jassert (appInstance != 0);
  11894. JUCEApplication* const app = appInstance;
  11895. int returnValue = 0;
  11896. static bool reentrancyCheck = false;
  11897. if (! reentrancyCheck)
  11898. {
  11899. reentrancyCheck = true;
  11900. JUCE_TRY
  11901. {
  11902. // give the app a chance to clean up..
  11903. app->shutdown();
  11904. }
  11905. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11906. catch (const std::exception& e)
  11907. {
  11908. app->unhandledException (&e, __FILE__, __LINE__);
  11909. }
  11910. catch (...)
  11911. {
  11912. app->unhandledException (0, __FILE__, __LINE__);
  11913. }
  11914. #endif
  11915. JUCE_TRY
  11916. {
  11917. shutdownJuce_GUI();
  11918. returnValue = app->getApplicationReturnValue();
  11919. appInstance = 0;
  11920. delete app;
  11921. }
  11922. JUCE_CATCH_ALL_ASSERT
  11923. if (useMaximumForce)
  11924. {
  11925. Process::terminate();
  11926. }
  11927. reentrancyCheck = false;
  11928. }
  11929. return returnValue;
  11930. }
  11931. int JUCEApplication::main (int argc, char* argv[],
  11932. JUCEApplication* const newApp)
  11933. {
  11934. juce_setCurrentExecutableFileName (argv[0]);
  11935. String cmd;
  11936. for (int i = 1; i < argc; ++i)
  11937. cmd << argv[i] << T(' ');
  11938. return JUCEApplication::main (cmd, newApp);
  11939. }
  11940. void JUCEApplication::actionListenerCallback (const String& message)
  11941. {
  11942. if (message.startsWith (getApplicationName() + "/"))
  11943. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  11944. }
  11945. static bool juceInitialisedGUI = false;
  11946. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  11947. {
  11948. if (! juceInitialisedGUI)
  11949. {
  11950. juceInitialisedGUI = true;
  11951. initialiseJuce_NonGUI();
  11952. MessageManager::getInstance();
  11953. Font::initialiseDefaultFontNames();
  11954. LookAndFeel::setDefaultLookAndFeel (0);
  11955. #if JUCE_WIN32 && JUCE_DEBUG
  11956. // This section is just for catching people who mess up their project settings and
  11957. // turn RTTI off..
  11958. try
  11959. {
  11960. TextButton tb (String::empty);
  11961. Component* c = &tb;
  11962. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  11963. c = dynamic_cast <Button*> (c);
  11964. }
  11965. catch (...)
  11966. {
  11967. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  11968. // got as far as this catch statement, then why haven't you got exception catching
  11969. // turned on in the debugger???
  11970. jassertfalse
  11971. }
  11972. #endif
  11973. }
  11974. }
  11975. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  11976. {
  11977. if (juceInitialisedGUI)
  11978. {
  11979. DeletedAtShutdown::deleteAll();
  11980. LookAndFeel::clearDefaultLookAndFeel();
  11981. shutdownJuce_NonGUI();
  11982. juceInitialisedGUI = false;
  11983. }
  11984. }
  11985. END_JUCE_NAMESPACE
  11986. /********* End of inlined file: juce_Application.cpp *********/
  11987. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  11988. BEGIN_JUCE_NAMESPACE
  11989. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  11990. : commandID (commandID_),
  11991. flags (0)
  11992. {
  11993. }
  11994. void ApplicationCommandInfo::setInfo (const String& shortName_,
  11995. const String& description_,
  11996. const String& categoryName_,
  11997. const int flags_) throw()
  11998. {
  11999. shortName = shortName_;
  12000. description = description_;
  12001. categoryName = categoryName_;
  12002. flags = flags_;
  12003. }
  12004. void ApplicationCommandInfo::setActive (const bool b) throw()
  12005. {
  12006. if (b)
  12007. flags &= ~isDisabled;
  12008. else
  12009. flags |= isDisabled;
  12010. }
  12011. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12012. {
  12013. if (b)
  12014. flags |= isTicked;
  12015. else
  12016. flags &= ~isTicked;
  12017. }
  12018. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12019. {
  12020. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12021. }
  12022. END_JUCE_NAMESPACE
  12023. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12024. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12025. BEGIN_JUCE_NAMESPACE
  12026. ApplicationCommandManager::ApplicationCommandManager()
  12027. : listeners (8),
  12028. firstTarget (0)
  12029. {
  12030. keyMappings = new KeyPressMappingSet (this);
  12031. Desktop::getInstance().addFocusChangeListener (this);
  12032. }
  12033. ApplicationCommandManager::~ApplicationCommandManager()
  12034. {
  12035. Desktop::getInstance().removeFocusChangeListener (this);
  12036. deleteAndZero (keyMappings);
  12037. }
  12038. void ApplicationCommandManager::clearCommands()
  12039. {
  12040. commands.clear();
  12041. keyMappings->clearAllKeyPresses();
  12042. triggerAsyncUpdate();
  12043. }
  12044. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12045. {
  12046. // zero isn't a valid command ID!
  12047. jassert (newCommand.commandID != 0);
  12048. // the name isn't optional!
  12049. jassert (newCommand.shortName.isNotEmpty());
  12050. if (getCommandForID (newCommand.commandID) == 0)
  12051. {
  12052. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12053. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12054. commands.add (newInfo);
  12055. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12056. triggerAsyncUpdate();
  12057. }
  12058. else
  12059. {
  12060. // trying to re-register the same command with different parameters?
  12061. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12062. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12063. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12064. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12065. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12066. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12067. }
  12068. }
  12069. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12070. {
  12071. if (target != 0)
  12072. {
  12073. Array <CommandID> commandIDs;
  12074. target->getAllCommands (commandIDs);
  12075. for (int i = 0; i < commandIDs.size(); ++i)
  12076. {
  12077. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12078. target->getCommandInfo (info.commandID, info);
  12079. registerCommand (info);
  12080. }
  12081. }
  12082. }
  12083. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12084. {
  12085. for (int i = commands.size(); --i >= 0;)
  12086. {
  12087. if (commands.getUnchecked (i)->commandID == commandID)
  12088. {
  12089. commands.remove (i);
  12090. triggerAsyncUpdate();
  12091. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12092. for (int j = keys.size(); --j >= 0;)
  12093. keyMappings->removeKeyPress (keys.getReference (j));
  12094. }
  12095. }
  12096. }
  12097. void ApplicationCommandManager::commandStatusChanged()
  12098. {
  12099. triggerAsyncUpdate();
  12100. }
  12101. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12102. {
  12103. for (int i = commands.size(); --i >= 0;)
  12104. if (commands.getUnchecked(i)->commandID == commandID)
  12105. return commands.getUnchecked(i);
  12106. return 0;
  12107. }
  12108. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12109. {
  12110. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12111. return (ci != 0) ? ci->shortName : String::empty;
  12112. }
  12113. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12114. {
  12115. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12116. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12117. : String::empty;
  12118. }
  12119. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12120. {
  12121. StringArray s;
  12122. for (int i = 0; i < commands.size(); ++i)
  12123. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12124. return s;
  12125. }
  12126. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12127. {
  12128. Array <CommandID> results (4);
  12129. for (int i = 0; i < commands.size(); ++i)
  12130. if (commands.getUnchecked(i)->categoryName == categoryName)
  12131. results.add (commands.getUnchecked(i)->commandID);
  12132. return results;
  12133. }
  12134. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12135. {
  12136. ApplicationCommandTarget::InvocationInfo info (commandID);
  12137. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12138. return invoke (info, asynchronously);
  12139. }
  12140. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12141. {
  12142. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12143. // manager first..
  12144. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12145. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12146. if (target == 0)
  12147. return false;
  12148. ApplicationCommandInfo commandInfo (0);
  12149. target->getCommandInfo (info_.commandID, commandInfo);
  12150. ApplicationCommandTarget::InvocationInfo info (info_);
  12151. info.commandFlags = commandInfo.flags;
  12152. sendListenerInvokeCallback (info);
  12153. const bool ok = target->invoke (info, asynchronously);
  12154. commandStatusChanged();
  12155. return ok;
  12156. }
  12157. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12158. {
  12159. return firstTarget != 0 ? firstTarget
  12160. : findDefaultComponentTarget();
  12161. }
  12162. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12163. {
  12164. firstTarget = newTarget;
  12165. }
  12166. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12167. ApplicationCommandInfo& upToDateInfo)
  12168. {
  12169. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12170. if (target == 0)
  12171. target = JUCEApplication::getInstance();
  12172. if (target != 0)
  12173. target = target->getTargetForCommand (commandID);
  12174. if (target != 0)
  12175. target->getCommandInfo (commandID, upToDateInfo);
  12176. return target;
  12177. }
  12178. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12179. {
  12180. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12181. if (target == 0 && c != 0)
  12182. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12183. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12184. return target;
  12185. }
  12186. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12187. {
  12188. Component* c = Component::getCurrentlyFocusedComponent();
  12189. if (c == 0)
  12190. {
  12191. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12192. if (activeWindow != 0)
  12193. {
  12194. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12195. if (c == 0)
  12196. c = activeWindow;
  12197. }
  12198. }
  12199. if (c == 0)
  12200. {
  12201. // getting a bit desperate now - try all desktop comps..
  12202. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12203. {
  12204. ApplicationCommandTarget* const target
  12205. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12206. ->getPeer()->getLastFocusedSubcomponent());
  12207. if (target != 0)
  12208. return target;
  12209. }
  12210. }
  12211. if (c != 0)
  12212. {
  12213. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12214. // if we're focused on a ResizableWindow, chances are that it's the content
  12215. // component that really should get the event. And if not, the event will
  12216. // still be passed up to the top level window anyway, so let's send it to the
  12217. // content comp.
  12218. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12219. c = resizableWindow->getContentComponent();
  12220. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12221. if (target != 0)
  12222. return target;
  12223. }
  12224. return JUCEApplication::getInstance();
  12225. }
  12226. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12227. {
  12228. jassert (listener != 0);
  12229. if (listener != 0)
  12230. listeners.add (listener);
  12231. }
  12232. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12233. {
  12234. listeners.removeValue (listener);
  12235. }
  12236. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12237. {
  12238. for (int i = listeners.size(); --i >= 0;)
  12239. {
  12240. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12241. i = jmin (i, listeners.size());
  12242. }
  12243. }
  12244. void ApplicationCommandManager::handleAsyncUpdate()
  12245. {
  12246. for (int i = listeners.size(); --i >= 0;)
  12247. {
  12248. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12249. i = jmin (i, listeners.size());
  12250. }
  12251. }
  12252. void ApplicationCommandManager::globalFocusChanged (Component*)
  12253. {
  12254. commandStatusChanged();
  12255. }
  12256. END_JUCE_NAMESPACE
  12257. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12258. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12259. BEGIN_JUCE_NAMESPACE
  12260. ApplicationCommandTarget::ApplicationCommandTarget()
  12261. : messageInvoker (0)
  12262. {
  12263. }
  12264. ApplicationCommandTarget::~ApplicationCommandTarget()
  12265. {
  12266. deleteAndZero (messageInvoker);
  12267. }
  12268. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12269. {
  12270. if (isCommandActive (info.commandID))
  12271. {
  12272. if (async)
  12273. {
  12274. if (messageInvoker == 0)
  12275. messageInvoker = new CommandTargetMessageInvoker (this);
  12276. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12277. return true;
  12278. }
  12279. else
  12280. {
  12281. const bool success = perform (info);
  12282. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12283. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12284. // returns the command's info.
  12285. return success;
  12286. }
  12287. }
  12288. return false;
  12289. }
  12290. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12291. {
  12292. Component* c = dynamic_cast <Component*> (this);
  12293. if (c != 0)
  12294. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12295. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12296. return 0;
  12297. }
  12298. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12299. {
  12300. ApplicationCommandTarget* target = this;
  12301. int depth = 0;
  12302. while (target != 0)
  12303. {
  12304. Array <CommandID> commandIDs;
  12305. target->getAllCommands (commandIDs);
  12306. if (commandIDs.contains (commandID))
  12307. return target;
  12308. target = target->getNextCommandTarget();
  12309. ++depth;
  12310. jassert (depth < 100); // could be a recursive command chain??
  12311. jassert (target != this); // definitely a recursive command chain!
  12312. if (depth > 100 || target == this)
  12313. break;
  12314. }
  12315. if (target == 0)
  12316. {
  12317. target = JUCEApplication::getInstance();
  12318. if (target != 0)
  12319. {
  12320. Array <CommandID> commandIDs;
  12321. target->getAllCommands (commandIDs);
  12322. if (commandIDs.contains (commandID))
  12323. return target;
  12324. }
  12325. }
  12326. return 0;
  12327. }
  12328. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12329. {
  12330. ApplicationCommandInfo info (commandID);
  12331. info.flags = ApplicationCommandInfo::isDisabled;
  12332. getCommandInfo (commandID, info);
  12333. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12334. }
  12335. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12336. {
  12337. ApplicationCommandTarget* target = this;
  12338. int depth = 0;
  12339. while (target != 0)
  12340. {
  12341. if (target->tryToInvoke (info, async))
  12342. return true;
  12343. target = target->getNextCommandTarget();
  12344. ++depth;
  12345. jassert (depth < 100); // could be a recursive command chain??
  12346. jassert (target != this); // definitely a recursive command chain!
  12347. if (depth > 100 || target == this)
  12348. break;
  12349. }
  12350. if (target == 0)
  12351. {
  12352. target = JUCEApplication::getInstance();
  12353. if (target != 0)
  12354. return target->tryToInvoke (info, async);
  12355. }
  12356. return false;
  12357. }
  12358. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12359. {
  12360. ApplicationCommandTarget::InvocationInfo info (commandID);
  12361. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12362. return invoke (info, asynchronously);
  12363. }
  12364. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12365. : commandID (commandID_),
  12366. commandFlags (0),
  12367. invocationMethod (direct),
  12368. originatingComponent (0),
  12369. isKeyDown (false),
  12370. millisecsSinceKeyPressed (0)
  12371. {
  12372. }
  12373. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12374. : owner (owner_)
  12375. {
  12376. }
  12377. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12378. {
  12379. }
  12380. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12381. {
  12382. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12383. owner->tryToInvoke (*info, false);
  12384. delete info;
  12385. }
  12386. END_JUCE_NAMESPACE
  12387. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12388. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12389. BEGIN_JUCE_NAMESPACE
  12390. juce_ImplementSingleton (ApplicationProperties)
  12391. ApplicationProperties::ApplicationProperties() throw()
  12392. : userProps (0),
  12393. commonProps (0),
  12394. msBeforeSaving (3000),
  12395. options (PropertiesFile::storeAsBinary),
  12396. commonSettingsAreReadOnly (0)
  12397. {
  12398. }
  12399. ApplicationProperties::~ApplicationProperties()
  12400. {
  12401. closeFiles();
  12402. clearSingletonInstance();
  12403. }
  12404. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12405. const String& fileNameSuffix,
  12406. const String& folderName_,
  12407. const int millisecondsBeforeSaving,
  12408. const int propertiesFileOptions) throw()
  12409. {
  12410. appName = applicationName;
  12411. fileSuffix = fileNameSuffix;
  12412. folderName = folderName_;
  12413. msBeforeSaving = millisecondsBeforeSaving;
  12414. options = propertiesFileOptions;
  12415. }
  12416. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12417. const bool testCommonSettings,
  12418. const bool showWarningDialogOnFailure)
  12419. {
  12420. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12421. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12422. if (! (userOk && commonOk))
  12423. {
  12424. if (showWarningDialogOnFailure)
  12425. {
  12426. String filenames;
  12427. if (userProps != 0 && ! userOk)
  12428. filenames << '\n' << userProps->getFile().getFullPathName();
  12429. if (commonProps != 0 && ! commonOk)
  12430. filenames << '\n' << commonProps->getFile().getFullPathName();
  12431. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12432. appName + TRANS(" - Unable to save settings"),
  12433. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12434. + appName + TRANS(" needs to be able to write to the following files:\n")
  12435. + filenames
  12436. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12437. }
  12438. return false;
  12439. }
  12440. return true;
  12441. }
  12442. void ApplicationProperties::openFiles() throw()
  12443. {
  12444. // You need to call setStorageParameters() before trying to get hold of the
  12445. // properties!
  12446. jassert (appName.isNotEmpty());
  12447. if (appName.isNotEmpty())
  12448. {
  12449. if (userProps == 0)
  12450. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12451. false, msBeforeSaving, options);
  12452. if (commonProps == 0)
  12453. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12454. true, msBeforeSaving, options);
  12455. userProps->setFallbackPropertySet (commonProps);
  12456. }
  12457. }
  12458. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12459. {
  12460. if (userProps == 0)
  12461. openFiles();
  12462. return userProps;
  12463. }
  12464. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12465. {
  12466. if (commonProps == 0)
  12467. openFiles();
  12468. if (returnUserPropsIfReadOnly)
  12469. {
  12470. if (commonSettingsAreReadOnly == 0)
  12471. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12472. if (commonSettingsAreReadOnly > 0)
  12473. return userProps;
  12474. }
  12475. return commonProps;
  12476. }
  12477. bool ApplicationProperties::saveIfNeeded()
  12478. {
  12479. return (userProps == 0 || userProps->saveIfNeeded())
  12480. && (commonProps == 0 || commonProps->saveIfNeeded());
  12481. }
  12482. void ApplicationProperties::closeFiles()
  12483. {
  12484. deleteAndZero (userProps);
  12485. deleteAndZero (commonProps);
  12486. }
  12487. END_JUCE_NAMESPACE
  12488. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12489. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12490. BEGIN_JUCE_NAMESPACE
  12491. static VoidArray objectsToDelete (16);
  12492. static CriticalSection lock;
  12493. DeletedAtShutdown::DeletedAtShutdown() throw()
  12494. {
  12495. const ScopedLock sl (lock);
  12496. objectsToDelete.add (this);
  12497. }
  12498. DeletedAtShutdown::~DeletedAtShutdown()
  12499. {
  12500. const ScopedLock sl (lock);
  12501. objectsToDelete.removeValue (this);
  12502. }
  12503. void DeletedAtShutdown::deleteAll()
  12504. {
  12505. // make a local copy of the array, so it can't get into a loop if something
  12506. // creates another DeletedAtShutdown object during its destructor.
  12507. lock.enter();
  12508. const VoidArray localCopy (objectsToDelete);
  12509. lock.exit();
  12510. for (int i = localCopy.size(); --i >= 0;)
  12511. {
  12512. JUCE_TRY
  12513. {
  12514. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12515. // double-check that it's not already been deleted during another object's destructor.
  12516. lock.enter();
  12517. const bool okToDelete = objectsToDelete.contains (deletee);
  12518. lock.exit();
  12519. if (okToDelete)
  12520. delete deletee;
  12521. }
  12522. JUCE_CATCH_EXCEPTION
  12523. }
  12524. // if no objects got re-created during shutdown, this should have been emptied by their
  12525. // destructors
  12526. jassert (objectsToDelete.size() == 0);
  12527. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12528. }
  12529. END_JUCE_NAMESPACE
  12530. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12531. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12532. BEGIN_JUCE_NAMESPACE
  12533. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12534. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12535. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12536. static const tchar* const propertyTagName = T("VALUE");
  12537. PropertiesFile::PropertiesFile (const File& f,
  12538. const int millisecondsBeforeSaving,
  12539. const int options_) throw()
  12540. : PropertySet (ignoreCaseOfKeyNames),
  12541. file (f),
  12542. timerInterval (millisecondsBeforeSaving),
  12543. options (options_),
  12544. needsWriting (false)
  12545. {
  12546. // You need to correctly specify just one storage format for the file
  12547. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12548. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12549. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12550. InputStream* fileStream = f.createInputStream();
  12551. if (fileStream != 0)
  12552. {
  12553. int magicNumber = fileStream->readInt();
  12554. if (magicNumber == propFileMagicNumberCompressed)
  12555. {
  12556. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12557. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12558. magicNumber = propFileMagicNumber;
  12559. }
  12560. if (magicNumber == propFileMagicNumber)
  12561. {
  12562. BufferedInputStream in (fileStream, 2048, true);
  12563. int numValues = in.readInt();
  12564. while (--numValues >= 0 && ! in.isExhausted())
  12565. {
  12566. const String key (in.readString());
  12567. const String value (in.readString());
  12568. jassert (key.isNotEmpty());
  12569. if (key.isNotEmpty())
  12570. getAllProperties().set (key, value);
  12571. }
  12572. }
  12573. else
  12574. {
  12575. // Not a binary props file - let's see if it's XML..
  12576. delete fileStream;
  12577. XmlDocument parser (f);
  12578. XmlElement* doc = parser.getDocumentElement (true);
  12579. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  12580. {
  12581. delete doc;
  12582. doc = parser.getDocumentElement();
  12583. if (doc != 0)
  12584. {
  12585. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  12586. {
  12587. const String name (e->getStringAttribute (T("name")));
  12588. if (name.isNotEmpty())
  12589. getAllProperties().set (name, e->getStringAttribute (T("val")));
  12590. }
  12591. }
  12592. else
  12593. {
  12594. // must be a pretty broken XML file we're trying to parse here!
  12595. jassertfalse
  12596. }
  12597. delete doc;
  12598. }
  12599. }
  12600. }
  12601. }
  12602. PropertiesFile::~PropertiesFile()
  12603. {
  12604. saveIfNeeded();
  12605. }
  12606. bool PropertiesFile::saveIfNeeded()
  12607. {
  12608. const ScopedLock sl (getLock());
  12609. return (! needsWriting) || save();
  12610. }
  12611. bool PropertiesFile::needsToBeSaved() const throw()
  12612. {
  12613. const ScopedLock sl (getLock());
  12614. return needsWriting;
  12615. }
  12616. bool PropertiesFile::save()
  12617. {
  12618. const ScopedLock sl (getLock());
  12619. stopTimer();
  12620. if (file == File::nonexistent
  12621. || file.isDirectory()
  12622. || ! file.getParentDirectory().createDirectory())
  12623. return false;
  12624. if ((options & storeAsXML) != 0)
  12625. {
  12626. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  12627. for (int i = 0; i < getAllProperties().size(); ++i)
  12628. {
  12629. XmlElement* const e = new XmlElement (propertyTagName);
  12630. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  12631. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  12632. doc->addChildElement (e);
  12633. }
  12634. const bool ok = doc->writeToFile (file, String::empty);
  12635. delete doc;
  12636. return ok;
  12637. }
  12638. else
  12639. {
  12640. const File tempFile (file.getNonexistentSibling (false));
  12641. OutputStream* out = tempFile.createOutputStream();
  12642. if (out != 0)
  12643. {
  12644. if ((options & storeAsCompressedBinary) != 0)
  12645. {
  12646. out->writeInt (propFileMagicNumberCompressed);
  12647. out->flush();
  12648. out = new GZIPCompressorOutputStream (out, 9, true);
  12649. }
  12650. else
  12651. {
  12652. // have you set up the storage option flags correctly?
  12653. jassert ((options & storeAsBinary) != 0);
  12654. out->writeInt (propFileMagicNumber);
  12655. }
  12656. const int numProperties = getAllProperties().size();
  12657. out->writeInt (numProperties);
  12658. for (int i = 0; i < numProperties; ++i)
  12659. {
  12660. out->writeString (getAllProperties().getAllKeys() [i]);
  12661. out->writeString (getAllProperties().getAllValues() [i]);
  12662. }
  12663. out->flush();
  12664. delete out;
  12665. if (tempFile.moveFileTo (file))
  12666. {
  12667. needsWriting = false;
  12668. return true;
  12669. }
  12670. tempFile.deleteFile();
  12671. }
  12672. }
  12673. return false;
  12674. }
  12675. void PropertiesFile::timerCallback()
  12676. {
  12677. saveIfNeeded();
  12678. }
  12679. void PropertiesFile::propertyChanged()
  12680. {
  12681. sendChangeMessage (this);
  12682. needsWriting = true;
  12683. if (timerInterval > 0)
  12684. startTimer (timerInterval);
  12685. else if (timerInterval == 0)
  12686. saveIfNeeded();
  12687. }
  12688. const File PropertiesFile::getFile() const throw()
  12689. {
  12690. return file;
  12691. }
  12692. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  12693. const String& fileNameSuffix,
  12694. const String& folderName,
  12695. const bool commonToAllUsers)
  12696. {
  12697. // mustn't have illegal characters in this name..
  12698. jassert (applicationName == File::createLegalFileName (applicationName));
  12699. #if JUCE_MAC
  12700. File dir (commonToAllUsers ? "/Library/Preferences"
  12701. : "~/Library/Preferences");
  12702. if (folderName.isNotEmpty())
  12703. dir = dir.getChildFile (folderName);
  12704. #endif
  12705. #ifdef JUCE_LINUX
  12706. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  12707. + (folderName.isNotEmpty() ? folderName
  12708. : (T(".") + applicationName)));
  12709. #endif
  12710. #if JUCE_WIN32
  12711. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  12712. : File::userApplicationDataDirectory));
  12713. if (dir == File::nonexistent)
  12714. return File::nonexistent;
  12715. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  12716. : applicationName);
  12717. #endif
  12718. return dir.getChildFile (applicationName)
  12719. .withFileExtension (fileNameSuffix);
  12720. }
  12721. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  12722. const String& fileNameSuffix,
  12723. const String& folderName,
  12724. const bool commonToAllUsers,
  12725. const int millisecondsBeforeSaving,
  12726. const int propertiesFileOptions)
  12727. {
  12728. const File file (getDefaultAppSettingsFile (applicationName,
  12729. fileNameSuffix,
  12730. folderName,
  12731. commonToAllUsers));
  12732. jassert (file != File::nonexistent);
  12733. if (file == File::nonexistent)
  12734. return 0;
  12735. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  12736. }
  12737. END_JUCE_NAMESPACE
  12738. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  12739. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  12740. BEGIN_JUCE_NAMESPACE
  12741. #undef chunkName
  12742. #define chunkName(a) (int)littleEndianInt(a)
  12743. #define aiffFormatName TRANS("AIFF file")
  12744. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  12745. class AiffAudioFormatReader : public AudioFormatReader
  12746. {
  12747. public:
  12748. int bytesPerFrame;
  12749. int64 dataChunkStart;
  12750. bool littleEndian;
  12751. AiffAudioFormatReader (InputStream* in)
  12752. : AudioFormatReader (in, aiffFormatName)
  12753. {
  12754. if (input->readInt() == chunkName ("FORM"))
  12755. {
  12756. const int len = input->readIntBigEndian();
  12757. const int64 end = input->getPosition() + len;
  12758. const int nextType = input->readInt();
  12759. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  12760. {
  12761. bool hasGotVer = false;
  12762. bool hasGotData = false;
  12763. bool hasGotType = false;
  12764. while (input->getPosition() < end)
  12765. {
  12766. const int type = input->readInt();
  12767. const uint32 length = (uint32) input->readIntBigEndian();
  12768. const int64 chunkEnd = input->getPosition() + length;
  12769. if (type == chunkName ("FVER"))
  12770. {
  12771. hasGotVer = true;
  12772. const int ver = input->readIntBigEndian();
  12773. if (ver != 0 && ver != (int)0xa2805140)
  12774. break;
  12775. }
  12776. else if (type == chunkName ("COMM"))
  12777. {
  12778. hasGotType = true;
  12779. numChannels = (unsigned int)input->readShortBigEndian();
  12780. lengthInSamples = input->readIntBigEndian();
  12781. bitsPerSample = input->readShortBigEndian();
  12782. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  12783. unsigned char sampleRateBytes[10];
  12784. input->read (sampleRateBytes, 10);
  12785. const int byte0 = sampleRateBytes[0];
  12786. if ((byte0 & 0x80) != 0
  12787. || byte0 <= 0x3F || byte0 > 0x40
  12788. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  12789. break;
  12790. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  12791. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  12792. sampleRate = (int)sampRate;
  12793. if (length <= 18)
  12794. {
  12795. // some types don't have a chunk large enough to include a compression
  12796. // type, so assume it's just big-endian pcm
  12797. littleEndian = false;
  12798. }
  12799. else
  12800. {
  12801. const int compType = input->readInt();
  12802. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  12803. {
  12804. littleEndian = false;
  12805. }
  12806. else if (compType == chunkName ("sowt"))
  12807. {
  12808. littleEndian = true;
  12809. }
  12810. else
  12811. {
  12812. sampleRate = 0;
  12813. break;
  12814. }
  12815. }
  12816. }
  12817. else if (type == chunkName ("SSND"))
  12818. {
  12819. hasGotData = true;
  12820. const int offset = input->readIntBigEndian();
  12821. dataChunkStart = input->getPosition() + 4 + offset;
  12822. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  12823. }
  12824. else if ((hasGotVer && hasGotData && hasGotType)
  12825. || chunkEnd < input->getPosition()
  12826. || input->isExhausted())
  12827. {
  12828. break;
  12829. }
  12830. input->setPosition (chunkEnd);
  12831. }
  12832. }
  12833. }
  12834. }
  12835. ~AiffAudioFormatReader()
  12836. {
  12837. }
  12838. bool read (int** destSamples,
  12839. int64 startSampleInFile,
  12840. int numSamples)
  12841. {
  12842. int64 start = startSampleInFile;
  12843. int startOffsetInDestBuffer = 0;
  12844. if (startSampleInFile < 0)
  12845. {
  12846. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  12847. int** destChan = destSamples;
  12848. for (int i = 2; --i >= 0;)
  12849. {
  12850. if (*destChan != 0)
  12851. {
  12852. zeromem (*destChan, sizeof (int) * silence);
  12853. ++destChan;
  12854. }
  12855. }
  12856. startOffsetInDestBuffer += silence;
  12857. numSamples -= silence;
  12858. start = 0;
  12859. }
  12860. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  12861. if (numToDo > 0)
  12862. {
  12863. input->setPosition (dataChunkStart + start * bytesPerFrame);
  12864. int num = numToDo;
  12865. int* left = destSamples[0];
  12866. if (left != 0)
  12867. left += startOffsetInDestBuffer;
  12868. int* right = destSamples[1];
  12869. if (right != 0)
  12870. right += startOffsetInDestBuffer;
  12871. // (keep this a multiple of 3)
  12872. const int tempBufSize = 1440 * 4;
  12873. char tempBuffer [tempBufSize];
  12874. while (num > 0)
  12875. {
  12876. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  12877. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  12878. if (bytesRead < numThisTime * bytesPerFrame)
  12879. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  12880. if (bitsPerSample == 16)
  12881. {
  12882. if (littleEndian)
  12883. {
  12884. const short* src = (const short*) tempBuffer;
  12885. if (numChannels > 1)
  12886. {
  12887. if (left == 0)
  12888. {
  12889. for (int i = numThisTime; --i >= 0;)
  12890. {
  12891. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12892. ++src;
  12893. }
  12894. }
  12895. else if (right == 0)
  12896. {
  12897. for (int i = numThisTime; --i >= 0;)
  12898. {
  12899. ++src;
  12900. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12901. }
  12902. }
  12903. else
  12904. {
  12905. for (int i = numThisTime; --i >= 0;)
  12906. {
  12907. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12908. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12909. }
  12910. }
  12911. }
  12912. else
  12913. {
  12914. for (int i = numThisTime; --i >= 0;)
  12915. {
  12916. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12917. }
  12918. }
  12919. }
  12920. else
  12921. {
  12922. const char* src = (const char*) tempBuffer;
  12923. if (numChannels > 1)
  12924. {
  12925. if (left == 0)
  12926. {
  12927. for (int i = numThisTime; --i >= 0;)
  12928. {
  12929. *right++ = bigEndianShort (src) << 16;
  12930. src += 4;
  12931. }
  12932. }
  12933. else if (right == 0)
  12934. {
  12935. for (int i = numThisTime; --i >= 0;)
  12936. {
  12937. src += 2;
  12938. *left++ = bigEndianShort (src) << 16;
  12939. src += 2;
  12940. }
  12941. }
  12942. else
  12943. {
  12944. for (int i = numThisTime; --i >= 0;)
  12945. {
  12946. *left++ = bigEndianShort (src) << 16;
  12947. src += 2;
  12948. *right++ = bigEndianShort (src) << 16;
  12949. src += 2;
  12950. }
  12951. }
  12952. }
  12953. else
  12954. {
  12955. for (int i = numThisTime; --i >= 0;)
  12956. {
  12957. *left++ = bigEndianShort (src) << 16;
  12958. src += 2;
  12959. }
  12960. }
  12961. }
  12962. }
  12963. else if (bitsPerSample == 24)
  12964. {
  12965. const char* src = (const char*)tempBuffer;
  12966. if (littleEndian)
  12967. {
  12968. if (numChannels > 1)
  12969. {
  12970. if (left == 0)
  12971. {
  12972. for (int i = numThisTime; --i >= 0;)
  12973. {
  12974. *right++ = littleEndian24Bit (src) << 8;
  12975. src += 6;
  12976. }
  12977. }
  12978. else if (right == 0)
  12979. {
  12980. for (int i = numThisTime; --i >= 0;)
  12981. {
  12982. src += 3;
  12983. *left++ = littleEndian24Bit (src) << 8;
  12984. src += 3;
  12985. }
  12986. }
  12987. else
  12988. {
  12989. for (int i = numThisTime; --i >= 0;)
  12990. {
  12991. *left++ = littleEndian24Bit (src) << 8;
  12992. src += 3;
  12993. *right++ = littleEndian24Bit (src) << 8;
  12994. src += 3;
  12995. }
  12996. }
  12997. }
  12998. else
  12999. {
  13000. for (int i = numThisTime; --i >= 0;)
  13001. {
  13002. *left++ = littleEndian24Bit (src) << 8;
  13003. src += 3;
  13004. }
  13005. }
  13006. }
  13007. else
  13008. {
  13009. if (numChannels > 1)
  13010. {
  13011. if (left == 0)
  13012. {
  13013. for (int i = numThisTime; --i >= 0;)
  13014. {
  13015. *right++ = bigEndian24Bit (src) << 8;
  13016. src += 6;
  13017. }
  13018. }
  13019. else if (right == 0)
  13020. {
  13021. for (int i = numThisTime; --i >= 0;)
  13022. {
  13023. src += 3;
  13024. *left++ = bigEndian24Bit (src) << 8;
  13025. src += 3;
  13026. }
  13027. }
  13028. else
  13029. {
  13030. for (int i = numThisTime; --i >= 0;)
  13031. {
  13032. *left++ = bigEndian24Bit (src) << 8;
  13033. src += 3;
  13034. *right++ = bigEndian24Bit (src) << 8;
  13035. src += 3;
  13036. }
  13037. }
  13038. }
  13039. else
  13040. {
  13041. for (int i = numThisTime; --i >= 0;)
  13042. {
  13043. *left++ = bigEndian24Bit (src) << 8;
  13044. src += 3;
  13045. }
  13046. }
  13047. }
  13048. }
  13049. else if (bitsPerSample == 32)
  13050. {
  13051. const unsigned int* src = (const unsigned int*) tempBuffer;
  13052. unsigned int* l = (unsigned int*) left;
  13053. unsigned int* r = (unsigned int*) right;
  13054. if (littleEndian)
  13055. {
  13056. if (numChannels > 1)
  13057. {
  13058. if (l == 0)
  13059. {
  13060. for (int i = numThisTime; --i >= 0;)
  13061. {
  13062. ++src;
  13063. *r++ = swapIfBigEndian (*src++);
  13064. }
  13065. }
  13066. else if (r == 0)
  13067. {
  13068. for (int i = numThisTime; --i >= 0;)
  13069. {
  13070. *l++ = swapIfBigEndian (*src++);
  13071. ++src;
  13072. }
  13073. }
  13074. else
  13075. {
  13076. for (int i = numThisTime; --i >= 0;)
  13077. {
  13078. *l++ = swapIfBigEndian (*src++);
  13079. *r++ = swapIfBigEndian (*src++);
  13080. }
  13081. }
  13082. }
  13083. else
  13084. {
  13085. for (int i = numThisTime; --i >= 0;)
  13086. {
  13087. *l++ = swapIfBigEndian (*src++);
  13088. }
  13089. }
  13090. }
  13091. else
  13092. {
  13093. if (numChannels > 1)
  13094. {
  13095. if (l == 0)
  13096. {
  13097. for (int i = numThisTime; --i >= 0;)
  13098. {
  13099. ++src;
  13100. *r++ = swapIfLittleEndian (*src++);
  13101. }
  13102. }
  13103. else if (r == 0)
  13104. {
  13105. for (int i = numThisTime; --i >= 0;)
  13106. {
  13107. *l++ = swapIfLittleEndian (*src++);
  13108. ++src;
  13109. }
  13110. }
  13111. else
  13112. {
  13113. for (int i = numThisTime; --i >= 0;)
  13114. {
  13115. *l++ = swapIfLittleEndian (*src++);
  13116. *r++ = swapIfLittleEndian (*src++);
  13117. }
  13118. }
  13119. }
  13120. else
  13121. {
  13122. for (int i = numThisTime; --i >= 0;)
  13123. {
  13124. *l++ = swapIfLittleEndian (*src++);
  13125. }
  13126. }
  13127. }
  13128. left = (int*) l;
  13129. right = (int*) r;
  13130. }
  13131. else if (bitsPerSample == 8)
  13132. {
  13133. const char* src = (const char*) tempBuffer;
  13134. if (numChannels > 1)
  13135. {
  13136. if (left == 0)
  13137. {
  13138. for (int i = numThisTime; --i >= 0;)
  13139. {
  13140. *right++ = ((int) *src++) << 24;
  13141. ++src;
  13142. }
  13143. }
  13144. else if (right == 0)
  13145. {
  13146. for (int i = numThisTime; --i >= 0;)
  13147. {
  13148. ++src;
  13149. *left++ = ((int) *src++) << 24;
  13150. }
  13151. }
  13152. else
  13153. {
  13154. for (int i = numThisTime; --i >= 0;)
  13155. {
  13156. *left++ = ((int) *src++) << 24;
  13157. *right++ = ((int) *src++) << 24;
  13158. }
  13159. }
  13160. }
  13161. else
  13162. {
  13163. for (int i = numThisTime; --i >= 0;)
  13164. {
  13165. *left++ = ((int) *src++) << 24;
  13166. }
  13167. }
  13168. }
  13169. num -= numThisTime;
  13170. }
  13171. }
  13172. if (numToDo < numSamples)
  13173. {
  13174. int** destChan = destSamples;
  13175. while (*destChan != 0)
  13176. {
  13177. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13178. sizeof (int) * (numSamples - numToDo));
  13179. ++destChan;
  13180. }
  13181. }
  13182. return true;
  13183. }
  13184. juce_UseDebuggingNewOperator
  13185. private:
  13186. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13187. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13188. };
  13189. class AiffAudioFormatWriter : public AudioFormatWriter
  13190. {
  13191. MemoryBlock tempBlock;
  13192. uint32 lengthInSamples, bytesWritten;
  13193. int64 headerPosition;
  13194. bool writeFailed;
  13195. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13196. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13197. void writeHeader()
  13198. {
  13199. const bool couldSeekOk = output->setPosition (headerPosition);
  13200. (void) couldSeekOk;
  13201. // if this fails, you've given it an output stream that can't seek! It needs
  13202. // to be able to seek back to write the header
  13203. jassert (couldSeekOk);
  13204. const int headerLen = 54;
  13205. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13206. audioBytes += (audioBytes & 1);
  13207. output->writeInt (chunkName ("FORM"));
  13208. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13209. output->writeInt (chunkName ("AIFF"));
  13210. output->writeInt (chunkName ("COMM"));
  13211. output->writeIntBigEndian (18);
  13212. output->writeShortBigEndian ((short) numChannels);
  13213. output->writeIntBigEndian (lengthInSamples);
  13214. output->writeShortBigEndian ((short) bitsPerSample);
  13215. uint8 sampleRateBytes[10];
  13216. zeromem (sampleRateBytes, 10);
  13217. if (sampleRate <= 1)
  13218. {
  13219. sampleRateBytes[0] = 0x3f;
  13220. sampleRateBytes[1] = 0xff;
  13221. sampleRateBytes[2] = 0x80;
  13222. }
  13223. else
  13224. {
  13225. int mask = 0x40000000;
  13226. sampleRateBytes[0] = 0x40;
  13227. if (sampleRate >= mask)
  13228. {
  13229. jassertfalse
  13230. sampleRateBytes[1] = 0x1d;
  13231. }
  13232. else
  13233. {
  13234. int n = (int) sampleRate;
  13235. int i;
  13236. for (i = 0; i <= 32 ; ++i)
  13237. {
  13238. if ((n & mask) != 0)
  13239. break;
  13240. mask >>= 1;
  13241. }
  13242. n = n << (i + 1);
  13243. sampleRateBytes[1] = (uint8) (29 - i);
  13244. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13245. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13246. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13247. sampleRateBytes[5] = (uint8) (n & 0xff);
  13248. }
  13249. }
  13250. output->write (sampleRateBytes, 10);
  13251. output->writeInt (chunkName ("SSND"));
  13252. output->writeIntBigEndian (audioBytes + 8);
  13253. output->writeInt (0);
  13254. output->writeInt (0);
  13255. jassert (output->getPosition() == headerLen);
  13256. }
  13257. public:
  13258. AiffAudioFormatWriter (OutputStream* out,
  13259. const double sampleRate,
  13260. const unsigned int chans,
  13261. const int bits)
  13262. : AudioFormatWriter (out,
  13263. aiffFormatName,
  13264. sampleRate,
  13265. chans,
  13266. bits),
  13267. lengthInSamples (0),
  13268. bytesWritten (0),
  13269. writeFailed (false)
  13270. {
  13271. headerPosition = out->getPosition();
  13272. writeHeader();
  13273. }
  13274. ~AiffAudioFormatWriter()
  13275. {
  13276. if ((bytesWritten & 1) != 0)
  13277. output->writeByte (0);
  13278. writeHeader();
  13279. }
  13280. bool write (const int** data, int numSamples)
  13281. {
  13282. if (writeFailed)
  13283. return false;
  13284. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13285. tempBlock.ensureSize (bytes, false);
  13286. char* buffer = (char*) tempBlock.getData();
  13287. const int* left = data[0];
  13288. const int* right = data[1];
  13289. if (right == 0)
  13290. right = left;
  13291. if (bitsPerSample == 16)
  13292. {
  13293. short* b = (short*) buffer;
  13294. if (numChannels > 1)
  13295. {
  13296. for (int i = numSamples; --i >= 0;)
  13297. {
  13298. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13299. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13300. }
  13301. }
  13302. else
  13303. {
  13304. for (int i = numSamples; --i >= 0;)
  13305. {
  13306. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13307. }
  13308. }
  13309. }
  13310. else if (bitsPerSample == 24)
  13311. {
  13312. char* b = (char*) buffer;
  13313. if (numChannels > 1)
  13314. {
  13315. for (int i = numSamples; --i >= 0;)
  13316. {
  13317. bigEndian24BitToChars (*left++ >> 8, b);
  13318. b += 3;
  13319. bigEndian24BitToChars (*right++ >> 8, b);
  13320. b += 3;
  13321. }
  13322. }
  13323. else
  13324. {
  13325. for (int i = numSamples; --i >= 0;)
  13326. {
  13327. bigEndian24BitToChars (*left++ >> 8, b);
  13328. b += 3;
  13329. }
  13330. }
  13331. }
  13332. else if (bitsPerSample == 32)
  13333. {
  13334. unsigned int* b = (unsigned int*) buffer;
  13335. if (numChannels > 1)
  13336. {
  13337. for (int i = numSamples; --i >= 0;)
  13338. {
  13339. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13340. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13341. }
  13342. }
  13343. else
  13344. {
  13345. for (int i = numSamples; --i >= 0;)
  13346. {
  13347. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13348. }
  13349. }
  13350. }
  13351. else if (bitsPerSample == 8)
  13352. {
  13353. char* b = (char*)buffer;
  13354. if (numChannels > 1)
  13355. {
  13356. for (int i = numSamples; --i >= 0;)
  13357. {
  13358. *b++ = (char) (*left++ >> 24);
  13359. *b++ = (char) (*right++ >> 24);
  13360. }
  13361. }
  13362. else
  13363. {
  13364. for (int i = numSamples; --i >= 0;)
  13365. {
  13366. *b++ = (char) (*left++ >> 24);
  13367. }
  13368. }
  13369. }
  13370. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13371. || ! output->write (buffer, bytes))
  13372. {
  13373. // failed to write to disk, so let's try writing the header.
  13374. // If it's just run out of disk space, then if it does manage
  13375. // to write the header, we'll still have a useable file..
  13376. writeHeader();
  13377. writeFailed = true;
  13378. return false;
  13379. }
  13380. else
  13381. {
  13382. bytesWritten += bytes;
  13383. lengthInSamples += numSamples;
  13384. return true;
  13385. }
  13386. }
  13387. juce_UseDebuggingNewOperator
  13388. };
  13389. AiffAudioFormat::AiffAudioFormat()
  13390. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13391. {
  13392. }
  13393. AiffAudioFormat::~AiffAudioFormat()
  13394. {
  13395. }
  13396. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13397. {
  13398. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13399. return Array <int> (rates);
  13400. }
  13401. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13402. {
  13403. const int depths[] = { 8, 16, 24, 0 };
  13404. return Array <int> (depths);
  13405. }
  13406. bool AiffAudioFormat::canDoStereo()
  13407. {
  13408. return true;
  13409. }
  13410. bool AiffAudioFormat::canDoMono()
  13411. {
  13412. return true;
  13413. }
  13414. #if JUCE_MAC
  13415. bool AiffAudioFormat::canHandleFile (const File& f)
  13416. {
  13417. if (AudioFormat::canHandleFile (f))
  13418. return true;
  13419. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13420. return type == 'AIFF' || type == 'AIFC'
  13421. || type == 'aiff' || type == 'aifc';
  13422. }
  13423. #endif
  13424. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13425. const bool deleteStreamIfOpeningFails)
  13426. {
  13427. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13428. if (w->sampleRate == 0)
  13429. {
  13430. if (! deleteStreamIfOpeningFails)
  13431. w->input = 0;
  13432. deleteAndZero (w);
  13433. }
  13434. return w;
  13435. }
  13436. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13437. double sampleRate,
  13438. unsigned int chans,
  13439. int bitsPerSample,
  13440. const StringPairArray& /*metadataValues*/,
  13441. int /*qualityOptionIndex*/)
  13442. {
  13443. if (getPossibleBitDepths().contains (bitsPerSample))
  13444. {
  13445. return new AiffAudioFormatWriter (out,
  13446. sampleRate,
  13447. chans,
  13448. bitsPerSample);
  13449. }
  13450. return 0;
  13451. }
  13452. END_JUCE_NAMESPACE
  13453. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13454. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13455. BEGIN_JUCE_NAMESPACE
  13456. #if JUCE_MAC
  13457. // Mac version doesn't need any native code because it's all done with files..
  13458. // Windows + Linux versions are in the platform-dependent code sections.
  13459. static void findCDs (OwnedArray<File>& cds)
  13460. {
  13461. File volumes ("/Volumes");
  13462. volumes.findChildFiles (cds, File::findDirectories, false);
  13463. for (int i = cds.size(); --i >= 0;)
  13464. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13465. cds.remove (i);
  13466. }
  13467. const StringArray AudioCDReader::getAvailableCDNames()
  13468. {
  13469. OwnedArray<File> cds;
  13470. findCDs (cds);
  13471. StringArray names;
  13472. for (int i = 0; i < cds.size(); ++i)
  13473. names.add (cds[i]->getFileName());
  13474. return names;
  13475. }
  13476. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13477. {
  13478. OwnedArray<File> cds;
  13479. findCDs (cds);
  13480. if (cds[index] != 0)
  13481. return new AudioCDReader (*cds[index]);
  13482. else
  13483. return 0;
  13484. }
  13485. AudioCDReader::AudioCDReader (const File& volume)
  13486. : AudioFormatReader (0, "CD Audio"),
  13487. volumeDir (volume),
  13488. currentReaderTrack (-1),
  13489. reader (0)
  13490. {
  13491. sampleRate = 44100.0;
  13492. bitsPerSample = 16;
  13493. numChannels = 2;
  13494. usesFloatingPointData = false;
  13495. refreshTrackLengths();
  13496. }
  13497. AudioCDReader::~AudioCDReader()
  13498. {
  13499. if (reader != 0)
  13500. delete reader;
  13501. }
  13502. static int getTrackNumber (const File& file)
  13503. {
  13504. return file.getFileName()
  13505. .initialSectionContainingOnly (T("0123456789"))
  13506. .getIntValue();
  13507. }
  13508. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13509. {
  13510. const int firstTrack = getTrackNumber (*first);
  13511. const int secondTrack = getTrackNumber (*second);
  13512. jassert (firstTrack > 0 && secondTrack > 0);
  13513. return firstTrack - secondTrack;
  13514. }
  13515. void AudioCDReader::refreshTrackLengths()
  13516. {
  13517. tracks.clear();
  13518. trackStartSamples.clear();
  13519. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13520. tracks.sort (*this);
  13521. AiffAudioFormat format;
  13522. int sample = 0;
  13523. for (int i = 0; i < tracks.size(); ++i)
  13524. {
  13525. trackStartSamples.add (sample);
  13526. FileInputStream* const in = tracks[i]->createInputStream();
  13527. if (in != 0)
  13528. {
  13529. AudioFormatReader* const r = format.createReaderFor (in, true);
  13530. if (r != 0)
  13531. {
  13532. sample += r->lengthInSamples;
  13533. delete r;
  13534. }
  13535. }
  13536. }
  13537. trackStartSamples.add (sample);
  13538. lengthInSamples = sample;
  13539. }
  13540. bool AudioCDReader::read (int** destSamples,
  13541. int64 startSampleInFile,
  13542. int numSamples)
  13543. {
  13544. while (numSamples > 0)
  13545. {
  13546. int track = -1;
  13547. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13548. {
  13549. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13550. {
  13551. track = i;
  13552. break;
  13553. }
  13554. }
  13555. if (track < 0)
  13556. return false;
  13557. if (track != currentReaderTrack)
  13558. {
  13559. deleteAndZero (reader);
  13560. if (tracks [track] != 0)
  13561. {
  13562. FileInputStream* const in = tracks [track]->createInputStream();
  13563. if (in != 0)
  13564. {
  13565. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  13566. AiffAudioFormat format;
  13567. reader = format.createReaderFor (bin, true);
  13568. if (reader == 0)
  13569. currentReaderTrack = -1;
  13570. else
  13571. currentReaderTrack = track;
  13572. }
  13573. }
  13574. }
  13575. if (reader == 0)
  13576. return false;
  13577. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  13578. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  13579. reader->read (destSamples, startPos, numAvailable);
  13580. numSamples -= numAvailable;
  13581. startSampleInFile += numAvailable;
  13582. }
  13583. return true;
  13584. }
  13585. bool AudioCDReader::isCDStillPresent() const
  13586. {
  13587. return volumeDir.exists();
  13588. }
  13589. int AudioCDReader::getNumTracks() const
  13590. {
  13591. return tracks.size();
  13592. }
  13593. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  13594. {
  13595. return trackStartSamples [trackNum];
  13596. }
  13597. bool AudioCDReader::isTrackAudio (int trackNum) const
  13598. {
  13599. return tracks [trackNum] != 0;
  13600. }
  13601. void AudioCDReader::enableIndexScanning (bool b)
  13602. {
  13603. // any way to do this on a Mac??
  13604. }
  13605. int AudioCDReader::getLastIndex() const
  13606. {
  13607. return 0;
  13608. }
  13609. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  13610. {
  13611. return Array <int>();
  13612. }
  13613. int AudioCDReader::getCDDBId()
  13614. {
  13615. return 0; //xxx
  13616. }
  13617. #endif
  13618. END_JUCE_NAMESPACE
  13619. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  13620. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  13621. BEGIN_JUCE_NAMESPACE
  13622. AudioFormatReader::AudioFormatReader (InputStream* const in,
  13623. const String& formatName_)
  13624. : sampleRate (0),
  13625. bitsPerSample (0),
  13626. lengthInSamples (0),
  13627. numChannels (0),
  13628. usesFloatingPointData (false),
  13629. input (in),
  13630. formatName (formatName_)
  13631. {
  13632. }
  13633. AudioFormatReader::~AudioFormatReader()
  13634. {
  13635. delete input;
  13636. }
  13637. static void findMaxMin (const float* src, const int num,
  13638. float& maxVal, float& minVal)
  13639. {
  13640. float mn = src[0];
  13641. float mx = mn;
  13642. for (int i = 1; i < num; ++i)
  13643. {
  13644. const float s = src[i];
  13645. if (s > mx)
  13646. mx = s;
  13647. if (s < mn)
  13648. mn = s;
  13649. }
  13650. maxVal = mx;
  13651. minVal = mn;
  13652. }
  13653. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  13654. int64 numSamples,
  13655. float& lowestLeft, float& highestLeft,
  13656. float& lowestRight, float& highestRight)
  13657. {
  13658. if (numSamples <= 0)
  13659. {
  13660. lowestLeft = 0;
  13661. lowestRight = 0;
  13662. highestLeft = 0;
  13663. highestRight = 0;
  13664. return;
  13665. }
  13666. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  13667. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13668. int* tempBuffer[3];
  13669. tempBuffer[0] = (int*) tempSpace.getData();
  13670. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13671. tempBuffer[2] = 0;
  13672. if (usesFloatingPointData)
  13673. {
  13674. float lmin = 1.0e6;
  13675. float lmax = -lmin;
  13676. float rmin = lmin;
  13677. float rmax = lmax;
  13678. while (numSamples > 0)
  13679. {
  13680. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13681. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13682. numSamples -= numToDo;
  13683. float bufmin, bufmax;
  13684. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  13685. lmin = jmin (lmin, bufmin);
  13686. lmax = jmax (lmax, bufmax);
  13687. if (numChannels > 1)
  13688. {
  13689. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  13690. rmin = jmin (rmin, bufmin);
  13691. rmax = jmax (rmax, bufmax);
  13692. }
  13693. }
  13694. if (numChannels <= 1)
  13695. {
  13696. rmax = lmax;
  13697. rmin = lmin;
  13698. }
  13699. lowestLeft = lmin;
  13700. highestLeft = lmax;
  13701. lowestRight = rmin;
  13702. highestRight = rmax;
  13703. }
  13704. else
  13705. {
  13706. int lmax = INT_MIN;
  13707. int lmin = INT_MAX;
  13708. int rmax = INT_MIN;
  13709. int rmin = INT_MAX;
  13710. while (numSamples > 0)
  13711. {
  13712. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13713. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13714. numSamples -= numToDo;
  13715. for (int j = numChannels; --j >= 0;)
  13716. {
  13717. int bufMax = INT_MIN;
  13718. int bufMin = INT_MAX;
  13719. const int* const b = tempBuffer[j];
  13720. for (int i = 0; i < numToDo; ++i)
  13721. {
  13722. const int samp = b[i];
  13723. if (samp < bufMin)
  13724. bufMin = samp;
  13725. if (samp > bufMax)
  13726. bufMax = samp;
  13727. }
  13728. if (j == 0)
  13729. {
  13730. lmax = jmax (lmax, bufMax);
  13731. lmin = jmin (lmin, bufMin);
  13732. }
  13733. else
  13734. {
  13735. rmax = jmax (rmax, bufMax);
  13736. rmin = jmin (rmin, bufMin);
  13737. }
  13738. }
  13739. }
  13740. if (numChannels <= 1)
  13741. {
  13742. rmax = lmax;
  13743. rmin = lmin;
  13744. }
  13745. lowestLeft = lmin / (float)INT_MAX;
  13746. highestLeft = lmax / (float)INT_MAX;
  13747. lowestRight = rmin / (float)INT_MAX;
  13748. highestRight = rmax / (float)INT_MAX;
  13749. }
  13750. }
  13751. int64 AudioFormatReader::searchForLevel (int64 startSample,
  13752. int64 numSamplesToSearch,
  13753. const double magnitudeRangeMinimum,
  13754. const double magnitudeRangeMaximum,
  13755. const int minimumConsecutiveSamples)
  13756. {
  13757. if (numSamplesToSearch == 0)
  13758. return -1;
  13759. const int bufferSize = 4096;
  13760. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13761. int* tempBuffer[3];
  13762. tempBuffer[0] = (int*) tempSpace.getData();
  13763. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13764. tempBuffer[2] = 0;
  13765. int consecutive = 0;
  13766. int64 firstMatchPos = -1;
  13767. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  13768. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  13769. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  13770. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  13771. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  13772. while (numSamplesToSearch != 0)
  13773. {
  13774. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  13775. int64 bufferStart = startSample;
  13776. if (numSamplesToSearch < 0)
  13777. bufferStart -= numThisTime;
  13778. if (bufferStart >= (int) lengthInSamples)
  13779. break;
  13780. read ((int**) tempBuffer, bufferStart, numThisTime);
  13781. int num = numThisTime;
  13782. while (--num >= 0)
  13783. {
  13784. if (numSamplesToSearch < 0)
  13785. --startSample;
  13786. bool matches = false;
  13787. const int index = (int) (startSample - bufferStart);
  13788. if (usesFloatingPointData)
  13789. {
  13790. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  13791. if (sample1 >= magnitudeRangeMinimum
  13792. && sample1 <= magnitudeRangeMaximum)
  13793. {
  13794. matches = true;
  13795. }
  13796. else if (numChannels > 1)
  13797. {
  13798. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  13799. matches = (sample2 >= magnitudeRangeMinimum
  13800. && sample2 <= magnitudeRangeMaximum);
  13801. }
  13802. }
  13803. else
  13804. {
  13805. const int sample1 = abs (tempBuffer[0] [index]);
  13806. if (sample1 >= intMagnitudeRangeMinimum
  13807. && sample1 <= intMagnitudeRangeMaximum)
  13808. {
  13809. matches = true;
  13810. }
  13811. else if (numChannels > 1)
  13812. {
  13813. const int sample2 = abs (tempBuffer[1][index]);
  13814. matches = (sample2 >= intMagnitudeRangeMinimum
  13815. && sample2 <= intMagnitudeRangeMaximum);
  13816. }
  13817. }
  13818. if (matches)
  13819. {
  13820. if (firstMatchPos < 0)
  13821. firstMatchPos = startSample;
  13822. if (++consecutive >= minimumConsecutiveSamples)
  13823. {
  13824. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  13825. return -1;
  13826. return firstMatchPos;
  13827. }
  13828. }
  13829. else
  13830. {
  13831. consecutive = 0;
  13832. firstMatchPos = -1;
  13833. }
  13834. if (numSamplesToSearch > 0)
  13835. ++startSample;
  13836. }
  13837. if (numSamplesToSearch > 0)
  13838. numSamplesToSearch -= numThisTime;
  13839. else
  13840. numSamplesToSearch += numThisTime;
  13841. }
  13842. return -1;
  13843. }
  13844. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  13845. const String& formatName_,
  13846. const double rate,
  13847. const unsigned int numChannels_,
  13848. const unsigned int bitsPerSample_)
  13849. : sampleRate (rate),
  13850. numChannels (numChannels_),
  13851. bitsPerSample (bitsPerSample_),
  13852. usesFloatingPointData (false),
  13853. output (out),
  13854. formatName (formatName_)
  13855. {
  13856. }
  13857. AudioFormatWriter::~AudioFormatWriter()
  13858. {
  13859. delete output;
  13860. }
  13861. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  13862. int64 startSample,
  13863. int numSamplesToRead)
  13864. {
  13865. const int bufferSize = 16384;
  13866. const int maxChans = 128;
  13867. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  13868. int* buffers [maxChans];
  13869. for (int i = maxChans; --i >= 0;)
  13870. buffers[i] = 0;
  13871. while (numSamplesToRead > 0)
  13872. {
  13873. const int numToDo = jmin (numSamplesToRead, bufferSize);
  13874. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  13875. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13876. if (! reader.read (buffers, startSample, numToDo))
  13877. return false;
  13878. if (reader.usesFloatingPointData != isFloatingPoint())
  13879. {
  13880. int** bufferChan = buffers;
  13881. while (*bufferChan != 0)
  13882. {
  13883. int* b = *bufferChan++;
  13884. if (isFloatingPoint())
  13885. {
  13886. // int -> float
  13887. const double factor = 1.0 / INT_MAX;
  13888. for (int i = 0; i < numToDo; ++i)
  13889. ((float*)b)[i] = (float) (factor * b[i]);
  13890. }
  13891. else
  13892. {
  13893. // float -> int
  13894. for (int i = 0; i < numToDo; ++i)
  13895. {
  13896. const double samp = *(const float*) b;
  13897. if (samp <= -1.0)
  13898. *b++ = INT_MIN;
  13899. else if (samp >= 1.0)
  13900. *b++ = INT_MAX;
  13901. else
  13902. *b++ = roundDoubleToInt (INT_MAX * samp);
  13903. }
  13904. }
  13905. }
  13906. }
  13907. if (! write ((const int**) buffers, numToDo))
  13908. return false;
  13909. numSamplesToRead -= numToDo;
  13910. startSample += numToDo;
  13911. }
  13912. return true;
  13913. }
  13914. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  13915. int numSamplesToRead,
  13916. const int samplesPerBlock)
  13917. {
  13918. const int maxChans = 128;
  13919. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  13920. int* buffers [maxChans];
  13921. while (numSamplesToRead > 0)
  13922. {
  13923. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  13924. AudioSourceChannelInfo info;
  13925. info.buffer = &tempBuffer;
  13926. info.startSample = 0;
  13927. info.numSamples = numToDo;
  13928. info.clearActiveBufferRegion();
  13929. source.getNextAudioBlock (info);
  13930. int i;
  13931. for (i = maxChans; --i >= 0;)
  13932. buffers[i] = 0;
  13933. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  13934. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13935. if (! isFloatingPoint())
  13936. {
  13937. int** bufferChan = buffers;
  13938. while (*bufferChan != 0)
  13939. {
  13940. int* b = *bufferChan++;
  13941. // float -> int
  13942. for (int j = numToDo; --j >= 0;)
  13943. {
  13944. const double samp = *(const float*) b;
  13945. if (samp <= -1.0)
  13946. *b++ = INT_MIN;
  13947. else if (samp >= 1.0)
  13948. *b++ = INT_MAX;
  13949. else
  13950. *b++ = roundDoubleToInt (INT_MAX * samp);
  13951. }
  13952. }
  13953. }
  13954. if (! write ((const int**) buffers, numToDo))
  13955. return false;
  13956. numSamplesToRead -= numToDo;
  13957. }
  13958. return true;
  13959. }
  13960. AudioFormat::AudioFormat (const String& name,
  13961. const tchar** const extensions)
  13962. : formatName (name),
  13963. fileExtensions (extensions)
  13964. {
  13965. }
  13966. AudioFormat::~AudioFormat()
  13967. {
  13968. }
  13969. const String& AudioFormat::getFormatName() const
  13970. {
  13971. return formatName;
  13972. }
  13973. const StringArray& AudioFormat::getFileExtensions() const
  13974. {
  13975. return fileExtensions;
  13976. }
  13977. bool AudioFormat::canHandleFile (const File& f)
  13978. {
  13979. for (int i = 0; i < fileExtensions.size(); ++i)
  13980. if (f.hasFileExtension (fileExtensions[i]))
  13981. return true;
  13982. return false;
  13983. }
  13984. bool AudioFormat::isCompressed()
  13985. {
  13986. return false;
  13987. }
  13988. const StringArray AudioFormat::getQualityOptions()
  13989. {
  13990. return StringArray();
  13991. }
  13992. END_JUCE_NAMESPACE
  13993. /********* End of inlined file: juce_AudioFormat.cpp *********/
  13994. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  13995. BEGIN_JUCE_NAMESPACE
  13996. AudioFormatManager::AudioFormatManager()
  13997. : knownFormats (4),
  13998. defaultFormatIndex (0)
  13999. {
  14000. }
  14001. AudioFormatManager::~AudioFormatManager()
  14002. {
  14003. clearFormats();
  14004. clearSingletonInstance();
  14005. }
  14006. juce_ImplementSingleton (AudioFormatManager);
  14007. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14008. const bool makeThisTheDefaultFormat)
  14009. {
  14010. jassert (newFormat != 0);
  14011. if (newFormat != 0)
  14012. {
  14013. #ifdef JUCE_DEBUG
  14014. for (int i = getNumKnownFormats(); --i >= 0;)
  14015. {
  14016. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14017. {
  14018. jassertfalse // trying to add the same format twice!
  14019. }
  14020. }
  14021. #endif
  14022. if (makeThisTheDefaultFormat)
  14023. defaultFormatIndex = knownFormats.size();
  14024. knownFormats.add (newFormat);
  14025. }
  14026. }
  14027. void AudioFormatManager::registerBasicFormats()
  14028. {
  14029. #if JUCE_MAC
  14030. registerFormat (new AiffAudioFormat(), true);
  14031. registerFormat (new WavAudioFormat(), false);
  14032. #else
  14033. registerFormat (new WavAudioFormat(), true);
  14034. registerFormat (new AiffAudioFormat(), false);
  14035. #endif
  14036. #if JUCE_USE_FLAC
  14037. registerFormat (new FlacAudioFormat(), false);
  14038. #endif
  14039. #if JUCE_USE_OGGVORBIS
  14040. registerFormat (new OggVorbisAudioFormat(), false);
  14041. #endif
  14042. }
  14043. void AudioFormatManager::clearFormats()
  14044. {
  14045. for (int i = getNumKnownFormats(); --i >= 0;)
  14046. {
  14047. AudioFormat* const af = getKnownFormat(i);
  14048. delete af;
  14049. }
  14050. knownFormats.clear();
  14051. defaultFormatIndex = 0;
  14052. }
  14053. int AudioFormatManager::getNumKnownFormats() const
  14054. {
  14055. return knownFormats.size();
  14056. }
  14057. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14058. {
  14059. return (AudioFormat*) knownFormats [index];
  14060. }
  14061. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14062. {
  14063. return getKnownFormat (defaultFormatIndex);
  14064. }
  14065. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14066. {
  14067. String e (fileExtension);
  14068. if (! e.startsWithChar (T('.')))
  14069. e = T(".") + e;
  14070. for (int i = 0; i < getNumKnownFormats(); ++i)
  14071. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14072. return getKnownFormat(i);
  14073. return 0;
  14074. }
  14075. const String AudioFormatManager::getWildcardForAllFormats() const
  14076. {
  14077. StringArray allExtensions;
  14078. int i;
  14079. for (i = 0; i < getNumKnownFormats(); ++i)
  14080. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14081. allExtensions.trim();
  14082. allExtensions.removeEmptyStrings();
  14083. String s;
  14084. for (i = 0; i < allExtensions.size(); ++i)
  14085. {
  14086. s << T('*');
  14087. if (! allExtensions[i].startsWithChar (T('.')))
  14088. s << T('.');
  14089. s << allExtensions[i];
  14090. if (i < allExtensions.size() - 1)
  14091. s << T(';');
  14092. }
  14093. return s;
  14094. }
  14095. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14096. {
  14097. // you need to actually register some formats before the manager can
  14098. // use them to open a file!
  14099. jassert (knownFormats.size() > 0);
  14100. for (int i = 0; i < getNumKnownFormats(); ++i)
  14101. {
  14102. AudioFormat* const af = getKnownFormat(i);
  14103. if (af->canHandleFile (file))
  14104. {
  14105. InputStream* const in = file.createInputStream();
  14106. if (in != 0)
  14107. {
  14108. AudioFormatReader* const r = af->createReaderFor (in, true);
  14109. if (r != 0)
  14110. return r;
  14111. }
  14112. }
  14113. }
  14114. return 0;
  14115. }
  14116. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14117. {
  14118. // you need to actually register some formats before the manager can
  14119. // use them to open a file!
  14120. jassert (knownFormats.size() > 0);
  14121. if (in != 0)
  14122. {
  14123. const int64 originalStreamPos = in->getPosition();
  14124. for (int i = 0; i < getNumKnownFormats(); ++i)
  14125. {
  14126. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14127. if (r != 0)
  14128. return r;
  14129. in->setPosition (originalStreamPos);
  14130. // the stream that is passed-in must be capable of being repositioned so
  14131. // that all the formats can have a go at opening it.
  14132. jassert (in->getPosition() == originalStreamPos);
  14133. }
  14134. delete in;
  14135. }
  14136. return 0;
  14137. }
  14138. END_JUCE_NAMESPACE
  14139. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14140. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14141. BEGIN_JUCE_NAMESPACE
  14142. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14143. const int64 startSample_,
  14144. const int64 length_,
  14145. const bool deleteSourceWhenDeleted_)
  14146. : AudioFormatReader (0, source_->getFormatName()),
  14147. source (source_),
  14148. startSample (startSample_),
  14149. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14150. {
  14151. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14152. sampleRate = source->sampleRate;
  14153. bitsPerSample = source->bitsPerSample;
  14154. lengthInSamples = length;
  14155. numChannels = source->numChannels;
  14156. usesFloatingPointData = source->usesFloatingPointData;
  14157. }
  14158. AudioSubsectionReader::~AudioSubsectionReader()
  14159. {
  14160. if (deleteSourceWhenDeleted)
  14161. delete source;
  14162. }
  14163. bool AudioSubsectionReader::read (int** destSamples,
  14164. int64 startSampleInFile,
  14165. int numSamples)
  14166. {
  14167. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14168. {
  14169. int** d = destSamples;
  14170. while (*d != 0)
  14171. {
  14172. zeromem (*d, sizeof (int) * numSamples);
  14173. ++d;
  14174. }
  14175. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14176. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14177. }
  14178. return source->read (destSamples,
  14179. startSampleInFile + startSample,
  14180. numSamples);
  14181. }
  14182. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14183. int64 numSamples,
  14184. float& lowestLeft,
  14185. float& highestLeft,
  14186. float& lowestRight,
  14187. float& highestRight)
  14188. {
  14189. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14190. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14191. source->readMaxLevels (startSampleInFile + startSample,
  14192. numSamples,
  14193. lowestLeft,
  14194. highestLeft,
  14195. lowestRight,
  14196. highestRight);
  14197. }
  14198. END_JUCE_NAMESPACE
  14199. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14200. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14201. BEGIN_JUCE_NAMESPACE
  14202. const int timeBeforeDeletingReader = 2000;
  14203. struct AudioThumbnailDataFormat
  14204. {
  14205. char thumbnailMagic[4];
  14206. int samplesPerThumbSample;
  14207. int64 totalSamples; // source samples
  14208. int64 numFinishedSamples; // source samples
  14209. int numThumbnailSamples;
  14210. int numChannels;
  14211. int sampleRate;
  14212. char future[16];
  14213. char data[1];
  14214. };
  14215. #if JUCE_BIG_ENDIAN
  14216. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14217. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14218. #endif
  14219. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14220. {
  14221. (void) d;
  14222. #if JUCE_BIG_ENDIAN
  14223. swap (d->samplesPerThumbSample);
  14224. swap (d->totalSamples);
  14225. swap (d->numFinishedSamples);
  14226. swap (d->numThumbnailSamples);
  14227. swap (d->numChannels);
  14228. swap (d->sampleRate);
  14229. #endif
  14230. }
  14231. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14232. AudioFormatManager& formatManagerToUse_,
  14233. AudioThumbnailCache& cacheToUse)
  14234. : formatManagerToUse (formatManagerToUse_),
  14235. cache (cacheToUse),
  14236. source (0),
  14237. reader (0),
  14238. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14239. {
  14240. clear();
  14241. }
  14242. AudioThumbnail::~AudioThumbnail()
  14243. {
  14244. cache.removeThumbnail (this);
  14245. const ScopedLock sl (readerLock);
  14246. deleteAndZero (reader);
  14247. delete source;
  14248. }
  14249. void AudioThumbnail::setSource (InputSource* const newSource)
  14250. {
  14251. cache.removeThumbnail (this);
  14252. timerCallback(); // stops the timer and deletes the reader
  14253. delete source;
  14254. source = newSource;
  14255. clear();
  14256. if (! (cache.loadThumb (*this, newSource->hashCode())
  14257. && isFullyLoaded()))
  14258. {
  14259. {
  14260. const ScopedLock sl (readerLock);
  14261. reader = createReader();
  14262. }
  14263. if (reader != 0)
  14264. {
  14265. initialiseFromAudioFile (*reader);
  14266. cache.addThumbnail (this);
  14267. }
  14268. }
  14269. sendChangeMessage (this);
  14270. }
  14271. bool AudioThumbnail::useTimeSlice()
  14272. {
  14273. const ScopedLock sl (readerLock);
  14274. if (isFullyLoaded())
  14275. {
  14276. if (reader != 0)
  14277. startTimer (timeBeforeDeletingReader);
  14278. cache.removeThumbnail (this);
  14279. return false;
  14280. }
  14281. if (reader == 0)
  14282. reader = createReader();
  14283. if (reader != 0)
  14284. {
  14285. readNextBlockFromAudioFile (*reader);
  14286. stopTimer();
  14287. sendChangeMessage (this);
  14288. const bool justFinished = isFullyLoaded();
  14289. if (justFinished)
  14290. cache.storeThumb (*this, source->hashCode());
  14291. return ! justFinished;
  14292. }
  14293. return false;
  14294. }
  14295. AudioFormatReader* AudioThumbnail::createReader() const
  14296. {
  14297. if (source != 0)
  14298. {
  14299. InputStream* const audioFileStream = source->createInputStream();
  14300. if (audioFileStream != 0)
  14301. return formatManagerToUse.createReaderFor (audioFileStream);
  14302. }
  14303. return 0;
  14304. }
  14305. void AudioThumbnail::timerCallback()
  14306. {
  14307. stopTimer();
  14308. const ScopedLock sl (readerLock);
  14309. deleteAndZero (reader);
  14310. }
  14311. void AudioThumbnail::clear()
  14312. {
  14313. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14314. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14315. d->thumbnailMagic[0] = 'j';
  14316. d->thumbnailMagic[1] = 'a';
  14317. d->thumbnailMagic[2] = 't';
  14318. d->thumbnailMagic[3] = 'm';
  14319. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14320. d->totalSamples = 0;
  14321. d->numFinishedSamples = 0;
  14322. d->numThumbnailSamples = 0;
  14323. d->numChannels = 0;
  14324. d->sampleRate = 0;
  14325. numSamplesCached = 0;
  14326. cacheNeedsRefilling = true;
  14327. }
  14328. void AudioThumbnail::loadFrom (InputStream& input)
  14329. {
  14330. data.setSize (0);
  14331. input.readIntoMemoryBlock (data);
  14332. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14333. swapEndiannessIfNeeded (d);
  14334. if (! (d->thumbnailMagic[0] == 'j'
  14335. && d->thumbnailMagic[1] == 'a'
  14336. && d->thumbnailMagic[2] == 't'
  14337. && d->thumbnailMagic[3] == 'm'))
  14338. {
  14339. clear();
  14340. }
  14341. numSamplesCached = 0;
  14342. cacheNeedsRefilling = true;
  14343. }
  14344. void AudioThumbnail::saveTo (OutputStream& output) const
  14345. {
  14346. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14347. swapEndiannessIfNeeded (d);
  14348. output.write (data.getData(), data.getSize());
  14349. swapEndiannessIfNeeded (d);
  14350. }
  14351. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14352. {
  14353. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14354. d->totalSamples = reader.lengthInSamples;
  14355. d->numChannels = jmin (2, reader.numChannels);
  14356. d->numFinishedSamples = 0;
  14357. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14358. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14359. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14360. d = (AudioThumbnailDataFormat*) data.getData();
  14361. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14362. return d->totalSamples > 0;
  14363. }
  14364. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14365. {
  14366. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14367. if (d->numFinishedSamples < d->totalSamples)
  14368. {
  14369. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14370. generateSection (reader,
  14371. d->numFinishedSamples,
  14372. numToDo);
  14373. d->numFinishedSamples += numToDo;
  14374. }
  14375. cacheNeedsRefilling = true;
  14376. return (d->numFinishedSamples < d->totalSamples);
  14377. }
  14378. int AudioThumbnail::getNumChannels() const throw()
  14379. {
  14380. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14381. jassert (d != 0);
  14382. return d->numChannels;
  14383. }
  14384. double AudioThumbnail::getTotalLength() const throw()
  14385. {
  14386. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14387. jassert (d != 0);
  14388. if (d->sampleRate > 0)
  14389. return d->totalSamples / (double)d->sampleRate;
  14390. else
  14391. return 0.0;
  14392. }
  14393. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14394. int64 startSample,
  14395. int numSamples)
  14396. {
  14397. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14398. jassert (d != 0);
  14399. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14400. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14401. char* l = getChannelData (0);
  14402. char* r = getChannelData (1);
  14403. for (int i = firstDataPos; i < lastDataPos; ++i)
  14404. {
  14405. const int sourceStart = i * d->samplesPerThumbSample;
  14406. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14407. float lowestLeft, highestLeft, lowestRight, highestRight;
  14408. reader.readMaxLevels (sourceStart,
  14409. sourceEnd - sourceStart,
  14410. lowestLeft,
  14411. highestLeft,
  14412. lowestRight,
  14413. highestRight);
  14414. int n = i * 2;
  14415. if (r != 0)
  14416. {
  14417. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14418. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14419. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14420. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14421. }
  14422. else
  14423. {
  14424. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14425. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14426. }
  14427. }
  14428. }
  14429. char* AudioThumbnail::getChannelData (int channel) const
  14430. {
  14431. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14432. jassert (d != 0);
  14433. if (channel >= 0 && channel < d->numChannels)
  14434. return d->data + (channel * 2 * d->numThumbnailSamples);
  14435. return 0;
  14436. }
  14437. bool AudioThumbnail::isFullyLoaded() const throw()
  14438. {
  14439. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14440. jassert (d != 0);
  14441. return d->numFinishedSamples >= d->totalSamples;
  14442. }
  14443. void AudioThumbnail::refillCache (const int numSamples,
  14444. double startTime,
  14445. const double timePerPixel)
  14446. {
  14447. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14448. jassert (d != 0);
  14449. if (numSamples <= 0
  14450. || timePerPixel <= 0.0
  14451. || d->sampleRate <= 0)
  14452. {
  14453. numSamplesCached = 0;
  14454. cacheNeedsRefilling = true;
  14455. return;
  14456. }
  14457. if (numSamples == numSamplesCached
  14458. && numChannelsCached == d->numChannels
  14459. && startTime == cachedStart
  14460. && timePerPixel == cachedTimePerPixel
  14461. && ! cacheNeedsRefilling)
  14462. {
  14463. return;
  14464. }
  14465. numSamplesCached = numSamples;
  14466. numChannelsCached = d->numChannels;
  14467. cachedStart = startTime;
  14468. cachedTimePerPixel = timePerPixel;
  14469. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14470. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14471. const ScopedLock sl (readerLock);
  14472. cacheNeedsRefilling = false;
  14473. if (needExtraDetail && reader == 0)
  14474. reader = createReader();
  14475. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14476. {
  14477. startTimer (timeBeforeDeletingReader);
  14478. char* cacheData = (char*) cachedLevels.getData();
  14479. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14480. for (int i = numSamples; --i >= 0;)
  14481. {
  14482. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14483. if (sample >= 0)
  14484. {
  14485. if (sample >= reader->lengthInSamples)
  14486. break;
  14487. float lmin, lmax, rmin, rmax;
  14488. reader->readMaxLevels (sample,
  14489. jmax (1, nextSample - sample),
  14490. lmin, lmax, rmin, rmax);
  14491. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14492. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14493. if (numChannelsCached > 1)
  14494. {
  14495. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14496. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14497. }
  14498. cacheData += 2 * numChannelsCached;
  14499. }
  14500. startTime += timePerPixel;
  14501. sample = nextSample;
  14502. }
  14503. }
  14504. else
  14505. {
  14506. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14507. {
  14508. char* const data = getChannelData (channelNum);
  14509. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14510. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14511. startTime = cachedStart;
  14512. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14513. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14514. for (int i = numSamples; --i >= 0;)
  14515. {
  14516. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14517. if (sample >= 0 && data != 0)
  14518. {
  14519. char mx = -128;
  14520. char mn = 127;
  14521. while (sample <= nextSample)
  14522. {
  14523. if (sample >= numFinished)
  14524. break;
  14525. const int n = sample << 1;
  14526. const char sampMin = data [n];
  14527. const char sampMax = data [n + 1];
  14528. if (sampMin < mn)
  14529. mn = sampMin;
  14530. if (sampMax > mx)
  14531. mx = sampMax;
  14532. ++sample;
  14533. }
  14534. if (mn <= mx)
  14535. {
  14536. cacheData[0] = mn;
  14537. cacheData[1] = mx;
  14538. }
  14539. else
  14540. {
  14541. cacheData[0] = 1;
  14542. cacheData[1] = 0;
  14543. }
  14544. }
  14545. else
  14546. {
  14547. cacheData[0] = 1;
  14548. cacheData[1] = 0;
  14549. }
  14550. cacheData += numChannelsCached * 2;
  14551. startTime += timePerPixel;
  14552. sample = nextSample;
  14553. }
  14554. }
  14555. }
  14556. }
  14557. void AudioThumbnail::drawChannel (Graphics& g,
  14558. int x, int y, int w, int h,
  14559. double startTime,
  14560. double endTime,
  14561. int channelNum,
  14562. const float verticalZoomFactor)
  14563. {
  14564. refillCache (w, startTime, (endTime - startTime) / w);
  14565. if (numSamplesCached >= w
  14566. && channelNum >= 0
  14567. && channelNum < numChannelsCached)
  14568. {
  14569. const float topY = (float) y;
  14570. const float bottomY = topY + h;
  14571. const float midY = topY + h * 0.5f;
  14572. const float vscale = verticalZoomFactor * h / 256.0f;
  14573. const Rectangle clip (g.getClipBounds());
  14574. const int skipLeft = clip.getX() - x;
  14575. w -= skipLeft;
  14576. x += skipLeft;
  14577. const char* cacheData = ((const char*) cachedLevels.getData())
  14578. + (channelNum << 1)
  14579. + skipLeft * (numChannelsCached << 1);
  14580. while (--w >= 0)
  14581. {
  14582. const char mn = cacheData[0];
  14583. const char mx = cacheData[1];
  14584. cacheData += numChannelsCached << 1;
  14585. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  14586. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  14587. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  14588. ++x;
  14589. if (x >= clip.getRight())
  14590. break;
  14591. }
  14592. }
  14593. }
  14594. END_JUCE_NAMESPACE
  14595. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  14596. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  14597. BEGIN_JUCE_NAMESPACE
  14598. struct ThumbnailCacheEntry
  14599. {
  14600. int64 hash;
  14601. uint32 lastUsed;
  14602. MemoryBlock data;
  14603. juce_UseDebuggingNewOperator
  14604. };
  14605. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  14606. : TimeSliceThread (T("thumb cache")),
  14607. maxNumThumbsToStore (maxNumThumbsToStore_)
  14608. {
  14609. startThread (2);
  14610. }
  14611. AudioThumbnailCache::~AudioThumbnailCache()
  14612. {
  14613. }
  14614. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  14615. {
  14616. for (int i = thumbs.size(); --i >= 0;)
  14617. {
  14618. if (thumbs[i]->hash == hashCode)
  14619. {
  14620. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  14621. thumbs[i]->data.getSize(),
  14622. false);
  14623. thumb.loadFrom (in);
  14624. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  14625. return true;
  14626. }
  14627. }
  14628. return false;
  14629. }
  14630. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  14631. const int64 hashCode)
  14632. {
  14633. MemoryOutputStream out;
  14634. thumb.saveTo (out);
  14635. ThumbnailCacheEntry* te = 0;
  14636. for (int i = thumbs.size(); --i >= 0;)
  14637. {
  14638. if (thumbs[i]->hash == hashCode)
  14639. {
  14640. te = thumbs[i];
  14641. break;
  14642. }
  14643. }
  14644. if (te == 0)
  14645. {
  14646. te = new ThumbnailCacheEntry();
  14647. te->hash = hashCode;
  14648. if (thumbs.size() < maxNumThumbsToStore)
  14649. {
  14650. thumbs.add (te);
  14651. }
  14652. else
  14653. {
  14654. int oldest = 0;
  14655. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  14656. int i;
  14657. for (i = thumbs.size(); --i >= 0;)
  14658. if (thumbs[i]->lastUsed < oldestTime)
  14659. oldest = i;
  14660. thumbs.set (i, te);
  14661. }
  14662. }
  14663. te->lastUsed = Time::getMillisecondCounter();
  14664. te->data.setSize (0);
  14665. te->data.append (out.getData(), out.getDataSize());
  14666. }
  14667. void AudioThumbnailCache::clear()
  14668. {
  14669. thumbs.clear();
  14670. }
  14671. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  14672. {
  14673. addTimeSliceClient (thumb);
  14674. }
  14675. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  14676. {
  14677. removeTimeSliceClient (thumb);
  14678. }
  14679. END_JUCE_NAMESPACE
  14680. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  14681. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14682. #if JUCE_QUICKTIME
  14683. #if ! defined (_WIN32)
  14684. #include <Quicktime/Movies.h>
  14685. #include <Quicktime/QTML.h>
  14686. #include <Quicktime/QuickTimeComponents.h>
  14687. #include <Quicktime/MediaHandlers.h>
  14688. #include <Quicktime/ImageCodec.h>
  14689. #else
  14690. #ifdef _MSC_VER
  14691. #pragma warning (push)
  14692. #pragma warning (disable : 4100)
  14693. #endif
  14694. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  14695. add its header directory to your include path.
  14696. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  14697. flag in juce_Config.h
  14698. */
  14699. #include <Movies.h>
  14700. #include <QTML.h>
  14701. #include <QuickTimeComponents.h>
  14702. #include <MediaHandlers.h>
  14703. #include <ImageCodec.h>
  14704. #ifdef _MSC_VER
  14705. #pragma warning (pop)
  14706. #endif
  14707. #endif
  14708. BEGIN_JUCE_NAMESPACE
  14709. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  14710. #define quickTimeFormatName TRANS("QuickTime file")
  14711. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  14712. class QTAudioReader : public AudioFormatReader
  14713. {
  14714. public:
  14715. QTAudioReader (InputStream* const input_, const int trackNum_)
  14716. : AudioFormatReader (input_, quickTimeFormatName),
  14717. ok (false),
  14718. movie (0),
  14719. trackNum (trackNum_),
  14720. extractor (0),
  14721. lastSampleRead (0),
  14722. lastThreadId (0),
  14723. dataHandle (0)
  14724. {
  14725. bufferList = (AudioBufferList*) juce_calloc (256);
  14726. #ifdef WIN32
  14727. if (InitializeQTML (0) != noErr)
  14728. return;
  14729. #endif
  14730. if (EnterMovies() != noErr)
  14731. return;
  14732. #if JUCE_MAC
  14733. EnterMoviesOnThread (0);
  14734. #endif
  14735. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  14736. if (! opened)
  14737. return;
  14738. {
  14739. const int numTracks = GetMovieTrackCount (movie);
  14740. int trackCount = 0;
  14741. for (int i = 1; i <= numTracks; ++i)
  14742. {
  14743. track = GetMovieIndTrack (movie, i);
  14744. media = GetTrackMedia (track);
  14745. OSType mediaType;
  14746. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  14747. if (mediaType == SoundMediaType
  14748. && trackCount++ == trackNum_)
  14749. {
  14750. ok = true;
  14751. break;
  14752. }
  14753. }
  14754. }
  14755. if (! ok)
  14756. return;
  14757. ok = false;
  14758. lengthInSamples = GetMediaDecodeDuration (media);
  14759. usesFloatingPointData = false;
  14760. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  14761. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  14762. / GetMediaTimeScale (media);
  14763. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  14764. unsigned long output_layout_size;
  14765. err = MovieAudioExtractionGetPropertyInfo (extractor,
  14766. kQTPropertyClass_MovieAudioExtraction_Audio,
  14767. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14768. 0, &output_layout_size, 0);
  14769. if (err != noErr)
  14770. return;
  14771. AudioChannelLayout* const qt_audio_channel_layout
  14772. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  14773. err = MovieAudioExtractionGetProperty (extractor,
  14774. kQTPropertyClass_MovieAudioExtraction_Audio,
  14775. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14776. output_layout_size, qt_audio_channel_layout, 0);
  14777. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  14778. err = MovieAudioExtractionSetProperty (extractor,
  14779. kQTPropertyClass_MovieAudioExtraction_Audio,
  14780. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14781. sizeof (qt_audio_channel_layout),
  14782. qt_audio_channel_layout);
  14783. juce_free (qt_audio_channel_layout);
  14784. err = MovieAudioExtractionGetProperty (extractor,
  14785. kQTPropertyClass_MovieAudioExtraction_Audio,
  14786. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14787. sizeof (inputStreamDesc),
  14788. &inputStreamDesc, 0);
  14789. if (err != noErr)
  14790. return;
  14791. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  14792. | kAudioFormatFlagIsPacked
  14793. | kAudioFormatFlagsNativeEndian;
  14794. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  14795. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  14796. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  14797. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  14798. err = MovieAudioExtractionSetProperty (extractor,
  14799. kQTPropertyClass_MovieAudioExtraction_Audio,
  14800. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14801. sizeof (inputStreamDesc),
  14802. &inputStreamDesc);
  14803. if (err != noErr)
  14804. return;
  14805. Boolean allChannelsDiscrete = false;
  14806. err = MovieAudioExtractionSetProperty (extractor,
  14807. kQTPropertyClass_MovieAudioExtraction_Movie,
  14808. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  14809. sizeof (allChannelsDiscrete),
  14810. &allChannelsDiscrete);
  14811. if (err != noErr)
  14812. return;
  14813. bufferList->mNumberBuffers = 1;
  14814. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  14815. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  14816. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  14817. sampleRate = inputStreamDesc.mSampleRate;
  14818. bitsPerSample = 16;
  14819. numChannels = inputStreamDesc.mChannelsPerFrame;
  14820. detachThread();
  14821. ok = true;
  14822. }
  14823. ~QTAudioReader()
  14824. {
  14825. if (dataHandle != 0)
  14826. DisposeHandle (dataHandle);
  14827. if (extractor != 0)
  14828. {
  14829. MovieAudioExtractionEnd (extractor);
  14830. extractor = 0;
  14831. }
  14832. checkThreadIsAttached();
  14833. DisposeMovie (movie);
  14834. juce_free (bufferList->mBuffers[0].mData);
  14835. juce_free (bufferList);
  14836. }
  14837. bool read (int** destSamples,
  14838. int64 startSample,
  14839. int numSamples)
  14840. {
  14841. checkThreadIsAttached();
  14842. int done = 0;
  14843. while (numSamples > 0)
  14844. {
  14845. if (! loadFrame ((int) startSample))
  14846. return false;
  14847. const int numToDo = jmin (numSamples, samplesPerFrame);
  14848. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  14849. {
  14850. if (destSamples[j] != 0)
  14851. {
  14852. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  14853. for (int i = 0; i < numToDo; ++i)
  14854. destSamples[j][done + i] = src [i << 1] << 16;
  14855. }
  14856. }
  14857. done += numToDo;
  14858. startSample += numToDo;
  14859. numSamples -= numToDo;
  14860. }
  14861. detachThread();
  14862. return true;
  14863. }
  14864. bool loadFrame (const int sampleNum)
  14865. {
  14866. if (lastSampleRead != sampleNum)
  14867. {
  14868. TimeRecord time;
  14869. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  14870. time.base = 0;
  14871. time.value.hi = 0;
  14872. time.value.lo = (UInt32) sampleNum;
  14873. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  14874. kQTPropertyClass_MovieAudioExtraction_Movie,
  14875. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  14876. sizeof (time), &time);
  14877. if (err != noErr)
  14878. return false;
  14879. }
  14880. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  14881. UInt32 outFlags = 0;
  14882. UInt32 actualNumSamples = samplesPerFrame;
  14883. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  14884. bufferList, &outFlags);
  14885. lastSampleRead = sampleNum + samplesPerFrame;
  14886. return err == noErr;
  14887. }
  14888. juce_UseDebuggingNewOperator
  14889. bool ok;
  14890. private:
  14891. Movie movie;
  14892. Media media;
  14893. Track track;
  14894. const int trackNum;
  14895. double trackUnitsPerFrame;
  14896. int samplesPerFrame;
  14897. int lastSampleRead, lastThreadId;
  14898. MovieAudioExtractionRef extractor;
  14899. AudioStreamBasicDescription inputStreamDesc;
  14900. AudioBufferList* bufferList;
  14901. Handle dataHandle;
  14902. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  14903. {
  14904. input->setPosition (offset);
  14905. input->read (dataPtr, size);
  14906. return noErr;
  14907. }
  14908. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  14909. {
  14910. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  14911. }*/
  14912. void checkThreadIsAttached()
  14913. {
  14914. #if JUCE_MAC
  14915. if (Thread::getCurrentThreadId() != lastThreadId)
  14916. EnterMoviesOnThread (0);
  14917. AttachMovieToCurrentThread (movie);
  14918. #endif
  14919. }
  14920. void detachThread()
  14921. {
  14922. #if JUCE_MAC
  14923. DetachMovieFromCurrentThread (movie);
  14924. #endif
  14925. }
  14926. };
  14927. QuickTimeAudioFormat::QuickTimeAudioFormat()
  14928. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  14929. {
  14930. }
  14931. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  14932. {
  14933. }
  14934. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  14935. {
  14936. return Array<int>();
  14937. }
  14938. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  14939. {
  14940. return Array<int>();
  14941. }
  14942. bool QuickTimeAudioFormat::canDoStereo()
  14943. {
  14944. return true;
  14945. }
  14946. bool QuickTimeAudioFormat::canDoMono()
  14947. {
  14948. return true;
  14949. }
  14950. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  14951. const bool deleteStreamIfOpeningFails)
  14952. {
  14953. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  14954. if (! r->ok)
  14955. {
  14956. if (! deleteStreamIfOpeningFails)
  14957. r->input = 0;
  14958. deleteAndZero (r);
  14959. }
  14960. return r;
  14961. }
  14962. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  14963. double /*sampleRateToUse*/,
  14964. unsigned int /*numberOfChannels*/,
  14965. int /*bitsPerSample*/,
  14966. const StringPairArray& /*metadataValues*/,
  14967. int /*qualityOptionIndex*/)
  14968. {
  14969. jassertfalse // not yet implemented!
  14970. return 0;
  14971. }
  14972. END_JUCE_NAMESPACE
  14973. #endif
  14974. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14975. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  14976. BEGIN_JUCE_NAMESPACE
  14977. #define wavFormatName TRANS("WAV file")
  14978. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  14979. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  14980. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  14981. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  14982. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  14983. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  14984. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  14985. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  14986. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  14987. const String& originator,
  14988. const String& originatorRef,
  14989. const Time& date,
  14990. const int64 timeReferenceSamples,
  14991. const String& codingHistory)
  14992. {
  14993. StringPairArray m;
  14994. m.set (bwavDescription, description);
  14995. m.set (bwavOriginator, originator);
  14996. m.set (bwavOriginatorRef, originatorRef);
  14997. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  14998. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  14999. m.set (bwavTimeReference, String (timeReferenceSamples));
  15000. m.set (bwavCodingHistory, codingHistory);
  15001. return m;
  15002. }
  15003. #if JUCE_MSVC
  15004. #pragma pack (push, 1)
  15005. #define PACKED
  15006. #elif defined (JUCE_GCC)
  15007. #define PACKED __attribute__((packed))
  15008. #else
  15009. #define PACKED
  15010. #endif
  15011. struct BWAVChunk
  15012. {
  15013. char description [256];
  15014. char originator [32];
  15015. char originatorRef [32];
  15016. char originationDate [10];
  15017. char originationTime [8];
  15018. uint32 timeRefLow;
  15019. uint32 timeRefHigh;
  15020. uint16 version;
  15021. uint8 umid[64];
  15022. uint8 reserved[190];
  15023. char codingHistory[1];
  15024. void copyTo (StringPairArray& values) const
  15025. {
  15026. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15027. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15028. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15029. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15030. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15031. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15032. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15033. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15034. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15035. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15036. }
  15037. static MemoryBlock createFrom (const StringPairArray& values)
  15038. {
  15039. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15040. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15041. data.fillWith (0);
  15042. BWAVChunk* b = (BWAVChunk*) data.getData();
  15043. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15044. // operations get done in the right order
  15045. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15046. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15047. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15048. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15049. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15050. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15051. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15052. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15053. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15054. if (b->description[0] != 0
  15055. || b->originator[0] != 0
  15056. || b->originationDate[0] != 0
  15057. || b->originationTime[0] != 0
  15058. || b->codingHistory[0] != 0
  15059. || time != 0)
  15060. {
  15061. return data;
  15062. }
  15063. return MemoryBlock();
  15064. }
  15065. } PACKED;
  15066. #if JUCE_MSVC
  15067. #pragma pack (pop)
  15068. #endif
  15069. #undef PACKED
  15070. #undef chunkName
  15071. #define chunkName(a) ((int) littleEndianInt(a))
  15072. class WavAudioFormatReader : public AudioFormatReader
  15073. {
  15074. int bytesPerFrame;
  15075. int64 dataChunkStart, dataLength;
  15076. WavAudioFormatReader (const WavAudioFormatReader&);
  15077. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15078. public:
  15079. WavAudioFormatReader (InputStream* const in)
  15080. : AudioFormatReader (in, wavFormatName),
  15081. dataLength (0)
  15082. {
  15083. if (input->readInt() == chunkName ("RIFF"))
  15084. {
  15085. const uint32 len = (uint32) input->readInt();
  15086. const int64 end = input->getPosition() + len;
  15087. bool hasGotType = false;
  15088. bool hasGotData = false;
  15089. if (input->readInt() == chunkName ("WAVE"))
  15090. {
  15091. while (input->getPosition() < end
  15092. && ! input->isExhausted())
  15093. {
  15094. const int chunkType = input->readInt();
  15095. uint32 length = (uint32) input->readInt();
  15096. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15097. if (chunkType == chunkName ("fmt "))
  15098. {
  15099. // read the format chunk
  15100. const short format = input->readShort();
  15101. const short numChans = input->readShort();
  15102. sampleRate = input->readInt();
  15103. const int bytesPerSec = input->readInt();
  15104. numChannels = numChans;
  15105. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15106. bitsPerSample = 8 * bytesPerFrame / numChans;
  15107. if (format == 3)
  15108. usesFloatingPointData = true;
  15109. else if (format != 1)
  15110. bytesPerFrame = 0;
  15111. hasGotType = true;
  15112. }
  15113. else if (chunkType == chunkName ("data"))
  15114. {
  15115. // get the data chunk's position
  15116. dataLength = length;
  15117. dataChunkStart = input->getPosition();
  15118. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15119. hasGotData = true;
  15120. }
  15121. else if (chunkType == chunkName ("bext"))
  15122. {
  15123. // Broadcast-wav extension chunk..
  15124. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15125. if (bwav != 0)
  15126. {
  15127. input->read (bwav, length);
  15128. bwav->copyTo (metadataValues);
  15129. juce_free (bwav);
  15130. }
  15131. }
  15132. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15133. {
  15134. break;
  15135. }
  15136. input->setPosition (chunkEnd);
  15137. }
  15138. }
  15139. }
  15140. }
  15141. ~WavAudioFormatReader()
  15142. {
  15143. }
  15144. bool read (int** destSamples,
  15145. int64 startSampleInFile,
  15146. int numSamples)
  15147. {
  15148. int64 start = startSampleInFile;
  15149. int startOffsetInDestBuffer = 0;
  15150. if (startSampleInFile < 0)
  15151. {
  15152. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15153. int** destChan = destSamples;
  15154. for (int i = 2; --i >= 0;)
  15155. {
  15156. if (*destChan != 0)
  15157. {
  15158. zeromem (*destChan, sizeof (int) * silence);
  15159. ++destChan;
  15160. }
  15161. }
  15162. startOffsetInDestBuffer += silence;
  15163. numSamples -= silence;
  15164. start = 0;
  15165. }
  15166. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15167. if (numToDo > 0)
  15168. {
  15169. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15170. int num = numToDo;
  15171. int* left = destSamples[0];
  15172. if (left != 0)
  15173. left += startOffsetInDestBuffer;
  15174. int* right = destSamples[1];
  15175. if (right != 0)
  15176. right += startOffsetInDestBuffer;
  15177. // (keep this a multiple of 3)
  15178. const int tempBufSize = 1440 * 4;
  15179. char tempBuffer [tempBufSize];
  15180. while (num > 0)
  15181. {
  15182. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15183. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15184. if (bytesRead < numThisTime * bytesPerFrame)
  15185. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15186. if (bitsPerSample == 16)
  15187. {
  15188. const short* src = (const short*) tempBuffer;
  15189. if (numChannels > 1)
  15190. {
  15191. if (left == 0)
  15192. {
  15193. for (int i = numThisTime; --i >= 0;)
  15194. {
  15195. ++src;
  15196. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15197. }
  15198. }
  15199. else if (right == 0)
  15200. {
  15201. for (int i = numThisTime; --i >= 0;)
  15202. {
  15203. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15204. ++src;
  15205. }
  15206. }
  15207. else
  15208. {
  15209. for (int i = numThisTime; --i >= 0;)
  15210. {
  15211. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15212. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15213. }
  15214. }
  15215. }
  15216. else
  15217. {
  15218. for (int i = numThisTime; --i >= 0;)
  15219. {
  15220. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15221. }
  15222. }
  15223. }
  15224. else if (bitsPerSample == 24)
  15225. {
  15226. const char* src = (const char*) tempBuffer;
  15227. if (numChannels > 1)
  15228. {
  15229. if (left == 0)
  15230. {
  15231. for (int i = numThisTime; --i >= 0;)
  15232. {
  15233. src += 6;
  15234. *right++ = littleEndian24Bit (src) << 8;
  15235. }
  15236. }
  15237. else if (right == 0)
  15238. {
  15239. for (int i = numThisTime; --i >= 0;)
  15240. {
  15241. *left++ = littleEndian24Bit (src) << 8;
  15242. src += 6;
  15243. }
  15244. }
  15245. else
  15246. {
  15247. for (int i = 0; i < numThisTime; ++i)
  15248. {
  15249. *left++ = littleEndian24Bit (src) << 8;
  15250. src += 3;
  15251. *right++ = littleEndian24Bit (src) << 8;
  15252. src += 3;
  15253. }
  15254. }
  15255. }
  15256. else
  15257. {
  15258. for (int i = 0; i < numThisTime; ++i)
  15259. {
  15260. *left++ = littleEndian24Bit (src) << 8;
  15261. src += 3;
  15262. }
  15263. }
  15264. }
  15265. else if (bitsPerSample == 32)
  15266. {
  15267. const unsigned int* src = (const unsigned int*) tempBuffer;
  15268. unsigned int* l = (unsigned int*) left;
  15269. unsigned int* r = (unsigned int*) right;
  15270. if (numChannels > 1)
  15271. {
  15272. if (l == 0)
  15273. {
  15274. for (int i = numThisTime; --i >= 0;)
  15275. {
  15276. ++src;
  15277. *r++ = swapIfBigEndian (*src++);
  15278. }
  15279. }
  15280. else if (r == 0)
  15281. {
  15282. for (int i = numThisTime; --i >= 0;)
  15283. {
  15284. *l++ = swapIfBigEndian (*src++);
  15285. ++src;
  15286. }
  15287. }
  15288. else
  15289. {
  15290. for (int i = numThisTime; --i >= 0;)
  15291. {
  15292. *l++ = swapIfBigEndian (*src++);
  15293. *r++ = swapIfBigEndian (*src++);
  15294. }
  15295. }
  15296. }
  15297. else
  15298. {
  15299. for (int i = numThisTime; --i >= 0;)
  15300. {
  15301. *l++ = swapIfBigEndian (*src++);
  15302. }
  15303. }
  15304. left = (int*)l;
  15305. right = (int*)r;
  15306. }
  15307. else if (bitsPerSample == 8)
  15308. {
  15309. const unsigned char* src = (const unsigned char*) tempBuffer;
  15310. if (numChannels > 1)
  15311. {
  15312. if (left == 0)
  15313. {
  15314. for (int i = numThisTime; --i >= 0;)
  15315. {
  15316. ++src;
  15317. *right++ = ((int) *src++ - 128) << 24;
  15318. }
  15319. }
  15320. else if (right == 0)
  15321. {
  15322. for (int i = numThisTime; --i >= 0;)
  15323. {
  15324. *left++ = ((int) *src++ - 128) << 24;
  15325. ++src;
  15326. }
  15327. }
  15328. else
  15329. {
  15330. for (int i = numThisTime; --i >= 0;)
  15331. {
  15332. *left++ = ((int) *src++ - 128) << 24;
  15333. *right++ = ((int) *src++ - 128) << 24;
  15334. }
  15335. }
  15336. }
  15337. else
  15338. {
  15339. for (int i = numThisTime; --i >= 0;)
  15340. {
  15341. *left++ = ((int)*src++ - 128) << 24;
  15342. }
  15343. }
  15344. }
  15345. num -= numThisTime;
  15346. }
  15347. }
  15348. if (numToDo < numSamples)
  15349. {
  15350. int** destChan = destSamples;
  15351. while (*destChan != 0)
  15352. {
  15353. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15354. sizeof (int) * (numSamples - numToDo));
  15355. ++destChan;
  15356. }
  15357. }
  15358. return true;
  15359. }
  15360. juce_UseDebuggingNewOperator
  15361. };
  15362. class WavAudioFormatWriter : public AudioFormatWriter
  15363. {
  15364. MemoryBlock tempBlock, bwavChunk;
  15365. uint32 lengthInSamples, bytesWritten;
  15366. int64 headerPosition;
  15367. bool writeFailed;
  15368. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15369. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15370. void writeHeader()
  15371. {
  15372. const bool seekedOk = output->setPosition (headerPosition);
  15373. (void) seekedOk;
  15374. // if this fails, you've given it an output stream that can't seek! It needs
  15375. // to be able to seek back to write the header
  15376. jassert (seekedOk);
  15377. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15378. output->writeInt (chunkName ("RIFF"));
  15379. output->writeInt (lengthInSamples * bytesPerFrame
  15380. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15381. output->writeInt (chunkName ("WAVE"));
  15382. output->writeInt (chunkName ("fmt "));
  15383. output->writeInt (16);
  15384. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15385. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15386. output->writeShort ((short) numChannels);
  15387. output->writeInt ((int) sampleRate);
  15388. output->writeInt (bytesPerFrame * (int) sampleRate);
  15389. output->writeShort ((short) bytesPerFrame);
  15390. output->writeShort ((short) bitsPerSample);
  15391. if (bwavChunk.getSize() > 0)
  15392. {
  15393. output->writeInt (chunkName ("bext"));
  15394. output->writeInt (bwavChunk.getSize());
  15395. output->write (bwavChunk.getData(), bwavChunk.getSize());
  15396. }
  15397. output->writeInt (chunkName ("data"));
  15398. output->writeInt (lengthInSamples * bytesPerFrame);
  15399. usesFloatingPointData = (bitsPerSample == 32);
  15400. }
  15401. public:
  15402. WavAudioFormatWriter (OutputStream* const out,
  15403. const double sampleRate,
  15404. const unsigned int numChannels_,
  15405. const int bits,
  15406. const StringPairArray& metadataValues)
  15407. : AudioFormatWriter (out,
  15408. wavFormatName,
  15409. sampleRate,
  15410. numChannels_,
  15411. bits),
  15412. lengthInSamples (0),
  15413. bytesWritten (0),
  15414. writeFailed (false)
  15415. {
  15416. if (metadataValues.size() > 0)
  15417. bwavChunk = BWAVChunk::createFrom (metadataValues);
  15418. headerPosition = out->getPosition();
  15419. writeHeader();
  15420. }
  15421. ~WavAudioFormatWriter()
  15422. {
  15423. writeHeader();
  15424. }
  15425. bool write (const int** data, int numSamples)
  15426. {
  15427. if (writeFailed)
  15428. return false;
  15429. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15430. tempBlock.ensureSize (bytes, false);
  15431. char* buffer = (char*) tempBlock.getData();
  15432. const int* left = data[0];
  15433. const int* right = data[1];
  15434. if (right == 0)
  15435. right = left;
  15436. if (bitsPerSample == 16)
  15437. {
  15438. short* b = (short*) buffer;
  15439. if (numChannels > 1)
  15440. {
  15441. for (int i = numSamples; --i >= 0;)
  15442. {
  15443. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15444. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  15445. }
  15446. }
  15447. else
  15448. {
  15449. for (int i = numSamples; --i >= 0;)
  15450. {
  15451. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15452. }
  15453. }
  15454. }
  15455. else if (bitsPerSample == 24)
  15456. {
  15457. char* b = (char*) buffer;
  15458. if (numChannels > 1)
  15459. {
  15460. for (int i = numSamples; --i >= 0;)
  15461. {
  15462. littleEndian24BitToChars ((*left++) >> 8, b);
  15463. b += 3;
  15464. littleEndian24BitToChars ((*right++) >> 8, b);
  15465. b += 3;
  15466. }
  15467. }
  15468. else
  15469. {
  15470. for (int i = numSamples; --i >= 0;)
  15471. {
  15472. littleEndian24BitToChars ((*left++) >> 8, b);
  15473. b += 3;
  15474. }
  15475. }
  15476. }
  15477. else if (bitsPerSample == 32)
  15478. {
  15479. unsigned int* b = (unsigned int*) buffer;
  15480. if (numChannels > 1)
  15481. {
  15482. for (int i = numSamples; --i >= 0;)
  15483. {
  15484. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15485. *b++ = swapIfBigEndian ((unsigned int) *right++);
  15486. }
  15487. }
  15488. else
  15489. {
  15490. for (int i = numSamples; --i >= 0;)
  15491. {
  15492. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15493. }
  15494. }
  15495. }
  15496. else if (bitsPerSample == 8)
  15497. {
  15498. unsigned char* b = (unsigned char*) buffer;
  15499. if (numChannels > 1)
  15500. {
  15501. for (int i = numSamples; --i >= 0;)
  15502. {
  15503. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15504. *b++ = (unsigned char) (128 + (*right++ >> 24));
  15505. }
  15506. }
  15507. else
  15508. {
  15509. for (int i = numSamples; --i >= 0;)
  15510. {
  15511. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15512. }
  15513. }
  15514. }
  15515. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15516. || ! output->write (buffer, bytes))
  15517. {
  15518. // failed to write to disk, so let's try writing the header.
  15519. // If it's just run out of disk space, then if it does manage
  15520. // to write the header, we'll still have a useable file..
  15521. writeHeader();
  15522. writeFailed = true;
  15523. return false;
  15524. }
  15525. else
  15526. {
  15527. bytesWritten += bytes;
  15528. lengthInSamples += numSamples;
  15529. return true;
  15530. }
  15531. }
  15532. juce_UseDebuggingNewOperator
  15533. };
  15534. WavAudioFormat::WavAudioFormat()
  15535. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  15536. {
  15537. }
  15538. WavAudioFormat::~WavAudioFormat()
  15539. {
  15540. }
  15541. const Array <int> WavAudioFormat::getPossibleSampleRates()
  15542. {
  15543. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15544. return Array <int> (rates);
  15545. }
  15546. const Array <int> WavAudioFormat::getPossibleBitDepths()
  15547. {
  15548. const int depths[] = { 8, 16, 24, 32, 0 };
  15549. return Array <int> (depths);
  15550. }
  15551. bool WavAudioFormat::canDoStereo()
  15552. {
  15553. return true;
  15554. }
  15555. bool WavAudioFormat::canDoMono()
  15556. {
  15557. return true;
  15558. }
  15559. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  15560. const bool deleteStreamIfOpeningFails)
  15561. {
  15562. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  15563. if (r->sampleRate == 0)
  15564. {
  15565. if (! deleteStreamIfOpeningFails)
  15566. r->input = 0;
  15567. deleteAndZero (r);
  15568. }
  15569. return r;
  15570. }
  15571. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  15572. double sampleRate,
  15573. unsigned int numChannels,
  15574. int bitsPerSample,
  15575. const StringPairArray& metadataValues,
  15576. int /*qualityOptionIndex*/)
  15577. {
  15578. if (getPossibleBitDepths().contains (bitsPerSample))
  15579. {
  15580. return new WavAudioFormatWriter (out,
  15581. sampleRate,
  15582. numChannels,
  15583. bitsPerSample,
  15584. metadataValues);
  15585. }
  15586. return 0;
  15587. }
  15588. END_JUCE_NAMESPACE
  15589. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  15590. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15591. BEGIN_JUCE_NAMESPACE
  15592. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  15593. const bool deleteReaderWhenThisIsDeleted)
  15594. : reader (reader_),
  15595. deleteReader (deleteReaderWhenThisIsDeleted),
  15596. nextPlayPos (0),
  15597. looping (false)
  15598. {
  15599. jassert (reader != 0);
  15600. }
  15601. AudioFormatReaderSource::~AudioFormatReaderSource()
  15602. {
  15603. releaseResources();
  15604. if (deleteReader)
  15605. delete reader;
  15606. }
  15607. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  15608. {
  15609. nextPlayPos = newPosition;
  15610. }
  15611. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  15612. {
  15613. looping = shouldLoop;
  15614. }
  15615. int AudioFormatReaderSource::getNextReadPosition() const
  15616. {
  15617. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  15618. : nextPlayPos;
  15619. }
  15620. int AudioFormatReaderSource::getTotalLength() const
  15621. {
  15622. return (int) reader->lengthInSamples;
  15623. }
  15624. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  15625. double /*sampleRate*/)
  15626. {
  15627. }
  15628. void AudioFormatReaderSource::releaseResources()
  15629. {
  15630. }
  15631. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15632. {
  15633. if (info.numSamples > 0)
  15634. {
  15635. const int start = nextPlayPos;
  15636. if (looping)
  15637. {
  15638. const int newStart = start % (int) reader->lengthInSamples;
  15639. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  15640. if (newEnd > newStart)
  15641. {
  15642. info.buffer->readFromAudioReader (reader,
  15643. info.startSample,
  15644. newEnd - newStart,
  15645. newStart,
  15646. true, true);
  15647. }
  15648. else
  15649. {
  15650. const int endSamps = (int) reader->lengthInSamples - newStart;
  15651. info.buffer->readFromAudioReader (reader,
  15652. info.startSample,
  15653. endSamps,
  15654. newStart,
  15655. true, true);
  15656. info.buffer->readFromAudioReader (reader,
  15657. info.startSample + endSamps,
  15658. newEnd,
  15659. 0,
  15660. true, true);
  15661. }
  15662. nextPlayPos = newEnd;
  15663. }
  15664. else
  15665. {
  15666. info.buffer->readFromAudioReader (reader,
  15667. info.startSample,
  15668. info.numSamples,
  15669. start,
  15670. true, true);
  15671. nextPlayPos += info.numSamples;
  15672. }
  15673. }
  15674. }
  15675. END_JUCE_NAMESPACE
  15676. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15677. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  15678. BEGIN_JUCE_NAMESPACE
  15679. AudioSourcePlayer::AudioSourcePlayer()
  15680. : source (0),
  15681. sampleRate (0),
  15682. bufferSize (0),
  15683. tempBuffer (2, 8)
  15684. {
  15685. }
  15686. AudioSourcePlayer::~AudioSourcePlayer()
  15687. {
  15688. setSource (0);
  15689. }
  15690. void AudioSourcePlayer::setSource (AudioSource* newSource)
  15691. {
  15692. if (source != newSource)
  15693. {
  15694. AudioSource* const oldSource = source;
  15695. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  15696. newSource->prepareToPlay (bufferSize, sampleRate);
  15697. {
  15698. const ScopedLock sl (readLock);
  15699. source = newSource;
  15700. }
  15701. if (oldSource != 0)
  15702. oldSource->releaseResources();
  15703. }
  15704. }
  15705. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  15706. int totalNumInputChannels,
  15707. float** outputChannelData,
  15708. int totalNumOutputChannels,
  15709. int numSamples)
  15710. {
  15711. // these should have been prepared by audioDeviceAboutToStart()...
  15712. jassert (sampleRate > 0 && bufferSize > 0);
  15713. const ScopedLock sl (readLock);
  15714. if (source != 0)
  15715. {
  15716. AudioSourceChannelInfo info;
  15717. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  15718. // messy stuff needed to compact the channels down into an array
  15719. // of non-zero pointers..
  15720. for (i = 0; i < totalNumInputChannels; ++i)
  15721. {
  15722. if (inputChannelData[i] != 0)
  15723. {
  15724. inputChans [numInputs++] = inputChannelData[i];
  15725. if (numInputs >= numElementsInArray (inputChans))
  15726. break;
  15727. }
  15728. }
  15729. for (i = 0; i < totalNumOutputChannels; ++i)
  15730. {
  15731. if (outputChannelData[i] != 0)
  15732. {
  15733. outputChans [numOutputs++] = outputChannelData[i];
  15734. if (numOutputs >= numElementsInArray (outputChans))
  15735. break;
  15736. }
  15737. }
  15738. if (numInputs > numOutputs)
  15739. {
  15740. // if there aren't enough output channels for the number of
  15741. // inputs, we need to create some temporary extra ones (can't
  15742. // use the input data in case it gets written to)
  15743. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  15744. false, false, true);
  15745. for (i = 0; i < numOutputs; ++i)
  15746. {
  15747. channels[numActiveChans] = outputChans[i];
  15748. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15749. ++numActiveChans;
  15750. }
  15751. for (i = numOutputs; i < numInputs; ++i)
  15752. {
  15753. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  15754. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15755. ++numActiveChans;
  15756. }
  15757. }
  15758. else
  15759. {
  15760. for (i = 0; i < numInputs; ++i)
  15761. {
  15762. channels[numActiveChans] = outputChans[i];
  15763. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15764. ++numActiveChans;
  15765. }
  15766. for (i = numInputs; i < numOutputs; ++i)
  15767. {
  15768. channels[numActiveChans] = outputChans[i];
  15769. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  15770. ++numActiveChans;
  15771. }
  15772. }
  15773. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  15774. info.buffer = &buffer;
  15775. info.startSample = 0;
  15776. info.numSamples = numSamples;
  15777. source->getNextAudioBlock (info);
  15778. }
  15779. else
  15780. {
  15781. for (int i = 0; i < totalNumOutputChannels; ++i)
  15782. if (outputChannelData[i] != 0)
  15783. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  15784. }
  15785. }
  15786. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  15787. {
  15788. sampleRate = device->getCurrentSampleRate();
  15789. bufferSize = device->getCurrentBufferSizeSamples();
  15790. zeromem (channels, sizeof (channels));
  15791. if (source != 0)
  15792. source->prepareToPlay (bufferSize, sampleRate);
  15793. }
  15794. void AudioSourcePlayer::audioDeviceStopped()
  15795. {
  15796. if (source != 0)
  15797. source->releaseResources();
  15798. sampleRate = 0.0;
  15799. bufferSize = 0;
  15800. tempBuffer.setSize (2, 8);
  15801. }
  15802. END_JUCE_NAMESPACE
  15803. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  15804. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  15805. BEGIN_JUCE_NAMESPACE
  15806. AudioTransportSource::AudioTransportSource()
  15807. : source (0),
  15808. resamplerSource (0),
  15809. bufferingSource (0),
  15810. positionableSource (0),
  15811. masterSource (0),
  15812. gain (1.0f),
  15813. lastGain (1.0f),
  15814. playing (false),
  15815. stopped (true),
  15816. sampleRate (44100.0),
  15817. sourceSampleRate (0.0),
  15818. blockSize (128),
  15819. readAheadBufferSize (0),
  15820. isPrepared (false),
  15821. inputStreamEOF (false)
  15822. {
  15823. }
  15824. AudioTransportSource::~AudioTransportSource()
  15825. {
  15826. setSource (0);
  15827. releaseResources();
  15828. }
  15829. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  15830. int readAheadBufferSize_,
  15831. double sourceSampleRateToCorrectFor)
  15832. {
  15833. if (source == newSource)
  15834. {
  15835. if (source == 0)
  15836. return;
  15837. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  15838. }
  15839. readAheadBufferSize = readAheadBufferSize_;
  15840. sourceSampleRate = sourceSampleRateToCorrectFor;
  15841. ResamplingAudioSource* newResamplerSource = 0;
  15842. BufferingAudioSource* newBufferingSource = 0;
  15843. PositionableAudioSource* newPositionableSource = 0;
  15844. AudioSource* newMasterSource = 0;
  15845. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  15846. BufferingAudioSource* oldBufferingSource = bufferingSource;
  15847. AudioSource* oldMasterSource = masterSource;
  15848. if (newSource != 0)
  15849. {
  15850. newPositionableSource = newSource;
  15851. if (readAheadBufferSize_ > 0)
  15852. newPositionableSource = newBufferingSource
  15853. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  15854. newPositionableSource->setNextReadPosition (0);
  15855. if (sourceSampleRateToCorrectFor != 0)
  15856. newMasterSource = newResamplerSource
  15857. = new ResamplingAudioSource (newPositionableSource, false);
  15858. else
  15859. newMasterSource = newPositionableSource;
  15860. if (isPrepared)
  15861. {
  15862. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  15863. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15864. newMasterSource->prepareToPlay (blockSize, sampleRate);
  15865. }
  15866. }
  15867. {
  15868. const ScopedLock sl (callbackLock);
  15869. source = newSource;
  15870. resamplerSource = newResamplerSource;
  15871. bufferingSource = newBufferingSource;
  15872. masterSource = newMasterSource;
  15873. positionableSource = newPositionableSource;
  15874. playing = false;
  15875. }
  15876. if (oldMasterSource != 0)
  15877. oldMasterSource->releaseResources();
  15878. if (oldResamplerSource != 0)
  15879. delete oldResamplerSource;
  15880. if (oldBufferingSource != 0)
  15881. delete oldBufferingSource;
  15882. }
  15883. void AudioTransportSource::start()
  15884. {
  15885. if ((! playing) && masterSource != 0)
  15886. {
  15887. callbackLock.enter();
  15888. playing = true;
  15889. stopped = false;
  15890. inputStreamEOF = false;
  15891. callbackLock.exit();
  15892. sendChangeMessage (this);
  15893. }
  15894. }
  15895. void AudioTransportSource::stop()
  15896. {
  15897. if (playing)
  15898. {
  15899. callbackLock.enter();
  15900. playing = false;
  15901. callbackLock.exit();
  15902. int n = 500;
  15903. while (--n >= 0 && ! stopped)
  15904. Thread::sleep (2);
  15905. sendChangeMessage (this);
  15906. }
  15907. }
  15908. void AudioTransportSource::setPosition (double newPosition)
  15909. {
  15910. if (sampleRate > 0.0)
  15911. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  15912. }
  15913. double AudioTransportSource::getCurrentPosition() const
  15914. {
  15915. if (sampleRate > 0.0)
  15916. return getNextReadPosition() / sampleRate;
  15917. else
  15918. return 0.0;
  15919. }
  15920. void AudioTransportSource::setNextReadPosition (int newPosition)
  15921. {
  15922. if (positionableSource != 0)
  15923. {
  15924. if (sampleRate > 0 && sourceSampleRate > 0)
  15925. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  15926. positionableSource->setNextReadPosition (newPosition);
  15927. }
  15928. }
  15929. int AudioTransportSource::getNextReadPosition() const
  15930. {
  15931. if (positionableSource != 0)
  15932. {
  15933. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15934. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  15935. }
  15936. return 0;
  15937. }
  15938. int AudioTransportSource::getTotalLength() const
  15939. {
  15940. const ScopedLock sl (callbackLock);
  15941. if (positionableSource != 0)
  15942. {
  15943. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15944. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  15945. }
  15946. return 0;
  15947. }
  15948. bool AudioTransportSource::isLooping() const
  15949. {
  15950. const ScopedLock sl (callbackLock);
  15951. return positionableSource != 0
  15952. && positionableSource->isLooping();
  15953. }
  15954. void AudioTransportSource::setGain (const float newGain) throw()
  15955. {
  15956. gain = newGain;
  15957. }
  15958. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  15959. double sampleRate_)
  15960. {
  15961. const ScopedLock sl (callbackLock);
  15962. sampleRate = sampleRate_;
  15963. blockSize = samplesPerBlockExpected;
  15964. if (masterSource != 0)
  15965. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  15966. if (resamplerSource != 0 && sourceSampleRate != 0)
  15967. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15968. isPrepared = true;
  15969. }
  15970. void AudioTransportSource::releaseResources()
  15971. {
  15972. const ScopedLock sl (callbackLock);
  15973. if (masterSource != 0)
  15974. masterSource->releaseResources();
  15975. isPrepared = false;
  15976. }
  15977. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15978. {
  15979. const ScopedLock sl (callbackLock);
  15980. inputStreamEOF = false;
  15981. if (masterSource != 0 && ! stopped)
  15982. {
  15983. masterSource->getNextAudioBlock (info);
  15984. if (! playing)
  15985. {
  15986. // just stopped playing, so fade out the last block..
  15987. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  15988. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  15989. if (info.numSamples > 256)
  15990. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  15991. }
  15992. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  15993. && ! positionableSource->isLooping())
  15994. {
  15995. playing = false;
  15996. inputStreamEOF = true;
  15997. sendChangeMessage (this);
  15998. }
  15999. stopped = ! playing;
  16000. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16001. {
  16002. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16003. lastGain, gain);
  16004. }
  16005. }
  16006. else
  16007. {
  16008. info.clearActiveBufferRegion();
  16009. stopped = true;
  16010. }
  16011. lastGain = gain;
  16012. }
  16013. END_JUCE_NAMESPACE
  16014. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16015. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16016. BEGIN_JUCE_NAMESPACE
  16017. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16018. public Thread,
  16019. private Timer
  16020. {
  16021. public:
  16022. SharedBufferingAudioSourceThread()
  16023. : Thread ("Audio Buffer"),
  16024. sources (8)
  16025. {
  16026. }
  16027. ~SharedBufferingAudioSourceThread()
  16028. {
  16029. stopThread (10000);
  16030. clearSingletonInstance();
  16031. }
  16032. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16033. void addSource (BufferingAudioSource* source)
  16034. {
  16035. const ScopedLock sl (lock);
  16036. if (! sources.contains ((void*) source))
  16037. {
  16038. sources.add ((void*) source);
  16039. startThread();
  16040. stopTimer();
  16041. }
  16042. notify();
  16043. }
  16044. void removeSource (BufferingAudioSource* source)
  16045. {
  16046. const ScopedLock sl (lock);
  16047. sources.removeValue ((void*) source);
  16048. if (sources.size() == 0)
  16049. startTimer (5000);
  16050. }
  16051. private:
  16052. VoidArray sources;
  16053. CriticalSection lock;
  16054. void run()
  16055. {
  16056. while (! threadShouldExit())
  16057. {
  16058. bool busy = false;
  16059. for (int i = sources.size(); --i >= 0;)
  16060. {
  16061. if (threadShouldExit())
  16062. return;
  16063. const ScopedLock sl (lock);
  16064. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16065. if (b != 0 && b->readNextBufferChunk())
  16066. busy = true;
  16067. }
  16068. if (! busy)
  16069. wait (500);
  16070. }
  16071. }
  16072. void timerCallback()
  16073. {
  16074. stopTimer();
  16075. if (sources.size() == 0)
  16076. deleteInstance();
  16077. }
  16078. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16079. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16080. };
  16081. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16082. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16083. const bool deleteSourceWhenDeleted_,
  16084. int numberOfSamplesToBuffer_)
  16085. : source (source_),
  16086. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16087. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16088. buffer (2, 0),
  16089. bufferValidStart (0),
  16090. bufferValidEnd (0),
  16091. nextPlayPos (0),
  16092. wasSourceLooping (false)
  16093. {
  16094. jassert (source_ != 0);
  16095. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16096. // not using a larger buffer..
  16097. }
  16098. BufferingAudioSource::~BufferingAudioSource()
  16099. {
  16100. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16101. if (thread != 0)
  16102. thread->removeSource (this);
  16103. if (deleteSourceWhenDeleted)
  16104. delete source;
  16105. }
  16106. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16107. {
  16108. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16109. sampleRate = sampleRate_;
  16110. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16111. buffer.clear();
  16112. bufferValidStart = 0;
  16113. bufferValidEnd = 0;
  16114. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16115. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16116. buffer.getNumSamples() / 2))
  16117. {
  16118. SharedBufferingAudioSourceThread::getInstance()->notify();
  16119. Thread::sleep (5);
  16120. }
  16121. }
  16122. void BufferingAudioSource::releaseResources()
  16123. {
  16124. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16125. if (thread != 0)
  16126. thread->removeSource (this);
  16127. buffer.setSize (2, 0);
  16128. source->releaseResources();
  16129. }
  16130. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16131. {
  16132. const ScopedLock sl (bufferStartPosLock);
  16133. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16134. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16135. if (validStart == validEnd)
  16136. {
  16137. // total cache miss
  16138. info.clearActiveBufferRegion();
  16139. }
  16140. else
  16141. {
  16142. if (validStart > 0)
  16143. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16144. if (validEnd < info.numSamples)
  16145. info.buffer->clear (info.startSample + validEnd,
  16146. info.numSamples - validEnd); // partial cache miss at end
  16147. if (validStart < validEnd)
  16148. {
  16149. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16150. {
  16151. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16152. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16153. if (startBufferIndex < endBufferIndex)
  16154. {
  16155. info.buffer->copyFrom (chan, info.startSample + validStart,
  16156. buffer,
  16157. chan, startBufferIndex,
  16158. validEnd - validStart);
  16159. }
  16160. else
  16161. {
  16162. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16163. info.buffer->copyFrom (chan, info.startSample + validStart,
  16164. buffer,
  16165. chan, startBufferIndex,
  16166. initialSize);
  16167. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16168. buffer,
  16169. chan, 0,
  16170. (validEnd - validStart) - initialSize);
  16171. }
  16172. }
  16173. }
  16174. nextPlayPos += info.numSamples;
  16175. }
  16176. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16177. if (thread != 0)
  16178. thread->notify();
  16179. }
  16180. int BufferingAudioSource::getNextReadPosition() const
  16181. {
  16182. return (source->isLooping() && nextPlayPos > 0)
  16183. ? nextPlayPos % source->getTotalLength()
  16184. : nextPlayPos;
  16185. }
  16186. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16187. {
  16188. const ScopedLock sl (bufferStartPosLock);
  16189. nextPlayPos = newPosition;
  16190. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16191. if (thread != 0)
  16192. thread->notify();
  16193. }
  16194. bool BufferingAudioSource::readNextBufferChunk()
  16195. {
  16196. bufferStartPosLock.enter();
  16197. if (wasSourceLooping != isLooping())
  16198. {
  16199. wasSourceLooping = isLooping();
  16200. bufferValidStart = 0;
  16201. bufferValidEnd = 0;
  16202. }
  16203. int newBVS = jmax (0, nextPlayPos);
  16204. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16205. int sectionToReadStart = 0;
  16206. int sectionToReadEnd = 0;
  16207. const int maxChunkSize = 2048;
  16208. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16209. {
  16210. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16211. sectionToReadStart = newBVS;
  16212. sectionToReadEnd = newBVE;
  16213. bufferValidStart = 0;
  16214. bufferValidEnd = 0;
  16215. }
  16216. else if (abs (newBVS - bufferValidStart) > 512
  16217. || abs (newBVE - bufferValidEnd) > 512)
  16218. {
  16219. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16220. sectionToReadStart = bufferValidEnd;
  16221. sectionToReadEnd = newBVE;
  16222. bufferValidStart = newBVS;
  16223. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16224. }
  16225. bufferStartPosLock.exit();
  16226. if (sectionToReadStart != sectionToReadEnd)
  16227. {
  16228. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16229. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16230. if (bufferIndexStart < bufferIndexEnd)
  16231. {
  16232. readBufferSection (sectionToReadStart,
  16233. sectionToReadEnd - sectionToReadStart,
  16234. bufferIndexStart);
  16235. }
  16236. else
  16237. {
  16238. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16239. readBufferSection (sectionToReadStart,
  16240. initialSize,
  16241. bufferIndexStart);
  16242. readBufferSection (sectionToReadStart + initialSize,
  16243. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16244. 0);
  16245. }
  16246. const ScopedLock sl2 (bufferStartPosLock);
  16247. bufferValidStart = newBVS;
  16248. bufferValidEnd = newBVE;
  16249. return true;
  16250. }
  16251. else
  16252. {
  16253. return false;
  16254. }
  16255. }
  16256. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16257. {
  16258. if (source->getNextReadPosition() != start)
  16259. source->setNextReadPosition (start);
  16260. AudioSourceChannelInfo info;
  16261. info.buffer = &buffer;
  16262. info.startSample = bufferOffset;
  16263. info.numSamples = length;
  16264. source->getNextAudioBlock (info);
  16265. }
  16266. END_JUCE_NAMESPACE
  16267. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16268. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16269. BEGIN_JUCE_NAMESPACE
  16270. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16271. const bool deleteSourceWhenDeleted_)
  16272. : requiredNumberOfChannels (2),
  16273. source (source_),
  16274. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16275. buffer (2, 16)
  16276. {
  16277. remappedInfo.buffer = &buffer;
  16278. remappedInfo.startSample = 0;
  16279. }
  16280. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16281. {
  16282. if (deleteSourceWhenDeleted)
  16283. delete source;
  16284. }
  16285. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16286. {
  16287. const ScopedLock sl (lock);
  16288. requiredNumberOfChannels = requiredNumberOfChannels_;
  16289. }
  16290. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16291. {
  16292. const ScopedLock sl (lock);
  16293. remappedInputs.clear();
  16294. remappedOutputs.clear();
  16295. }
  16296. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16297. {
  16298. const ScopedLock sl (lock);
  16299. while (remappedInputs.size() < destIndex)
  16300. remappedInputs.add (-1);
  16301. remappedInputs.set (destIndex, sourceIndex);
  16302. }
  16303. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16304. {
  16305. const ScopedLock sl (lock);
  16306. while (remappedOutputs.size() < sourceIndex)
  16307. remappedOutputs.add (-1);
  16308. remappedOutputs.set (sourceIndex, destIndex);
  16309. }
  16310. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16311. {
  16312. const ScopedLock sl (lock);
  16313. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16314. return remappedInputs.getUnchecked (inputChannelIndex);
  16315. return -1;
  16316. }
  16317. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16318. {
  16319. const ScopedLock sl (lock);
  16320. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16321. return remappedOutputs .getUnchecked (outputChannelIndex);
  16322. return -1;
  16323. }
  16324. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16325. {
  16326. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16327. }
  16328. void ChannelRemappingAudioSource::releaseResources()
  16329. {
  16330. source->releaseResources();
  16331. }
  16332. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16333. {
  16334. const ScopedLock sl (lock);
  16335. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16336. const int numChans = bufferToFill.buffer->getNumChannels();
  16337. int i;
  16338. for (i = 0; i < buffer.getNumChannels(); ++i)
  16339. {
  16340. const int remappedChan = getRemappedInputChannel (i);
  16341. if (remappedChan >= 0 && remappedChan < numChans)
  16342. {
  16343. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16344. remappedChan,
  16345. bufferToFill.startSample,
  16346. bufferToFill.numSamples);
  16347. }
  16348. else
  16349. {
  16350. buffer.clear (i, 0, bufferToFill.numSamples);
  16351. }
  16352. }
  16353. remappedInfo.numSamples = bufferToFill.numSamples;
  16354. source->getNextAudioBlock (remappedInfo);
  16355. bufferToFill.clearActiveBufferRegion();
  16356. for (i = 0; i < requiredNumberOfChannels; ++i)
  16357. {
  16358. const int remappedChan = getRemappedOutputChannel (i);
  16359. if (remappedChan >= 0 && remappedChan < numChans)
  16360. {
  16361. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16362. buffer, i, 0, bufferToFill.numSamples);
  16363. }
  16364. }
  16365. }
  16366. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16367. {
  16368. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16369. String ins, outs;
  16370. int i;
  16371. const ScopedLock sl (lock);
  16372. for (i = 0; i < remappedInputs.size(); ++i)
  16373. ins << remappedInputs.getUnchecked(i) << T(' ');
  16374. for (i = 0; i < remappedOutputs.size(); ++i)
  16375. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16376. e->setAttribute (T("inputs"), ins.trimEnd());
  16377. e->setAttribute (T("outputs"), outs.trimEnd());
  16378. return e;
  16379. }
  16380. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16381. {
  16382. if (e.hasTagName (T("MAPPINGS")))
  16383. {
  16384. const ScopedLock sl (lock);
  16385. clearAllMappings();
  16386. StringArray ins, outs;
  16387. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  16388. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  16389. int i;
  16390. for (i = 0; i < ins.size(); ++i)
  16391. remappedInputs.add (ins[i].getIntValue());
  16392. for (i = 0; i < outs.size(); ++i)
  16393. remappedOutputs.add (outs[i].getIntValue());
  16394. }
  16395. }
  16396. END_JUCE_NAMESPACE
  16397. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16398. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16399. BEGIN_JUCE_NAMESPACE
  16400. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  16401. const bool deleteInputWhenDeleted_)
  16402. : input (inputSource),
  16403. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  16404. {
  16405. jassert (inputSource != 0);
  16406. for (int i = 2; --i >= 0;)
  16407. iirFilters.add (new IIRFilter());
  16408. }
  16409. IIRFilterAudioSource::~IIRFilterAudioSource()
  16410. {
  16411. if (deleteInputWhenDeleted)
  16412. delete input;
  16413. }
  16414. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  16415. {
  16416. for (int i = iirFilters.size(); --i >= 0;)
  16417. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  16418. }
  16419. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16420. {
  16421. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16422. for (int i = iirFilters.size(); --i >= 0;)
  16423. iirFilters.getUnchecked(i)->reset();
  16424. }
  16425. void IIRFilterAudioSource::releaseResources()
  16426. {
  16427. input->releaseResources();
  16428. }
  16429. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16430. {
  16431. input->getNextAudioBlock (bufferToFill);
  16432. const int numChannels = bufferToFill.buffer->getNumChannels();
  16433. while (numChannels > iirFilters.size())
  16434. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  16435. for (int i = 0; i < numChannels; ++i)
  16436. iirFilters.getUnchecked(i)
  16437. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  16438. bufferToFill.numSamples);
  16439. }
  16440. END_JUCE_NAMESPACE
  16441. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16442. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  16443. BEGIN_JUCE_NAMESPACE
  16444. MixerAudioSource::MixerAudioSource()
  16445. : tempBuffer (2, 0),
  16446. currentSampleRate (0.0),
  16447. bufferSizeExpected (0)
  16448. {
  16449. }
  16450. MixerAudioSource::~MixerAudioSource()
  16451. {
  16452. removeAllInputs();
  16453. }
  16454. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  16455. {
  16456. if (input != 0 && ! inputs.contains (input))
  16457. {
  16458. lock.enter();
  16459. double localRate = currentSampleRate;
  16460. int localBufferSize = bufferSizeExpected;
  16461. lock.exit();
  16462. if (localRate != 0.0)
  16463. input->prepareToPlay (localBufferSize, localRate);
  16464. const ScopedLock sl (lock);
  16465. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  16466. inputs.add (input);
  16467. }
  16468. }
  16469. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  16470. {
  16471. if (input != 0)
  16472. {
  16473. lock.enter();
  16474. const int index = inputs.indexOf ((void*) input);
  16475. if (index >= 0)
  16476. {
  16477. inputsToDelete.shiftBits (index, 1);
  16478. inputs.remove (index);
  16479. }
  16480. lock.exit();
  16481. if (index >= 0)
  16482. {
  16483. input->releaseResources();
  16484. if (deleteInput)
  16485. delete input;
  16486. }
  16487. }
  16488. }
  16489. void MixerAudioSource::removeAllInputs()
  16490. {
  16491. lock.enter();
  16492. VoidArray inputsCopy (inputs);
  16493. BitArray inputsToDeleteCopy (inputsToDelete);
  16494. inputs.clear();
  16495. lock.exit();
  16496. for (int i = inputsCopy.size(); --i >= 0;)
  16497. if (inputsToDeleteCopy[i])
  16498. delete (AudioSource*) inputsCopy[i];
  16499. }
  16500. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16501. {
  16502. tempBuffer.setSize (2, samplesPerBlockExpected);
  16503. const ScopedLock sl (lock);
  16504. currentSampleRate = sampleRate;
  16505. bufferSizeExpected = samplesPerBlockExpected;
  16506. for (int i = inputs.size(); --i >= 0;)
  16507. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  16508. sampleRate);
  16509. }
  16510. void MixerAudioSource::releaseResources()
  16511. {
  16512. const ScopedLock sl (lock);
  16513. for (int i = inputs.size(); --i >= 0;)
  16514. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  16515. tempBuffer.setSize (2, 0);
  16516. currentSampleRate = 0;
  16517. bufferSizeExpected = 0;
  16518. }
  16519. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16520. {
  16521. const ScopedLock sl (lock);
  16522. if (inputs.size() > 0)
  16523. {
  16524. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  16525. if (inputs.size() > 1)
  16526. {
  16527. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  16528. info.buffer->getNumSamples());
  16529. AudioSourceChannelInfo info2;
  16530. info2.buffer = &tempBuffer;
  16531. info2.numSamples = info.numSamples;
  16532. info2.startSample = 0;
  16533. for (int i = 1; i < inputs.size(); ++i)
  16534. {
  16535. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  16536. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  16537. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  16538. }
  16539. }
  16540. }
  16541. else
  16542. {
  16543. info.clearActiveBufferRegion();
  16544. }
  16545. }
  16546. END_JUCE_NAMESPACE
  16547. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  16548. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  16549. BEGIN_JUCE_NAMESPACE
  16550. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  16551. const bool deleteInputWhenDeleted_)
  16552. : input (inputSource),
  16553. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  16554. ratio (1.0),
  16555. lastRatio (1.0),
  16556. buffer (2, 0),
  16557. sampsInBuffer (0)
  16558. {
  16559. jassert (input != 0);
  16560. }
  16561. ResamplingAudioSource::~ResamplingAudioSource()
  16562. {
  16563. if (deleteInputWhenDeleted)
  16564. delete input;
  16565. }
  16566. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  16567. {
  16568. jassert (samplesInPerOutputSample > 0);
  16569. const ScopedLock sl (ratioLock);
  16570. ratio = jmax (0.0, samplesInPerOutputSample);
  16571. }
  16572. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  16573. double sampleRate)
  16574. {
  16575. const ScopedLock sl (ratioLock);
  16576. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16577. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  16578. buffer.clear();
  16579. sampsInBuffer = 0;
  16580. bufferPos = 0;
  16581. subSampleOffset = 0.0;
  16582. createLowPass (ratio);
  16583. resetFilters();
  16584. }
  16585. void ResamplingAudioSource::releaseResources()
  16586. {
  16587. input->releaseResources();
  16588. buffer.setSize (2, 0);
  16589. }
  16590. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16591. {
  16592. const ScopedLock sl (ratioLock);
  16593. if (lastRatio != ratio)
  16594. {
  16595. createLowPass (ratio);
  16596. lastRatio = ratio;
  16597. }
  16598. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  16599. int bufferSize = buffer.getNumSamples();
  16600. if (bufferSize < sampsNeeded + 8)
  16601. {
  16602. bufferPos %= bufferSize;
  16603. bufferSize = sampsNeeded + 32;
  16604. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  16605. }
  16606. bufferPos %= bufferSize;
  16607. int endOfBufferPos = bufferPos + sampsInBuffer;
  16608. while (sampsNeeded > sampsInBuffer)
  16609. {
  16610. endOfBufferPos %= bufferSize;
  16611. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  16612. bufferSize - endOfBufferPos);
  16613. AudioSourceChannelInfo readInfo;
  16614. readInfo.buffer = &buffer;
  16615. readInfo.numSamples = numToDo;
  16616. readInfo.startSample = endOfBufferPos;
  16617. input->getNextAudioBlock (readInfo);
  16618. if (ratio > 1.0)
  16619. {
  16620. // for down-sampling, pre-apply the filter..
  16621. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16622. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  16623. }
  16624. sampsInBuffer += numToDo;
  16625. endOfBufferPos += numToDo;
  16626. }
  16627. float* dl = info.buffer->getSampleData (0, info.startSample);
  16628. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  16629. const float* const bl = buffer.getSampleData (0, 0);
  16630. const float* const br = buffer.getSampleData (1, 0);
  16631. int nextPos = (bufferPos + 1) % bufferSize;
  16632. for (int m = info.numSamples; --m >= 0;)
  16633. {
  16634. const float alpha = (float) subSampleOffset;
  16635. const float invAlpha = 1.0f - alpha;
  16636. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  16637. if (dr != 0)
  16638. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  16639. subSampleOffset += ratio;
  16640. jassert (sampsInBuffer > 0);
  16641. while (subSampleOffset >= 1.0)
  16642. {
  16643. if (++bufferPos >= bufferSize)
  16644. bufferPos = 0;
  16645. --sampsInBuffer;
  16646. nextPos = (bufferPos + 1) % bufferSize;
  16647. subSampleOffset -= 1.0;
  16648. }
  16649. }
  16650. if (ratio < 1.0)
  16651. {
  16652. // for up-sampling, apply the filter after transposing..
  16653. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16654. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  16655. }
  16656. jassert (sampsInBuffer >= 0);
  16657. }
  16658. void ResamplingAudioSource::createLowPass (const double ratio)
  16659. {
  16660. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  16661. : 0.5 * ratio;
  16662. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  16663. const double nSquared = n * n;
  16664. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  16665. setFilterCoefficients (c1,
  16666. c1 * 2.0f,
  16667. c1,
  16668. 1.0,
  16669. c1 * 2.0 * (1.0 - nSquared),
  16670. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  16671. }
  16672. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  16673. {
  16674. const double a = 1.0 / c4;
  16675. c1 *= a;
  16676. c2 *= a;
  16677. c3 *= a;
  16678. c5 *= a;
  16679. c6 *= a;
  16680. coefficients[0] = c1;
  16681. coefficients[1] = c2;
  16682. coefficients[2] = c3;
  16683. coefficients[3] = c4;
  16684. coefficients[4] = c5;
  16685. coefficients[5] = c6;
  16686. }
  16687. void ResamplingAudioSource::resetFilters()
  16688. {
  16689. zeromem (filterStates, sizeof (filterStates));
  16690. }
  16691. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  16692. {
  16693. while (--num >= 0)
  16694. {
  16695. const double in = *samples;
  16696. double out = coefficients[0] * in
  16697. + coefficients[1] * fs.x1
  16698. + coefficients[2] * fs.x2
  16699. - coefficients[4] * fs.y1
  16700. - coefficients[5] * fs.y2;
  16701. #if JUCE_INTEL
  16702. if (! (out < -1.0e-8 || out > 1.0e-8))
  16703. out = 0;
  16704. #endif
  16705. fs.x2 = fs.x1;
  16706. fs.x1 = in;
  16707. fs.y2 = fs.y1;
  16708. fs.y1 = out;
  16709. *samples++ = (float) out;
  16710. }
  16711. }
  16712. END_JUCE_NAMESPACE
  16713. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  16714. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16715. BEGIN_JUCE_NAMESPACE
  16716. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  16717. : frequency (1000.0),
  16718. sampleRate (44100.0),
  16719. currentPhase (0.0),
  16720. phasePerSample (0.0),
  16721. amplitude (0.5f)
  16722. {
  16723. }
  16724. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  16725. {
  16726. }
  16727. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  16728. {
  16729. amplitude = newAmplitude;
  16730. }
  16731. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  16732. {
  16733. frequency = newFrequencyHz;
  16734. phasePerSample = 0.0;
  16735. }
  16736. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16737. double sampleRate_)
  16738. {
  16739. currentPhase = 0.0;
  16740. phasePerSample = 0.0;
  16741. sampleRate = sampleRate_;
  16742. }
  16743. void ToneGeneratorAudioSource::releaseResources()
  16744. {
  16745. }
  16746. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16747. {
  16748. if (phasePerSample == 0.0)
  16749. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  16750. for (int i = 0; i < info.numSamples; ++i)
  16751. {
  16752. const float sample = amplitude * (float) sin (currentPhase);
  16753. currentPhase += phasePerSample;
  16754. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  16755. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  16756. }
  16757. }
  16758. END_JUCE_NAMESPACE
  16759. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16760. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  16761. BEGIN_JUCE_NAMESPACE
  16762. AudioDeviceManager::AudioDeviceManager()
  16763. : currentAudioDevice (0),
  16764. currentCallback (0),
  16765. numInputChansNeeded (0),
  16766. numOutputChansNeeded (2),
  16767. lastExplicitSettings (0),
  16768. listNeedsScanning (true),
  16769. useInputNames (false),
  16770. enabledMidiInputs (4),
  16771. midiCallbacks (4),
  16772. midiCallbackDevices (4),
  16773. defaultMidiOutput (0),
  16774. cpuUsageMs (0),
  16775. timeToCpuScale (0)
  16776. {
  16777. callbackHandler.owner = this;
  16778. AudioIODeviceType::createDeviceTypes (availableDeviceTypes);
  16779. }
  16780. AudioDeviceManager::~AudioDeviceManager()
  16781. {
  16782. stopDevice();
  16783. deleteAndZero (currentAudioDevice);
  16784. deleteAndZero (defaultMidiOutput);
  16785. delete lastExplicitSettings;
  16786. }
  16787. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  16788. const int numOutputChannelsNeeded,
  16789. const XmlElement* const e,
  16790. const bool selectDefaultDeviceOnFailure,
  16791. const String& preferredDefaultDeviceName)
  16792. {
  16793. if (listNeedsScanning)
  16794. refreshDeviceList();
  16795. numInputChansNeeded = numInputChannelsNeeded;
  16796. numOutputChansNeeded = numOutputChannelsNeeded;
  16797. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  16798. {
  16799. lastExplicitSettings = new XmlElement (*e);
  16800. BitArray ins, outs;
  16801. ins.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  16802. outs.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  16803. String error (setAudioDevice (e->getStringAttribute (T("audioDeviceName")),
  16804. e->getIntAttribute (T("audioDeviceBufferSize")),
  16805. e->getDoubleAttribute (T("audioDeviceRate")),
  16806. e->hasAttribute (T("audioDeviceInChans")) ? &ins : 0,
  16807. e->hasAttribute (T("audioDeviceOutChans")) ? &outs : 0,
  16808. true));
  16809. midiInsFromXml.clear();
  16810. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  16811. midiInsFromXml.add (c->getStringAttribute (T("name")));
  16812. const StringArray allMidiIns (MidiInput::getDevices());
  16813. for (int i = allMidiIns.size(); --i >= 0;)
  16814. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  16815. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  16816. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  16817. false, preferredDefaultDeviceName);
  16818. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  16819. return error;
  16820. }
  16821. else
  16822. {
  16823. setInputDeviceNamesUsed (numOutputChannelsNeeded == 0);
  16824. String defaultDevice;
  16825. if (preferredDefaultDeviceName.isNotEmpty())
  16826. {
  16827. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16828. {
  16829. const StringArray devs (availableDeviceTypes.getUnchecked(i)->getDeviceNames());
  16830. for (int j = 0; j < devs.size(); ++j)
  16831. {
  16832. if (devs[j].matchesWildcard (preferredDefaultDeviceName, true))
  16833. {
  16834. defaultDevice = devs[j];
  16835. break;
  16836. }
  16837. }
  16838. }
  16839. }
  16840. if (defaultDevice.isEmpty() && availableDeviceTypes [0] != 0)
  16841. defaultDevice = availableDeviceTypes[0]->getDefaultDeviceName (numOutputChannelsNeeded == 0,
  16842. numInputChannelsNeeded,
  16843. numOutputChannelsNeeded);
  16844. return setAudioDevice (defaultDevice, 0, 0, 0, 0, false);
  16845. }
  16846. }
  16847. XmlElement* AudioDeviceManager::createStateXml() const
  16848. {
  16849. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  16850. }
  16851. const StringArray AudioDeviceManager::getAvailableAudioDeviceNames() const
  16852. {
  16853. if (listNeedsScanning)
  16854. refreshDeviceList();
  16855. StringArray names;
  16856. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16857. names.addArray (availableDeviceTypes[i]->getDeviceNames (useInputNames));
  16858. return names;
  16859. }
  16860. void AudioDeviceManager::refreshDeviceList() const
  16861. {
  16862. listNeedsScanning = false;
  16863. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16864. availableDeviceTypes[i]->scanForDevices();
  16865. }
  16866. void AudioDeviceManager::setInputDeviceNamesUsed (const bool useInputNames_)
  16867. {
  16868. useInputNames = useInputNames_;
  16869. sendChangeMessage (this);
  16870. }
  16871. void AudioDeviceManager::addDeviceNamesToComboBox (ComboBox& combo) const
  16872. {
  16873. int n = 0;
  16874. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16875. {
  16876. AudioIODeviceType* const type = availableDeviceTypes[i];
  16877. if (availableDeviceTypes.size() > 1)
  16878. combo.addSectionHeading (type->getTypeName() + T(" devices:"));
  16879. const StringArray names (type->getDeviceNames (useInputNames));
  16880. for (int j = 0; j < names.size(); ++j)
  16881. combo.addItem (names[j], ++n);
  16882. combo.addSeparator();
  16883. }
  16884. combo.addItem (TRANS("<< no audio device >>"), -1);
  16885. }
  16886. const String AudioDeviceManager::getCurrentAudioDeviceName() const
  16887. {
  16888. if (currentAudioDevice != 0)
  16889. return currentAudioDevice->getName();
  16890. return String::empty;
  16891. }
  16892. const String AudioDeviceManager::setAudioDevice (const String& deviceNameToUse,
  16893. int blockSizeToUse,
  16894. double sampleRateToUse,
  16895. const BitArray* inChans,
  16896. const BitArray* outChans,
  16897. const bool treatAsChosenDevice)
  16898. {
  16899. stopDevice();
  16900. String error;
  16901. if (deviceNameToUse.isNotEmpty())
  16902. {
  16903. const StringArray devNames (getAvailableAudioDeviceNames());
  16904. int index = devNames.indexOf (deviceNameToUse, true);
  16905. if (index >= 0)
  16906. {
  16907. if (currentAudioDevice == 0
  16908. || currentAudioDevice->getLastError().isNotEmpty()
  16909. || ! deviceNameToUse.equalsIgnoreCase (currentAudioDevice->getName()))
  16910. {
  16911. // change of device..
  16912. deleteAndZero (currentAudioDevice);
  16913. int n = 0;
  16914. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16915. {
  16916. AudioIODeviceType* const type = availableDeviceTypes[i];
  16917. const StringArray names (type->getDeviceNames (useInputNames));
  16918. if (index >= n && index < n + names.size())
  16919. {
  16920. currentAudioDevice = type->createDevice (deviceNameToUse);
  16921. break;
  16922. }
  16923. n += names.size();
  16924. }
  16925. error = currentAudioDevice->getLastError();
  16926. if (error.isNotEmpty())
  16927. {
  16928. deleteAndZero (currentAudioDevice);
  16929. return error;
  16930. }
  16931. inputChannels.clear();
  16932. inputChannels.setRange (0, numInputChansNeeded, true);
  16933. outputChannels.clear();
  16934. outputChannels.setRange (0, numOutputChansNeeded, true);
  16935. }
  16936. if (inChans != 0)
  16937. inputChannels = *inChans;
  16938. if (outChans != 0)
  16939. outputChannels = *outChans;
  16940. error = restartDevice (blockSizeToUse,
  16941. sampleRateToUse,
  16942. inputChannels,
  16943. outputChannels);
  16944. if (error.isNotEmpty())
  16945. {
  16946. deleteAndZero (currentAudioDevice);
  16947. }
  16948. }
  16949. else
  16950. {
  16951. deleteAndZero (currentAudioDevice);
  16952. error << "No such device: " << deviceNameToUse;
  16953. }
  16954. }
  16955. else
  16956. {
  16957. deleteAndZero (currentAudioDevice);
  16958. }
  16959. if (treatAsChosenDevice && error.isEmpty())
  16960. updateXml();
  16961. return error;
  16962. }
  16963. const String AudioDeviceManager::restartDevice (int blockSizeToUse,
  16964. double sampleRateToUse,
  16965. const BitArray& inChans,
  16966. const BitArray& outChans)
  16967. {
  16968. stopDevice();
  16969. inputChannels = inChans;
  16970. outputChannels = outChans;
  16971. if (sampleRateToUse > 0)
  16972. {
  16973. bool ok = false;
  16974. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  16975. {
  16976. const double sr = currentAudioDevice->getSampleRate (i);
  16977. if (sr == sampleRateToUse)
  16978. ok = true;
  16979. }
  16980. if (! ok)
  16981. sampleRateToUse = 0;
  16982. }
  16983. if (sampleRateToUse == 0)
  16984. {
  16985. double lowestAbove44 = 0.0;
  16986. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  16987. {
  16988. const double sr = currentAudioDevice->getSampleRate (i);
  16989. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  16990. lowestAbove44 = sr;
  16991. }
  16992. if (lowestAbove44 == 0.0)
  16993. sampleRateToUse = currentAudioDevice->getSampleRate (0);
  16994. else
  16995. sampleRateToUse = lowestAbove44;
  16996. }
  16997. const String error (currentAudioDevice->open (inChans, outChans,
  16998. sampleRateToUse, blockSizeToUse));
  16999. if (error.isEmpty())
  17000. currentAudioDevice->start (&callbackHandler);
  17001. sendChangeMessage (this);
  17002. return error;
  17003. }
  17004. void AudioDeviceManager::stopDevice()
  17005. {
  17006. if (currentAudioDevice != 0)
  17007. currentAudioDevice->stop();
  17008. }
  17009. void AudioDeviceManager::closeAudioDevice()
  17010. {
  17011. if (currentAudioDevice != 0)
  17012. {
  17013. lastRunningDevice = currentAudioDevice->getName();
  17014. lastRunningBlockSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17015. lastRunningSampleRate = currentAudioDevice->getCurrentSampleRate();
  17016. lastRunningIns = inputChannels;
  17017. lastRunningOuts = outputChannels;
  17018. stopDevice();
  17019. setAudioDevice (String::empty, 0, 0, 0, 0, false);
  17020. }
  17021. }
  17022. void AudioDeviceManager::restartLastAudioDevice()
  17023. {
  17024. if (currentAudioDevice == 0)
  17025. {
  17026. if (lastRunningDevice.isEmpty())
  17027. {
  17028. // This method will only reload the last device that was running
  17029. // before closeAudioDevice() was called - you need to actually open
  17030. // one first, with setAudioDevice().
  17031. jassertfalse
  17032. return;
  17033. }
  17034. setAudioDevice (lastRunningDevice,
  17035. lastRunningBlockSize,
  17036. lastRunningSampleRate,
  17037. &lastRunningIns,
  17038. &lastRunningOuts,
  17039. false);
  17040. }
  17041. }
  17042. void AudioDeviceManager::setInputChannels (const BitArray& newEnabledChannels,
  17043. const bool treatAsChosenDevice)
  17044. {
  17045. if (currentAudioDevice != 0
  17046. && newEnabledChannels != inputChannels)
  17047. {
  17048. setAudioDevice (currentAudioDevice->getName(),
  17049. currentAudioDevice->getCurrentBufferSizeSamples(),
  17050. currentAudioDevice->getCurrentSampleRate(),
  17051. &newEnabledChannels, 0,
  17052. treatAsChosenDevice);
  17053. }
  17054. }
  17055. void AudioDeviceManager::setOutputChannels (const BitArray& newEnabledChannels,
  17056. const bool treatAsChosenDevice)
  17057. {
  17058. if (currentAudioDevice != 0
  17059. && newEnabledChannels != outputChannels)
  17060. {
  17061. setAudioDevice (currentAudioDevice->getName(),
  17062. currentAudioDevice->getCurrentBufferSizeSamples(),
  17063. currentAudioDevice->getCurrentSampleRate(),
  17064. 0, &newEnabledChannels,
  17065. treatAsChosenDevice);
  17066. }
  17067. }
  17068. void AudioDeviceManager::updateXml()
  17069. {
  17070. delete lastExplicitSettings;
  17071. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17072. lastExplicitSettings->setAttribute (T("audioDeviceName"), getCurrentAudioDeviceName());
  17073. if (currentAudioDevice != 0)
  17074. {
  17075. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17076. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17077. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17078. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), inputChannels.toString (2));
  17079. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), outputChannels.toString (2));
  17080. }
  17081. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17082. {
  17083. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17084. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17085. lastExplicitSettings->addChildElement (m);
  17086. }
  17087. if (midiInsFromXml.size() > 0)
  17088. {
  17089. // Add any midi devices that have been enabled before, but which aren't currently
  17090. // open because the device has been disconnected.
  17091. const StringArray availableMidiDevices (MidiInput::getDevices());
  17092. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17093. {
  17094. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17095. {
  17096. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17097. m->setAttribute (T("name"), midiInsFromXml[i]);
  17098. lastExplicitSettings->addChildElement (m);
  17099. }
  17100. }
  17101. }
  17102. if (defaultMidiOutputName.isNotEmpty())
  17103. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17104. }
  17105. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17106. {
  17107. if (newCallback != currentCallback)
  17108. {
  17109. AudioIODeviceCallback* lastCallback = currentCallback;
  17110. audioCallbackLock.enter();
  17111. currentCallback = 0;
  17112. audioCallbackLock.exit();
  17113. if (currentAudioDevice != 0)
  17114. {
  17115. if (lastCallback != 0)
  17116. lastCallback->audioDeviceStopped();
  17117. if (newCallback != 0)
  17118. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17119. }
  17120. currentCallback = newCallback;
  17121. }
  17122. }
  17123. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17124. int totalNumInputChannels,
  17125. float** outputChannelData,
  17126. int totalNumOutputChannels,
  17127. int numSamples)
  17128. {
  17129. const ScopedLock sl (audioCallbackLock);
  17130. if (currentCallback != 0)
  17131. {
  17132. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17133. currentCallback->audioDeviceIOCallback (inputChannelData,
  17134. totalNumInputChannels,
  17135. outputChannelData,
  17136. totalNumOutputChannels,
  17137. numSamples);
  17138. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17139. const double filterAmount = 0.2;
  17140. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17141. }
  17142. else
  17143. {
  17144. for (int i = 0; i < totalNumOutputChannels; ++i)
  17145. if (outputChannelData [i] != 0)
  17146. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17147. }
  17148. }
  17149. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17150. {
  17151. cpuUsageMs = 0;
  17152. const double sampleRate = device->getCurrentSampleRate();
  17153. const int blockSize = device->getCurrentBufferSizeSamples();
  17154. if (sampleRate > 0.0 && blockSize > 0)
  17155. {
  17156. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17157. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17158. }
  17159. if (currentCallback != 0)
  17160. currentCallback->audioDeviceAboutToStart (device);
  17161. sendChangeMessage (this);
  17162. }
  17163. void AudioDeviceManager::audioDeviceStoppedInt()
  17164. {
  17165. cpuUsageMs = 0;
  17166. timeToCpuScale = 0;
  17167. sendChangeMessage (this);
  17168. if (currentCallback != 0)
  17169. currentCallback->audioDeviceStopped();
  17170. }
  17171. double AudioDeviceManager::getCpuUsage() const
  17172. {
  17173. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17174. }
  17175. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17176. const bool enabled)
  17177. {
  17178. if (enabled != isMidiInputEnabled (name))
  17179. {
  17180. if (enabled)
  17181. {
  17182. const int index = MidiInput::getDevices().indexOf (name);
  17183. if (index >= 0)
  17184. {
  17185. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17186. if (min != 0)
  17187. {
  17188. enabledMidiInputs.add (min);
  17189. min->start();
  17190. }
  17191. }
  17192. }
  17193. else
  17194. {
  17195. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17196. if (enabledMidiInputs[i]->getName() == name)
  17197. enabledMidiInputs.remove (i);
  17198. }
  17199. updateXml();
  17200. sendChangeMessage (this);
  17201. }
  17202. }
  17203. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17204. {
  17205. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17206. if (enabledMidiInputs[i]->getName() == name)
  17207. return true;
  17208. return false;
  17209. }
  17210. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17211. MidiInputCallback* callback)
  17212. {
  17213. removeMidiInputCallback (callback);
  17214. if (name.isEmpty())
  17215. {
  17216. midiCallbacks.add (callback);
  17217. midiCallbackDevices.add (0);
  17218. }
  17219. else
  17220. {
  17221. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17222. {
  17223. if (enabledMidiInputs[i]->getName() == name)
  17224. {
  17225. const ScopedLock sl (midiCallbackLock);
  17226. if (! midiCallbacks.contains (callback))
  17227. {
  17228. midiCallbacks.add (callback);
  17229. midiCallbackDevices.add (enabledMidiInputs[i]);
  17230. }
  17231. break;
  17232. }
  17233. }
  17234. }
  17235. }
  17236. void AudioDeviceManager::removeMidiInputCallback (MidiInputCallback* callback)
  17237. {
  17238. const ScopedLock sl (midiCallbackLock);
  17239. const int index = midiCallbacks.indexOf (callback);
  17240. midiCallbacks.remove (index);
  17241. midiCallbackDevices.remove (index);
  17242. }
  17243. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17244. const MidiMessage& message)
  17245. {
  17246. if (! message.isActiveSense())
  17247. {
  17248. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17249. const ScopedLock sl (midiCallbackLock);
  17250. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17251. {
  17252. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17253. if (md == source || (md == 0 && isDefaultSource))
  17254. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17255. }
  17256. }
  17257. }
  17258. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17259. {
  17260. if (defaultMidiOutputName != deviceName)
  17261. {
  17262. deleteAndZero (defaultMidiOutput);
  17263. defaultMidiOutputName = deviceName;
  17264. if (deviceName.isNotEmpty())
  17265. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  17266. updateXml();
  17267. sendChangeMessage (this);
  17268. }
  17269. }
  17270. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  17271. int totalNumInputChannels,
  17272. float** outputChannelData,
  17273. int totalNumOutputChannels,
  17274. int numSamples)
  17275. {
  17276. owner->audioDeviceIOCallbackInt (inputChannelData, totalNumInputChannels, outputChannelData, totalNumOutputChannels, numSamples);
  17277. }
  17278. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  17279. {
  17280. owner->audioDeviceAboutToStartInt (device);
  17281. }
  17282. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  17283. {
  17284. owner->audioDeviceStoppedInt();
  17285. }
  17286. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  17287. {
  17288. owner->handleIncomingMidiMessageInt (source, message);
  17289. }
  17290. END_JUCE_NAMESPACE
  17291. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  17292. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  17293. BEGIN_JUCE_NAMESPACE
  17294. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  17295. : name (deviceName),
  17296. typeName (typeName_)
  17297. {
  17298. }
  17299. AudioIODevice::~AudioIODevice()
  17300. {
  17301. }
  17302. bool AudioIODevice::hasControlPanel() const
  17303. {
  17304. return false;
  17305. }
  17306. bool AudioIODevice::showControlPanel()
  17307. {
  17308. jassertfalse // this should only be called for devices which return true from
  17309. // their hasControlPanel() method.
  17310. return false;
  17311. }
  17312. END_JUCE_NAMESPACE
  17313. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  17314. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  17315. BEGIN_JUCE_NAMESPACE
  17316. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  17317. : typeName (name)
  17318. {
  17319. }
  17320. AudioIODeviceType::~AudioIODeviceType()
  17321. {
  17322. }
  17323. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  17324. #if JUCE_WIN32 && JUCE_ASIO
  17325. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  17326. #endif
  17327. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17328. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  17329. #endif
  17330. void AudioIODeviceType::createDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  17331. {
  17332. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  17333. if (defaultDeviceType != 0)
  17334. list.add (defaultDeviceType);
  17335. #if JUCE_WIN32 && JUCE_ASIO
  17336. list.add (juce_createASIOAudioIODeviceType());
  17337. #endif
  17338. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17339. list.add (juce_createWDMAudioIODeviceType());
  17340. #endif
  17341. }
  17342. END_JUCE_NAMESPACE
  17343. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  17344. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  17345. BEGIN_JUCE_NAMESPACE
  17346. MidiOutput::MidiOutput() throw()
  17347. : Thread ("midi out"),
  17348. internal (0),
  17349. firstMessage (0)
  17350. {
  17351. }
  17352. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  17353. const int len,
  17354. const double sampleNumber) throw()
  17355. : message (data, len, sampleNumber)
  17356. {
  17357. }
  17358. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  17359. const double millisecondCounterToStartAt,
  17360. double samplesPerSecondForBuffer) throw()
  17361. {
  17362. // You've got to call startBackgroundThread() for this to actually work..
  17363. jassert (isThreadRunning());
  17364. // this needs to be a value in the future - RTFM for this method!
  17365. jassert (millisecondCounterToStartAt > 0);
  17366. samplesPerSecondForBuffer *= 0.001;
  17367. MidiBuffer::Iterator i (buffer);
  17368. const uint8* data;
  17369. int len, time;
  17370. while (i.getNextEvent (data, len, time))
  17371. {
  17372. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  17373. PendingMessage* const m
  17374. = new PendingMessage (data, len, eventTime);
  17375. const ScopedLock sl (lock);
  17376. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  17377. {
  17378. m->next = firstMessage;
  17379. firstMessage = m;
  17380. }
  17381. else
  17382. {
  17383. PendingMessage* mm = firstMessage;
  17384. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  17385. mm = mm->next;
  17386. m->next = mm->next;
  17387. mm->next = m;
  17388. }
  17389. }
  17390. notify();
  17391. }
  17392. void MidiOutput::clearAllPendingMessages() throw()
  17393. {
  17394. const ScopedLock sl (lock);
  17395. while (firstMessage != 0)
  17396. {
  17397. PendingMessage* const m = firstMessage;
  17398. firstMessage = firstMessage->next;
  17399. delete m;
  17400. }
  17401. }
  17402. void MidiOutput::startBackgroundThread() throw()
  17403. {
  17404. startThread (9);
  17405. }
  17406. void MidiOutput::stopBackgroundThread() throw()
  17407. {
  17408. stopThread (5000);
  17409. }
  17410. void MidiOutput::run()
  17411. {
  17412. while (! threadShouldExit())
  17413. {
  17414. uint32 now = Time::getMillisecondCounter();
  17415. uint32 eventTime = 0;
  17416. uint32 timeToWait = 500;
  17417. lock.enter();
  17418. PendingMessage* message = firstMessage;
  17419. if (message != 0)
  17420. {
  17421. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  17422. if (eventTime > now + 20)
  17423. {
  17424. timeToWait = jmax (10, eventTime - now - 100);
  17425. message = 0;
  17426. }
  17427. else
  17428. {
  17429. firstMessage = message->next;
  17430. }
  17431. }
  17432. lock.exit();
  17433. if (message != 0)
  17434. {
  17435. if (eventTime > now)
  17436. {
  17437. Time::waitForMillisecondCounter (eventTime);
  17438. if (threadShouldExit())
  17439. break;
  17440. }
  17441. if (eventTime > now - 200)
  17442. sendMessageNow (message->message);
  17443. delete message;
  17444. }
  17445. else
  17446. {
  17447. jassert (timeToWait < 1000 * 30);
  17448. wait (timeToWait);
  17449. }
  17450. }
  17451. clearAllPendingMessages();
  17452. }
  17453. END_JUCE_NAMESPACE
  17454. /********* End of inlined file: juce_MidiOutput.cpp *********/
  17455. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  17456. BEGIN_JUCE_NAMESPACE
  17457. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17458. {
  17459. const double maxVal = (double) 0x7fff;
  17460. char* intData = (char*) dest;
  17461. for (int i = 0; i < numSamples; ++i)
  17462. {
  17463. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17464. intData += destBytesPerSample;
  17465. }
  17466. }
  17467. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17468. {
  17469. const double maxVal = (double) 0x7fff;
  17470. char* intData = (char*) dest;
  17471. for (int i = 0; i < numSamples; ++i)
  17472. {
  17473. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17474. intData += destBytesPerSample;
  17475. }
  17476. }
  17477. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17478. {
  17479. const double maxVal = (double) 0x7fffff;
  17480. char* intData = (char*) dest;
  17481. for (int i = 0; i < numSamples; ++i)
  17482. {
  17483. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17484. intData += destBytesPerSample;
  17485. }
  17486. }
  17487. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17488. {
  17489. const double maxVal = (double) 0x7fffff;
  17490. char* intData = (char*) dest;
  17491. for (int i = 0; i < numSamples; ++i)
  17492. {
  17493. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17494. intData += destBytesPerSample;
  17495. }
  17496. }
  17497. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17498. {
  17499. const double maxVal = (double) 0x7fffffff;
  17500. char* intData = (char*) dest;
  17501. for (int i = 0; i < numSamples; ++i)
  17502. {
  17503. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17504. intData += destBytesPerSample;
  17505. }
  17506. }
  17507. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17508. {
  17509. const double maxVal = (double) 0x7fffffff;
  17510. char* intData = (char*) dest;
  17511. for (int i = 0; i < numSamples; ++i)
  17512. {
  17513. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17514. intData += destBytesPerSample;
  17515. }
  17516. }
  17517. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17518. {
  17519. char* d = (char*) dest;
  17520. for (int i = 0; i < numSamples; ++i)
  17521. {
  17522. *(float*)d = source[i];
  17523. #if JUCE_BIG_ENDIAN
  17524. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17525. #endif
  17526. d += destBytesPerSample;
  17527. }
  17528. }
  17529. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17530. {
  17531. char* d = (char*) dest;
  17532. for (int i = 0; i < numSamples; ++i)
  17533. {
  17534. *(float*)d = source[i];
  17535. #if JUCE_LITTLE_ENDIAN
  17536. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17537. #endif
  17538. d += destBytesPerSample;
  17539. }
  17540. }
  17541. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17542. {
  17543. const float scale = 1.0f / 0x7fff;
  17544. const char* intData = (const char*) source;
  17545. for (int i = 0; i < numSamples; ++i)
  17546. {
  17547. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  17548. intData += srcBytesPerSample;
  17549. }
  17550. }
  17551. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17552. {
  17553. const float scale = 1.0f / 0x7fff;
  17554. const char* intData = (const char*) source;
  17555. for (int i = 0; i < numSamples; ++i)
  17556. {
  17557. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  17558. intData += srcBytesPerSample;
  17559. }
  17560. }
  17561. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17562. {
  17563. const float scale = 1.0f / 0x7fffff;
  17564. const char* intData = (const char*) source;
  17565. for (int i = 0; i < numSamples; ++i)
  17566. {
  17567. dest[i] = scale * (short) littleEndian24Bit (intData);
  17568. intData += srcBytesPerSample;
  17569. }
  17570. }
  17571. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17572. {
  17573. const float scale = 1.0f / 0x7fffff;
  17574. const char* intData = (const char*) source;
  17575. for (int i = 0; i < numSamples; ++i)
  17576. {
  17577. dest[i] = scale * (short) bigEndian24Bit (intData);
  17578. intData += srcBytesPerSample;
  17579. }
  17580. }
  17581. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17582. {
  17583. const float scale = 1.0f / 0x7fffffff;
  17584. const char* intData = (const char*) source;
  17585. for (int i = 0; i < numSamples; ++i)
  17586. {
  17587. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  17588. intData += srcBytesPerSample;
  17589. }
  17590. }
  17591. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17592. {
  17593. const float scale = 1.0f / 0x7fffffff;
  17594. const char* intData = (const char*) source;
  17595. for (int i = 0; i < numSamples; ++i)
  17596. {
  17597. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  17598. intData += srcBytesPerSample;
  17599. }
  17600. }
  17601. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17602. {
  17603. const char* s = (const char*) source;
  17604. for (int i = 0; i < numSamples; ++i)
  17605. {
  17606. dest[i] = *(float*)s;
  17607. #if JUCE_BIG_ENDIAN
  17608. uint32* const d = (uint32*) (dest + i);
  17609. *d = swapByteOrder (*d);
  17610. #endif
  17611. s += srcBytesPerSample;
  17612. }
  17613. }
  17614. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17615. {
  17616. const char* s = (const char*) source;
  17617. for (int i = 0; i < numSamples; ++i)
  17618. {
  17619. dest[i] = *(float*)s;
  17620. #if JUCE_LITTLE_ENDIAN
  17621. uint32* const d = (uint32*) (dest + i);
  17622. *d = swapByteOrder (*d);
  17623. #endif
  17624. s += srcBytesPerSample;
  17625. }
  17626. }
  17627. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  17628. const float* const source,
  17629. void* const dest,
  17630. const int numSamples)
  17631. {
  17632. switch (destFormat)
  17633. {
  17634. case int16LE:
  17635. convertFloatToInt16LE (source, dest, numSamples);
  17636. break;
  17637. case int16BE:
  17638. convertFloatToInt16BE (source, dest, numSamples);
  17639. break;
  17640. case int24LE:
  17641. convertFloatToInt24LE (source, dest, numSamples);
  17642. break;
  17643. case int24BE:
  17644. convertFloatToInt24BE (source, dest, numSamples);
  17645. break;
  17646. case int32LE:
  17647. convertFloatToInt32LE (source, dest, numSamples);
  17648. break;
  17649. case int32BE:
  17650. convertFloatToInt32BE (source, dest, numSamples);
  17651. break;
  17652. case float32LE:
  17653. convertFloatToFloat32LE (source, dest, numSamples);
  17654. break;
  17655. case float32BE:
  17656. convertFloatToFloat32BE (source, dest, numSamples);
  17657. break;
  17658. default:
  17659. jassertfalse
  17660. break;
  17661. }
  17662. }
  17663. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  17664. const void* const source,
  17665. float* const dest,
  17666. const int numSamples)
  17667. {
  17668. switch (sourceFormat)
  17669. {
  17670. case int16LE:
  17671. convertInt16LEToFloat (source, dest, numSamples);
  17672. break;
  17673. case int16BE:
  17674. convertInt16BEToFloat (source, dest, numSamples);
  17675. break;
  17676. case int24LE:
  17677. convertInt24LEToFloat (source, dest, numSamples);
  17678. break;
  17679. case int24BE:
  17680. convertInt24BEToFloat (source, dest, numSamples);
  17681. break;
  17682. case int32LE:
  17683. convertInt32LEToFloat (source, dest, numSamples);
  17684. break;
  17685. case int32BE:
  17686. convertInt32BEToFloat (source, dest, numSamples);
  17687. break;
  17688. case float32LE:
  17689. convertFloat32LEToFloat (source, dest, numSamples);
  17690. break;
  17691. case float32BE:
  17692. convertFloat32BEToFloat (source, dest, numSamples);
  17693. break;
  17694. default:
  17695. jassertfalse
  17696. break;
  17697. }
  17698. }
  17699. void AudioDataConverters::interleaveSamples (const float** const source,
  17700. float* const dest,
  17701. const int numSamples,
  17702. const int numChannels)
  17703. {
  17704. for (int chan = 0; chan < numChannels; ++chan)
  17705. {
  17706. int i = chan;
  17707. const float* src = source [chan];
  17708. for (int j = 0; j < numSamples; ++j)
  17709. {
  17710. dest [i] = src [j];
  17711. i += numChannels;
  17712. }
  17713. }
  17714. }
  17715. void AudioDataConverters::deinterleaveSamples (const float* const source,
  17716. float** const dest,
  17717. const int numSamples,
  17718. const int numChannels)
  17719. {
  17720. for (int chan = 0; chan < numChannels; ++chan)
  17721. {
  17722. int i = chan;
  17723. float* dst = dest [chan];
  17724. for (int j = 0; j < numSamples; ++j)
  17725. {
  17726. dst [j] = source [i];
  17727. i += numChannels;
  17728. }
  17729. }
  17730. }
  17731. END_JUCE_NAMESPACE
  17732. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  17733. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  17734. BEGIN_JUCE_NAMESPACE
  17735. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  17736. const int numSamples) throw()
  17737. : numChannels (numChannels_),
  17738. size (numSamples)
  17739. {
  17740. jassert (numSamples >= 0);
  17741. jassert (numChannels_ > 0 && numChannels_ <= maxNumAudioSampleBufferChannels);
  17742. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  17743. allocatedData = (float*) juce_malloc (allocatedBytes);
  17744. float* chan = allocatedData;
  17745. for (int i = 0; i < numChannels_; ++i)
  17746. {
  17747. channels[i] = chan;
  17748. chan += numSamples;
  17749. }
  17750. channels [numChannels_] = 0;
  17751. }
  17752. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  17753. const int numChannels_,
  17754. const int numSamples) throw()
  17755. : numChannels (numChannels_),
  17756. size (numSamples),
  17757. allocatedBytes (0),
  17758. allocatedData (0)
  17759. {
  17760. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17761. for (int i = 0; i < numChannels_; ++i)
  17762. {
  17763. // you have to pass in the same number of valid pointers as numChannels
  17764. jassert (dataToReferTo[i] != 0);
  17765. channels[i] = dataToReferTo[i];
  17766. }
  17767. channels [numChannels_] = 0;
  17768. }
  17769. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  17770. const int numChannels_,
  17771. const int numSamples) throw()
  17772. {
  17773. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17774. juce_free (allocatedData);
  17775. allocatedData = 0;
  17776. allocatedBytes = 0;
  17777. numChannels = numChannels_;
  17778. size = numSamples;
  17779. for (int i = 0; i < numChannels_; ++i)
  17780. {
  17781. // you have to pass in the same number of valid pointers as numChannels
  17782. jassert (dataToReferTo[i] != 0);
  17783. channels[i] = dataToReferTo[i];
  17784. }
  17785. channels [numChannels_] = 0;
  17786. }
  17787. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  17788. : numChannels (other.numChannels),
  17789. size (other.size)
  17790. {
  17791. if (other.allocatedData != 0)
  17792. {
  17793. allocatedBytes = numChannels * size * sizeof (float) + 32;
  17794. allocatedData = (float*) juce_malloc (allocatedBytes);
  17795. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  17796. float* chan = allocatedData;
  17797. for (int i = 0; i < numChannels; ++i)
  17798. {
  17799. channels[i] = chan;
  17800. chan += size;
  17801. }
  17802. channels [numChannels] = 0;
  17803. }
  17804. else
  17805. {
  17806. allocatedData = 0;
  17807. allocatedBytes = 0;
  17808. memcpy (channels, other.channels, sizeof (channels));
  17809. }
  17810. }
  17811. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  17812. {
  17813. if (this != &other)
  17814. {
  17815. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  17816. const int numBytes = size * sizeof (float);
  17817. for (int i = 0; i < numChannels; ++i)
  17818. memcpy (channels[i], other.channels[i], numBytes);
  17819. }
  17820. return *this;
  17821. }
  17822. AudioSampleBuffer::~AudioSampleBuffer() throw()
  17823. {
  17824. juce_free (allocatedData);
  17825. }
  17826. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  17827. const int sampleOffset) const throw()
  17828. {
  17829. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  17830. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  17831. return channels [channelNumber] + sampleOffset;
  17832. }
  17833. void AudioSampleBuffer::setSize (const int newNumChannels,
  17834. const int newNumSamples,
  17835. const bool keepExistingContent,
  17836. const bool clearExtraSpace,
  17837. const bool avoidReallocating) throw()
  17838. {
  17839. jassert (newNumChannels > 0 && newNumChannels <= maxNumAudioSampleBufferChannels);
  17840. if (newNumSamples != size || newNumChannels != numChannels)
  17841. {
  17842. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  17843. if (keepExistingContent)
  17844. {
  17845. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  17846. : (float*) juce_malloc (newTotalBytes);
  17847. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  17848. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  17849. {
  17850. memcpy (newData + i * newNumSamples,
  17851. channels[i],
  17852. sizeToCopy);
  17853. }
  17854. juce_free (allocatedData);
  17855. allocatedData = newData;
  17856. allocatedBytes = newTotalBytes;
  17857. }
  17858. else
  17859. {
  17860. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  17861. {
  17862. if (clearExtraSpace)
  17863. zeromem (allocatedData, newTotalBytes);
  17864. }
  17865. else
  17866. {
  17867. juce_free (allocatedData);
  17868. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  17869. : (float*) juce_malloc (newTotalBytes);
  17870. allocatedBytes = newTotalBytes;
  17871. }
  17872. }
  17873. size = newNumSamples;
  17874. numChannels = newNumChannels;
  17875. float* chan = allocatedData;
  17876. for (int i = 0; i < newNumChannels; ++i)
  17877. {
  17878. channels[i] = chan;
  17879. chan += size;
  17880. }
  17881. channels [newNumChannels] = 0;
  17882. }
  17883. }
  17884. void AudioSampleBuffer::clear() throw()
  17885. {
  17886. for (int i = 0; i < numChannels; ++i)
  17887. zeromem (channels[i], size * sizeof (float));
  17888. }
  17889. void AudioSampleBuffer::clear (const int startSample,
  17890. const int numSamples) throw()
  17891. {
  17892. jassert (startSample >= 0 && startSample + numSamples <= size);
  17893. for (int i = 0; i < numChannels; ++i)
  17894. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  17895. }
  17896. void AudioSampleBuffer::clear (const int channel,
  17897. const int startSample,
  17898. const int numSamples) throw()
  17899. {
  17900. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17901. jassert (startSample >= 0 && startSample + numSamples <= size);
  17902. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  17903. }
  17904. void AudioSampleBuffer::applyGain (const int channel,
  17905. const int startSample,
  17906. int numSamples,
  17907. const float gain) throw()
  17908. {
  17909. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17910. jassert (startSample >= 0 && startSample + numSamples <= size);
  17911. if (gain != 1.0f)
  17912. {
  17913. float* d = channels [channel] + startSample;
  17914. if (gain == 0.0f)
  17915. {
  17916. zeromem (d, sizeof (float) * numSamples);
  17917. }
  17918. else
  17919. {
  17920. while (--numSamples >= 0)
  17921. *d++ *= gain;
  17922. }
  17923. }
  17924. }
  17925. void AudioSampleBuffer::applyGainRamp (const int channel,
  17926. const int startSample,
  17927. int numSamples,
  17928. float startGain,
  17929. float endGain) throw()
  17930. {
  17931. if (startGain == endGain)
  17932. {
  17933. applyGain (channel, startSample, numSamples, startGain);
  17934. }
  17935. else
  17936. {
  17937. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17938. jassert (startSample >= 0 && startSample + numSamples <= size);
  17939. const float increment = (endGain - startGain) / numSamples;
  17940. float* d = channels [channel] + startSample;
  17941. while (--numSamples >= 0)
  17942. {
  17943. *d++ *= startGain;
  17944. startGain += increment;
  17945. }
  17946. }
  17947. }
  17948. void AudioSampleBuffer::applyGain (const int startSample,
  17949. const int numSamples,
  17950. const float gain) throw()
  17951. {
  17952. for (int i = 0; i < numChannels; ++i)
  17953. applyGain (i, startSample, numSamples, gain);
  17954. }
  17955. void AudioSampleBuffer::addFrom (const int destChannel,
  17956. const int destStartSample,
  17957. const AudioSampleBuffer& source,
  17958. const int sourceChannel,
  17959. const int sourceStartSample,
  17960. int numSamples,
  17961. const float gain) throw()
  17962. {
  17963. jassert (&source != this || sourceChannel != destChannel);
  17964. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  17965. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  17966. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  17967. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  17968. if (gain != 0.0f && numSamples > 0)
  17969. {
  17970. float* d = channels [destChannel] + destStartSample;
  17971. const float* s = source.channels [sourceChannel] + sourceStartSample;
  17972. if (gain != 1.0f)
  17973. {
  17974. while (--numSamples >= 0)
  17975. *d++ += gain * *s++;
  17976. }
  17977. else
  17978. {
  17979. while (--numSamples >= 0)
  17980. *d++ += *s++;
  17981. }
  17982. }
  17983. }
  17984. void AudioSampleBuffer::addFrom (const int destChannel,
  17985. const int destStartSample,
  17986. const float* source,
  17987. int numSamples,
  17988. const float gain) throw()
  17989. {
  17990. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  17991. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  17992. jassert (source != 0);
  17993. if (gain != 0.0f && numSamples > 0)
  17994. {
  17995. float* d = channels [destChannel] + destStartSample;
  17996. if (gain != 1.0f)
  17997. {
  17998. while (--numSamples >= 0)
  17999. *d++ += gain * *source++;
  18000. }
  18001. else
  18002. {
  18003. while (--numSamples >= 0)
  18004. *d++ += *source++;
  18005. }
  18006. }
  18007. }
  18008. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18009. const int destStartSample,
  18010. const float* source,
  18011. int numSamples,
  18012. float startGain,
  18013. const float endGain) throw()
  18014. {
  18015. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18016. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18017. jassert (source != 0);
  18018. if (startGain == endGain)
  18019. {
  18020. addFrom (destChannel,
  18021. destStartSample,
  18022. source,
  18023. numSamples,
  18024. startGain);
  18025. }
  18026. else
  18027. {
  18028. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18029. {
  18030. const float increment = (endGain - startGain) / numSamples;
  18031. float* d = channels [destChannel] + destStartSample;
  18032. while (--numSamples >= 0)
  18033. {
  18034. *d++ += startGain * *source++;
  18035. startGain += increment;
  18036. }
  18037. }
  18038. }
  18039. }
  18040. void AudioSampleBuffer::copyFrom (const int destChannel,
  18041. const int destStartSample,
  18042. const AudioSampleBuffer& source,
  18043. const int sourceChannel,
  18044. const int sourceStartSample,
  18045. int numSamples) throw()
  18046. {
  18047. jassert (&source != this || sourceChannel != destChannel);
  18048. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18049. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18050. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18051. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18052. if (numSamples > 0)
  18053. {
  18054. memcpy (channels [destChannel] + destStartSample,
  18055. source.channels [sourceChannel] + sourceStartSample,
  18056. sizeof (float) * numSamples);
  18057. }
  18058. }
  18059. void AudioSampleBuffer::copyFrom (const int destChannel,
  18060. const int destStartSample,
  18061. const float* source,
  18062. int numSamples) throw()
  18063. {
  18064. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18065. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18066. jassert (source != 0);
  18067. if (numSamples > 0)
  18068. {
  18069. memcpy (channels [destChannel] + destStartSample,
  18070. source,
  18071. sizeof (float) * numSamples);
  18072. }
  18073. }
  18074. void AudioSampleBuffer::findMinMax (const int channel,
  18075. const int startSample,
  18076. int numSamples,
  18077. float& minVal,
  18078. float& maxVal) const throw()
  18079. {
  18080. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18081. jassert (startSample >= 0 && startSample + numSamples <= size);
  18082. if (numSamples <= 0)
  18083. {
  18084. minVal = 0.0f;
  18085. maxVal = 0.0f;
  18086. }
  18087. else
  18088. {
  18089. const float* d = channels [channel] + startSample;
  18090. float mn = *d++;
  18091. float mx = mn;
  18092. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18093. {
  18094. const float samp = *d++;
  18095. if (samp > mx)
  18096. mx = samp;
  18097. if (samp < mn)
  18098. mn = samp;
  18099. }
  18100. maxVal = mx;
  18101. minVal = mn;
  18102. }
  18103. }
  18104. float AudioSampleBuffer::getMagnitude (const int channel,
  18105. const int startSample,
  18106. const int numSamples) const throw()
  18107. {
  18108. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18109. jassert (startSample >= 0 && startSample + numSamples <= size);
  18110. float mn, mx;
  18111. findMinMax (channel, startSample, numSamples, mn, mx);
  18112. return jmax (mn, -mn, mx, -mx);
  18113. }
  18114. float AudioSampleBuffer::getMagnitude (const int startSample,
  18115. const int numSamples) const throw()
  18116. {
  18117. float mag = 0.0f;
  18118. for (int i = 0; i < numChannels; ++i)
  18119. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18120. return mag;
  18121. }
  18122. float AudioSampleBuffer::getRMSLevel (const int channel,
  18123. const int startSample,
  18124. const int numSamples) const throw()
  18125. {
  18126. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18127. jassert (startSample >= 0 && startSample + numSamples <= size);
  18128. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18129. return 0.0f;
  18130. const float* const data = channels [channel] + startSample;
  18131. double sum = 0.0;
  18132. for (int i = 0; i < numSamples; ++i)
  18133. {
  18134. const float sample = data [i];
  18135. sum += sample * sample;
  18136. }
  18137. return (float) sqrt (sum / numSamples);
  18138. }
  18139. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18140. const int startSample,
  18141. const int numSamples,
  18142. const int readerStartSample,
  18143. const bool useLeftChan,
  18144. const bool useRightChan) throw()
  18145. {
  18146. jassert (reader != 0);
  18147. jassert (startSample >= 0 && startSample + numSamples <= size);
  18148. if (numSamples > 0)
  18149. {
  18150. int* chans[3];
  18151. if (useLeftChan == useRightChan)
  18152. {
  18153. chans[0] = (int*) getSampleData (0, startSample);
  18154. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18155. }
  18156. else if (useLeftChan || (reader->numChannels == 1))
  18157. {
  18158. chans[0] = (int*) getSampleData (0, startSample);
  18159. chans[1] = 0;
  18160. }
  18161. else if (useRightChan)
  18162. {
  18163. chans[0] = 0;
  18164. chans[1] = (int*) getSampleData (0, startSample);
  18165. }
  18166. chans[2] = 0;
  18167. reader->read (chans, readerStartSample, numSamples);
  18168. if (! reader->usesFloatingPointData)
  18169. {
  18170. for (int j = 0; j < 2; ++j)
  18171. {
  18172. float* const d = (float*) (chans[j]);
  18173. if (d != 0)
  18174. {
  18175. const float multiplier = 1.0f / 0x7fffffff;
  18176. for (int i = 0; i < numSamples; ++i)
  18177. d[i] = *(int*)(d + i) * multiplier;
  18178. }
  18179. }
  18180. }
  18181. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18182. {
  18183. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18184. memcpy (getSampleData (1, startSample),
  18185. getSampleData (0, startSample),
  18186. sizeof (float) * numSamples);
  18187. }
  18188. }
  18189. }
  18190. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18191. const int startSample,
  18192. const int numSamples) const throw()
  18193. {
  18194. jassert (startSample >= 0 && startSample + numSamples <= size);
  18195. if (numSamples > 0)
  18196. {
  18197. int* chans [3];
  18198. if (writer->isFloatingPoint())
  18199. {
  18200. chans[0] = (int*) getSampleData (0, startSample);
  18201. if (numChannels > 1)
  18202. chans[1] = (int*) getSampleData (1, startSample);
  18203. else
  18204. chans[1] = 0;
  18205. chans[2] = 0;
  18206. writer->write ((const int**) chans, numSamples);
  18207. }
  18208. else
  18209. {
  18210. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18211. if (numChannels > 1)
  18212. chans[1] = chans[0] + numSamples;
  18213. else
  18214. chans[1] = 0;
  18215. chans[2] = 0;
  18216. for (int j = 0; j < 2; ++j)
  18217. {
  18218. int* const dest = chans[j];
  18219. if (dest != 0)
  18220. {
  18221. const float* const src = channels [j] + startSample;
  18222. for (int i = 0; i < numSamples; ++i)
  18223. {
  18224. const double samp = src[i];
  18225. if (samp <= -1.0)
  18226. dest[i] = INT_MIN;
  18227. else if (samp >= 1.0)
  18228. dest[i] = INT_MAX;
  18229. else
  18230. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18231. }
  18232. }
  18233. }
  18234. writer->write ((const int**) chans, numSamples);
  18235. juce_free (chans[0]);
  18236. }
  18237. }
  18238. }
  18239. END_JUCE_NAMESPACE
  18240. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  18241. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  18242. BEGIN_JUCE_NAMESPACE
  18243. IIRFilter::IIRFilter() throw()
  18244. : active (false)
  18245. {
  18246. reset();
  18247. }
  18248. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  18249. : active (other.active)
  18250. {
  18251. const ScopedLock sl (other.processLock);
  18252. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18253. reset();
  18254. }
  18255. IIRFilter::~IIRFilter() throw()
  18256. {
  18257. }
  18258. void IIRFilter::reset() throw()
  18259. {
  18260. const ScopedLock sl (processLock);
  18261. x1 = 0;
  18262. x2 = 0;
  18263. y1 = 0;
  18264. y2 = 0;
  18265. }
  18266. void IIRFilter::processSamples (float* const samples,
  18267. const int numSamples) throw()
  18268. {
  18269. const ScopedLock sl (processLock);
  18270. if (active)
  18271. {
  18272. for (int i = 0; i < numSamples; ++i)
  18273. {
  18274. const float in = samples[i];
  18275. float out = coefficients[0] * in
  18276. + coefficients[1] * x1
  18277. + coefficients[2] * x2
  18278. - coefficients[4] * y1
  18279. - coefficients[5] * y2;
  18280. #if JUCE_INTEL
  18281. if (! (out < -1.0e-8 || out > 1.0e-8))
  18282. out = 0;
  18283. #endif
  18284. x2 = x1;
  18285. x1 = in;
  18286. y2 = y1;
  18287. y1 = out;
  18288. samples[i] = out;
  18289. }
  18290. }
  18291. }
  18292. void IIRFilter::makeLowPass (const double sampleRate,
  18293. const double frequency) throw()
  18294. {
  18295. jassert (sampleRate > 0);
  18296. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  18297. const double nSquared = n * n;
  18298. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18299. setCoefficients (c1,
  18300. c1 * 2.0f,
  18301. c1,
  18302. 1.0,
  18303. c1 * 2.0 * (1.0 - nSquared),
  18304. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18305. }
  18306. void IIRFilter::makeHighPass (const double sampleRate,
  18307. const double frequency) throw()
  18308. {
  18309. const double n = tan (double_Pi * frequency / sampleRate);
  18310. const double nSquared = n * n;
  18311. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18312. setCoefficients (c1,
  18313. c1 * -2.0f,
  18314. c1,
  18315. 1.0,
  18316. c1 * 2.0 * (nSquared - 1.0),
  18317. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18318. }
  18319. void IIRFilter::makeLowShelf (const double sampleRate,
  18320. const double cutOffFrequency,
  18321. const double Q,
  18322. const float gainFactor) throw()
  18323. {
  18324. jassert (sampleRate > 0);
  18325. jassert (Q > 0);
  18326. const double A = jmax (0.0f, gainFactor);
  18327. const double aminus1 = A - 1.0;
  18328. const double aplus1 = A + 1.0;
  18329. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18330. const double coso = cos (omega);
  18331. const double beta = sin (omega) * sqrt (A) / Q;
  18332. const double aminus1TimesCoso = aminus1 * coso;
  18333. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  18334. A * 2.0 * (aminus1 - aplus1 * coso),
  18335. A * (aplus1 - aminus1TimesCoso - beta),
  18336. aplus1 + aminus1TimesCoso + beta,
  18337. -2.0 * (aminus1 + aplus1 * coso),
  18338. aplus1 + aminus1TimesCoso - beta);
  18339. }
  18340. void IIRFilter::makeHighShelf (const double sampleRate,
  18341. const double cutOffFrequency,
  18342. const double Q,
  18343. const float gainFactor) throw()
  18344. {
  18345. jassert (sampleRate > 0);
  18346. jassert (Q > 0);
  18347. const double A = jmax (0.0f, gainFactor);
  18348. const double aminus1 = A - 1.0;
  18349. const double aplus1 = A + 1.0;
  18350. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18351. const double coso = cos (omega);
  18352. const double beta = sin (omega) * sqrt (A) / Q;
  18353. const double aminus1TimesCoso = aminus1 * coso;
  18354. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  18355. A * -2.0 * (aminus1 + aplus1 * coso),
  18356. A * (aplus1 + aminus1TimesCoso - beta),
  18357. aplus1 - aminus1TimesCoso + beta,
  18358. 2.0 * (aminus1 - aplus1 * coso),
  18359. aplus1 - aminus1TimesCoso - beta);
  18360. }
  18361. void IIRFilter::makeBandPass (const double sampleRate,
  18362. const double centreFrequency,
  18363. const double Q,
  18364. const float gainFactor) throw()
  18365. {
  18366. jassert (sampleRate > 0);
  18367. jassert (Q > 0);
  18368. const double A = jmax (0.0f, gainFactor);
  18369. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  18370. const double alpha = 0.5 * sin (omega) / Q;
  18371. const double c2 = -2.0 * cos (omega);
  18372. const double alphaTimesA = alpha * A;
  18373. const double alphaOverA = alpha / A;
  18374. setCoefficients (1.0 + alphaTimesA,
  18375. c2,
  18376. 1.0 - alphaTimesA,
  18377. 1.0 + alphaOverA,
  18378. c2,
  18379. 1.0 - alphaOverA);
  18380. }
  18381. void IIRFilter::makeInactive() throw()
  18382. {
  18383. const ScopedLock sl (processLock);
  18384. active = false;
  18385. }
  18386. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  18387. {
  18388. const ScopedLock sl (processLock);
  18389. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18390. active = other.active;
  18391. }
  18392. void IIRFilter::setCoefficients (double c1,
  18393. double c2,
  18394. double c3,
  18395. double c4,
  18396. double c5,
  18397. double c6) throw()
  18398. {
  18399. const double a = 1.0 / c4;
  18400. c1 *= a;
  18401. c2 *= a;
  18402. c3 *= a;
  18403. c5 *= a;
  18404. c6 *= a;
  18405. const ScopedLock sl (processLock);
  18406. coefficients[0] = (float) c1;
  18407. coefficients[1] = (float) c2;
  18408. coefficients[2] = (float) c3;
  18409. coefficients[3] = (float) c4;
  18410. coefficients[4] = (float) c5;
  18411. coefficients[5] = (float) c6;
  18412. active = true;
  18413. }
  18414. END_JUCE_NAMESPACE
  18415. /********* End of inlined file: juce_IIRFilter.cpp *********/
  18416. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  18417. BEGIN_JUCE_NAMESPACE
  18418. MidiBuffer::MidiBuffer() throw()
  18419. : ArrayAllocationBase <uint8> (32),
  18420. bytesUsed (0)
  18421. {
  18422. }
  18423. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  18424. : ArrayAllocationBase <uint8> (32),
  18425. bytesUsed (other.bytesUsed)
  18426. {
  18427. ensureAllocatedSize (bytesUsed);
  18428. memcpy (elements, other.elements, bytesUsed);
  18429. }
  18430. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  18431. {
  18432. if (this != &other)
  18433. {
  18434. bytesUsed = other.bytesUsed;
  18435. ensureAllocatedSize (bytesUsed);
  18436. if (bytesUsed > 0)
  18437. memcpy (elements, other.elements, bytesUsed);
  18438. }
  18439. return *this;
  18440. }
  18441. MidiBuffer::~MidiBuffer() throw()
  18442. {
  18443. }
  18444. void MidiBuffer::clear() throw()
  18445. {
  18446. bytesUsed = 0;
  18447. }
  18448. void MidiBuffer::clear (const int startSample,
  18449. const int numSamples) throw()
  18450. {
  18451. uint8* const start = findEventAfter (elements, startSample - 1);
  18452. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  18453. if (end > start)
  18454. {
  18455. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  18456. if (bytesToMove > 0)
  18457. memmove (start, end, bytesToMove);
  18458. bytesUsed -= (int) (end - start);
  18459. }
  18460. }
  18461. void MidiBuffer::addEvent (const MidiMessage& m,
  18462. const int sampleNumber) throw()
  18463. {
  18464. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  18465. }
  18466. static int findActualEventLength (const uint8* const data,
  18467. const int maxBytes) throw()
  18468. {
  18469. unsigned int byte = (unsigned int) *data;
  18470. int size = 0;
  18471. if (byte == 0xf0 || byte == 0xf7)
  18472. {
  18473. const uint8* d = data + 1;
  18474. while (d < data + maxBytes)
  18475. if (*d++ == 0xf7)
  18476. break;
  18477. size = (int) (d - data);
  18478. }
  18479. else if (byte == 0xff)
  18480. {
  18481. int n;
  18482. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  18483. size = jmin (maxBytes, n + 2 + bytesLeft);
  18484. }
  18485. else if (byte >= 0x80)
  18486. {
  18487. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  18488. }
  18489. return size;
  18490. }
  18491. void MidiBuffer::addEvent (const uint8* const newData,
  18492. const int maxBytes,
  18493. const int sampleNumber) throw()
  18494. {
  18495. const int numBytes = findActualEventLength (newData, maxBytes);
  18496. if (numBytes > 0)
  18497. {
  18498. ensureAllocatedSize (bytesUsed + numBytes + 6);
  18499. uint8* d = findEventAfter (elements, sampleNumber);
  18500. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  18501. if (bytesToMove > 0)
  18502. memmove (d + numBytes + 6,
  18503. d,
  18504. bytesToMove);
  18505. *(int*) d = sampleNumber;
  18506. d += 4;
  18507. *(uint16*) d = (uint16) numBytes;
  18508. d += 2;
  18509. memcpy (d, newData, numBytes);
  18510. bytesUsed += numBytes + 6;
  18511. }
  18512. }
  18513. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  18514. const int startSample,
  18515. const int numSamples,
  18516. const int sampleDeltaToAdd) throw()
  18517. {
  18518. Iterator i (otherBuffer);
  18519. i.setNextSamplePosition (startSample);
  18520. const uint8* data;
  18521. int size, position;
  18522. while (i.getNextEvent (data, size, position)
  18523. && (position < startSample + numSamples || numSamples < 0))
  18524. {
  18525. addEvent (data, size, position + sampleDeltaToAdd);
  18526. }
  18527. }
  18528. bool MidiBuffer::isEmpty() const throw()
  18529. {
  18530. return bytesUsed == 0;
  18531. }
  18532. int MidiBuffer::getNumEvents() const throw()
  18533. {
  18534. int n = 0;
  18535. const uint8* d = elements;
  18536. const uint8* const end = elements + bytesUsed;
  18537. while (d < end)
  18538. {
  18539. d += 4;
  18540. d += 2 + *(const uint16*) d;
  18541. ++n;
  18542. }
  18543. return n;
  18544. }
  18545. int MidiBuffer::getFirstEventTime() const throw()
  18546. {
  18547. return (bytesUsed > 0) ? *(const int*) elements : 0;
  18548. }
  18549. int MidiBuffer::getLastEventTime() const throw()
  18550. {
  18551. if (bytesUsed == 0)
  18552. return 0;
  18553. const uint8* d = elements;
  18554. const uint8* const endData = d + bytesUsed;
  18555. for (;;)
  18556. {
  18557. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  18558. if (nextOne >= endData)
  18559. return *(const int*) d;
  18560. d = nextOne;
  18561. }
  18562. }
  18563. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  18564. {
  18565. const uint8* const endData = elements + bytesUsed;
  18566. while (d < endData && *(int*) d <= samplePosition)
  18567. {
  18568. d += 4;
  18569. d += 2 + *(uint16*) d;
  18570. }
  18571. return d;
  18572. }
  18573. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  18574. : buffer (buffer),
  18575. data (buffer.elements)
  18576. {
  18577. }
  18578. MidiBuffer::Iterator::~Iterator() throw()
  18579. {
  18580. }
  18581. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  18582. {
  18583. data = buffer.elements;
  18584. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  18585. while (data < dataEnd && *(int*) data < samplePosition)
  18586. {
  18587. data += 4;
  18588. data += 2 + *(uint16*) data;
  18589. }
  18590. }
  18591. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  18592. int& numBytes,
  18593. int& samplePosition) throw()
  18594. {
  18595. if (data >= buffer.elements + buffer.bytesUsed)
  18596. return false;
  18597. samplePosition = *(int*) data;
  18598. data += 4;
  18599. numBytes = *(uint16*) data;
  18600. data += 2;
  18601. midiData = data;
  18602. data += numBytes;
  18603. return true;
  18604. }
  18605. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  18606. int& samplePosition) throw()
  18607. {
  18608. if (data >= buffer.elements + buffer.bytesUsed)
  18609. return false;
  18610. samplePosition = *(int*) data;
  18611. data += 4;
  18612. const int numBytes = *(uint16*) data;
  18613. data += 2;
  18614. result = MidiMessage (data, numBytes, samplePosition);
  18615. data += numBytes;
  18616. return true;
  18617. }
  18618. END_JUCE_NAMESPACE
  18619. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  18620. /********* Start of inlined file: juce_MidiFile.cpp *********/
  18621. BEGIN_JUCE_NAMESPACE
  18622. struct TempoInfo
  18623. {
  18624. double bpm, timestamp;
  18625. };
  18626. struct TimeSigInfo
  18627. {
  18628. int numerator, denominator;
  18629. double timestamp;
  18630. };
  18631. MidiFile::MidiFile() throw()
  18632. : numTracks (0),
  18633. timeFormat ((short)(unsigned short)0xe728)
  18634. {
  18635. }
  18636. MidiFile::~MidiFile() throw()
  18637. {
  18638. clear();
  18639. }
  18640. void MidiFile::clear() throw()
  18641. {
  18642. while (numTracks > 0)
  18643. delete tracks [--numTracks];
  18644. }
  18645. int MidiFile::getNumTracks() const throw()
  18646. {
  18647. return numTracks;
  18648. }
  18649. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  18650. {
  18651. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  18652. }
  18653. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  18654. {
  18655. jassert (numTracks < numElementsInArray (tracks));
  18656. if (numTracks < numElementsInArray (tracks))
  18657. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  18658. }
  18659. short MidiFile::getTimeFormat() const throw()
  18660. {
  18661. return timeFormat;
  18662. }
  18663. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  18664. {
  18665. timeFormat = (short)ticks;
  18666. }
  18667. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  18668. const int subframeResolution) throw()
  18669. {
  18670. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  18671. }
  18672. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  18673. {
  18674. for (int i = numTracks; --i >= 0;)
  18675. {
  18676. const int numEvents = tracks[i]->getNumEvents();
  18677. for (int j = 0; j < numEvents; ++j)
  18678. {
  18679. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18680. if (m.isTempoMetaEvent())
  18681. tempoChangeEvents.addEvent (m);
  18682. }
  18683. }
  18684. }
  18685. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  18686. {
  18687. for (int i = numTracks; --i >= 0;)
  18688. {
  18689. const int numEvents = tracks[i]->getNumEvents();
  18690. for (int j = 0; j < numEvents; ++j)
  18691. {
  18692. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18693. if (m.isTimeSignatureMetaEvent())
  18694. timeSigEvents.addEvent (m);
  18695. }
  18696. }
  18697. }
  18698. double MidiFile::getLastTimestamp() const
  18699. {
  18700. double t = 0.0;
  18701. for (int i = numTracks; --i >= 0;)
  18702. t = jmax (t, tracks[i]->getEndTime());
  18703. return t;
  18704. }
  18705. static bool parseMidiHeader (const char* &data,
  18706. short& timeFormat,
  18707. short& fileType,
  18708. short& numberOfTracks)
  18709. {
  18710. unsigned int ch = (int) bigEndianInt (data);
  18711. data += 4;
  18712. if (ch != bigEndianInt ("MThd"))
  18713. {
  18714. bool ok = false;
  18715. if (ch == bigEndianInt ("RIFF"))
  18716. {
  18717. for (int i = 0; i < 8; ++i)
  18718. {
  18719. ch = bigEndianInt (data);
  18720. data += 4;
  18721. if (ch == bigEndianInt ("MThd"))
  18722. {
  18723. ok = true;
  18724. break;
  18725. }
  18726. }
  18727. }
  18728. if (! ok)
  18729. return false;
  18730. }
  18731. unsigned int bytesRemaining = bigEndianInt (data);
  18732. data += 4;
  18733. fileType = (short)bigEndianShort (data);
  18734. data += 2;
  18735. numberOfTracks = (short)bigEndianShort (data);
  18736. data += 2;
  18737. timeFormat = (short)bigEndianShort (data);
  18738. data += 2;
  18739. bytesRemaining -= 6;
  18740. data += bytesRemaining;
  18741. return true;
  18742. }
  18743. bool MidiFile::readFrom (InputStream& sourceStream)
  18744. {
  18745. clear();
  18746. MemoryBlock data;
  18747. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  18748. // (put a sanity-check on the file size, as midi files are generally small)
  18749. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  18750. {
  18751. int size = data.getSize();
  18752. const char* d = (char*) data.getData();
  18753. short fileType, expectedTracks;
  18754. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  18755. {
  18756. size -= (int) (d - (char*) data.getData());
  18757. int track = 0;
  18758. while (size > 0 && track < expectedTracks)
  18759. {
  18760. const int chunkType = (int)bigEndianInt (d);
  18761. d += 4;
  18762. const int chunkSize = (int)bigEndianInt (d);
  18763. d += 4;
  18764. if (chunkSize <= 0)
  18765. break;
  18766. if (size < 0)
  18767. return false;
  18768. if (chunkType == (int)bigEndianInt ("MTrk"))
  18769. {
  18770. readNextTrack (d, chunkSize);
  18771. }
  18772. size -= chunkSize + 8;
  18773. d += chunkSize;
  18774. ++track;
  18775. }
  18776. return true;
  18777. }
  18778. }
  18779. return false;
  18780. }
  18781. // a comparator that puts all the note-offs before note-ons that have the same time
  18782. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  18783. const MidiMessageSequence::MidiEventHolder* const second) throw()
  18784. {
  18785. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  18786. if (diff == 0)
  18787. {
  18788. if (first->message.isNoteOff() && second->message.isNoteOn())
  18789. return -1;
  18790. else if (first->message.isNoteOn() && second->message.isNoteOff())
  18791. return 1;
  18792. else
  18793. return 0;
  18794. }
  18795. else
  18796. {
  18797. return (diff > 0) ? 1 : -1;
  18798. }
  18799. }
  18800. void MidiFile::readNextTrack (const char* data, int size)
  18801. {
  18802. double time = 0;
  18803. char lastStatusByte = 0;
  18804. MidiMessageSequence result;
  18805. while (size > 0)
  18806. {
  18807. int bytesUsed;
  18808. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  18809. data += bytesUsed;
  18810. size -= bytesUsed;
  18811. time += delay;
  18812. int messSize = 0;
  18813. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  18814. if (messSize <= 0)
  18815. break;
  18816. size -= messSize;
  18817. data += messSize;
  18818. result.addEvent (mm);
  18819. const char firstByte = *(mm.getRawData());
  18820. if ((firstByte & 0xf0) != 0xf0)
  18821. lastStatusByte = firstByte;
  18822. }
  18823. // use a sort that puts all the note-offs before note-ons that have the same time
  18824. result.list.sort (*this, true);
  18825. result.updateMatchedPairs();
  18826. addTrack (result);
  18827. }
  18828. static double convertTicksToSeconds (const double time,
  18829. const MidiMessageSequence& tempoEvents,
  18830. const int timeFormat)
  18831. {
  18832. if (timeFormat > 0)
  18833. {
  18834. int numer = 4, denom = 4;
  18835. double tempoTime = 0.0, correctedTempoTime = 0.0;
  18836. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  18837. double secsPerTick = 0.5 * tickLen;
  18838. const int numEvents = tempoEvents.getNumEvents();
  18839. for (int i = 0; i < numEvents; ++i)
  18840. {
  18841. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  18842. if (time <= m.getTimeStamp())
  18843. break;
  18844. if (timeFormat > 0)
  18845. {
  18846. correctedTempoTime = correctedTempoTime
  18847. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  18848. }
  18849. else
  18850. {
  18851. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  18852. }
  18853. tempoTime = m.getTimeStamp();
  18854. if (m.isTempoMetaEvent())
  18855. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  18856. else if (m.isTimeSignatureMetaEvent())
  18857. m.getTimeSignatureInfo (numer, denom);
  18858. while (i + 1 < numEvents)
  18859. {
  18860. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  18861. if (m2.getTimeStamp() == tempoTime)
  18862. {
  18863. ++i;
  18864. if (m2.isTempoMetaEvent())
  18865. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  18866. else if (m2.isTimeSignatureMetaEvent())
  18867. m2.getTimeSignatureInfo (numer, denom);
  18868. }
  18869. else
  18870. {
  18871. break;
  18872. }
  18873. }
  18874. }
  18875. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  18876. }
  18877. else
  18878. {
  18879. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  18880. }
  18881. }
  18882. void MidiFile::convertTimestampTicksToSeconds()
  18883. {
  18884. MidiMessageSequence tempoEvents;
  18885. findAllTempoEvents (tempoEvents);
  18886. findAllTimeSigEvents (tempoEvents);
  18887. for (int i = 0; i < numTracks; ++i)
  18888. {
  18889. MidiMessageSequence& ms = *tracks[i];
  18890. for (int j = ms.getNumEvents(); --j >= 0;)
  18891. {
  18892. MidiMessage& m = ms.getEventPointer(j)->message;
  18893. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  18894. tempoEvents,
  18895. timeFormat));
  18896. }
  18897. }
  18898. }
  18899. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  18900. {
  18901. unsigned int buffer = v & 0x7F;
  18902. while ((v >>= 7) != 0)
  18903. {
  18904. buffer <<= 8;
  18905. buffer |= ((v & 0x7F) | 0x80);
  18906. }
  18907. for (;;)
  18908. {
  18909. out.writeByte ((char) buffer);
  18910. if (buffer & 0x80)
  18911. buffer >>= 8;
  18912. else
  18913. break;
  18914. }
  18915. }
  18916. bool MidiFile::writeTo (OutputStream& out)
  18917. {
  18918. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  18919. out.writeIntBigEndian (6);
  18920. out.writeShortBigEndian (1); // type
  18921. out.writeShortBigEndian (numTracks);
  18922. out.writeShortBigEndian (timeFormat);
  18923. for (int i = 0; i < numTracks; ++i)
  18924. writeTrack (out, i);
  18925. out.flush();
  18926. return true;
  18927. }
  18928. void MidiFile::writeTrack (OutputStream& mainOut,
  18929. const int trackNum)
  18930. {
  18931. MemoryOutputStream out;
  18932. const MidiMessageSequence& ms = *tracks[trackNum];
  18933. int lastTick = 0;
  18934. char lastStatusByte = 0;
  18935. for (int i = 0; i < ms.getNumEvents(); ++i)
  18936. {
  18937. const MidiMessage& mm = ms.getEventPointer(i)->message;
  18938. const int tick = roundDoubleToInt (mm.getTimeStamp());
  18939. const int delta = jmax (0, tick - lastTick);
  18940. writeVariableLengthInt (out, delta);
  18941. lastTick = tick;
  18942. const char statusByte = *(mm.getRawData());
  18943. if ((statusByte == lastStatusByte)
  18944. && ((statusByte & 0xf0) != 0xf0)
  18945. && i > 0
  18946. && mm.getRawDataSize() > 1)
  18947. {
  18948. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  18949. }
  18950. else
  18951. {
  18952. out.write (mm.getRawData(), mm.getRawDataSize());
  18953. }
  18954. lastStatusByte = statusByte;
  18955. }
  18956. out.writeByte (0);
  18957. const MidiMessage m (MidiMessage::endOfTrack());
  18958. out.write (m.getRawData(),
  18959. m.getRawDataSize());
  18960. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  18961. mainOut.writeIntBigEndian (out.getDataSize());
  18962. mainOut.write (out.getData(), out.getDataSize());
  18963. }
  18964. END_JUCE_NAMESPACE
  18965. /********* End of inlined file: juce_MidiFile.cpp *********/
  18966. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  18967. BEGIN_JUCE_NAMESPACE
  18968. MidiKeyboardState::MidiKeyboardState()
  18969. : listeners (2)
  18970. {
  18971. zeromem (noteStates, sizeof (noteStates));
  18972. }
  18973. MidiKeyboardState::~MidiKeyboardState()
  18974. {
  18975. }
  18976. void MidiKeyboardState::reset()
  18977. {
  18978. const ScopedLock sl (lock);
  18979. zeromem (noteStates, sizeof (noteStates));
  18980. eventsToAdd.clear();
  18981. }
  18982. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  18983. {
  18984. jassert (midiChannel >= 0 && midiChannel <= 16);
  18985. return ((unsigned int) n) < 128
  18986. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  18987. }
  18988. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  18989. {
  18990. return ((unsigned int) n) < 128
  18991. && (noteStates[n] & midiChannelMask) != 0;
  18992. }
  18993. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  18994. {
  18995. jassert (midiChannel >= 0 && midiChannel <= 16);
  18996. jassert (((unsigned int) midiNoteNumber) < 128);
  18997. const ScopedLock sl (lock);
  18998. if (((unsigned int) midiNoteNumber) < 128)
  18999. {
  19000. const int timeNow = (int) Time::getMillisecondCounter();
  19001. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19002. eventsToAdd.clear (0, timeNow - 500);
  19003. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19004. }
  19005. }
  19006. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19007. {
  19008. if (((unsigned int) midiNoteNumber) < 128)
  19009. {
  19010. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19011. for (int i = listeners.size(); --i >= 0;)
  19012. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19013. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19014. }
  19015. }
  19016. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19017. {
  19018. const ScopedLock sl (lock);
  19019. if (isNoteOn (midiChannel, midiNoteNumber))
  19020. {
  19021. const int timeNow = (int) Time::getMillisecondCounter();
  19022. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19023. eventsToAdd.clear (0, timeNow - 500);
  19024. noteOffInternal (midiChannel, midiNoteNumber);
  19025. }
  19026. }
  19027. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19028. {
  19029. if (isNoteOn (midiChannel, midiNoteNumber))
  19030. {
  19031. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19032. for (int i = listeners.size(); --i >= 0;)
  19033. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19034. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19035. }
  19036. }
  19037. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19038. {
  19039. const ScopedLock sl (lock);
  19040. if (midiChannel <= 0)
  19041. {
  19042. for (int i = 1; i <= 16; ++i)
  19043. allNotesOff (i);
  19044. }
  19045. else
  19046. {
  19047. for (int i = 0; i < 128; ++i)
  19048. noteOff (midiChannel, i);
  19049. }
  19050. }
  19051. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19052. {
  19053. if (message.isNoteOn())
  19054. {
  19055. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19056. }
  19057. else if (message.isNoteOff())
  19058. {
  19059. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19060. }
  19061. else if (message.isAllNotesOff())
  19062. {
  19063. for (int i = 0; i < 128; ++i)
  19064. noteOffInternal (message.getChannel(), i);
  19065. }
  19066. }
  19067. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19068. const int startSample,
  19069. const int numSamples,
  19070. const bool injectIndirectEvents)
  19071. {
  19072. MidiBuffer::Iterator i (buffer);
  19073. MidiMessage message (0xf4, 0.0);
  19074. int time;
  19075. const ScopedLock sl (lock);
  19076. while (i.getNextEvent (message, time))
  19077. processNextMidiEvent (message);
  19078. if (injectIndirectEvents)
  19079. {
  19080. MidiBuffer::Iterator i2 (eventsToAdd);
  19081. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19082. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19083. while (i2.getNextEvent (message, time))
  19084. {
  19085. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19086. buffer.addEvent (message, startSample + pos);
  19087. }
  19088. }
  19089. eventsToAdd.clear();
  19090. }
  19091. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19092. {
  19093. const ScopedLock sl (lock);
  19094. listeners.addIfNotAlreadyThere (listener);
  19095. }
  19096. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19097. {
  19098. const ScopedLock sl (lock);
  19099. listeners.removeValue (listener);
  19100. }
  19101. END_JUCE_NAMESPACE
  19102. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19103. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19104. BEGIN_JUCE_NAMESPACE
  19105. int MidiMessage::readVariableLengthVal (const uint8* data,
  19106. int& numBytesUsed) throw()
  19107. {
  19108. numBytesUsed = 0;
  19109. int v = 0;
  19110. int i;
  19111. do
  19112. {
  19113. i = (int) *data++;
  19114. if (++numBytesUsed > 6)
  19115. break;
  19116. v = (v << 7) + (i & 0x7f);
  19117. } while (i & 0x80);
  19118. return v;
  19119. }
  19120. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19121. {
  19122. // this method only works for valid starting bytes of a short midi message
  19123. jassert (firstByte >= 0x80
  19124. && firstByte != 0xff
  19125. && firstByte != 0xf0
  19126. && firstByte != 0xf7);
  19127. static const char messageLengths[] =
  19128. {
  19129. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19130. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19131. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19132. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19133. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19134. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19135. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19136. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19137. };
  19138. return messageLengths [firstByte & 0x7f];
  19139. }
  19140. MidiMessage::MidiMessage (const uint8* const d,
  19141. const int dataSize,
  19142. const double t) throw()
  19143. : timeStamp (t),
  19144. message (0),
  19145. size (dataSize)
  19146. {
  19147. jassert (dataSize > 0);
  19148. if (dataSize <= 4)
  19149. data = (uint8*) &message;
  19150. else
  19151. data = (uint8*) juce_malloc (dataSize);
  19152. memcpy (data, d, dataSize);
  19153. // check that the length matches the data..
  19154. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19155. }
  19156. MidiMessage::MidiMessage (const int byte1,
  19157. const double t) throw()
  19158. : timeStamp (t),
  19159. data ((uint8*) &message),
  19160. size (1)
  19161. {
  19162. data[0] = (uint8) byte1;
  19163. // check that the length matches the data..
  19164. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19165. }
  19166. MidiMessage::MidiMessage (const int byte1,
  19167. const int byte2,
  19168. const double t) throw()
  19169. : timeStamp (t),
  19170. data ((uint8*) &message),
  19171. size (2)
  19172. {
  19173. data[0] = (uint8) byte1;
  19174. data[1] = (uint8) byte2;
  19175. // check that the length matches the data..
  19176. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19177. }
  19178. MidiMessage::MidiMessage (const int byte1,
  19179. const int byte2,
  19180. const int byte3,
  19181. const double t) throw()
  19182. : timeStamp (t),
  19183. data ((uint8*) &message),
  19184. size (3)
  19185. {
  19186. data[0] = (uint8) byte1;
  19187. data[1] = (uint8) byte2;
  19188. data[2] = (uint8) byte3;
  19189. // check that the length matches the data..
  19190. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19191. }
  19192. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19193. : timeStamp (other.timeStamp),
  19194. message (other.message),
  19195. size (other.size)
  19196. {
  19197. if (other.data != (uint8*) &other.message)
  19198. {
  19199. data = (uint8*) juce_malloc (size);
  19200. memcpy (data, other.data, size);
  19201. }
  19202. else
  19203. {
  19204. data = (uint8*) &message;
  19205. }
  19206. }
  19207. MidiMessage::MidiMessage (const MidiMessage& other,
  19208. const double newTimeStamp) throw()
  19209. : timeStamp (newTimeStamp),
  19210. message (other.message),
  19211. size (other.size)
  19212. {
  19213. if (other.data != (uint8*) &other.message)
  19214. {
  19215. data = (uint8*) juce_malloc (size);
  19216. memcpy (data, other.data, size);
  19217. }
  19218. else
  19219. {
  19220. data = (uint8*) &message;
  19221. }
  19222. }
  19223. MidiMessage::MidiMessage (const uint8* src,
  19224. int sz,
  19225. int& numBytesUsed,
  19226. const uint8 lastStatusByte,
  19227. double t) throw()
  19228. : timeStamp (t),
  19229. data ((uint8*) &message),
  19230. message (0)
  19231. {
  19232. unsigned int byte = (unsigned int) *src;
  19233. if (byte < 0x80)
  19234. {
  19235. byte = (unsigned int) (uint8) lastStatusByte;
  19236. numBytesUsed = -1;
  19237. }
  19238. else
  19239. {
  19240. numBytesUsed = 0;
  19241. --sz;
  19242. ++src;
  19243. }
  19244. if (byte >= 0x80)
  19245. {
  19246. if (byte == 0xf0)
  19247. {
  19248. const uint8* d = (const uint8*) src;
  19249. while (d < src + sz)
  19250. {
  19251. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  19252. {
  19253. if (*d == 0xf7) // include an 0xf7 if we hit one
  19254. ++d;
  19255. break;
  19256. }
  19257. ++d;
  19258. }
  19259. size = 1 + (int) (d - src);
  19260. data = (uint8*) juce_malloc (size);
  19261. *data = (uint8) byte;
  19262. memcpy (data + 1, src, size - 1);
  19263. }
  19264. else if (byte == 0xff)
  19265. {
  19266. int n;
  19267. const int bytesLeft = readVariableLengthVal (src + 1, n);
  19268. size = jmin (sz + 1, n + 2 + bytesLeft);
  19269. data = (uint8*) juce_malloc (size);
  19270. *data = (uint8) byte;
  19271. memcpy (data + 1, src, size - 1);
  19272. }
  19273. else
  19274. {
  19275. size = getMessageLengthFromFirstByte ((uint8) byte);
  19276. *data = (uint8) byte;
  19277. if (size > 1)
  19278. {
  19279. data[1] = src[0];
  19280. if (size > 2)
  19281. data[2] = src[1];
  19282. }
  19283. }
  19284. numBytesUsed += size;
  19285. }
  19286. else
  19287. {
  19288. message = 0;
  19289. size = 0;
  19290. }
  19291. }
  19292. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  19293. {
  19294. if (this == &other)
  19295. return *this;
  19296. timeStamp = other.timeStamp;
  19297. size = other.size;
  19298. message = other.message;
  19299. if (data != (uint8*) &message)
  19300. juce_free (data);
  19301. if (other.data != (uint8*) &other.message)
  19302. {
  19303. data = (uint8*) juce_malloc (size);
  19304. memcpy (data, other.data, size);
  19305. }
  19306. else
  19307. {
  19308. data = (uint8*) &message;
  19309. }
  19310. return *this;
  19311. }
  19312. MidiMessage::~MidiMessage() throw()
  19313. {
  19314. if (data != (uint8*) &message)
  19315. juce_free (data);
  19316. }
  19317. int MidiMessage::getChannel() const throw()
  19318. {
  19319. if ((data[0] & 0xf0) != 0xf0)
  19320. return (data[0] & 0xf) + 1;
  19321. else
  19322. return 0;
  19323. }
  19324. bool MidiMessage::isForChannel (const int channel) const throw()
  19325. {
  19326. return ((data[0] & 0xf) == channel - 1)
  19327. && ((data[0] & 0xf0) != 0xf0);
  19328. }
  19329. void MidiMessage::setChannel (const int channel) throw()
  19330. {
  19331. if ((data[0] & 0xf0) != (uint8) 0xf0)
  19332. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  19333. | (uint8)(channel - 1));
  19334. }
  19335. bool MidiMessage::isNoteOn() const throw()
  19336. {
  19337. return ((data[0] & 0xf0) == 0x90)
  19338. && (data[2] != 0);
  19339. }
  19340. bool MidiMessage::isNoteOff() const throw()
  19341. {
  19342. return ((data[0] & 0xf0) == 0x80)
  19343. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  19344. }
  19345. bool MidiMessage::isNoteOnOrOff() const throw()
  19346. {
  19347. const int d = data[0] & 0xf0;
  19348. return (d == 0x90) || (d == 0x80);
  19349. }
  19350. int MidiMessage::getNoteNumber() const throw()
  19351. {
  19352. return data[1];
  19353. }
  19354. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  19355. {
  19356. if (isNoteOnOrOff())
  19357. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  19358. }
  19359. uint8 MidiMessage::getVelocity() const throw()
  19360. {
  19361. if (isNoteOnOrOff())
  19362. return data[2];
  19363. else
  19364. return 0;
  19365. }
  19366. float MidiMessage::getFloatVelocity() const throw()
  19367. {
  19368. return getVelocity() * (1.0f / 127.0f);
  19369. }
  19370. void MidiMessage::setVelocity (const float newVelocity) throw()
  19371. {
  19372. if (isNoteOnOrOff())
  19373. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  19374. }
  19375. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  19376. {
  19377. if (isNoteOnOrOff())
  19378. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  19379. }
  19380. bool MidiMessage::isAftertouch() const throw()
  19381. {
  19382. return (data[0] & 0xf0) == 0xa0;
  19383. }
  19384. int MidiMessage::getAfterTouchValue() const throw()
  19385. {
  19386. return data[2];
  19387. }
  19388. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  19389. const int noteNum,
  19390. const int aftertouchValue) throw()
  19391. {
  19392. jassert (channel > 0 && channel <= 16);
  19393. jassert (((unsigned int) noteNum) <= 127);
  19394. jassert (((unsigned int) aftertouchValue) <= 127);
  19395. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  19396. noteNum & 0x7f,
  19397. aftertouchValue & 0x7f);
  19398. }
  19399. bool MidiMessage::isChannelPressure() const throw()
  19400. {
  19401. return (data[0] & 0xf0) == 0xd0;
  19402. }
  19403. int MidiMessage::getChannelPressureValue() const throw()
  19404. {
  19405. jassert (isChannelPressure());
  19406. return data[1];
  19407. }
  19408. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  19409. const int pressure) throw()
  19410. {
  19411. jassert (channel > 0 && channel <= 16);
  19412. jassert (((unsigned int) pressure) <= 127);
  19413. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  19414. pressure & 0x7f);
  19415. }
  19416. bool MidiMessage::isProgramChange() const throw()
  19417. {
  19418. return (data[0] & 0xf0) == 0xc0;
  19419. }
  19420. int MidiMessage::getProgramChangeNumber() const throw()
  19421. {
  19422. return data[1];
  19423. }
  19424. const MidiMessage MidiMessage::programChange (const int channel,
  19425. const int programNumber) throw()
  19426. {
  19427. jassert (channel > 0 && channel <= 16);
  19428. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  19429. programNumber & 0x7f);
  19430. }
  19431. bool MidiMessage::isPitchWheel() const throw()
  19432. {
  19433. return (data[0] & 0xf0) == 0xe0;
  19434. }
  19435. int MidiMessage::getPitchWheelValue() const throw()
  19436. {
  19437. return data[1] | (data[2] << 7);
  19438. }
  19439. const MidiMessage MidiMessage::pitchWheel (const int channel,
  19440. const int position) throw()
  19441. {
  19442. jassert (channel > 0 && channel <= 16);
  19443. jassert (((unsigned int) position) <= 0x3fff);
  19444. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  19445. position & 127,
  19446. (position >> 7) & 127);
  19447. }
  19448. bool MidiMessage::isController() const throw()
  19449. {
  19450. return (data[0] & 0xf0) == 0xb0;
  19451. }
  19452. int MidiMessage::getControllerNumber() const throw()
  19453. {
  19454. jassert (isController());
  19455. return data[1];
  19456. }
  19457. int MidiMessage::getControllerValue() const throw()
  19458. {
  19459. jassert (isController());
  19460. return data[2];
  19461. }
  19462. const MidiMessage MidiMessage::controllerEvent (const int channel,
  19463. const int controllerType,
  19464. const int value) throw()
  19465. {
  19466. // the channel must be between 1 and 16 inclusive
  19467. jassert (channel > 0 && channel <= 16);
  19468. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  19469. controllerType & 127,
  19470. value & 127);
  19471. }
  19472. const MidiMessage MidiMessage::noteOn (const int channel,
  19473. const int noteNumber,
  19474. const float velocity) throw()
  19475. {
  19476. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  19477. }
  19478. const MidiMessage MidiMessage::noteOn (const int channel,
  19479. const int noteNumber,
  19480. const uint8 velocity) throw()
  19481. {
  19482. jassert (channel > 0 && channel <= 16);
  19483. jassert (((unsigned int) noteNumber) <= 127);
  19484. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  19485. noteNumber & 127,
  19486. jlimit (0, 127, roundFloatToInt (velocity)));
  19487. }
  19488. const MidiMessage MidiMessage::noteOff (const int channel,
  19489. const int noteNumber) throw()
  19490. {
  19491. jassert (channel > 0 && channel <= 16);
  19492. jassert (((unsigned int) noteNumber) <= 127);
  19493. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  19494. }
  19495. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  19496. {
  19497. jassert (channel > 0 && channel <= 16);
  19498. return controllerEvent (channel, 123, 0);
  19499. }
  19500. bool MidiMessage::isAllNotesOff() const throw()
  19501. {
  19502. return (data[0] & 0xf0) == 0xb0
  19503. && data[1] == 123;
  19504. }
  19505. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  19506. {
  19507. return controllerEvent (channel, 120, 0);
  19508. }
  19509. bool MidiMessage::isAllSoundOff() const throw()
  19510. {
  19511. return (data[0] & 0xf0) == 0xb0
  19512. && data[1] == 120;
  19513. }
  19514. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  19515. {
  19516. return controllerEvent (channel, 121, 0);
  19517. }
  19518. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  19519. {
  19520. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  19521. uint8 buf[8];
  19522. buf[0] = 0xf0;
  19523. buf[1] = 0x7f;
  19524. buf[2] = 0x7f;
  19525. buf[3] = 0x04;
  19526. buf[4] = 0x01;
  19527. buf[5] = (uint8) (vol & 0x7f);
  19528. buf[6] = (uint8) (vol >> 7);
  19529. buf[7] = 0xf7;
  19530. return MidiMessage (buf, 8);
  19531. }
  19532. bool MidiMessage::isSysEx() const throw()
  19533. {
  19534. return *data == 0xf0;
  19535. }
  19536. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  19537. const int dataSize) throw()
  19538. {
  19539. MemoryBlock mm (dataSize + 2);
  19540. uint8* const m = (uint8*) mm.getData();
  19541. m[0] = 0xf0;
  19542. memcpy (m + 1, sysexData, dataSize);
  19543. m[dataSize + 1] = 0xf7;
  19544. return MidiMessage (m, dataSize + 2);
  19545. }
  19546. const uint8* MidiMessage::getSysExData() const throw()
  19547. {
  19548. return (isSysEx()) ? getRawData() + 1
  19549. : 0;
  19550. }
  19551. int MidiMessage::getSysExDataSize() const throw()
  19552. {
  19553. return (isSysEx()) ? size - 2
  19554. : 0;
  19555. }
  19556. bool MidiMessage::isMetaEvent() const throw()
  19557. {
  19558. return *data == 0xff;
  19559. }
  19560. bool MidiMessage::isActiveSense() const throw()
  19561. {
  19562. return *data == 0xfe;
  19563. }
  19564. int MidiMessage::getMetaEventType() const throw()
  19565. {
  19566. if (*data != 0xff)
  19567. return -1;
  19568. else
  19569. return data[1];
  19570. }
  19571. int MidiMessage::getMetaEventLength() const throw()
  19572. {
  19573. if (*data == 0xff)
  19574. {
  19575. int n;
  19576. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  19577. }
  19578. return 0;
  19579. }
  19580. const uint8* MidiMessage::getMetaEventData() const throw()
  19581. {
  19582. int n;
  19583. const uint8* d = data + 2;
  19584. readVariableLengthVal (d, n);
  19585. return d + n;
  19586. }
  19587. bool MidiMessage::isTrackMetaEvent() const throw()
  19588. {
  19589. return getMetaEventType() == 0;
  19590. }
  19591. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  19592. {
  19593. return getMetaEventType() == 47;
  19594. }
  19595. bool MidiMessage::isTextMetaEvent() const throw()
  19596. {
  19597. const int t = getMetaEventType();
  19598. return t > 0 && t < 16;
  19599. }
  19600. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  19601. {
  19602. return String ((const char*) getMetaEventData(),
  19603. getMetaEventLength());
  19604. }
  19605. bool MidiMessage::isTrackNameEvent() const throw()
  19606. {
  19607. return (data[1] == 3)
  19608. && (*data == 0xff);
  19609. }
  19610. bool MidiMessage::isTempoMetaEvent() const throw()
  19611. {
  19612. return (data[1] == 81)
  19613. && (*data == 0xff);
  19614. }
  19615. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  19616. {
  19617. return (data[1] == 0x20)
  19618. && (*data == 0xff)
  19619. && (data[2] == 1);
  19620. }
  19621. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  19622. {
  19623. return data[3] + 1;
  19624. }
  19625. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  19626. {
  19627. if (! isTempoMetaEvent())
  19628. return 0.0;
  19629. const uint8* const d = getMetaEventData();
  19630. return (((unsigned int) d[0] << 16)
  19631. | ((unsigned int) d[1] << 8)
  19632. | d[2])
  19633. / 1000000.0;
  19634. }
  19635. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  19636. {
  19637. if (timeFormat > 0)
  19638. {
  19639. if (! isTempoMetaEvent())
  19640. return 0.5 / timeFormat;
  19641. return getTempoSecondsPerQuarterNote() / timeFormat;
  19642. }
  19643. else
  19644. {
  19645. const int frameCode = (-timeFormat) >> 8;
  19646. double framesPerSecond;
  19647. switch (frameCode)
  19648. {
  19649. case 24: framesPerSecond = 24.0; break;
  19650. case 25: framesPerSecond = 25.0; break;
  19651. case 29: framesPerSecond = 29.97; break;
  19652. case 30: framesPerSecond = 30.0; break;
  19653. default: framesPerSecond = 30.0; break;
  19654. }
  19655. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  19656. }
  19657. }
  19658. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  19659. {
  19660. uint8 d[8];
  19661. d[0] = 0xff;
  19662. d[1] = 81;
  19663. d[2] = 3;
  19664. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  19665. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  19666. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  19667. return MidiMessage (d, 6, 0.0);
  19668. }
  19669. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  19670. {
  19671. return (data[1] == 0x58)
  19672. && (*data == (uint8) 0xff);
  19673. }
  19674. void MidiMessage::getTimeSignatureInfo (int& numerator,
  19675. int& denominator) const throw()
  19676. {
  19677. if (isTimeSignatureMetaEvent())
  19678. {
  19679. const uint8* const d = getMetaEventData();
  19680. numerator = d[0];
  19681. denominator = 1 << d[1];
  19682. }
  19683. else
  19684. {
  19685. numerator = 4;
  19686. denominator = 4;
  19687. }
  19688. }
  19689. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  19690. const int denominator) throw()
  19691. {
  19692. uint8 d[8];
  19693. d[0] = 0xff;
  19694. d[1] = 0x58;
  19695. d[2] = 0x04;
  19696. d[3] = (uint8) numerator;
  19697. int n = 1;
  19698. int powerOfTwo = 0;
  19699. while (n < denominator)
  19700. {
  19701. n <<= 1;
  19702. ++powerOfTwo;
  19703. }
  19704. d[4] = (uint8) powerOfTwo;
  19705. d[5] = 0x01;
  19706. d[6] = 96;
  19707. return MidiMessage (d, 7, 0.0);
  19708. }
  19709. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  19710. {
  19711. uint8 d[8];
  19712. d[0] = 0xff;
  19713. d[1] = 0x20;
  19714. d[2] = 0x01;
  19715. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  19716. return MidiMessage (d, 4, 0.0);
  19717. }
  19718. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  19719. {
  19720. return getMetaEventType() == 89;
  19721. }
  19722. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  19723. {
  19724. return (int) *getMetaEventData();
  19725. }
  19726. const MidiMessage MidiMessage::endOfTrack() throw()
  19727. {
  19728. return MidiMessage (0xff, 0x2f, 0, 0.0);
  19729. }
  19730. bool MidiMessage::isSongPositionPointer() const throw()
  19731. {
  19732. return *data == 0xf2;
  19733. }
  19734. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  19735. {
  19736. return data[1] | (data[2] << 7);
  19737. }
  19738. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  19739. {
  19740. return MidiMessage (0xf2,
  19741. positionInMidiBeats & 127,
  19742. (positionInMidiBeats >> 7) & 127);
  19743. }
  19744. bool MidiMessage::isMidiStart() const throw()
  19745. {
  19746. return *data == 0xfa;
  19747. }
  19748. const MidiMessage MidiMessage::midiStart() throw()
  19749. {
  19750. return MidiMessage (0xfa);
  19751. }
  19752. bool MidiMessage::isMidiContinue() const throw()
  19753. {
  19754. return *data == 0xfb;
  19755. }
  19756. const MidiMessage MidiMessage::midiContinue() throw()
  19757. {
  19758. return MidiMessage (0xfb);
  19759. }
  19760. bool MidiMessage::isMidiStop() const throw()
  19761. {
  19762. return *data == 0xfc;
  19763. }
  19764. const MidiMessage MidiMessage::midiStop() throw()
  19765. {
  19766. return MidiMessage (0xfc);
  19767. }
  19768. bool MidiMessage::isMidiClock() const throw()
  19769. {
  19770. return *data == 0xf8;
  19771. }
  19772. const MidiMessage MidiMessage::midiClock() throw()
  19773. {
  19774. return MidiMessage (0xf8);
  19775. }
  19776. bool MidiMessage::isQuarterFrame() const throw()
  19777. {
  19778. return *data == 0xf1;
  19779. }
  19780. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  19781. {
  19782. return ((int) data[1]) >> 4;
  19783. }
  19784. int MidiMessage::getQuarterFrameValue() const throw()
  19785. {
  19786. return ((int) data[1]) & 0x0f;
  19787. }
  19788. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  19789. const int value) throw()
  19790. {
  19791. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  19792. }
  19793. bool MidiMessage::isFullFrame() const throw()
  19794. {
  19795. return data[0] == 0xf0
  19796. && data[1] == 0x7f
  19797. && size >= 10
  19798. && data[3] == 0x01
  19799. && data[4] == 0x01;
  19800. }
  19801. void MidiMessage::getFullFrameParameters (int& hours,
  19802. int& minutes,
  19803. int& seconds,
  19804. int& frames,
  19805. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  19806. {
  19807. jassert (isFullFrame());
  19808. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  19809. hours = data[5] & 0x1f;
  19810. minutes = data[6];
  19811. seconds = data[7];
  19812. frames = data[8];
  19813. }
  19814. const MidiMessage MidiMessage::fullFrame (const int hours,
  19815. const int minutes,
  19816. const int seconds,
  19817. const int frames,
  19818. MidiMessage::SmpteTimecodeType timecodeType)
  19819. {
  19820. uint8 d[10];
  19821. d[0] = 0xf0;
  19822. d[1] = 0x7f;
  19823. d[2] = 0x7f;
  19824. d[3] = 0x01;
  19825. d[4] = 0x01;
  19826. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  19827. d[6] = (uint8) minutes;
  19828. d[7] = (uint8) seconds;
  19829. d[8] = (uint8) frames;
  19830. d[9] = 0xf7;
  19831. return MidiMessage (d, 10, 0.0);
  19832. }
  19833. bool MidiMessage::isMidiMachineControlMessage() const throw()
  19834. {
  19835. return data[0] == 0xf0
  19836. && data[1] == 0x7f
  19837. && data[3] == 0x06
  19838. && size > 5;
  19839. }
  19840. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  19841. {
  19842. jassert (isMidiMachineControlMessage());
  19843. return (MidiMachineControlCommand) data[4];
  19844. }
  19845. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  19846. {
  19847. uint8 d[6];
  19848. d[0] = 0xf0;
  19849. d[1] = 0x7f;
  19850. d[2] = 0x00;
  19851. d[3] = 0x06;
  19852. d[4] = (uint8) command;
  19853. d[5] = 0xf7;
  19854. return MidiMessage (d, 6, 0.0);
  19855. }
  19856. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  19857. int& minutes,
  19858. int& seconds,
  19859. int& frames) const throw()
  19860. {
  19861. if (size >= 12
  19862. && data[0] == 0xf0
  19863. && data[1] == 0x7f
  19864. && data[3] == 0x06
  19865. && data[4] == 0x44
  19866. && data[5] == 0x06
  19867. && data[6] == 0x01)
  19868. {
  19869. hours = data[7] % 24; // (that some machines send out hours > 24)
  19870. minutes = data[8];
  19871. seconds = data[9];
  19872. frames = data[10];
  19873. return true;
  19874. }
  19875. return false;
  19876. }
  19877. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  19878. int minutes,
  19879. int seconds,
  19880. int frames)
  19881. {
  19882. uint8 d[12];
  19883. d[0] = 0xf0;
  19884. d[1] = 0x7f;
  19885. d[2] = 0x00;
  19886. d[3] = 0x06;
  19887. d[4] = 0x44;
  19888. d[5] = 0x06;
  19889. d[6] = 0x01;
  19890. d[7] = (uint8) hours;
  19891. d[8] = (uint8) minutes;
  19892. d[9] = (uint8) seconds;
  19893. d[10] = (uint8) frames;
  19894. d[11] = 0xf7;
  19895. return MidiMessage (d, 12, 0.0);
  19896. }
  19897. const String MidiMessage::getMidiNoteName (int note,
  19898. bool useSharps,
  19899. bool includeOctaveNumber,
  19900. int octaveNumForMiddleC) throw()
  19901. {
  19902. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  19903. "F", "F#", "G", "G#", "A",
  19904. "A#", "B" };
  19905. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  19906. "F", "Gb", "G", "Ab", "A",
  19907. "Bb", "B" };
  19908. if (((unsigned int) note) < 128)
  19909. {
  19910. const String s ((useSharps) ? sharpNoteNames [note % 12]
  19911. : flatNoteNames [note % 12]);
  19912. if (includeOctaveNumber)
  19913. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  19914. else
  19915. return s;
  19916. }
  19917. return String::empty;
  19918. }
  19919. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  19920. {
  19921. noteNumber -= 12 * 6 + 9; // now 0 = A440
  19922. return 440.0 * pow (2.0, noteNumber / 12.0);
  19923. }
  19924. const String MidiMessage::getGMInstrumentName (int n) throw()
  19925. {
  19926. const char *names[] =
  19927. {
  19928. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  19929. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  19930. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  19931. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  19932. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  19933. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  19934. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  19935. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  19936. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  19937. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  19938. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  19939. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  19940. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  19941. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  19942. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  19943. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  19944. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  19945. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  19946. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  19947. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  19948. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  19949. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  19950. "Applause", "Gunshot"
  19951. };
  19952. return (((unsigned int) n) < 128) ? names[n]
  19953. : (const char*)0;
  19954. }
  19955. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  19956. {
  19957. const char* names[] =
  19958. {
  19959. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  19960. "Bass", "Strings", "Ensemble", "Brass",
  19961. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  19962. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  19963. };
  19964. return (((unsigned int) n) <= 15) ? names[n]
  19965. : (const char*)0;
  19966. }
  19967. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  19968. {
  19969. const char* names[] =
  19970. {
  19971. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  19972. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  19973. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  19974. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  19975. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  19976. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  19977. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  19978. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  19979. "Mute Triangle", "Open Triangle"
  19980. };
  19981. return (n >= 35 && n <= 81) ? names [n - 35]
  19982. : (const char*)0;
  19983. }
  19984. const String MidiMessage::getControllerName (int n) throw()
  19985. {
  19986. const char* names[] =
  19987. {
  19988. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  19989. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  19990. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  19991. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  19992. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  19993. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  19994. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  19995. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  19996. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  19997. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  19998. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  19999. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20000. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20001. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20002. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20003. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20004. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20005. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20006. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20008. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20009. "Poly Operation"
  20010. };
  20011. return (((unsigned int) n) < 128) ? names[n]
  20012. : (const char*)0;
  20013. }
  20014. END_JUCE_NAMESPACE
  20015. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20016. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20017. BEGIN_JUCE_NAMESPACE
  20018. MidiMessageCollector::MidiMessageCollector()
  20019. : lastCallbackTime (0),
  20020. sampleRate (44100.0001)
  20021. {
  20022. }
  20023. MidiMessageCollector::~MidiMessageCollector()
  20024. {
  20025. }
  20026. void MidiMessageCollector::reset (const double sampleRate_)
  20027. {
  20028. jassert (sampleRate_ > 0);
  20029. const ScopedLock sl (midiCallbackLock);
  20030. sampleRate = sampleRate_;
  20031. incomingMessages.clear();
  20032. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20033. }
  20034. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20035. {
  20036. // you need to call reset() to set the correct sample rate before using this object
  20037. jassert (sampleRate != 44100.0001);
  20038. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20039. // for details of what the number should be.
  20040. jassert (message.getTimeStamp() != 0);
  20041. const ScopedLock sl (midiCallbackLock);
  20042. const int sampleNumber
  20043. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20044. incomingMessages.addEvent (message, sampleNumber);
  20045. // if the messages don't get used for over a second, we'd better
  20046. // get rid of any old ones to avoid the queue getting too big
  20047. if (sampleNumber > sampleRate)
  20048. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20049. }
  20050. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20051. const int numSamples)
  20052. {
  20053. // you need to call reset() to set the correct sample rate before using this object
  20054. jassert (sampleRate != 44100.0001);
  20055. const double timeNow = Time::getMillisecondCounterHiRes();
  20056. const double msElapsed = timeNow - lastCallbackTime;
  20057. const ScopedLock sl (midiCallbackLock);
  20058. lastCallbackTime = timeNow;
  20059. if (! incomingMessages.isEmpty())
  20060. {
  20061. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20062. int startSample = 0;
  20063. int scale = 1 << 16;
  20064. const uint8* midiData;
  20065. int numBytes, samplePosition;
  20066. MidiBuffer::Iterator iter (incomingMessages);
  20067. if (numSourceSamples > numSamples)
  20068. {
  20069. // if our list of events is longer than the buffer we're being
  20070. // asked for, scale them down to squeeze them all in..
  20071. const int maxBlockLengthToUse = numSamples << 3;
  20072. if (numSourceSamples > maxBlockLengthToUse)
  20073. {
  20074. startSample = numSourceSamples - maxBlockLengthToUse;
  20075. numSourceSamples = maxBlockLengthToUse;
  20076. iter.setNextSamplePosition (startSample);
  20077. }
  20078. scale = (numSamples << 10) / numSourceSamples;
  20079. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20080. {
  20081. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20082. destBuffer.addEvent (midiData, numBytes,
  20083. jlimit (0, numSamples - 1, samplePosition));
  20084. }
  20085. }
  20086. else
  20087. {
  20088. // if our event list is shorter than the number we need, put them
  20089. // towards the end of the buffer
  20090. startSample = numSamples - numSourceSamples;
  20091. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20092. {
  20093. destBuffer.addEvent (midiData, numBytes,
  20094. jlimit (0, numSamples - 1, samplePosition + startSample));
  20095. }
  20096. }
  20097. incomingMessages.clear();
  20098. }
  20099. }
  20100. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20101. {
  20102. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20103. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20104. addMessageToQueue (m);
  20105. }
  20106. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20107. {
  20108. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20109. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20110. addMessageToQueue (m);
  20111. }
  20112. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20113. {
  20114. addMessageToQueue (message);
  20115. }
  20116. END_JUCE_NAMESPACE
  20117. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20118. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20119. BEGIN_JUCE_NAMESPACE
  20120. MidiMessageSequence::MidiMessageSequence()
  20121. {
  20122. }
  20123. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20124. {
  20125. list.ensureStorageAllocated (other.list.size());
  20126. for (int i = 0; i < other.list.size(); ++i)
  20127. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20128. }
  20129. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20130. {
  20131. if (this != &other)
  20132. {
  20133. clear();
  20134. for (int i = 0; i < other.list.size(); ++i)
  20135. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20136. }
  20137. return *this;
  20138. }
  20139. MidiMessageSequence::~MidiMessageSequence()
  20140. {
  20141. }
  20142. void MidiMessageSequence::clear()
  20143. {
  20144. list.clear();
  20145. }
  20146. int MidiMessageSequence::getNumEvents() const
  20147. {
  20148. return list.size();
  20149. }
  20150. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20151. {
  20152. return list [index];
  20153. }
  20154. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20155. {
  20156. const MidiEventHolder* const meh = list [index];
  20157. if (meh != 0 && meh->noteOffObject != 0)
  20158. return meh->noteOffObject->message.getTimeStamp();
  20159. else
  20160. return 0.0;
  20161. }
  20162. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20163. {
  20164. const MidiEventHolder* const meh = list [index];
  20165. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20166. }
  20167. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20168. {
  20169. return list.indexOf (event);
  20170. }
  20171. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20172. {
  20173. const int numEvents = list.size();
  20174. int i;
  20175. for (i = 0; i < numEvents; ++i)
  20176. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20177. break;
  20178. return i;
  20179. }
  20180. double MidiMessageSequence::getStartTime() const
  20181. {
  20182. if (list.size() > 0)
  20183. return list.getUnchecked(0)->message.getTimeStamp();
  20184. else
  20185. return 0;
  20186. }
  20187. double MidiMessageSequence::getEndTime() const
  20188. {
  20189. if (list.size() > 0)
  20190. return list.getLast()->message.getTimeStamp();
  20191. else
  20192. return 0;
  20193. }
  20194. double MidiMessageSequence::getEventTime (const int index) const
  20195. {
  20196. if (((unsigned int) index) < (unsigned int) list.size())
  20197. return list.getUnchecked (index)->message.getTimeStamp();
  20198. return 0.0;
  20199. }
  20200. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20201. double timeAdjustment)
  20202. {
  20203. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20204. timeAdjustment += newMessage.getTimeStamp();
  20205. newOne->message.setTimeStamp (timeAdjustment);
  20206. int i;
  20207. for (i = list.size(); --i >= 0;)
  20208. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20209. break;
  20210. list.insert (i + 1, newOne);
  20211. }
  20212. void MidiMessageSequence::deleteEvent (const int index,
  20213. const bool deleteMatchingNoteUp)
  20214. {
  20215. if (((unsigned int) index) < (unsigned int) list.size())
  20216. {
  20217. if (deleteMatchingNoteUp)
  20218. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  20219. list.remove (index);
  20220. }
  20221. }
  20222. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  20223. double timeAdjustment,
  20224. double firstAllowableTime,
  20225. double endOfAllowableDestTimes)
  20226. {
  20227. firstAllowableTime -= timeAdjustment;
  20228. endOfAllowableDestTimes -= timeAdjustment;
  20229. for (int i = 0; i < other.list.size(); ++i)
  20230. {
  20231. const MidiMessage& m = other.list.getUnchecked(i)->message;
  20232. const double t = m.getTimeStamp();
  20233. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  20234. {
  20235. MidiEventHolder* const newOne = new MidiEventHolder (m);
  20236. newOne->message.setTimeStamp (timeAdjustment + t);
  20237. list.add (newOne);
  20238. }
  20239. }
  20240. sort();
  20241. }
  20242. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20243. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20244. {
  20245. const double diff = first->message.getTimeStamp()
  20246. - second->message.getTimeStamp();
  20247. return (diff == 0) ? 0
  20248. : ((diff > 0) ? 1
  20249. : -1);
  20250. }
  20251. void MidiMessageSequence::sort()
  20252. {
  20253. list.sort (*this, true);
  20254. }
  20255. void MidiMessageSequence::updateMatchedPairs()
  20256. {
  20257. for (int i = 0; i < list.size(); ++i)
  20258. {
  20259. const MidiMessage& m1 = list.getUnchecked(i)->message;
  20260. if (m1.isNoteOn())
  20261. {
  20262. list.getUnchecked(i)->noteOffObject = 0;
  20263. const int note = m1.getNoteNumber();
  20264. const int chan = m1.getChannel();
  20265. const int len = list.size();
  20266. for (int j = i + 1; j < len; ++j)
  20267. {
  20268. const MidiMessage& m = list.getUnchecked(j)->message;
  20269. if (m.getNoteNumber() == note && m.getChannel() == chan)
  20270. {
  20271. if (m.isNoteOff())
  20272. {
  20273. list.getUnchecked(i)->noteOffObject = list[j];
  20274. break;
  20275. }
  20276. else if (m.isNoteOn())
  20277. {
  20278. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  20279. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  20280. list.getUnchecked(i)->noteOffObject = list[j];
  20281. break;
  20282. }
  20283. }
  20284. }
  20285. }
  20286. }
  20287. }
  20288. void MidiMessageSequence::addTimeToMessages (const double delta)
  20289. {
  20290. for (int i = list.size(); --i >= 0;)
  20291. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  20292. + delta);
  20293. }
  20294. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  20295. MidiMessageSequence& destSequence,
  20296. const bool alsoIncludeMetaEvents) const
  20297. {
  20298. for (int i = 0; i < list.size(); ++i)
  20299. {
  20300. const MidiMessage& mm = list.getUnchecked(i)->message;
  20301. if (mm.isForChannel (channelNumberToExtract)
  20302. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  20303. {
  20304. destSequence.addEvent (mm);
  20305. }
  20306. }
  20307. }
  20308. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  20309. {
  20310. for (int i = 0; i < list.size(); ++i)
  20311. {
  20312. const MidiMessage& mm = list.getUnchecked(i)->message;
  20313. if (mm.isSysEx())
  20314. destSequence.addEvent (mm);
  20315. }
  20316. }
  20317. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  20318. {
  20319. for (int i = list.size(); --i >= 0;)
  20320. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  20321. list.remove(i);
  20322. }
  20323. void MidiMessageSequence::deleteSysExMessages()
  20324. {
  20325. for (int i = list.size(); --i >= 0;)
  20326. if (list.getUnchecked(i)->message.isSysEx())
  20327. list.remove(i);
  20328. }
  20329. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  20330. const double time,
  20331. OwnedArray<MidiMessage>& dest)
  20332. {
  20333. bool doneProg = false;
  20334. bool donePitchWheel = false;
  20335. Array <int> doneControllers (32);
  20336. for (int i = list.size(); --i >= 0;)
  20337. {
  20338. const MidiMessage& mm = list.getUnchecked(i)->message;
  20339. if (mm.isForChannel (channelNumber)
  20340. && mm.getTimeStamp() <= time)
  20341. {
  20342. if (mm.isProgramChange())
  20343. {
  20344. if (! doneProg)
  20345. {
  20346. dest.add (new MidiMessage (mm, 0.0));
  20347. doneProg = true;
  20348. }
  20349. }
  20350. else if (mm.isController())
  20351. {
  20352. if (! doneControllers.contains (mm.getControllerNumber()))
  20353. {
  20354. dest.add (new MidiMessage (mm, 0.0));
  20355. doneControllers.add (mm.getControllerNumber());
  20356. }
  20357. }
  20358. else if (mm.isPitchWheel())
  20359. {
  20360. if (! donePitchWheel)
  20361. {
  20362. dest.add (new MidiMessage (mm, 0.0));
  20363. donePitchWheel = true;
  20364. }
  20365. }
  20366. }
  20367. }
  20368. }
  20369. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  20370. : message (message_),
  20371. noteOffObject (0)
  20372. {
  20373. }
  20374. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  20375. {
  20376. }
  20377. END_JUCE_NAMESPACE
  20378. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  20379. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  20380. BEGIN_JUCE_NAMESPACE
  20381. AudioPluginFormat::AudioPluginFormat() throw()
  20382. {
  20383. }
  20384. AudioPluginFormat::~AudioPluginFormat()
  20385. {
  20386. }
  20387. END_JUCE_NAMESPACE
  20388. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  20389. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20390. BEGIN_JUCE_NAMESPACE
  20391. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  20392. {
  20393. }
  20394. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  20395. {
  20396. }
  20397. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  20398. void AudioPluginFormatManager::addDefaultFormats()
  20399. {
  20400. #ifdef JUCE_DEBUG
  20401. // you should only call this method once!
  20402. for (int i = formats.size(); --i >= 0;)
  20403. {
  20404. #if JUCE_PLUGINHOST_VST
  20405. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  20406. #endif
  20407. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20408. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  20409. #endif
  20410. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20411. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  20412. #endif
  20413. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20414. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  20415. #endif
  20416. }
  20417. #endif
  20418. #if JUCE_PLUGINHOST_VST
  20419. formats.add (new VSTPluginFormat());
  20420. #endif
  20421. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20422. formats.add (new AudioUnitPluginFormat());
  20423. #endif
  20424. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20425. formats.add (new DirectXPluginFormat());
  20426. #endif
  20427. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20428. formats.add (new LADSPAPluginFormat());
  20429. #endif
  20430. }
  20431. int AudioPluginFormatManager::getNumFormats() throw()
  20432. {
  20433. return formats.size();
  20434. }
  20435. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  20436. {
  20437. return formats [index];
  20438. }
  20439. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  20440. {
  20441. formats.add (format);
  20442. }
  20443. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  20444. String& errorMessage) const
  20445. {
  20446. AudioPluginInstance* result = 0;
  20447. for (int i = 0; i < formats.size(); ++i)
  20448. {
  20449. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  20450. if (result != 0)
  20451. break;
  20452. }
  20453. if (result == 0)
  20454. {
  20455. if (description.file != File::nonexistent && ! description.file.exists())
  20456. errorMessage = TRANS ("This plug-in file no longer exists");
  20457. else
  20458. errorMessage = TRANS ("This plug-in failed to load correctly");
  20459. }
  20460. return result;
  20461. }
  20462. END_JUCE_NAMESPACE
  20463. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20464. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  20465. #define JUCE_PLUGIN_HOST 1
  20466. BEGIN_JUCE_NAMESPACE
  20467. AudioPluginInstance::AudioPluginInstance()
  20468. {
  20469. }
  20470. AudioPluginInstance::~AudioPluginInstance()
  20471. {
  20472. }
  20473. END_JUCE_NAMESPACE
  20474. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  20475. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  20476. BEGIN_JUCE_NAMESPACE
  20477. KnownPluginList::KnownPluginList()
  20478. {
  20479. }
  20480. KnownPluginList::~KnownPluginList()
  20481. {
  20482. }
  20483. void KnownPluginList::clear()
  20484. {
  20485. if (types.size() > 0)
  20486. {
  20487. types.clear();
  20488. sendChangeMessage (this);
  20489. }
  20490. }
  20491. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  20492. {
  20493. for (int i = 0; i < types.size(); ++i)
  20494. if (types.getUnchecked(i)->file == file)
  20495. return types.getUnchecked(i);
  20496. return 0;
  20497. }
  20498. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  20499. {
  20500. for (int i = 0; i < types.size(); ++i)
  20501. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  20502. return types.getUnchecked(i);
  20503. return 0;
  20504. }
  20505. bool KnownPluginList::addType (const PluginDescription& type)
  20506. {
  20507. for (int i = types.size(); --i >= 0;)
  20508. {
  20509. if (types.getUnchecked(i)->isDuplicateOf (type))
  20510. {
  20511. // strange - found a duplicate plugin with different info..
  20512. jassert (types.getUnchecked(i)->name == type.name);
  20513. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  20514. *types.getUnchecked(i) = type;
  20515. return false;
  20516. }
  20517. }
  20518. types.add (new PluginDescription (type));
  20519. sendChangeMessage (this);
  20520. return true;
  20521. }
  20522. void KnownPluginList::removeType (const int index) throw()
  20523. {
  20524. types.remove (index);
  20525. sendChangeMessage (this);
  20526. }
  20527. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  20528. {
  20529. if (getTypeForFile (possiblePluginFile) == 0)
  20530. return false;
  20531. for (int i = types.size(); --i >= 0;)
  20532. {
  20533. const PluginDescription* const d = types.getUnchecked(i);
  20534. if (d->file == possiblePluginFile
  20535. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20536. {
  20537. return false;
  20538. }
  20539. }
  20540. return true;
  20541. }
  20542. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  20543. const bool dontRescanIfAlreadyInList,
  20544. OwnedArray <PluginDescription>& typesFound)
  20545. {
  20546. bool addedOne = false;
  20547. if (dontRescanIfAlreadyInList
  20548. && getTypeForFile (possiblePluginFile) != 0)
  20549. {
  20550. bool needsRescanning = false;
  20551. for (int i = types.size(); --i >= 0;)
  20552. {
  20553. const PluginDescription* const d = types.getUnchecked(i);
  20554. if (d->file == possiblePluginFile)
  20555. {
  20556. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20557. needsRescanning = true;
  20558. else
  20559. typesFound.add (new PluginDescription (*d));
  20560. }
  20561. }
  20562. if (! needsRescanning)
  20563. return false;
  20564. }
  20565. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  20566. {
  20567. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  20568. OwnedArray <PluginDescription> found;
  20569. format->findAllTypesForFile (found, possiblePluginFile);
  20570. for (int i = 0; i < found.size(); ++i)
  20571. {
  20572. PluginDescription* const desc = found.getUnchecked(i);
  20573. jassert (desc != 0);
  20574. if (addType (*desc))
  20575. addedOne = true;
  20576. typesFound.add (new PluginDescription (*desc));
  20577. }
  20578. }
  20579. return addedOne;
  20580. }
  20581. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  20582. OwnedArray <PluginDescription>& typesFound)
  20583. {
  20584. for (int i = 0; i < files.size(); ++i)
  20585. {
  20586. const File f (files [i]);
  20587. if (! scanAndAddFile (f, true, typesFound))
  20588. {
  20589. if (f.isDirectory())
  20590. {
  20591. StringArray s;
  20592. {
  20593. OwnedArray <File> subFiles;
  20594. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  20595. for (int j = 0; j < subFiles.size(); ++j)
  20596. s.add (subFiles.getUnchecked (j)->getFullPathName());
  20597. }
  20598. scanAndAddDragAndDroppedFiles (s, typesFound);
  20599. }
  20600. }
  20601. }
  20602. }
  20603. class PluginSorter
  20604. {
  20605. public:
  20606. KnownPluginList::SortMethod method;
  20607. PluginSorter() throw() {}
  20608. int compareElements (const PluginDescription* const first,
  20609. const PluginDescription* const second) const throw()
  20610. {
  20611. int diff = 0;
  20612. if (method == KnownPluginList::sortByCategory)
  20613. diff = first->category.compareLexicographically (second->category);
  20614. else if (method == KnownPluginList::sortByManufacturer)
  20615. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  20616. else if (method == KnownPluginList::sortByFileSystemLocation)
  20617. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  20618. if (diff == 0)
  20619. diff = first->name.compareLexicographically (second->name);
  20620. return diff;
  20621. }
  20622. };
  20623. void KnownPluginList::sort (const SortMethod method)
  20624. {
  20625. if (method != defaultOrder)
  20626. {
  20627. PluginSorter sorter;
  20628. sorter.method = method;
  20629. types.sort (sorter, true);
  20630. sendChangeMessage (this);
  20631. }
  20632. }
  20633. XmlElement* KnownPluginList::createXml() const
  20634. {
  20635. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  20636. for (int i = 0; i < types.size(); ++i)
  20637. e->addChildElement (types.getUnchecked(i)->createXml());
  20638. return e;
  20639. }
  20640. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  20641. {
  20642. clear();
  20643. if (xml.hasTagName (T("KNOWNPLUGINS")))
  20644. {
  20645. forEachXmlChildElement (xml, e)
  20646. {
  20647. PluginDescription info;
  20648. if (info.loadFromXml (*e))
  20649. addType (info);
  20650. }
  20651. }
  20652. }
  20653. const int menuIdBase = 0x324503f4;
  20654. // This is used to turn a bunch of paths into a nested menu structure.
  20655. struct PluginFilesystemTree
  20656. {
  20657. private:
  20658. String folder;
  20659. OwnedArray <PluginFilesystemTree> subFolders;
  20660. Array <PluginDescription*> plugins;
  20661. void addPlugin (PluginDescription* const pd, const String& path)
  20662. {
  20663. if (path.isEmpty())
  20664. {
  20665. plugins.add (pd);
  20666. }
  20667. else
  20668. {
  20669. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  20670. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  20671. for (int i = subFolders.size(); --i >= 0;)
  20672. {
  20673. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  20674. {
  20675. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  20676. return;
  20677. }
  20678. }
  20679. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  20680. newFolder->folder = firstSubFolder;
  20681. subFolders.add (newFolder);
  20682. newFolder->addPlugin (pd, remainingPath);
  20683. }
  20684. }
  20685. // removes any deeply nested folders that don't contain any actual plugins
  20686. void optimise()
  20687. {
  20688. for (int i = subFolders.size(); --i >= 0;)
  20689. {
  20690. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20691. sub->optimise();
  20692. if (sub->plugins.size() == 0)
  20693. {
  20694. for (int j = 0; j < sub->subFolders.size(); ++j)
  20695. subFolders.add (sub->subFolders.getUnchecked(j));
  20696. sub->subFolders.clear (false);
  20697. subFolders.remove (i);
  20698. }
  20699. }
  20700. }
  20701. public:
  20702. void buildTree (const Array <PluginDescription*>& allPlugins)
  20703. {
  20704. for (int i = 0; i < allPlugins.size(); ++i)
  20705. {
  20706. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  20707. if (path.substring (1, 2) == T(":"))
  20708. path = path.substring (2);
  20709. path = path.replaceCharacter (T('\\'), T('/'));
  20710. addPlugin (allPlugins.getUnchecked(i), path);
  20711. }
  20712. optimise();
  20713. }
  20714. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  20715. {
  20716. int i;
  20717. for (i = 0; i < subFolders.size(); ++i)
  20718. {
  20719. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20720. PopupMenu subMenu;
  20721. sub->addToMenu (subMenu, allPlugins);
  20722. m.addSubMenu (sub->folder, subMenu);
  20723. }
  20724. for (i = 0; i < plugins.size(); ++i)
  20725. {
  20726. PluginDescription* const plugin = plugins.getUnchecked(i);
  20727. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  20728. plugin->name, true, false);
  20729. }
  20730. }
  20731. };
  20732. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  20733. {
  20734. Array <PluginDescription*> sorted;
  20735. {
  20736. PluginSorter sorter;
  20737. sorter.method = sortMethod;
  20738. for (int i = 0; i < types.size(); ++i)
  20739. sorted.addSorted (sorter, types.getUnchecked(i));
  20740. }
  20741. if (sortMethod == sortByCategory
  20742. || sortMethod == sortByManufacturer)
  20743. {
  20744. String lastSubMenuName;
  20745. PopupMenu sub;
  20746. for (int i = 0; i < sorted.size(); ++i)
  20747. {
  20748. const PluginDescription* const pd = sorted.getUnchecked(i);
  20749. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  20750. : pd->manufacturerName);
  20751. if (thisSubMenuName.trim().isEmpty())
  20752. thisSubMenuName = T("Other");
  20753. if (thisSubMenuName != lastSubMenuName)
  20754. {
  20755. if (sub.getNumItems() > 0)
  20756. {
  20757. menu.addSubMenu (lastSubMenuName, sub);
  20758. sub.clear();
  20759. }
  20760. lastSubMenuName = thisSubMenuName;
  20761. }
  20762. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20763. }
  20764. if (sub.getNumItems() > 0)
  20765. menu.addSubMenu (lastSubMenuName, sub);
  20766. }
  20767. else if (sortMethod == sortByFileSystemLocation)
  20768. {
  20769. PluginFilesystemTree root;
  20770. root.buildTree (sorted);
  20771. root.addToMenu (menu, types);
  20772. }
  20773. else
  20774. {
  20775. for (int i = 0; i < sorted.size(); ++i)
  20776. {
  20777. const PluginDescription* const pd = sorted.getUnchecked(i);
  20778. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20779. }
  20780. }
  20781. }
  20782. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  20783. {
  20784. const int i = menuResultCode - menuIdBase;
  20785. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  20786. }
  20787. END_JUCE_NAMESPACE
  20788. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  20789. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  20790. BEGIN_JUCE_NAMESPACE
  20791. PluginDescription::PluginDescription() throw()
  20792. : uid (0),
  20793. isInstrument (false),
  20794. numInputChannels (0),
  20795. numOutputChannels (0)
  20796. {
  20797. }
  20798. PluginDescription::~PluginDescription() throw()
  20799. {
  20800. }
  20801. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  20802. : name (other.name),
  20803. pluginFormatName (other.pluginFormatName),
  20804. category (other.category),
  20805. manufacturerName (other.manufacturerName),
  20806. version (other.version),
  20807. file (other.file),
  20808. lastFileModTime (other.lastFileModTime),
  20809. uid (other.uid),
  20810. isInstrument (other.isInstrument),
  20811. numInputChannels (other.numInputChannels),
  20812. numOutputChannels (other.numOutputChannels)
  20813. {
  20814. }
  20815. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  20816. {
  20817. name = other.name;
  20818. pluginFormatName = other.pluginFormatName;
  20819. category = other.category;
  20820. manufacturerName = other.manufacturerName;
  20821. version = other.version;
  20822. file = other.file;
  20823. uid = other.uid;
  20824. isInstrument = other.isInstrument;
  20825. lastFileModTime = other.lastFileModTime;
  20826. numInputChannels = other.numInputChannels;
  20827. numOutputChannels = other.numOutputChannels;
  20828. return *this;
  20829. }
  20830. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  20831. {
  20832. return file == other.file
  20833. && uid == other.uid;
  20834. }
  20835. const String PluginDescription::createIdentifierString() const throw()
  20836. {
  20837. return pluginFormatName
  20838. + T("-") + name
  20839. + T("-") + String::toHexString (file.getFileName().hashCode())
  20840. + T("-") + String::toHexString (uid);
  20841. }
  20842. XmlElement* PluginDescription::createXml() const
  20843. {
  20844. XmlElement* const e = new XmlElement (T("PLUGIN"));
  20845. e->setAttribute (T("name"), name);
  20846. e->setAttribute (T("format"), pluginFormatName);
  20847. e->setAttribute (T("category"), category);
  20848. e->setAttribute (T("manufacturer"), manufacturerName);
  20849. e->setAttribute (T("version"), version);
  20850. e->setAttribute (T("file"), file.getFullPathName());
  20851. e->setAttribute (T("uid"), String::toHexString (uid));
  20852. e->setAttribute (T("isInstrument"), isInstrument);
  20853. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  20854. e->setAttribute (T("numInputs"), numInputChannels);
  20855. e->setAttribute (T("numOutputs"), numOutputChannels);
  20856. return e;
  20857. }
  20858. bool PluginDescription::loadFromXml (const XmlElement& xml)
  20859. {
  20860. if (xml.hasTagName (T("PLUGIN")))
  20861. {
  20862. name = xml.getStringAttribute (T("name"));
  20863. pluginFormatName = xml.getStringAttribute (T("format"));
  20864. category = xml.getStringAttribute (T("category"));
  20865. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  20866. version = xml.getStringAttribute (T("version"));
  20867. file = File (xml.getStringAttribute (T("file")));
  20868. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  20869. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  20870. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  20871. numInputChannels = xml.getIntAttribute (T("numInputs"));
  20872. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  20873. return true;
  20874. }
  20875. return false;
  20876. }
  20877. END_JUCE_NAMESPACE
  20878. /********* End of inlined file: juce_PluginDescription.cpp *********/
  20879. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  20880. BEGIN_JUCE_NAMESPACE
  20881. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  20882. AudioPluginFormat& formatToLookFor,
  20883. FileSearchPath directoriesToSearch,
  20884. const bool recursive,
  20885. const File& deadMansPedalFile_)
  20886. : list (listToAddTo),
  20887. format (formatToLookFor),
  20888. deadMansPedalFile (deadMansPedalFile_),
  20889. nextIndex (0),
  20890. progress (0)
  20891. {
  20892. directoriesToSearch.removeRedundantPaths();
  20893. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  20894. recursiveFileSearch (directoriesToSearch [j], recursive);
  20895. // If any plugins have crashed recently when being loaded, move them to the
  20896. // end of the list to give the others a chance to load correctly..
  20897. const StringArray crashedPlugins (getDeadMansPedalFile());
  20898. for (int i = 0; i < crashedPlugins.size(); ++i)
  20899. {
  20900. const File f (crashedPlugins[i]);
  20901. for (int j = filesToScan.size(); --j >= 0;)
  20902. if (f == *filesToScan.getUnchecked (j))
  20903. filesToScan.move (j, -1);
  20904. }
  20905. }
  20906. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  20907. {
  20908. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  20909. // .component or .vst directories.
  20910. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  20911. while (iter.next())
  20912. {
  20913. const File f (iter.getFile());
  20914. bool isPlugin = false;
  20915. if (format.fileMightContainThisPluginType (f))
  20916. {
  20917. isPlugin = true;
  20918. filesToScan.add (new File (f));
  20919. }
  20920. if (recursive && (! isPlugin) && f.isDirectory())
  20921. recursiveFileSearch (f, true);
  20922. }
  20923. }
  20924. PluginDirectoryScanner::~PluginDirectoryScanner()
  20925. {
  20926. }
  20927. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  20928. {
  20929. File* const file = filesToScan [nextIndex];
  20930. if (file != 0)
  20931. return *file;
  20932. return File::nonexistent;
  20933. }
  20934. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  20935. {
  20936. File* const file = filesToScan [nextIndex];
  20937. if (file != 0)
  20938. {
  20939. if (! list.isListingUpToDate (*file))
  20940. {
  20941. OwnedArray <PluginDescription> typesFound;
  20942. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  20943. StringArray crashedPlugins (getDeadMansPedalFile());
  20944. crashedPlugins.removeString (file->getFullPathName());
  20945. crashedPlugins.add (file->getFullPathName());
  20946. setDeadMansPedalFile (crashedPlugins);
  20947. list.scanAndAddFile (*file,
  20948. dontRescanIfAlreadyInList,
  20949. typesFound);
  20950. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  20951. crashedPlugins.removeString (file->getFullPathName());
  20952. setDeadMansPedalFile (crashedPlugins);
  20953. if (typesFound.size() == 0)
  20954. failedFiles.add (file->getFullPathName());
  20955. }
  20956. ++nextIndex;
  20957. progress = nextIndex / (float) filesToScan.size();
  20958. }
  20959. return nextIndex < filesToScan.size();
  20960. }
  20961. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  20962. {
  20963. StringArray lines;
  20964. if (deadMansPedalFile != File::nonexistent)
  20965. {
  20966. lines.addLines (deadMansPedalFile.loadFileAsString());
  20967. lines.removeEmptyStrings();
  20968. }
  20969. return lines;
  20970. }
  20971. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  20972. {
  20973. if (deadMansPedalFile != File::nonexistent)
  20974. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  20975. }
  20976. END_JUCE_NAMESPACE
  20977. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  20978. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  20979. BEGIN_JUCE_NAMESPACE
  20980. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  20981. const File& deadMansPedalFile_,
  20982. PropertiesFile* const propertiesToUse_)
  20983. : list (listToEdit),
  20984. deadMansPedalFile (deadMansPedalFile_),
  20985. propertiesToUse (propertiesToUse_)
  20986. {
  20987. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  20988. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  20989. optionsButton->addButtonListener (this);
  20990. optionsButton->setTriggeredOnMouseDown (true);
  20991. setSize (400, 600);
  20992. list.addChangeListener (this);
  20993. }
  20994. PluginListComponent::~PluginListComponent()
  20995. {
  20996. list.removeChangeListener (this);
  20997. deleteAllChildren();
  20998. }
  20999. void PluginListComponent::resized()
  21000. {
  21001. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21002. optionsButton->changeWidthToFitText (24);
  21003. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21004. }
  21005. void PluginListComponent::changeListenerCallback (void*)
  21006. {
  21007. listBox->updateContent();
  21008. listBox->repaint();
  21009. }
  21010. int PluginListComponent::getNumRows()
  21011. {
  21012. return list.getNumTypes();
  21013. }
  21014. void PluginListComponent::paintListBoxItem (int row,
  21015. Graphics& g,
  21016. int width, int height,
  21017. bool rowIsSelected)
  21018. {
  21019. if (rowIsSelected)
  21020. g.fillAll (findColour (TextEditor::highlightColourId));
  21021. const PluginDescription* const pd = list.getType (row);
  21022. if (pd != 0)
  21023. {
  21024. GlyphArrangement ga;
  21025. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21026. g.setColour (Colours::black);
  21027. ga.draw (g);
  21028. float x, y, r, b;
  21029. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21030. String desc;
  21031. desc << pd->pluginFormatName
  21032. << (pd->isInstrument ? " instrument" : " effect")
  21033. << " - "
  21034. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21035. << " / "
  21036. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21037. if (pd->manufacturerName.isNotEmpty())
  21038. desc << " - " << pd->manufacturerName;
  21039. if (pd->version.isNotEmpty())
  21040. desc << " - " << pd->version;
  21041. if (pd->category.isNotEmpty())
  21042. desc << " - category: '" << pd->category << '\'';
  21043. g.setColour (Colours::grey);
  21044. ga.clear();
  21045. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21046. ga.draw (g);
  21047. }
  21048. }
  21049. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21050. {
  21051. list.removeType (lastRowSelected);
  21052. }
  21053. void PluginListComponent::buttonClicked (Button* b)
  21054. {
  21055. if (optionsButton == b)
  21056. {
  21057. PopupMenu menu;
  21058. menu.addItem (1, TRANS("Clear list"));
  21059. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21060. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21061. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21062. menu.addSeparator();
  21063. menu.addItem (2, TRANS("Sort alphabetically"));
  21064. menu.addItem (3, TRANS("Sort by category"));
  21065. menu.addItem (4, TRANS("Sort by manufacturer"));
  21066. menu.addSeparator();
  21067. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21068. {
  21069. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21070. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21071. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21072. }
  21073. const int r = menu.showAt (optionsButton);
  21074. if (r == 1)
  21075. {
  21076. list.clear();
  21077. }
  21078. else if (r == 2)
  21079. {
  21080. list.sort (KnownPluginList::sortAlphabetically);
  21081. }
  21082. else if (r == 3)
  21083. {
  21084. list.sort (KnownPluginList::sortByCategory);
  21085. }
  21086. else if (r == 4)
  21087. {
  21088. list.sort (KnownPluginList::sortByManufacturer);
  21089. }
  21090. else if (r == 5)
  21091. {
  21092. const SparseSet <int> selected (listBox->getSelectedRows());
  21093. for (int i = list.getNumTypes(); --i >= 0;)
  21094. if (selected.contains (i))
  21095. list.removeType (i);
  21096. }
  21097. else if (r == 6)
  21098. {
  21099. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21100. if (desc != 0)
  21101. desc->file.getParentDirectory().startAsProcess();
  21102. }
  21103. else if (r == 7)
  21104. {
  21105. for (int i = list.getNumTypes(); --i >= 0;)
  21106. {
  21107. if (list.getType (i)->file != File::nonexistent
  21108. && ! list.getType (i)->file.exists())
  21109. {
  21110. list.removeType (i);
  21111. }
  21112. }
  21113. }
  21114. else if (r != 0)
  21115. {
  21116. typeToScan = r - 10;
  21117. startTimer (1);
  21118. }
  21119. }
  21120. }
  21121. void PluginListComponent::timerCallback()
  21122. {
  21123. stopTimer();
  21124. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21125. }
  21126. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21127. {
  21128. return true;
  21129. }
  21130. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21131. {
  21132. OwnedArray <PluginDescription> typesFound;
  21133. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21134. }
  21135. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21136. {
  21137. if (format == 0)
  21138. return;
  21139. FileSearchPath path (format->getDefaultLocationsToSearch());
  21140. if (propertiesToUse != 0)
  21141. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21142. {
  21143. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21144. FileSearchPathListComponent pathList;
  21145. pathList.setSize (500, 300);
  21146. pathList.setPath (path);
  21147. aw.addCustomComponent (&pathList);
  21148. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21149. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21150. if (aw.runModalLoop() == 0)
  21151. return;
  21152. path = pathList.getPath();
  21153. }
  21154. if (propertiesToUse != 0)
  21155. {
  21156. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21157. propertiesToUse->saveIfNeeded();
  21158. }
  21159. double progress = 0.0;
  21160. AlertWindow aw (TRANS("Scanning for plugins..."),
  21161. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21162. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21163. aw.addProgressBarComponent (progress);
  21164. aw.enterModalState();
  21165. MessageManager::getInstance()->dispatchPendingMessages();
  21166. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21167. for (;;)
  21168. {
  21169. aw.setMessage (TRANS("Testing:\n\n")
  21170. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21171. MessageManager::getInstance()->dispatchPendingMessages (500);
  21172. if (! scanner.scanNextFile (true))
  21173. break;
  21174. if (! aw.isCurrentlyModal())
  21175. break;
  21176. progress = scanner.getProgress();
  21177. }
  21178. if (scanner.getFailedFiles().size() > 0)
  21179. {
  21180. StringArray shortNames;
  21181. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21182. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21183. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21184. TRANS("Scan complete"),
  21185. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21186. + shortNames.joinIntoString (", "));
  21187. }
  21188. }
  21189. END_JUCE_NAMESPACE
  21190. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21191. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21192. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  21193. #include <Carbon/Carbon.h>
  21194. #include <AudioToolbox/AudioToolbox.h>
  21195. #include <AudioUnit/AudioUnitCarbonView.h>
  21196. BEGIN_JUCE_NAMESPACE
  21197. #if JUCE_MAC
  21198. extern void juce_callAnyTimersSynchronously();
  21199. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  21200. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  21201. #if MACOS_10_3_OR_EARLIER
  21202. #define kAudioUnitType_Generator 'augn'
  21203. #endif
  21204. // Change this to disable logging of various activities
  21205. #ifndef AU_LOGGING
  21206. #define AU_LOGGING 1
  21207. #endif
  21208. #if AU_LOGGING
  21209. #define log(a) Logger::writeToLog(a);
  21210. #else
  21211. #define log(a)
  21212. #endif
  21213. static int insideCallback = 0;
  21214. class AudioUnitPluginWindow;
  21215. class AudioUnitPluginInstance : public AudioPluginInstance
  21216. {
  21217. public:
  21218. ~AudioUnitPluginInstance();
  21219. // AudioPluginInstance methods:
  21220. void fillInPluginDescription (PluginDescription& desc) const
  21221. {
  21222. desc.name = pluginName;
  21223. desc.file = file;
  21224. desc.uid = ((int) componentDesc.componentType)
  21225. ^ ((int) componentDesc.componentSubType)
  21226. ^ ((int) componentDesc.componentManufacturer);
  21227. desc.lastFileModTime = file.getLastModificationTime();
  21228. desc.pluginFormatName = "AudioUnit";
  21229. desc.category = getCategory();
  21230. desc.manufacturerName = manufacturer;
  21231. desc.version = version;
  21232. desc.numInputChannels = getNumInputChannels();
  21233. desc.numOutputChannels = getNumOutputChannels();
  21234. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  21235. }
  21236. const String getName() const { return pluginName; }
  21237. bool acceptsMidi() const { return wantsMidiMessages; }
  21238. bool producesMidi() const { return false; }
  21239. // AudioProcessor methods:
  21240. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21241. void releaseResources();
  21242. void processBlock (AudioSampleBuffer& buffer,
  21243. MidiBuffer& midiMessages);
  21244. AudioProcessorEditor* createEditor();
  21245. const String getInputChannelName (const int index) const;
  21246. bool isInputChannelStereoPair (int index) const;
  21247. const String getOutputChannelName (const int index) const;
  21248. bool isOutputChannelStereoPair (int index) const;
  21249. int getNumParameters();
  21250. float getParameter (int index);
  21251. void setParameter (int index, float newValue);
  21252. const String getParameterName (int index);
  21253. const String getParameterText (int index);
  21254. bool isParameterAutomatable (int index) const;
  21255. int getNumPrograms();
  21256. int getCurrentProgram();
  21257. void setCurrentProgram (int index);
  21258. const String getProgramName (int index);
  21259. void changeProgramName (int index, const String& newName);
  21260. void getStateInformation (MemoryBlock& destData);
  21261. void getCurrentProgramStateInformation (MemoryBlock& destData);
  21262. void setStateInformation (const void* data, int sizeInBytes);
  21263. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21264. juce_UseDebuggingNewOperator
  21265. private:
  21266. friend class AudioUnitPluginWindow;
  21267. friend class AudioUnitPluginFormat;
  21268. ComponentDescription componentDesc;
  21269. String pluginName, manufacturer, version;
  21270. File file;
  21271. CriticalSection lock;
  21272. bool initialised, wantsMidiMessages, wasPlaying;
  21273. AudioBufferList* outputBufferList;
  21274. AudioTimeStamp timeStamp;
  21275. AudioSampleBuffer* currentBuffer;
  21276. AudioUnit audioUnit;
  21277. Array <int> parameterIds;
  21278. bool getComponentDescFromFile (const File& file);
  21279. void initialise();
  21280. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21281. const AudioTimeStamp* inTimeStamp,
  21282. UInt32 inBusNumber,
  21283. UInt32 inNumberFrames,
  21284. AudioBufferList* ioData) const;
  21285. static OSStatus renderGetInputCallback (void* inRefCon,
  21286. AudioUnitRenderActionFlags* ioActionFlags,
  21287. const AudioTimeStamp* inTimeStamp,
  21288. UInt32 inBusNumber,
  21289. UInt32 inNumberFrames,
  21290. AudioBufferList* ioData)
  21291. {
  21292. return ((AudioUnitPluginInstance*) inRefCon)
  21293. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  21294. }
  21295. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  21296. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  21297. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  21298. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21299. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21300. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  21301. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  21302. {
  21303. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  21304. }
  21305. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  21306. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  21307. Float64* outCurrentMeasureDownBeat)
  21308. {
  21309. return ((AudioUnitPluginInstance*) inHostUserData)
  21310. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  21311. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  21312. }
  21313. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21314. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21315. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  21316. {
  21317. return ((AudioUnitPluginInstance*) inHostUserData)
  21318. ->getTransportState (outIsPlaying, outTransportStateChanged,
  21319. outCurrentSampleInTimeLine, outIsCycling,
  21320. outCycleStartBeat, outCycleEndBeat);
  21321. }
  21322. void getNumChannels (int& numIns, int& numOuts)
  21323. {
  21324. numIns = 0;
  21325. numOuts = 0;
  21326. AUChannelInfo supportedChannels [128];
  21327. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  21328. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  21329. 0, supportedChannels, &supportedChannelsSize) == noErr
  21330. && supportedChannelsSize > 0)
  21331. {
  21332. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  21333. {
  21334. numIns = jmax (numIns, supportedChannels[i].inChannels);
  21335. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  21336. }
  21337. }
  21338. else
  21339. {
  21340. // (this really means the plugin will take any number of ins/outs as long
  21341. // as they are the same)
  21342. numIns = numOuts = 2;
  21343. }
  21344. }
  21345. const String getCategory() const;
  21346. AudioUnitPluginInstance (const File& file);
  21347. };
  21348. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  21349. : file (file_),
  21350. initialised (false),
  21351. wantsMidiMessages (false),
  21352. audioUnit (0),
  21353. outputBufferList (0),
  21354. currentBuffer (0)
  21355. {
  21356. try
  21357. {
  21358. ++insideCallback;
  21359. log (T("Opening AU: ") + file.getFullPathName());
  21360. if (getComponentDescFromFile (file))
  21361. {
  21362. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  21363. if (comp != 0)
  21364. {
  21365. audioUnit = (AudioUnit) OpenComponent (comp);
  21366. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  21367. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  21368. }
  21369. }
  21370. --insideCallback;
  21371. }
  21372. catch (...)
  21373. {
  21374. --insideCallback;
  21375. }
  21376. }
  21377. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  21378. {
  21379. {
  21380. const ScopedLock sl (lock);
  21381. jassert (insideCallback == 0);
  21382. if (audioUnit != 0)
  21383. {
  21384. AudioUnitUninitialize (audioUnit);
  21385. CloseComponent (audioUnit);
  21386. audioUnit = 0;
  21387. }
  21388. }
  21389. juce_free (outputBufferList);
  21390. }
  21391. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  21392. {
  21393. zerostruct (componentDesc);
  21394. if (! file.hasFileExtension (T(".component")))
  21395. return false;
  21396. const String filename (file.getFullPathName());
  21397. const char* const utf8 = filename.toUTF8();
  21398. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  21399. strlen (utf8), file.isDirectory());
  21400. if (url != 0)
  21401. {
  21402. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  21403. CFRelease (url);
  21404. if (bundleRef != 0)
  21405. {
  21406. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  21407. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  21408. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  21409. if (pluginName.isEmpty())
  21410. pluginName = file.getFileNameWithoutExtension();
  21411. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  21412. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  21413. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  21414. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  21415. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  21416. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  21417. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  21418. UseResFile (resFileId);
  21419. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  21420. {
  21421. Handle h = Get1IndResource ('thng', i);
  21422. if (h != 0)
  21423. {
  21424. HLock (h);
  21425. const uint32* const types = (const uint32*) *h;
  21426. if (types[0] == kAudioUnitType_MusicDevice
  21427. || types[0] == kAudioUnitType_MusicEffect
  21428. || types[0] == kAudioUnitType_Effect
  21429. || types[0] == kAudioUnitType_Generator
  21430. || types[0] == kAudioUnitType_Panner)
  21431. {
  21432. componentDesc.componentType = types[0];
  21433. componentDesc.componentSubType = types[1];
  21434. componentDesc.componentManufacturer = types[2];
  21435. break;
  21436. }
  21437. HUnlock (h);
  21438. ReleaseResource (h);
  21439. }
  21440. }
  21441. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  21442. CFRelease (bundleRef);
  21443. }
  21444. }
  21445. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  21446. }
  21447. void AudioUnitPluginInstance::initialise()
  21448. {
  21449. if (initialised || audioUnit == 0)
  21450. return;
  21451. log (T("Initialising AU: ") + pluginName);
  21452. parameterIds.clear();
  21453. {
  21454. UInt32 paramListSize = 0;
  21455. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21456. 0, 0, &paramListSize);
  21457. if (paramListSize > 0)
  21458. {
  21459. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  21460. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21461. 0, &parameterIds.getReference(0), &paramListSize);
  21462. }
  21463. }
  21464. {
  21465. AURenderCallbackStruct info;
  21466. zerostruct (info);
  21467. info.inputProcRefCon = this;
  21468. info.inputProc = renderGetInputCallback;
  21469. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  21470. 0, &info, sizeof (info));
  21471. }
  21472. {
  21473. HostCallbackInfo info;
  21474. zerostruct (info);
  21475. info.hostUserData = this;
  21476. info.beatAndTempoProc = getBeatAndTempoCallback;
  21477. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  21478. info.transportStateProc = getTransportStateCallback;
  21479. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  21480. 0, &info, sizeof (info));
  21481. }
  21482. int numIns, numOuts;
  21483. getNumChannels (numIns, numOuts);
  21484. setPlayConfigDetails (numIns, numOuts, 0, 0);
  21485. initialised = AudioUnitInitialize (audioUnit) == noErr;
  21486. setLatencySamples (0);
  21487. }
  21488. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  21489. int samplesPerBlockExpected)
  21490. {
  21491. initialise();
  21492. if (initialised)
  21493. {
  21494. int numIns, numOuts;
  21495. getNumChannels (numIns, numOuts);
  21496. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  21497. Float64 latencySecs = 0.0;
  21498. UInt32 latencySize = sizeof (latencySecs);
  21499. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  21500. 0, &latencySecs, &latencySize);
  21501. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  21502. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21503. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21504. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21505. AudioStreamBasicDescription stream;
  21506. zerostruct (stream);
  21507. stream.mSampleRate = sampleRate_;
  21508. stream.mFormatID = kAudioFormatLinearPCM;
  21509. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  21510. stream.mFramesPerPacket = 1;
  21511. stream.mBytesPerPacket = 4;
  21512. stream.mBytesPerFrame = 4;
  21513. stream.mBitsPerChannel = 32;
  21514. stream.mChannelsPerFrame = numIns;
  21515. OSStatus err = AudioUnitSetProperty (audioUnit,
  21516. kAudioUnitProperty_StreamFormat,
  21517. kAudioUnitScope_Input,
  21518. 0, &stream, sizeof (stream));
  21519. stream.mChannelsPerFrame = numOuts;
  21520. err = AudioUnitSetProperty (audioUnit,
  21521. kAudioUnitProperty_StreamFormat,
  21522. kAudioUnitScope_Output,
  21523. 0, &stream, sizeof (stream));
  21524. juce_free (outputBufferList);
  21525. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  21526. outputBufferList->mNumberBuffers = numOuts;
  21527. for (int i = numOuts; --i >= 0;)
  21528. outputBufferList->mBuffers[i].mNumberChannels = 1;
  21529. zerostruct (timeStamp);
  21530. timeStamp.mSampleTime = 0;
  21531. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21532. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  21533. currentBuffer = 0;
  21534. wasPlaying = false;
  21535. }
  21536. }
  21537. void AudioUnitPluginInstance::releaseResources()
  21538. {
  21539. if (initialised)
  21540. {
  21541. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21542. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21543. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21544. juce_free (outputBufferList);
  21545. outputBufferList = 0;
  21546. currentBuffer = 0;
  21547. }
  21548. }
  21549. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21550. const AudioTimeStamp* inTimeStamp,
  21551. UInt32 inBusNumber,
  21552. UInt32 inNumberFrames,
  21553. AudioBufferList* ioData) const
  21554. {
  21555. if (inBusNumber == 0
  21556. && currentBuffer != 0)
  21557. {
  21558. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  21559. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  21560. {
  21561. if (i < currentBuffer->getNumChannels())
  21562. {
  21563. memcpy (ioData->mBuffers[i].mData,
  21564. currentBuffer->getSampleData (i, 0),
  21565. sizeof (float) * inNumberFrames);
  21566. }
  21567. else
  21568. {
  21569. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  21570. }
  21571. }
  21572. }
  21573. return noErr;
  21574. }
  21575. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  21576. MidiBuffer& midiMessages)
  21577. {
  21578. const int numSamples = buffer.getNumSamples();
  21579. if (initialised)
  21580. {
  21581. AudioUnitRenderActionFlags flags = 0;
  21582. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21583. for (int i = getNumOutputChannels(); --i >= 0;)
  21584. {
  21585. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  21586. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  21587. }
  21588. currentBuffer = &buffer;
  21589. if (wantsMidiMessages)
  21590. {
  21591. const uint8* midiEventData;
  21592. int midiEventSize, midiEventPosition;
  21593. MidiBuffer::Iterator i (midiMessages);
  21594. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  21595. {
  21596. if (midiEventSize <= 3)
  21597. MusicDeviceMIDIEvent (audioUnit,
  21598. midiEventData[0], midiEventData[1], midiEventData[2],
  21599. midiEventPosition);
  21600. else
  21601. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  21602. }
  21603. midiMessages.clear();
  21604. }
  21605. AudioUnitRender (audioUnit, &flags, &timeStamp,
  21606. 0, numSamples, outputBufferList);
  21607. timeStamp.mSampleTime += numSamples;
  21608. }
  21609. else
  21610. {
  21611. // Not initialised, so just bypass..
  21612. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  21613. buffer.clear (i, 0, buffer.getNumSamples());
  21614. }
  21615. }
  21616. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  21617. {
  21618. AudioPlayHead* const ph = getPlayHead();
  21619. AudioPlayHead::CurrentPositionInfo result;
  21620. if (ph != 0 && ph->getCurrentPosition (result))
  21621. {
  21622. *outCurrentBeat = result.ppqPosition;
  21623. *outCurrentTempo = result.bpm;
  21624. }
  21625. else
  21626. {
  21627. *outCurrentBeat = 0;
  21628. *outCurrentTempo = 120.0;
  21629. }
  21630. return noErr;
  21631. }
  21632. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  21633. Float32* outTimeSig_Numerator,
  21634. UInt32* outTimeSig_Denominator,
  21635. Float64* outCurrentMeasureDownBeat) const
  21636. {
  21637. AudioPlayHead* const ph = getPlayHead();
  21638. AudioPlayHead::CurrentPositionInfo result;
  21639. if (ph != 0 && ph->getCurrentPosition (result))
  21640. {
  21641. *outTimeSig_Numerator = result.timeSigNumerator;
  21642. *outTimeSig_Denominator = result.timeSigDenominator;
  21643. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  21644. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  21645. }
  21646. else
  21647. {
  21648. *outDeltaSampleOffsetToNextBeat = 0;
  21649. *outTimeSig_Numerator = 4;
  21650. *outTimeSig_Denominator = 4;
  21651. *outCurrentMeasureDownBeat = 0;
  21652. }
  21653. return noErr;
  21654. }
  21655. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  21656. Boolean* outTransportStateChanged,
  21657. Float64* outCurrentSampleInTimeLine,
  21658. Boolean* outIsCycling,
  21659. Float64* outCycleStartBeat,
  21660. Float64* outCycleEndBeat)
  21661. {
  21662. AudioPlayHead* const ph = getPlayHead();
  21663. AudioPlayHead::CurrentPositionInfo result;
  21664. if (ph != 0 && ph->getCurrentPosition (result))
  21665. {
  21666. *outIsPlaying = result.isPlaying;
  21667. *outTransportStateChanged = result.isPlaying != wasPlaying;
  21668. wasPlaying = result.isPlaying;
  21669. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  21670. *outIsCycling = false;
  21671. *outCycleStartBeat = 0;
  21672. *outCycleEndBeat = 0;
  21673. }
  21674. else
  21675. {
  21676. *outIsPlaying = false;
  21677. *outTransportStateChanged = false;
  21678. *outCurrentSampleInTimeLine = 0;
  21679. *outIsCycling = false;
  21680. *outCycleStartBeat = 0;
  21681. *outCycleEndBeat = 0;
  21682. }
  21683. return noErr;
  21684. }
  21685. static VoidArray activeWindows;
  21686. class AudioUnitPluginWindow : public AudioProcessorEditor,
  21687. public Timer
  21688. {
  21689. public:
  21690. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  21691. : AudioProcessorEditor (&plugin_),
  21692. plugin (plugin_),
  21693. isOpen (false),
  21694. pluginWantsKeys (false),
  21695. wasShowing (false),
  21696. recursiveResize (false),
  21697. viewComponent (0),
  21698. pluginViewRef (0)
  21699. {
  21700. movementWatcher = new CompMovementWatcher (this);
  21701. activeWindows.add (this);
  21702. setOpaque (true);
  21703. setVisible (true);
  21704. setSize (1, 1);
  21705. ComponentDescription viewList [16];
  21706. UInt32 viewListSize = sizeof (viewList);
  21707. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  21708. 0, &viewList, &viewListSize);
  21709. componentRecord = FindNextComponent (0, &viewList[0]);
  21710. }
  21711. ~AudioUnitPluginWindow()
  21712. {
  21713. deleteAndZero (movementWatcher);
  21714. closePluginWindow();
  21715. activeWindows.removeValue (this);
  21716. plugin.editorBeingDeleted (this);
  21717. }
  21718. bool isValid() const throw() { return componentRecord != 0; }
  21719. void componentMovedOrResized()
  21720. {
  21721. if (recursiveResize)
  21722. return;
  21723. Component* const topComp = getTopLevelComponent();
  21724. if (topComp->getPeer() != 0)
  21725. {
  21726. int x = 0, y = 0;
  21727. relativePositionToOtherComponent (topComp, x, y);
  21728. recursiveResize = true;
  21729. if (pluginViewRef != 0)
  21730. {
  21731. HIRect r;
  21732. r.origin.x = (float) x;
  21733. r.origin.y = (float) y;
  21734. r.size.width = (float) getWidth();
  21735. r.size.height = (float) getHeight();
  21736. HIViewSetFrame (pluginViewRef, &r);
  21737. }
  21738. recursiveResize = false;
  21739. }
  21740. }
  21741. void componentVisibilityChanged()
  21742. {
  21743. const bool isShowingNow = isShowing();
  21744. if (wasShowing != isShowingNow)
  21745. {
  21746. wasShowing = isShowingNow;
  21747. if (isShowingNow)
  21748. openPluginWindow();
  21749. else
  21750. closePluginWindow();
  21751. }
  21752. componentMovedOrResized();
  21753. }
  21754. void componentPeerChanged()
  21755. {
  21756. closePluginWindow();
  21757. openPluginWindow();
  21758. }
  21759. void timerCallback()
  21760. {
  21761. if (pluginViewRef != 0)
  21762. {
  21763. HIRect bounds;
  21764. HIViewGetBounds (pluginViewRef, &bounds);
  21765. const int w = jmax (32, (int) bounds.size.width);
  21766. const int h = jmax (32, (int) bounds.size.height);
  21767. if (w != getWidth() || h != getHeight())
  21768. {
  21769. setSize (w, h);
  21770. startTimer (50);
  21771. }
  21772. else
  21773. {
  21774. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  21775. }
  21776. }
  21777. }
  21778. bool keyStateChanged()
  21779. {
  21780. return pluginWantsKeys;
  21781. }
  21782. bool keyPressed (const KeyPress&)
  21783. {
  21784. return pluginWantsKeys;
  21785. }
  21786. void paint (Graphics& g)
  21787. {
  21788. if (isOpen)
  21789. {
  21790. ComponentPeer* const peer = getPeer();
  21791. if (peer != 0)
  21792. {
  21793. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  21794. getScreenY() - peer->getScreenY(),
  21795. getWidth(), getHeight());
  21796. }
  21797. }
  21798. else
  21799. {
  21800. g.fillAll (Colours::black);
  21801. }
  21802. }
  21803. void broughtToFront()
  21804. {
  21805. activeWindows.removeValue (this);
  21806. activeWindows.add (this);
  21807. }
  21808. juce_UseDebuggingNewOperator
  21809. private:
  21810. AudioUnitPluginInstance& plugin;
  21811. bool isOpen, wasShowing, recursiveResize;
  21812. bool pluginWantsKeys;
  21813. ComponentRecord* componentRecord;
  21814. AudioUnitCarbonView viewComponent;
  21815. HIViewRef pluginViewRef;
  21816. void openPluginWindow()
  21817. {
  21818. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  21819. return;
  21820. log (T("Opening AU GUI: ") + plugin.getName());
  21821. isOpen = true;
  21822. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  21823. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  21824. if (viewComponent != 0)
  21825. {
  21826. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  21827. getScreenY() - getTopLevelComponent()->getScreenY() };
  21828. Float32Point size = { 250, 200 };
  21829. AudioUnitCarbonViewCreate (viewComponent,
  21830. plugin.audioUnit,
  21831. (WindowRef) getWindowHandle(),
  21832. HIViewGetRoot ((WindowRef) getWindowHandle()),
  21833. &pos, &size,
  21834. (ControlRef*) &pluginViewRef);
  21835. }
  21836. timerCallback(); // to set our comp to the right size
  21837. repaint();
  21838. }
  21839. void closePluginWindow()
  21840. {
  21841. stopTimer();
  21842. if (isOpen)
  21843. {
  21844. log (T("Closing AU GUI: ") + plugin.getName());
  21845. isOpen = false;
  21846. if (viewComponent != 0)
  21847. CloseComponent (viewComponent);
  21848. pluginViewRef = 0;
  21849. }
  21850. }
  21851. class CompMovementWatcher : public ComponentMovementWatcher
  21852. {
  21853. public:
  21854. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  21855. : ComponentMovementWatcher (owner_),
  21856. owner (owner_)
  21857. {
  21858. }
  21859. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  21860. {
  21861. owner->componentMovedOrResized();
  21862. }
  21863. void componentPeerChanged()
  21864. {
  21865. owner->componentPeerChanged();
  21866. }
  21867. void componentVisibilityChanged (Component&)
  21868. {
  21869. owner->componentVisibilityChanged();
  21870. }
  21871. private:
  21872. AudioUnitPluginWindow* const owner;
  21873. };
  21874. CompMovementWatcher* movementWatcher;
  21875. };
  21876. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  21877. {
  21878. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  21879. if (! w->isValid())
  21880. deleteAndZero (w);
  21881. return w;
  21882. }
  21883. const String AudioUnitPluginInstance::getCategory() const
  21884. {
  21885. const char* result = 0;
  21886. switch (componentDesc.componentType)
  21887. {
  21888. case kAudioUnitType_Effect:
  21889. case kAudioUnitType_MusicEffect:
  21890. result = "Effect";
  21891. break;
  21892. case kAudioUnitType_MusicDevice:
  21893. result = "Synth";
  21894. break;
  21895. case kAudioUnitType_Generator:
  21896. result = "Generator";
  21897. break;
  21898. case kAudioUnitType_Panner:
  21899. result = "Panner";
  21900. break;
  21901. default:
  21902. break;
  21903. }
  21904. return result;
  21905. }
  21906. int AudioUnitPluginInstance::getNumParameters()
  21907. {
  21908. return parameterIds.size();
  21909. }
  21910. float AudioUnitPluginInstance::getParameter (int index)
  21911. {
  21912. const ScopedLock sl (lock);
  21913. Float32 value = 0.0f;
  21914. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  21915. {
  21916. AudioUnitGetParameter (audioUnit,
  21917. (UInt32) parameterIds.getUnchecked (index),
  21918. kAudioUnitScope_Global, 0,
  21919. &value);
  21920. }
  21921. return value;
  21922. }
  21923. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  21924. {
  21925. const ScopedLock sl (lock);
  21926. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  21927. {
  21928. AudioUnitSetParameter (audioUnit,
  21929. (UInt32) parameterIds.getUnchecked (index),
  21930. kAudioUnitScope_Global, 0,
  21931. newValue, 0);
  21932. }
  21933. }
  21934. const String AudioUnitPluginInstance::getParameterName (int index)
  21935. {
  21936. AudioUnitParameterInfo info;
  21937. zerostruct (info);
  21938. UInt32 sz = sizeof (info);
  21939. String name;
  21940. if (AudioUnitGetProperty (audioUnit,
  21941. kAudioUnitProperty_ParameterInfo,
  21942. kAudioUnitScope_Global,
  21943. parameterIds [index], &info, &sz) == noErr)
  21944. {
  21945. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  21946. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  21947. else
  21948. name = String (info.name, sizeof (info.name));
  21949. }
  21950. return name;
  21951. }
  21952. const String AudioUnitPluginInstance::getParameterText (int index)
  21953. {
  21954. return String (getParameter (index));
  21955. }
  21956. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  21957. {
  21958. AudioUnitParameterInfo info;
  21959. UInt32 sz = sizeof (info);
  21960. if (AudioUnitGetProperty (audioUnit,
  21961. kAudioUnitProperty_ParameterInfo,
  21962. kAudioUnitScope_Global,
  21963. parameterIds [index], &info, &sz) == noErr)
  21964. {
  21965. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  21966. }
  21967. return true;
  21968. }
  21969. int AudioUnitPluginInstance::getNumPrograms()
  21970. {
  21971. CFArrayRef presets;
  21972. UInt32 sz = sizeof (CFArrayRef);
  21973. int num = 0;
  21974. if (AudioUnitGetProperty (audioUnit,
  21975. kAudioUnitProperty_FactoryPresets,
  21976. kAudioUnitScope_Global,
  21977. 0, &presets, &sz) == noErr)
  21978. {
  21979. num = (int) CFArrayGetCount (presets);
  21980. CFRelease (presets);
  21981. }
  21982. return num;
  21983. }
  21984. int AudioUnitPluginInstance::getCurrentProgram()
  21985. {
  21986. AUPreset current;
  21987. current.presetNumber = 0;
  21988. UInt32 sz = sizeof (AUPreset);
  21989. AudioUnitGetProperty (audioUnit,
  21990. kAudioUnitProperty_FactoryPresets,
  21991. kAudioUnitScope_Global,
  21992. 0, &current, &sz);
  21993. return current.presetNumber;
  21994. }
  21995. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  21996. {
  21997. AUPreset current;
  21998. current.presetNumber = newIndex;
  21999. current.presetName = 0;
  22000. AudioUnitSetProperty (audioUnit,
  22001. kAudioUnitProperty_FactoryPresets,
  22002. kAudioUnitScope_Global,
  22003. 0, &current, sizeof (AUPreset));
  22004. }
  22005. const String AudioUnitPluginInstance::getProgramName (int index)
  22006. {
  22007. String s;
  22008. CFArrayRef presets;
  22009. UInt32 sz = sizeof (CFArrayRef);
  22010. if (AudioUnitGetProperty (audioUnit,
  22011. kAudioUnitProperty_FactoryPresets,
  22012. kAudioUnitScope_Global,
  22013. 0, &presets, &sz) == noErr)
  22014. {
  22015. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22016. {
  22017. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22018. if (p != 0 && p->presetNumber == index)
  22019. {
  22020. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22021. break;
  22022. }
  22023. }
  22024. CFRelease (presets);
  22025. }
  22026. return s;
  22027. }
  22028. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22029. {
  22030. jassertfalse // xxx not implemented!
  22031. }
  22032. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22033. {
  22034. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22035. return T("Input ") + String (index + 1);
  22036. return String::empty;
  22037. }
  22038. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22039. {
  22040. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22041. return false;
  22042. return true;
  22043. }
  22044. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22045. {
  22046. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22047. return T("Output ") + String (index + 1);
  22048. return String::empty;
  22049. }
  22050. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22051. {
  22052. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22053. return false;
  22054. return true;
  22055. }
  22056. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22057. {
  22058. getCurrentProgramStateInformation (destData);
  22059. }
  22060. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  22061. {
  22062. CFPropertyListRef propertyList = 0;
  22063. UInt32 sz = sizeof (CFPropertyListRef);
  22064. if (AudioUnitGetProperty (audioUnit,
  22065. kAudioUnitProperty_ClassInfo,
  22066. kAudioUnitScope_Global,
  22067. 0, &propertyList, &sz) == noErr)
  22068. {
  22069. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  22070. CFWriteStreamOpen (stream);
  22071. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  22072. CFWriteStreamClose (stream);
  22073. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  22074. destData.setSize (bytesWritten);
  22075. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  22076. CFRelease (data);
  22077. CFRelease (stream);
  22078. CFRelease (propertyList);
  22079. }
  22080. }
  22081. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  22082. {
  22083. setCurrentProgramStateInformation (data, sizeInBytes);
  22084. }
  22085. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  22086. {
  22087. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  22088. (const UInt8*) data,
  22089. sizeInBytes,
  22090. kCFAllocatorNull);
  22091. CFReadStreamOpen (stream);
  22092. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  22093. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  22094. stream,
  22095. 0,
  22096. kCFPropertyListImmutable,
  22097. &format,
  22098. 0);
  22099. CFRelease (stream);
  22100. if (propertyList != 0)
  22101. AudioUnitSetProperty (audioUnit,
  22102. kAudioUnitProperty_ClassInfo,
  22103. kAudioUnitScope_Global,
  22104. 0, &propertyList, sizeof (propertyList));
  22105. }
  22106. AudioUnitPluginFormat::AudioUnitPluginFormat()
  22107. {
  22108. }
  22109. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  22110. {
  22111. }
  22112. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22113. const File& file)
  22114. {
  22115. if (! fileMightContainThisPluginType (file))
  22116. return;
  22117. PluginDescription desc;
  22118. desc.file = file;
  22119. desc.uid = 0;
  22120. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  22121. if (instance == 0)
  22122. return;
  22123. try
  22124. {
  22125. instance->fillInPluginDescription (desc);
  22126. results.add (new PluginDescription (desc));
  22127. }
  22128. catch (...)
  22129. {
  22130. // crashed while loading...
  22131. }
  22132. deleteAndZero (instance);
  22133. }
  22134. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  22135. {
  22136. AudioUnitPluginInstance* result = 0;
  22137. if (fileMightContainThisPluginType (desc.file))
  22138. {
  22139. result = new AudioUnitPluginInstance (desc.file);
  22140. if (result->audioUnit != 0)
  22141. {
  22142. result->initialise();
  22143. }
  22144. else
  22145. {
  22146. deleteAndZero (result);
  22147. }
  22148. }
  22149. return result;
  22150. }
  22151. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  22152. {
  22153. return f.hasFileExtension (T(".component"))
  22154. && f.isDirectory();
  22155. }
  22156. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  22157. {
  22158. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  22159. }
  22160. #endif
  22161. END_JUCE_NAMESPACE
  22162. #undef log
  22163. #endif
  22164. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  22165. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  22166. #if JUCE_PLUGINHOST_VST
  22167. #ifdef _WIN32
  22168. #undef _WIN32_WINNT
  22169. #define _WIN32_WINNT 0x500
  22170. #undef STRICT
  22171. #define STRICT
  22172. #include <windows.h>
  22173. #include <float.h>
  22174. #pragma warning (disable : 4312)
  22175. #elif defined (LINUX)
  22176. #include <float.h>
  22177. #include <sys/time.h>
  22178. #include <X11/Xlib.h>
  22179. #include <X11/Xutil.h>
  22180. #include <X11/Xatom.h>
  22181. #undef Font
  22182. #undef KeyPress
  22183. #undef Drawable
  22184. #undef Time
  22185. #else
  22186. #include <Carbon/Carbon.h>
  22187. #endif
  22188. BEGIN_JUCE_NAMESPACE
  22189. #undef PRAGMA_ALIGN_SUPPORTED
  22190. #define VST_FORCE_DEPRECATED 0
  22191. #ifdef _MSC_VER
  22192. #pragma warning (push)
  22193. #pragma warning (disable: 4996)
  22194. #endif
  22195. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  22196. your include path if you want to add VST support.
  22197. If you're not interested in VSTs, you can disable them by changing the
  22198. JUCE_PLUGINHOST_VST flag in juce_Config.h
  22199. */
  22200. #include "pluginterfaces/vst2.x/aeffectx.h"
  22201. #ifdef _MSC_VER
  22202. #pragma warning (pop)
  22203. #endif
  22204. #if JUCE_LINUX
  22205. #define Font JUCE_NAMESPACE::Font
  22206. #define KeyPress JUCE_NAMESPACE::KeyPress
  22207. #define Drawable JUCE_NAMESPACE::Drawable
  22208. #define Time JUCE_NAMESPACE::Time
  22209. #endif
  22210. #if ! JUCE_WIN32
  22211. #define _fpreset()
  22212. #define _clearfp()
  22213. #endif
  22214. extern void juce_callAnyTimersSynchronously();
  22215. const int fxbVersionNum = 1;
  22216. struct fxProgram
  22217. {
  22218. long chunkMagic; // 'CcnK'
  22219. long byteSize; // of this chunk, excl. magic + byteSize
  22220. long fxMagic; // 'FxCk'
  22221. long version;
  22222. long fxID; // fx unique id
  22223. long fxVersion;
  22224. long numParams;
  22225. char prgName[28];
  22226. float params[1]; // variable no. of parameters
  22227. };
  22228. struct fxSet
  22229. {
  22230. long chunkMagic; // 'CcnK'
  22231. long byteSize; // of this chunk, excl. magic + byteSize
  22232. long fxMagic; // 'FxBk'
  22233. long version;
  22234. long fxID; // fx unique id
  22235. long fxVersion;
  22236. long numPrograms;
  22237. char future[128];
  22238. fxProgram programs[1]; // variable no. of programs
  22239. };
  22240. struct fxChunkSet
  22241. {
  22242. long chunkMagic; // 'CcnK'
  22243. long byteSize; // of this chunk, excl. magic + byteSize
  22244. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22245. long version;
  22246. long fxID; // fx unique id
  22247. long fxVersion;
  22248. long numPrograms;
  22249. char future[128];
  22250. long chunkSize;
  22251. char chunk[8]; // variable
  22252. };
  22253. struct fxProgramSet
  22254. {
  22255. long chunkMagic; // 'CcnK'
  22256. long byteSize; // of this chunk, excl. magic + byteSize
  22257. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22258. long version;
  22259. long fxID; // fx unique id
  22260. long fxVersion;
  22261. long numPrograms;
  22262. char name[28];
  22263. long chunkSize;
  22264. char chunk[8]; // variable
  22265. };
  22266. #ifdef JUCE_LITTLE_ENDIAN
  22267. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  22268. static float vst_swapFloat (const float x) throw()
  22269. {
  22270. union { uint32 asInt; float asFloat; } n;
  22271. n.asFloat = x;
  22272. n.asInt = swapByteOrder (n.asInt);
  22273. return n.asFloat;
  22274. }
  22275. #else
  22276. #define vst_swap(x) (x)
  22277. #define vst_swapFloat(x) (x)
  22278. #endif
  22279. typedef AEffect* (*MainCall) (audioMasterCallback);
  22280. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  22281. static int shellUIDToCreate = 0;
  22282. static int insideVSTCallback = 0;
  22283. class VSTPluginWindow;
  22284. // Change this to disable logging of various VST activities
  22285. #ifndef VST_LOGGING
  22286. #define VST_LOGGING 1
  22287. #endif
  22288. #if VST_LOGGING
  22289. #define log(a) Logger::writeToLog(a);
  22290. #else
  22291. #define log(a)
  22292. #endif
  22293. #if JUCE_MAC
  22294. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22295. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22296. #if JUCE_PPC
  22297. static void* NewCFMFromMachO (void* const machofp) throw()
  22298. {
  22299. void* result = juce_malloc (8);
  22300. ((void**) result)[0] = machofp;
  22301. ((void**) result)[1] = result;
  22302. return result;
  22303. }
  22304. #endif
  22305. #endif
  22306. #if JUCE_LINUX
  22307. extern Display* display;
  22308. extern XContext improbableNumber;
  22309. typedef void (*EventProcPtr) (XEvent* ev);
  22310. static bool xErrorTriggered;
  22311. static int temporaryErrorHandler (Display*, XErrorEvent*)
  22312. {
  22313. xErrorTriggered = true;
  22314. return 0;
  22315. }
  22316. static int getPropertyFromXWindow (Window handle, Atom atom)
  22317. {
  22318. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  22319. xErrorTriggered = false;
  22320. int userSize;
  22321. unsigned long bytes, userCount;
  22322. unsigned char* data;
  22323. Atom userType;
  22324. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  22325. &userType, &userSize, &userCount, &bytes, &data);
  22326. XSetErrorHandler (oldErrorHandler);
  22327. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  22328. : 0;
  22329. }
  22330. static Window getChildWindow (Window windowToCheck)
  22331. {
  22332. Window rootWindow, parentWindow;
  22333. Window* childWindows;
  22334. unsigned int numChildren;
  22335. XQueryTree (display,
  22336. windowToCheck,
  22337. &rootWindow,
  22338. &parentWindow,
  22339. &childWindows,
  22340. &numChildren);
  22341. if (numChildren > 0)
  22342. return childWindows [0];
  22343. return 0;
  22344. }
  22345. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  22346. {
  22347. if (e.mods.isLeftButtonDown())
  22348. {
  22349. ev.xbutton.button = Button1;
  22350. ev.xbutton.state |= Button1Mask;
  22351. }
  22352. else if (e.mods.isRightButtonDown())
  22353. {
  22354. ev.xbutton.button = Button3;
  22355. ev.xbutton.state |= Button3Mask;
  22356. }
  22357. else if (e.mods.isMiddleButtonDown())
  22358. {
  22359. ev.xbutton.button = Button2;
  22360. ev.xbutton.state |= Button2Mask;
  22361. }
  22362. }
  22363. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  22364. {
  22365. if (e.mods.isLeftButtonDown())
  22366. ev.xmotion.state |= Button1Mask;
  22367. else if (e.mods.isRightButtonDown())
  22368. ev.xmotion.state |= Button3Mask;
  22369. else if (e.mods.isMiddleButtonDown())
  22370. ev.xmotion.state |= Button2Mask;
  22371. }
  22372. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  22373. {
  22374. if (e.mods.isLeftButtonDown())
  22375. ev.xcrossing.state |= Button1Mask;
  22376. else if (e.mods.isRightButtonDown())
  22377. ev.xcrossing.state |= Button3Mask;
  22378. else if (e.mods.isMiddleButtonDown())
  22379. ev.xcrossing.state |= Button2Mask;
  22380. }
  22381. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  22382. {
  22383. if (increment < 0)
  22384. {
  22385. ev.xbutton.button = Button5;
  22386. ev.xbutton.state |= Button5Mask;
  22387. }
  22388. else if (increment > 0)
  22389. {
  22390. ev.xbutton.button = Button4;
  22391. ev.xbutton.state |= Button4Mask;
  22392. }
  22393. }
  22394. #endif
  22395. static VoidArray activeModules;
  22396. class ModuleHandle : public ReferenceCountedObject
  22397. {
  22398. public:
  22399. File file;
  22400. MainCall moduleMain;
  22401. String pluginName;
  22402. static ModuleHandle* findOrCreateModule (const File& file)
  22403. {
  22404. for (int i = activeModules.size(); --i >= 0;)
  22405. {
  22406. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  22407. if (module->file == file)
  22408. return module;
  22409. }
  22410. _fpreset(); // (doesn't do any harm)
  22411. ++insideVSTCallback;
  22412. shellUIDToCreate = 0;
  22413. log ("Attempting to load VST: " + file.getFullPathName());
  22414. ModuleHandle* m = new ModuleHandle (file);
  22415. if (! m->open())
  22416. deleteAndZero (m);
  22417. --insideVSTCallback;
  22418. _fpreset(); // (doesn't do any harm)
  22419. return m;
  22420. }
  22421. ModuleHandle (const File& file_)
  22422. : file (file_),
  22423. moduleMain (0),
  22424. #if JUCE_WIN32 || JUCE_LINUX
  22425. hModule (0)
  22426. #elif JUCE_MAC
  22427. fragId (0),
  22428. resHandle (0),
  22429. bundleRef (0),
  22430. resFileId (0)
  22431. #endif
  22432. {
  22433. activeModules.add (this);
  22434. #if JUCE_WIN32 || JUCE_LINUX
  22435. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  22436. #elif JUCE_MAC
  22437. PlatformUtilities::makeFSSpecFromPath (&parentDirFSSpec, file_.getParentDirectory().getFullPathName());
  22438. #endif
  22439. }
  22440. ~ModuleHandle()
  22441. {
  22442. activeModules.removeValue (this);
  22443. close();
  22444. }
  22445. juce_UseDebuggingNewOperator
  22446. #if JUCE_WIN32 || JUCE_LINUX
  22447. void* hModule;
  22448. String fullParentDirectoryPathName;
  22449. bool open()
  22450. {
  22451. #if JUCE_WIN32
  22452. static bool timePeriodSet = false;
  22453. if (! timePeriodSet)
  22454. {
  22455. timePeriodSet = true;
  22456. timeBeginPeriod (2);
  22457. }
  22458. #endif
  22459. pluginName = file.getFileNameWithoutExtension();
  22460. hModule = Process::loadDynamicLibrary (file.getFullPathName());
  22461. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "VSTPluginMain");
  22462. if (moduleMain == 0)
  22463. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "main");
  22464. return moduleMain != 0;
  22465. }
  22466. void close()
  22467. {
  22468. _fpreset(); // (doesn't do any harm)
  22469. Process::freeDynamicLibrary (hModule);
  22470. }
  22471. void closeEffect (AEffect* eff)
  22472. {
  22473. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22474. }
  22475. #else
  22476. CFragConnectionID fragId;
  22477. Handle resHandle;
  22478. CFBundleRef bundleRef;
  22479. FSSpec parentDirFSSpec;
  22480. short resFileId;
  22481. bool open()
  22482. {
  22483. bool ok = false;
  22484. const String filename (file.getFullPathName());
  22485. if (file.hasFileExtension (T(".vst")))
  22486. {
  22487. const char* const utf8 = filename.toUTF8();
  22488. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22489. strlen (utf8), file.isDirectory());
  22490. if (url != 0)
  22491. {
  22492. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22493. CFRelease (url);
  22494. if (bundleRef != 0)
  22495. {
  22496. if (CFBundleLoadExecutable (bundleRef))
  22497. {
  22498. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  22499. if (moduleMain == 0)
  22500. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  22501. if (moduleMain != 0)
  22502. {
  22503. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22504. if (name != 0)
  22505. {
  22506. if (CFGetTypeID (name) == CFStringGetTypeID())
  22507. {
  22508. char buffer[1024];
  22509. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  22510. pluginName = buffer;
  22511. }
  22512. }
  22513. if (pluginName.isEmpty())
  22514. pluginName = file.getFileNameWithoutExtension();
  22515. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22516. ok = true;
  22517. }
  22518. }
  22519. if (! ok)
  22520. {
  22521. CFBundleUnloadExecutable (bundleRef);
  22522. CFRelease (bundleRef);
  22523. bundleRef = 0;
  22524. }
  22525. }
  22526. }
  22527. }
  22528. #if JUCE_PPC
  22529. else
  22530. {
  22531. FSRef fn;
  22532. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  22533. {
  22534. resFileId = FSOpenResFile (&fn, fsRdPerm);
  22535. if (resFileId != -1)
  22536. {
  22537. const int numEffs = Count1Resources ('aEff');
  22538. for (int i = 0; i < numEffs; ++i)
  22539. {
  22540. resHandle = Get1IndResource ('aEff', i + 1);
  22541. if (resHandle != 0)
  22542. {
  22543. OSType type;
  22544. Str255 name;
  22545. SInt16 id;
  22546. GetResInfo (resHandle, &id, &type, name);
  22547. pluginName = String ((const char*) name + 1, name[0]);
  22548. DetachResource (resHandle);
  22549. HLock (resHandle);
  22550. Ptr ptr;
  22551. Str255 errorText;
  22552. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  22553. name, kPrivateCFragCopy,
  22554. &fragId, &ptr, errorText);
  22555. if (err == noErr)
  22556. {
  22557. moduleMain = (MainCall) newMachOFromCFM (ptr);
  22558. ok = true;
  22559. }
  22560. else
  22561. {
  22562. HUnlock (resHandle);
  22563. }
  22564. break;
  22565. }
  22566. }
  22567. if (! ok)
  22568. CloseResFile (resFileId);
  22569. }
  22570. }
  22571. }
  22572. #endif
  22573. return ok;
  22574. }
  22575. void close()
  22576. {
  22577. #if JUCE_PPC
  22578. if (fragId != 0)
  22579. {
  22580. if (moduleMain != 0)
  22581. disposeMachOFromCFM ((void*) moduleMain);
  22582. CloseConnection (&fragId);
  22583. HUnlock (resHandle);
  22584. if (resFileId != 0)
  22585. CloseResFile (resFileId);
  22586. }
  22587. else
  22588. #endif
  22589. if (bundleRef != 0)
  22590. {
  22591. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22592. if (CFGetRetainCount (bundleRef) == 1)
  22593. CFBundleUnloadExecutable (bundleRef);
  22594. if (CFGetRetainCount (bundleRef) > 0)
  22595. CFRelease (bundleRef);
  22596. }
  22597. }
  22598. void closeEffect (AEffect* eff)
  22599. {
  22600. #if JUCE_PPC
  22601. if (fragId != 0)
  22602. {
  22603. VoidArray thingsToDelete;
  22604. thingsToDelete.add ((void*) eff->dispatcher);
  22605. thingsToDelete.add ((void*) eff->process);
  22606. thingsToDelete.add ((void*) eff->setParameter);
  22607. thingsToDelete.add ((void*) eff->getParameter);
  22608. thingsToDelete.add ((void*) eff->processReplacing);
  22609. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22610. for (int i = thingsToDelete.size(); --i >= 0;)
  22611. disposeMachOFromCFM (thingsToDelete[i]);
  22612. }
  22613. else
  22614. #endif
  22615. {
  22616. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22617. }
  22618. }
  22619. #if JUCE_PPC
  22620. static void* newMachOFromCFM (void* cfmfp)
  22621. {
  22622. if (cfmfp == 0)
  22623. return 0;
  22624. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  22625. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  22626. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  22627. mfp[2] = 0x800c0000;
  22628. mfp[3] = 0x804c0004;
  22629. mfp[4] = 0x7c0903a6;
  22630. mfp[5] = 0x4e800420;
  22631. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  22632. return mfp;
  22633. }
  22634. static void disposeMachOFromCFM (void* ptr)
  22635. {
  22636. juce_free (ptr);
  22637. }
  22638. void coerceAEffectFunctionCalls (AEffect* eff)
  22639. {
  22640. if (fragId != 0)
  22641. {
  22642. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  22643. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  22644. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  22645. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  22646. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  22647. }
  22648. }
  22649. #endif
  22650. #endif
  22651. };
  22652. /**
  22653. An instance of a plugin, created by a VSTPluginFormat.
  22654. */
  22655. class VSTPluginInstance : public AudioPluginInstance,
  22656. private Timer,
  22657. private AsyncUpdater
  22658. {
  22659. public:
  22660. ~VSTPluginInstance();
  22661. // AudioPluginInstance methods:
  22662. void fillInPluginDescription (PluginDescription& desc) const
  22663. {
  22664. desc.name = name;
  22665. desc.file = module->file;
  22666. desc.uid = getUID();
  22667. desc.lastFileModTime = desc.file.getLastModificationTime();
  22668. desc.pluginFormatName = "VST";
  22669. desc.category = getCategory();
  22670. {
  22671. char buffer [kVstMaxVendorStrLen + 8];
  22672. zerostruct (buffer);
  22673. dispatch (effGetVendorString, 0, 0, buffer, 0);
  22674. desc.manufacturerName = buffer;
  22675. }
  22676. desc.version = getVersion();
  22677. desc.numInputChannels = getNumInputChannels();
  22678. desc.numOutputChannels = getNumOutputChannels();
  22679. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  22680. }
  22681. const String getName() const { return name; }
  22682. int getUID() const throw();
  22683. bool acceptsMidi() const { return wantsMidiMessages; }
  22684. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  22685. // AudioProcessor methods:
  22686. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22687. void releaseResources();
  22688. void processBlock (AudioSampleBuffer& buffer,
  22689. MidiBuffer& midiMessages);
  22690. AudioProcessorEditor* createEditor();
  22691. const String getInputChannelName (const int index) const;
  22692. bool isInputChannelStereoPair (int index) const;
  22693. const String getOutputChannelName (const int index) const;
  22694. bool isOutputChannelStereoPair (int index) const;
  22695. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  22696. float getParameter (int index);
  22697. void setParameter (int index, float newValue);
  22698. const String getParameterName (int index);
  22699. const String getParameterText (int index);
  22700. bool isParameterAutomatable (int index) const;
  22701. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  22702. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  22703. void setCurrentProgram (int index);
  22704. const String getProgramName (int index);
  22705. void changeProgramName (int index, const String& newName);
  22706. void getStateInformation (MemoryBlock& destData);
  22707. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22708. void setStateInformation (const void* data, int sizeInBytes);
  22709. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22710. void timerCallback();
  22711. void handleAsyncUpdate();
  22712. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  22713. juce_UseDebuggingNewOperator
  22714. private:
  22715. friend class VSTPluginWindow;
  22716. friend class VSTPluginFormat;
  22717. AEffect* effect;
  22718. String name;
  22719. CriticalSection lock;
  22720. bool wantsMidiMessages, initialised, isPowerOn;
  22721. mutable StringArray programNames;
  22722. AudioSampleBuffer tempBuffer;
  22723. CriticalSection midiInLock;
  22724. MidiBuffer incomingMidi;
  22725. void* midiEventsToSend;
  22726. int numAllocatedMidiEvents;
  22727. VstTimeInfo vstHostTime;
  22728. float** channels;
  22729. ReferenceCountedObjectPtr <ModuleHandle> module;
  22730. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  22731. bool restoreProgramSettings (const fxProgram* const prog);
  22732. const String getCurrentProgramName();
  22733. void setParamsInProgramBlock (fxProgram* const prog) throw();
  22734. void updateStoredProgramNames();
  22735. void initialise();
  22736. void ensureMidiEventSize (int numEventsNeeded);
  22737. void freeMidiEvents();
  22738. void handleMidiFromPlugin (const VstEvents* const events);
  22739. void createTempParameterStore (MemoryBlock& dest);
  22740. void restoreFromTempParameterStore (const MemoryBlock& mb);
  22741. const String getParameterLabel (int index) const;
  22742. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  22743. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  22744. void setChunkData (const char* data, int size, bool isPreset);
  22745. bool loadFromFXBFile (const void* data, int numBytes);
  22746. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  22747. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  22748. const String getVersion() const throw();
  22749. const String getCategory() const throw();
  22750. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  22751. void setPower (const bool on);
  22752. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  22753. };
  22754. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  22755. : effect (0),
  22756. wantsMidiMessages (false),
  22757. initialised (false),
  22758. isPowerOn (false),
  22759. numAllocatedMidiEvents (0),
  22760. midiEventsToSend (0),
  22761. tempBuffer (1, 1),
  22762. channels (0),
  22763. module (module_)
  22764. {
  22765. try
  22766. {
  22767. _fpreset();
  22768. ++insideVSTCallback;
  22769. name = module->pluginName;
  22770. log (T("Creating VST instance: ") + name);
  22771. #if JUCE_MAC
  22772. if (module->resFileId != 0)
  22773. UseResFile (module->resFileId);
  22774. #if JUCE_PPC
  22775. if (module->fragId != 0)
  22776. {
  22777. static void* audioMasterCoerced = 0;
  22778. if (audioMasterCoerced == 0)
  22779. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  22780. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  22781. }
  22782. else
  22783. #endif
  22784. #endif
  22785. {
  22786. effect = module->moduleMain (&audioMaster);
  22787. }
  22788. --insideVSTCallback;
  22789. if (effect != 0 && effect->magic == kEffectMagic)
  22790. {
  22791. #if JUCE_PPC
  22792. module->coerceAEffectFunctionCalls (effect);
  22793. #endif
  22794. jassert (effect->resvd2 == 0);
  22795. jassert (effect->object != 0);
  22796. _fpreset(); // some dodgy plugs fuck around with this
  22797. }
  22798. else
  22799. {
  22800. effect = 0;
  22801. }
  22802. }
  22803. catch (...)
  22804. {
  22805. --insideVSTCallback;
  22806. }
  22807. }
  22808. VSTPluginInstance::~VSTPluginInstance()
  22809. {
  22810. {
  22811. const ScopedLock sl (lock);
  22812. jassert (insideVSTCallback == 0);
  22813. if (effect != 0 && effect->magic == kEffectMagic)
  22814. {
  22815. try
  22816. {
  22817. #if JUCE_MAC
  22818. if (module->resFileId != 0)
  22819. UseResFile (module->resFileId);
  22820. #endif
  22821. // Must delete any editors before deleting the plugin instance!
  22822. jassert (getActiveEditor() == 0);
  22823. _fpreset(); // some dodgy plugs fuck around with this
  22824. module->closeEffect (effect);
  22825. }
  22826. catch (...)
  22827. {}
  22828. }
  22829. module = 0;
  22830. effect = 0;
  22831. }
  22832. freeMidiEvents();
  22833. juce_free (channels);
  22834. channels = 0;
  22835. }
  22836. void VSTPluginInstance::initialise()
  22837. {
  22838. if (initialised || effect == 0)
  22839. return;
  22840. log (T("Initialising VST: ") + module->pluginName);
  22841. initialised = true;
  22842. dispatch (effIdentify, 0, 0, 0, 0);
  22843. // this code would ask the plugin for its name, but so few plugins
  22844. // actually bother implementing this correctly, that it's better to
  22845. // just ignore it and use the file name instead.
  22846. /* {
  22847. char buffer [256];
  22848. zerostruct (buffer);
  22849. dispatch (effGetEffectName, 0, 0, buffer, 0);
  22850. name = String (buffer).trim();
  22851. if (name.isEmpty())
  22852. name = module->pluginName;
  22853. }
  22854. */
  22855. if (getSampleRate() > 0)
  22856. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  22857. if (getBlockSize() > 0)
  22858. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  22859. dispatch (effOpen, 0, 0, 0, 0);
  22860. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  22861. getSampleRate(), getBlockSize());
  22862. if (getNumPrograms() > 1)
  22863. setCurrentProgram (0);
  22864. else
  22865. dispatch (effSetProgram, 0, 0, 0, 0);
  22866. int i;
  22867. for (i = effect->numInputs; --i >= 0;)
  22868. dispatch (effConnectInput, i, 1, 0, 0);
  22869. for (i = effect->numOutputs; --i >= 0;)
  22870. dispatch (effConnectOutput, i, 1, 0, 0);
  22871. updateStoredProgramNames();
  22872. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  22873. setLatencySamples (effect->initialDelay);
  22874. }
  22875. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  22876. int samplesPerBlockExpected)
  22877. {
  22878. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  22879. sampleRate_, samplesPerBlockExpected);
  22880. setLatencySamples (effect->initialDelay);
  22881. juce_free (channels);
  22882. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  22883. vstHostTime.tempo = 120.0;
  22884. vstHostTime.timeSigNumerator = 4;
  22885. vstHostTime.timeSigDenominator = 4;
  22886. vstHostTime.sampleRate = sampleRate_;
  22887. vstHostTime.samplePos = 0;
  22888. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  22889. initialise();
  22890. if (initialised)
  22891. {
  22892. wantsMidiMessages = wantsMidiMessages
  22893. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  22894. if (wantsMidiMessages)
  22895. ensureMidiEventSize (256);
  22896. else
  22897. freeMidiEvents();
  22898. incomingMidi.clear();
  22899. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  22900. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  22901. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  22902. if (! isPowerOn)
  22903. setPower (true);
  22904. // dodgy hack to force some plugins to initialise the sample rate..
  22905. if ((! hasEditor()) && getNumParameters() > 0)
  22906. {
  22907. const float old = getParameter (0);
  22908. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  22909. setParameter (0, old);
  22910. }
  22911. dispatch (effStartProcess, 0, 0, 0, 0);
  22912. }
  22913. }
  22914. void VSTPluginInstance::releaseResources()
  22915. {
  22916. if (initialised)
  22917. {
  22918. dispatch (effStopProcess, 0, 0, 0, 0);
  22919. setPower (false);
  22920. }
  22921. tempBuffer.setSize (1, 1);
  22922. incomingMidi.clear();
  22923. freeMidiEvents();
  22924. juce_free (channels);
  22925. channels = 0;
  22926. }
  22927. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  22928. MidiBuffer& midiMessages)
  22929. {
  22930. const int numSamples = buffer.getNumSamples();
  22931. if (initialised)
  22932. {
  22933. #if JUCE_WIN32
  22934. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  22935. #elif JUCE_LINUX
  22936. timeval micro;
  22937. gettimeofday (&micro, 0);
  22938. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  22939. #elif JUCE_MAC
  22940. UnsignedWide micro;
  22941. Microseconds (&micro);
  22942. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  22943. #endif
  22944. if (wantsMidiMessages)
  22945. {
  22946. MidiBuffer::Iterator iter (midiMessages);
  22947. int eventIndex = 0;
  22948. const uint8* midiData;
  22949. int numBytesOfMidiData, samplePosition;
  22950. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  22951. {
  22952. if (numBytesOfMidiData < 4)
  22953. {
  22954. ensureMidiEventSize (eventIndex);
  22955. VstMidiEvent* const e
  22956. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  22957. // check that some plugin hasn't messed up our objects
  22958. jassert (e->type == kVstMidiType);
  22959. jassert (e->byteSize == 24);
  22960. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  22961. e->noteLength = 0;
  22962. e->noteOffset = 0;
  22963. e->midiData[0] = midiData[0];
  22964. e->midiData[1] = midiData[1];
  22965. e->midiData[2] = midiData[2];
  22966. e->detune = 0;
  22967. e->noteOffVelocity = 0;
  22968. }
  22969. }
  22970. if (midiEventsToSend == 0)
  22971. ensureMidiEventSize (1);
  22972. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  22973. try
  22974. {
  22975. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  22976. }
  22977. catch (...)
  22978. {}
  22979. }
  22980. int i;
  22981. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  22982. for (i = 0; i < maxChans; ++i)
  22983. channels[i] = buffer.getSampleData (i);
  22984. channels [maxChans] = 0;
  22985. _clearfp();
  22986. if ((effect->flags & effFlagsCanReplacing) != 0)
  22987. {
  22988. try
  22989. {
  22990. effect->processReplacing (effect, channels, channels, numSamples);
  22991. }
  22992. catch (...)
  22993. {}
  22994. }
  22995. else
  22996. {
  22997. tempBuffer.setSize (effect->numOutputs, numSamples);
  22998. tempBuffer.clear();
  22999. float* outs [64];
  23000. for (i = effect->numOutputs; --i >= 0;)
  23001. outs[i] = tempBuffer.getSampleData (i);
  23002. outs [effect->numOutputs] = 0;
  23003. try
  23004. {
  23005. effect->process (effect, channels, outs, numSamples);
  23006. }
  23007. catch (...)
  23008. {}
  23009. for (i = effect->numOutputs; --i >= 0;)
  23010. buffer.copyFrom (i, 0, outs[i], numSamples);
  23011. }
  23012. }
  23013. else
  23014. {
  23015. // Not initialised, so just bypass..
  23016. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23017. buffer.clear (i, 0, buffer.getNumSamples());
  23018. }
  23019. {
  23020. // copy any incoming midi..
  23021. const ScopedLock sl (midiInLock);
  23022. midiMessages = incomingMidi;
  23023. incomingMidi.clear();
  23024. }
  23025. }
  23026. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  23027. {
  23028. if (numEventsNeeded > numAllocatedMidiEvents)
  23029. {
  23030. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  23031. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  23032. if (midiEventsToSend == 0)
  23033. midiEventsToSend = juce_calloc (size);
  23034. else
  23035. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  23036. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  23037. {
  23038. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  23039. e->type = kVstMidiType;
  23040. e->byteSize = 24;
  23041. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  23042. }
  23043. numAllocatedMidiEvents = numEventsNeeded;
  23044. }
  23045. }
  23046. void VSTPluginInstance::freeMidiEvents()
  23047. {
  23048. if (midiEventsToSend != 0)
  23049. {
  23050. for (int i = numAllocatedMidiEvents; --i >= 0;)
  23051. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  23052. juce_free (midiEventsToSend);
  23053. midiEventsToSend = 0;
  23054. numAllocatedMidiEvents = 0;
  23055. }
  23056. }
  23057. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  23058. {
  23059. if (events != 0)
  23060. {
  23061. const ScopedLock sl (midiInLock);
  23062. for (int i = 0; i < events->numEvents; ++i)
  23063. {
  23064. const VstEvent* const e = events->events[i];
  23065. if (e->type == kVstMidiType)
  23066. {
  23067. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  23068. 3, e->deltaFrames);
  23069. }
  23070. }
  23071. }
  23072. }
  23073. static Array <VSTPluginWindow*> activeVSTWindows;
  23074. class VSTPluginWindow : public AudioProcessorEditor,
  23075. public Timer
  23076. {
  23077. public:
  23078. VSTPluginWindow (VSTPluginInstance& plugin_)
  23079. : AudioProcessorEditor (&plugin_),
  23080. plugin (plugin_),
  23081. isOpen (false),
  23082. wasShowing (false),
  23083. pluginRefusesToResize (false),
  23084. pluginWantsKeys (false),
  23085. alreadyInside (false),
  23086. recursiveResize (false)
  23087. {
  23088. #if JUCE_WIN32
  23089. sizeCheckCount = 0;
  23090. pluginHWND = 0;
  23091. #elif JUCE_LINUX
  23092. pluginWindow = None;
  23093. pluginProc = None;
  23094. #else
  23095. pluginViewRef = 0;
  23096. #endif
  23097. movementWatcher = new CompMovementWatcher (this);
  23098. activeVSTWindows.add (this);
  23099. setSize (1, 1);
  23100. setOpaque (true);
  23101. setVisible (true);
  23102. }
  23103. ~VSTPluginWindow()
  23104. {
  23105. deleteAndZero (movementWatcher);
  23106. closePluginWindow();
  23107. activeVSTWindows.removeValue (this);
  23108. plugin.editorBeingDeleted (this);
  23109. }
  23110. void componentMovedOrResized()
  23111. {
  23112. if (recursiveResize)
  23113. return;
  23114. Component* const topComp = getTopLevelComponent();
  23115. if (topComp->getPeer() != 0)
  23116. {
  23117. int x = 0, y = 0;
  23118. relativePositionToOtherComponent (topComp, x, y);
  23119. recursiveResize = true;
  23120. #if JUCE_MAC
  23121. if (pluginViewRef != 0)
  23122. {
  23123. HIRect r;
  23124. r.origin.x = (float) x;
  23125. r.origin.y = (float) y;
  23126. r.size.width = (float) getWidth();
  23127. r.size.height = (float) getHeight();
  23128. HIViewSetFrame (pluginViewRef, &r);
  23129. }
  23130. else if (pluginWindowRef != 0)
  23131. {
  23132. Rect r;
  23133. r.left = getScreenX();
  23134. r.top = getScreenY();
  23135. r.right = r.left + getWidth();
  23136. r.bottom = r.top + getHeight();
  23137. WindowGroupRef group = GetWindowGroup (pluginWindowRef);
  23138. WindowGroupAttributes atts;
  23139. GetWindowGroupAttributes (group, &atts);
  23140. ChangeWindowGroupAttributes (group, 0, kWindowGroupAttrMoveTogether);
  23141. SetWindowBounds (pluginWindowRef, kWindowContentRgn, &r);
  23142. if ((atts & kWindowGroupAttrMoveTogether) != 0)
  23143. ChangeWindowGroupAttributes (group, kWindowGroupAttrMoveTogether, 0);
  23144. }
  23145. else
  23146. {
  23147. repaint();
  23148. }
  23149. #elif JUCE_WIN32
  23150. if (pluginHWND != 0)
  23151. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  23152. #elif JUCE_LINUX
  23153. if (pluginWindow != 0)
  23154. {
  23155. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  23156. XMoveWindow (display, pluginWindow, x, y);
  23157. XMapRaised (display, pluginWindow);
  23158. }
  23159. #endif
  23160. recursiveResize = false;
  23161. }
  23162. }
  23163. void componentVisibilityChanged()
  23164. {
  23165. const bool isShowingNow = isShowing();
  23166. if (wasShowing != isShowingNow)
  23167. {
  23168. wasShowing = isShowingNow;
  23169. if (isShowingNow)
  23170. openPluginWindow();
  23171. else
  23172. closePluginWindow();
  23173. }
  23174. componentMovedOrResized();
  23175. }
  23176. void componentPeerChanged()
  23177. {
  23178. closePluginWindow();
  23179. openPluginWindow();
  23180. }
  23181. bool keyStateChanged()
  23182. {
  23183. return pluginWantsKeys;
  23184. }
  23185. bool keyPressed (const KeyPress&)
  23186. {
  23187. return pluginWantsKeys;
  23188. }
  23189. void paint (Graphics& g)
  23190. {
  23191. if (isOpen)
  23192. {
  23193. ComponentPeer* const peer = getPeer();
  23194. if (peer != 0)
  23195. {
  23196. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  23197. getScreenY() - peer->getScreenY(),
  23198. getWidth(), getHeight());
  23199. #if JUCE_MAC
  23200. if (pluginViewRef == 0)
  23201. {
  23202. ERect r;
  23203. r.left = getScreenX() - peer->getScreenX();
  23204. r.right = r.left + getWidth();
  23205. r.top = getScreenY() - peer->getScreenY();
  23206. r.bottom = r.top + getHeight();
  23207. dispatch (effEditDraw, 0, 0, &r, 0);
  23208. }
  23209. #elif JUCE_LINUX
  23210. if (pluginWindow != 0)
  23211. {
  23212. const Rectangle clip (g.getClipBounds());
  23213. XEvent ev;
  23214. zerostruct (ev);
  23215. ev.xexpose.type = Expose;
  23216. ev.xexpose.display = display;
  23217. ev.xexpose.window = pluginWindow;
  23218. ev.xexpose.x = clip.getX();
  23219. ev.xexpose.y = clip.getY();
  23220. ev.xexpose.width = clip.getWidth();
  23221. ev.xexpose.height = clip.getHeight();
  23222. sendEventToChild (&ev);
  23223. }
  23224. #endif
  23225. }
  23226. }
  23227. else
  23228. {
  23229. g.fillAll (Colours::black);
  23230. }
  23231. }
  23232. void timerCallback()
  23233. {
  23234. #if JUCE_WIN32
  23235. if (--sizeCheckCount <= 0)
  23236. {
  23237. sizeCheckCount = 10;
  23238. checkPluginWindowSize();
  23239. }
  23240. #endif
  23241. try
  23242. {
  23243. static bool reentrant = false;
  23244. if (! reentrant)
  23245. {
  23246. reentrant = true;
  23247. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  23248. reentrant = false;
  23249. }
  23250. }
  23251. catch (...)
  23252. {}
  23253. }
  23254. void mouseDown (const MouseEvent& e)
  23255. {
  23256. #if JUCE_MAC
  23257. if (! alreadyInside)
  23258. {
  23259. alreadyInside = true;
  23260. toFront (true);
  23261. dispatch (effEditMouse, e.x, e.y, 0, 0);
  23262. alreadyInside = false;
  23263. }
  23264. else
  23265. {
  23266. PostEvent (::mouseDown, 0);
  23267. }
  23268. #elif JUCE_LINUX
  23269. if (pluginWindow == 0)
  23270. return;
  23271. toFront (true);
  23272. XEvent ev;
  23273. zerostruct (ev);
  23274. ev.xbutton.display = display;
  23275. ev.xbutton.type = ButtonPress;
  23276. ev.xbutton.window = pluginWindow;
  23277. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23278. ev.xbutton.time = CurrentTime;
  23279. ev.xbutton.x = e.x;
  23280. ev.xbutton.y = e.y;
  23281. ev.xbutton.x_root = e.getScreenX();
  23282. ev.xbutton.y_root = e.getScreenY();
  23283. translateJuceToXButtonModifiers (e, ev);
  23284. sendEventToChild (&ev);
  23285. #else
  23286. (void) e;
  23287. toFront (true);
  23288. #endif
  23289. }
  23290. void broughtToFront()
  23291. {
  23292. activeVSTWindows.removeValue (this);
  23293. activeVSTWindows.add (this);
  23294. #if JUCE_MAC
  23295. dispatch (effEditTop, 0, 0, 0, 0);
  23296. #endif
  23297. }
  23298. juce_UseDebuggingNewOperator
  23299. private:
  23300. VSTPluginInstance& plugin;
  23301. bool isOpen, wasShowing, recursiveResize;
  23302. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  23303. #if JUCE_WIN32
  23304. HWND pluginHWND;
  23305. void* originalWndProc;
  23306. int sizeCheckCount;
  23307. #elif JUCE_MAC
  23308. HIViewRef pluginViewRef;
  23309. WindowRef pluginWindowRef;
  23310. #elif JUCE_LINUX
  23311. Window pluginWindow;
  23312. EventProcPtr pluginProc;
  23313. #endif
  23314. void openPluginWindow()
  23315. {
  23316. if (isOpen || getWindowHandle() == 0)
  23317. return;
  23318. log (T("Opening VST UI: ") + plugin.name);
  23319. isOpen = true;
  23320. ERect* rect = 0;
  23321. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23322. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  23323. // do this before and after like in the steinberg example
  23324. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23325. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  23326. // Install keyboard hooks
  23327. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  23328. #if JUCE_WIN32
  23329. originalWndProc = 0;
  23330. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  23331. if (pluginHWND == 0)
  23332. {
  23333. isOpen = false;
  23334. setSize (300, 150);
  23335. return;
  23336. }
  23337. #pragma warning (push)
  23338. #pragma warning (disable: 4244)
  23339. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  23340. if (! pluginWantsKeys)
  23341. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  23342. #pragma warning (pop)
  23343. int w, h;
  23344. RECT r;
  23345. GetWindowRect (pluginHWND, &r);
  23346. w = r.right - r.left;
  23347. h = r.bottom - r.top;
  23348. if (rect != 0)
  23349. {
  23350. const int rw = rect->right - rect->left;
  23351. const int rh = rect->bottom - rect->top;
  23352. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  23353. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  23354. {
  23355. // very dodgy logic to decide which size is right.
  23356. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  23357. {
  23358. SetWindowPos (pluginHWND, 0,
  23359. 0, 0, rw, rh,
  23360. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  23361. GetWindowRect (pluginHWND, &r);
  23362. w = r.right - r.left;
  23363. h = r.bottom - r.top;
  23364. pluginRefusesToResize = (w != rw) || (h != rh);
  23365. w = rw;
  23366. h = rh;
  23367. }
  23368. }
  23369. }
  23370. #elif JUCE_MAC
  23371. HIViewRef root = HIViewGetRoot ((WindowRef) getWindowHandle());
  23372. HIViewFindByID (root, kHIViewWindowContentID, &root);
  23373. pluginViewRef = HIViewGetFirstSubview (root);
  23374. while (pluginViewRef != 0 && juce_isHIViewCreatedByJuce (pluginViewRef))
  23375. pluginViewRef = HIViewGetNextView (pluginViewRef);
  23376. pluginWindowRef = 0;
  23377. if (pluginViewRef == 0)
  23378. {
  23379. WindowGroupRef ourGroup = GetWindowGroup ((WindowRef) getWindowHandle());
  23380. //DebugPrintWindowGroup (ourGroup);
  23381. //DebugPrintAllWindowGroups();
  23382. GetIndexedWindow (ourGroup, 1,
  23383. kWindowGroupContentsVisible,
  23384. &pluginWindowRef);
  23385. if (pluginWindowRef == (WindowRef) getWindowHandle()
  23386. || juce_isWindowCreatedByJuce (pluginWindowRef))
  23387. pluginWindowRef = 0;
  23388. }
  23389. int w = 250, h = 150;
  23390. if (rect != 0)
  23391. {
  23392. w = rect->right - rect->left;
  23393. h = rect->bottom - rect->top;
  23394. if (w == 0 || h == 0)
  23395. {
  23396. w = 250;
  23397. h = 150;
  23398. }
  23399. }
  23400. #elif JUCE_LINUX
  23401. pluginWindow = getChildWindow ((Window) getWindowHandle());
  23402. if (pluginWindow != 0)
  23403. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  23404. XInternAtom (display, "_XEventProc", False));
  23405. int w = 250, h = 150;
  23406. if (rect != 0)
  23407. {
  23408. w = rect->right - rect->left;
  23409. h = rect->bottom - rect->top;
  23410. if (w == 0 || h == 0)
  23411. {
  23412. w = 250;
  23413. h = 150;
  23414. }
  23415. }
  23416. if (pluginWindow != 0)
  23417. XMapRaised (display, pluginWindow);
  23418. #endif
  23419. // double-check it's not too tiny
  23420. w = jmax (w, 32);
  23421. h = jmax (h, 32);
  23422. setSize (w, h);
  23423. #if JUCE_WIN32
  23424. checkPluginWindowSize();
  23425. #endif
  23426. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  23427. repaint();
  23428. }
  23429. void closePluginWindow()
  23430. {
  23431. if (isOpen)
  23432. {
  23433. log (T("Closing VST UI: ") + plugin.getName());
  23434. isOpen = false;
  23435. dispatch (effEditClose, 0, 0, 0, 0);
  23436. #if JUCE_WIN32
  23437. #pragma warning (push)
  23438. #pragma warning (disable: 4244)
  23439. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23440. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  23441. #pragma warning (pop)
  23442. stopTimer();
  23443. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23444. DestroyWindow (pluginHWND);
  23445. pluginHWND = 0;
  23446. #elif JUCE_MAC
  23447. dispatch (effEditSleep, 0, 0, 0, 0);
  23448. pluginViewRef = 0;
  23449. stopTimer();
  23450. #elif JUCE_LINUX
  23451. stopTimer();
  23452. pluginWindow = 0;
  23453. pluginProc = 0;
  23454. #endif
  23455. }
  23456. }
  23457. #if JUCE_WIN32
  23458. void checkPluginWindowSize() throw()
  23459. {
  23460. RECT r;
  23461. GetWindowRect (pluginHWND, &r);
  23462. const int w = r.right - r.left;
  23463. const int h = r.bottom - r.top;
  23464. if (isShowing() && w > 0 && h > 0
  23465. && (w != getWidth() || h != getHeight())
  23466. && ! pluginRefusesToResize)
  23467. {
  23468. setSize (w, h);
  23469. sizeCheckCount = 0;
  23470. }
  23471. }
  23472. #endif
  23473. class CompMovementWatcher : public ComponentMovementWatcher
  23474. {
  23475. public:
  23476. CompMovementWatcher (VSTPluginWindow* const owner_)
  23477. : ComponentMovementWatcher (owner_),
  23478. owner (owner_)
  23479. {
  23480. }
  23481. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23482. {
  23483. owner->componentMovedOrResized();
  23484. }
  23485. void componentPeerChanged()
  23486. {
  23487. owner->componentPeerChanged();
  23488. }
  23489. void componentVisibilityChanged (Component&)
  23490. {
  23491. owner->componentVisibilityChanged();
  23492. }
  23493. private:
  23494. VSTPluginWindow* const owner;
  23495. };
  23496. CompMovementWatcher* movementWatcher;
  23497. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  23498. {
  23499. return plugin.dispatch (opcode, index, value, ptr, opt);
  23500. }
  23501. // hooks to get keyboard events from VST windows..
  23502. #if JUCE_WIN32
  23503. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  23504. {
  23505. for (int i = activeVSTWindows.size(); --i >= 0;)
  23506. {
  23507. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  23508. if (w->pluginHWND == hW)
  23509. {
  23510. if (message == WM_CHAR
  23511. || message == WM_KEYDOWN
  23512. || message == WM_SYSKEYDOWN
  23513. || message == WM_KEYUP
  23514. || message == WM_SYSKEYUP
  23515. || message == WM_APPCOMMAND)
  23516. {
  23517. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  23518. message, wParam, lParam);
  23519. }
  23520. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  23521. (HWND) w->pluginHWND,
  23522. message,
  23523. wParam,
  23524. lParam);
  23525. }
  23526. }
  23527. return DefWindowProc (hW, message, wParam, lParam);
  23528. }
  23529. #endif
  23530. #if JUCE_LINUX
  23531. // overload mouse/keyboard events to forward them to the plugin's inner window..
  23532. void sendEventToChild (XEvent* event)
  23533. {
  23534. if (pluginProc != 0)
  23535. {
  23536. // if the plugin publishes an event procedure, pass the event directly..
  23537. pluginProc (event);
  23538. }
  23539. else if (pluginWindow != 0)
  23540. {
  23541. // if the plugin has a window, then send the event to the window so that
  23542. // its message thread will pick it up..
  23543. XSendEvent (display, pluginWindow, False, 0L, event);
  23544. XFlush (display);
  23545. }
  23546. }
  23547. void mouseEnter (const MouseEvent& e)
  23548. {
  23549. if (pluginWindow != 0)
  23550. {
  23551. XEvent ev;
  23552. zerostruct (ev);
  23553. ev.xcrossing.display = display;
  23554. ev.xcrossing.type = EnterNotify;
  23555. ev.xcrossing.window = pluginWindow;
  23556. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23557. ev.xcrossing.time = CurrentTime;
  23558. ev.xcrossing.x = e.x;
  23559. ev.xcrossing.y = e.y;
  23560. ev.xcrossing.x_root = e.getScreenX();
  23561. ev.xcrossing.y_root = e.getScreenY();
  23562. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23563. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23564. translateJuceToXCrossingModifiers (e, ev);
  23565. sendEventToChild (&ev);
  23566. }
  23567. }
  23568. void mouseExit (const MouseEvent& e)
  23569. {
  23570. if (pluginWindow != 0)
  23571. {
  23572. XEvent ev;
  23573. zerostruct (ev);
  23574. ev.xcrossing.display = display;
  23575. ev.xcrossing.type = LeaveNotify;
  23576. ev.xcrossing.window = pluginWindow;
  23577. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23578. ev.xcrossing.time = CurrentTime;
  23579. ev.xcrossing.x = e.x;
  23580. ev.xcrossing.y = e.y;
  23581. ev.xcrossing.x_root = e.getScreenX();
  23582. ev.xcrossing.y_root = e.getScreenY();
  23583. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23584. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23585. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  23586. translateJuceToXCrossingModifiers (e, ev);
  23587. sendEventToChild (&ev);
  23588. }
  23589. }
  23590. void mouseMove (const MouseEvent& e)
  23591. {
  23592. if (pluginWindow != 0)
  23593. {
  23594. XEvent ev;
  23595. zerostruct (ev);
  23596. ev.xmotion.display = display;
  23597. ev.xmotion.type = MotionNotify;
  23598. ev.xmotion.window = pluginWindow;
  23599. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23600. ev.xmotion.time = CurrentTime;
  23601. ev.xmotion.is_hint = NotifyNormal;
  23602. ev.xmotion.x = e.x;
  23603. ev.xmotion.y = e.y;
  23604. ev.xmotion.x_root = e.getScreenX();
  23605. ev.xmotion.y_root = e.getScreenY();
  23606. sendEventToChild (&ev);
  23607. }
  23608. }
  23609. void mouseDrag (const MouseEvent& e)
  23610. {
  23611. if (pluginWindow != 0)
  23612. {
  23613. XEvent ev;
  23614. zerostruct (ev);
  23615. ev.xmotion.display = display;
  23616. ev.xmotion.type = MotionNotify;
  23617. ev.xmotion.window = pluginWindow;
  23618. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23619. ev.xmotion.time = CurrentTime;
  23620. ev.xmotion.x = e.x ;
  23621. ev.xmotion.y = e.y;
  23622. ev.xmotion.x_root = e.getScreenX();
  23623. ev.xmotion.y_root = e.getScreenY();
  23624. ev.xmotion.is_hint = NotifyNormal;
  23625. translateJuceToXMotionModifiers (e, ev);
  23626. sendEventToChild (&ev);
  23627. }
  23628. }
  23629. void mouseUp (const MouseEvent& e)
  23630. {
  23631. if (pluginWindow != 0)
  23632. {
  23633. XEvent ev;
  23634. zerostruct (ev);
  23635. ev.xbutton.display = display;
  23636. ev.xbutton.type = ButtonRelease;
  23637. ev.xbutton.window = pluginWindow;
  23638. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23639. ev.xbutton.time = CurrentTime;
  23640. ev.xbutton.x = e.x;
  23641. ev.xbutton.y = e.y;
  23642. ev.xbutton.x_root = e.getScreenX();
  23643. ev.xbutton.y_root = e.getScreenY();
  23644. translateJuceToXButtonModifiers (e, ev);
  23645. sendEventToChild (&ev);
  23646. }
  23647. }
  23648. void mouseWheelMove (const MouseEvent& e,
  23649. float incrementX,
  23650. float incrementY)
  23651. {
  23652. if (pluginWindow != 0)
  23653. {
  23654. XEvent ev;
  23655. zerostruct (ev);
  23656. ev.xbutton.display = display;
  23657. ev.xbutton.type = ButtonPress;
  23658. ev.xbutton.window = pluginWindow;
  23659. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23660. ev.xbutton.time = CurrentTime;
  23661. ev.xbutton.x = e.x;
  23662. ev.xbutton.y = e.y;
  23663. ev.xbutton.x_root = e.getScreenX();
  23664. ev.xbutton.y_root = e.getScreenY();
  23665. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  23666. sendEventToChild (&ev);
  23667. // TODO - put a usleep here ?
  23668. ev.xbutton.type = ButtonRelease;
  23669. sendEventToChild (&ev);
  23670. }
  23671. }
  23672. #endif
  23673. };
  23674. AudioProcessorEditor* VSTPluginInstance::createEditor()
  23675. {
  23676. if (hasEditor())
  23677. return new VSTPluginWindow (*this);
  23678. return 0;
  23679. }
  23680. void VSTPluginInstance::handleAsyncUpdate()
  23681. {
  23682. // indicates that something about the plugin has changed..
  23683. updateHostDisplay();
  23684. }
  23685. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  23686. {
  23687. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  23688. {
  23689. changeProgramName (getCurrentProgram(), prog->prgName);
  23690. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23691. setParameter (i, vst_swapFloat (prog->params[i]));
  23692. return true;
  23693. }
  23694. return false;
  23695. }
  23696. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  23697. const int dataSize)
  23698. {
  23699. if (dataSize < 28)
  23700. return false;
  23701. const fxSet* const set = (const fxSet*) data;
  23702. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  23703. || vst_swap (set->version) > fxbVersionNum)
  23704. return false;
  23705. if (vst_swap (set->fxMagic) == 'FxBk')
  23706. {
  23707. // bank of programs
  23708. if (vst_swap (set->numPrograms) >= 0)
  23709. {
  23710. const int oldProg = getCurrentProgram();
  23711. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  23712. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23713. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  23714. {
  23715. if (i != oldProg)
  23716. {
  23717. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  23718. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23719. return false;
  23720. if (vst_swap (set->numPrograms) > 0)
  23721. setCurrentProgram (i);
  23722. if (! restoreProgramSettings (prog))
  23723. return false;
  23724. }
  23725. }
  23726. if (vst_swap (set->numPrograms) > 0)
  23727. setCurrentProgram (oldProg);
  23728. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  23729. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23730. return false;
  23731. if (! restoreProgramSettings (prog))
  23732. return false;
  23733. }
  23734. }
  23735. else if (vst_swap (set->fxMagic) == 'FxCk')
  23736. {
  23737. // single program
  23738. const fxProgram* const prog = (const fxProgram*) data;
  23739. if (vst_swap (prog->chunkMagic) != 'CcnK')
  23740. return false;
  23741. changeProgramName (getCurrentProgram(), prog->prgName);
  23742. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23743. setParameter (i, vst_swapFloat (prog->params[i]));
  23744. }
  23745. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  23746. {
  23747. // non-preset chunk
  23748. const fxChunkSet* const cset = (const fxChunkSet*) data;
  23749. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  23750. return false;
  23751. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  23752. }
  23753. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  23754. {
  23755. // preset chunk
  23756. const fxProgramSet* const cset = (const fxProgramSet*) data;
  23757. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  23758. return false;
  23759. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  23760. changeProgramName (getCurrentProgram(), cset->name);
  23761. }
  23762. else
  23763. {
  23764. return false;
  23765. }
  23766. return true;
  23767. }
  23768. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  23769. {
  23770. const int numParams = getNumParameters();
  23771. prog->chunkMagic = vst_swap ('CcnK');
  23772. prog->byteSize = 0;
  23773. prog->fxMagic = vst_swap ('FxCk');
  23774. prog->version = vst_swap (fxbVersionNum);
  23775. prog->fxID = vst_swap (getUID());
  23776. prog->fxVersion = vst_swap (getVersionNumber());
  23777. prog->numParams = vst_swap (numParams);
  23778. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  23779. for (int i = 0; i < numParams; ++i)
  23780. prog->params[i] = vst_swapFloat (getParameter (i));
  23781. }
  23782. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  23783. {
  23784. const int numPrograms = getNumPrograms();
  23785. const int numParams = getNumParameters();
  23786. if (usesChunks())
  23787. {
  23788. if (isFXB)
  23789. {
  23790. MemoryBlock chunk;
  23791. getChunkData (chunk, false, maxSizeMB);
  23792. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  23793. dest.setSize (totalLen, true);
  23794. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  23795. set->chunkMagic = vst_swap ('CcnK');
  23796. set->byteSize = 0;
  23797. set->fxMagic = vst_swap ('FBCh');
  23798. set->version = vst_swap (fxbVersionNum);
  23799. set->fxID = vst_swap (getUID());
  23800. set->fxVersion = vst_swap (getVersionNumber());
  23801. set->numPrograms = vst_swap (numPrograms);
  23802. set->chunkSize = vst_swap (chunk.getSize());
  23803. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23804. }
  23805. else
  23806. {
  23807. MemoryBlock chunk;
  23808. getChunkData (chunk, true, maxSizeMB);
  23809. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  23810. dest.setSize (totalLen, true);
  23811. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  23812. set->chunkMagic = vst_swap ('CcnK');
  23813. set->byteSize = 0;
  23814. set->fxMagic = vst_swap ('FPCh');
  23815. set->version = vst_swap (fxbVersionNum);
  23816. set->fxID = vst_swap (getUID());
  23817. set->fxVersion = vst_swap (getVersionNumber());
  23818. set->numPrograms = vst_swap (numPrograms);
  23819. set->chunkSize = vst_swap (chunk.getSize());
  23820. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  23821. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23822. }
  23823. }
  23824. else
  23825. {
  23826. if (isFXB)
  23827. {
  23828. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23829. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  23830. dest.setSize (len, true);
  23831. fxSet* const set = (fxSet*) dest.getData();
  23832. set->chunkMagic = vst_swap ('CcnK');
  23833. set->byteSize = 0;
  23834. set->fxMagic = vst_swap ('FxBk');
  23835. set->version = vst_swap (fxbVersionNum);
  23836. set->fxID = vst_swap (getUID());
  23837. set->fxVersion = vst_swap (getVersionNumber());
  23838. set->numPrograms = vst_swap (numPrograms);
  23839. const int oldProgram = getCurrentProgram();
  23840. MemoryBlock oldSettings;
  23841. createTempParameterStore (oldSettings);
  23842. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  23843. for (int i = 0; i < numPrograms; ++i)
  23844. {
  23845. if (i != oldProgram)
  23846. {
  23847. setCurrentProgram (i);
  23848. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  23849. }
  23850. }
  23851. setCurrentProgram (oldProgram);
  23852. restoreFromTempParameterStore (oldSettings);
  23853. }
  23854. else
  23855. {
  23856. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23857. dest.setSize (totalLen, true);
  23858. setParamsInProgramBlock ((fxProgram*) dest.getData());
  23859. }
  23860. }
  23861. return true;
  23862. }
  23863. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  23864. {
  23865. if (usesChunks())
  23866. {
  23867. void* data = 0;
  23868. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  23869. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  23870. {
  23871. mb.setSize (bytes);
  23872. mb.copyFrom (data, 0, bytes);
  23873. }
  23874. }
  23875. }
  23876. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  23877. {
  23878. if (size > 0 && usesChunks())
  23879. {
  23880. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  23881. if (! isPreset)
  23882. updateStoredProgramNames();
  23883. }
  23884. }
  23885. void VSTPluginInstance::timerCallback()
  23886. {
  23887. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  23888. stopTimer();
  23889. }
  23890. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  23891. {
  23892. const ScopedLock sl (lock);
  23893. ++insideVSTCallback;
  23894. int result = 0;
  23895. try
  23896. {
  23897. if (effect != 0)
  23898. {
  23899. #if JUCE_MAC
  23900. if (module->resFileId != 0)
  23901. UseResFile (module->resFileId);
  23902. CGrafPtr oldPort;
  23903. if (getActiveEditor() != 0)
  23904. {
  23905. int x = 0, y = 0;
  23906. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  23907. GetPort (&oldPort);
  23908. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  23909. SetOrigin (-x, -y);
  23910. }
  23911. #endif
  23912. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  23913. #if JUCE_MAC
  23914. if (getActiveEditor() != 0)
  23915. SetPort (oldPort);
  23916. module->resFileId = CurResFile();
  23917. #endif
  23918. --insideVSTCallback;
  23919. return result;
  23920. }
  23921. }
  23922. catch (...)
  23923. {
  23924. //char s[512];
  23925. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  23926. }
  23927. --insideVSTCallback;
  23928. return result;
  23929. }
  23930. // handles non plugin-specific callbacks..
  23931. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  23932. {
  23933. (void) index;
  23934. (void) value;
  23935. (void) opt;
  23936. switch (opcode)
  23937. {
  23938. case audioMasterCanDo:
  23939. {
  23940. static const char* canDos[] = { "supplyIdle",
  23941. "sendVstEvents",
  23942. "sendVstMidiEvent",
  23943. "sendVstTimeInfo",
  23944. "receiveVstEvents",
  23945. "receiveVstMidiEvent",
  23946. "supportShell",
  23947. "shellCategory" };
  23948. for (int i = 0; i < numElementsInArray (canDos); ++i)
  23949. if (strcmp (canDos[i], (const char*) ptr) == 0)
  23950. return 1;
  23951. return 0;
  23952. }
  23953. case audioMasterVersion:
  23954. return 0x2400;
  23955. case audioMasterCurrentId:
  23956. return shellUIDToCreate;
  23957. case audioMasterGetNumAutomatableParameters:
  23958. return 0;
  23959. case audioMasterGetAutomationState:
  23960. return 1;
  23961. case audioMasterGetVendorVersion:
  23962. return 0x0101;
  23963. case audioMasterGetVendorString:
  23964. case audioMasterGetProductString:
  23965. JUCEApplication::getInstance()
  23966. ->getApplicationName().copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  23967. break;
  23968. case audioMasterGetSampleRate:
  23969. return 44100;
  23970. case audioMasterGetBlockSize:
  23971. return 512;
  23972. case audioMasterSetOutputSampleRate:
  23973. return 0;
  23974. default:
  23975. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  23976. break;
  23977. }
  23978. return 0;
  23979. }
  23980. // handles callbacks for a specific plugin
  23981. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  23982. {
  23983. switch (opcode)
  23984. {
  23985. case audioMasterAutomate:
  23986. sendParamChangeMessageToListeners (index, opt);
  23987. break;
  23988. case audioMasterProcessEvents:
  23989. handleMidiFromPlugin ((const VstEvents*) ptr);
  23990. break;
  23991. case audioMasterGetTime:
  23992. #ifdef _MSC_VER
  23993. #pragma warning (push)
  23994. #pragma warning (disable: 4311)
  23995. #endif
  23996. return (VstIntPtr) &vstHostTime;
  23997. #ifdef _MSC_VER
  23998. #pragma warning (pop)
  23999. #endif
  24000. break;
  24001. case audioMasterIdle:
  24002. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  24003. {
  24004. ++insideVSTCallback;
  24005. #if JUCE_MAC
  24006. if (getActiveEditor() != 0)
  24007. dispatch (effEditIdle, 0, 0, 0, 0);
  24008. #endif
  24009. const MessageManagerLock mml;
  24010. juce_callAnyTimersSynchronously();
  24011. handleUpdateNowIfNeeded();
  24012. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  24013. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  24014. --insideVSTCallback;
  24015. }
  24016. break;
  24017. case audioMasterUpdateDisplay:
  24018. triggerAsyncUpdate();
  24019. break;
  24020. case audioMasterTempoAt:
  24021. // returns (10000 * bpm)
  24022. break;
  24023. case audioMasterNeedIdle:
  24024. startTimer (50);
  24025. break;
  24026. case audioMasterSizeWindow:
  24027. if (getActiveEditor() != 0)
  24028. getActiveEditor()->setSize (index, value);
  24029. return 1;
  24030. case audioMasterGetSampleRate:
  24031. return (VstIntPtr) getSampleRate();
  24032. case audioMasterGetBlockSize:
  24033. return (VstIntPtr) getBlockSize();
  24034. case audioMasterWantMidi:
  24035. wantsMidiMessages = true;
  24036. break;
  24037. case audioMasterGetDirectory:
  24038. #if JUCE_MAC
  24039. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  24040. #else
  24041. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  24042. #endif
  24043. case audioMasterGetAutomationState:
  24044. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  24045. break;
  24046. // none of these are handled (yet)..
  24047. case audioMasterBeginEdit:
  24048. case audioMasterEndEdit:
  24049. case audioMasterSetTime:
  24050. case audioMasterPinConnected:
  24051. case audioMasterGetParameterQuantization:
  24052. case audioMasterIOChanged:
  24053. case audioMasterGetInputLatency:
  24054. case audioMasterGetOutputLatency:
  24055. case audioMasterGetPreviousPlug:
  24056. case audioMasterGetNextPlug:
  24057. case audioMasterWillReplaceOrAccumulate:
  24058. case audioMasterGetCurrentProcessLevel:
  24059. case audioMasterOfflineStart:
  24060. case audioMasterOfflineRead:
  24061. case audioMasterOfflineWrite:
  24062. case audioMasterOfflineGetCurrentPass:
  24063. case audioMasterOfflineGetCurrentMetaPass:
  24064. case audioMasterVendorSpecific:
  24065. case audioMasterSetIcon:
  24066. case audioMasterGetLanguage:
  24067. case audioMasterOpenWindow:
  24068. case audioMasterCloseWindow:
  24069. break;
  24070. default:
  24071. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24072. }
  24073. return 0;
  24074. }
  24075. // entry point for all callbacks from the plugin
  24076. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  24077. {
  24078. try
  24079. {
  24080. if (effect != 0 && effect->resvd2 != 0)
  24081. {
  24082. return ((VSTPluginInstance*)(effect->resvd2))
  24083. ->handleCallback (opcode, index, value, ptr, opt);
  24084. }
  24085. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24086. }
  24087. catch (...)
  24088. {
  24089. return 0;
  24090. }
  24091. }
  24092. const String VSTPluginInstance::getVersion() const throw()
  24093. {
  24094. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  24095. String s;
  24096. if (v != 0)
  24097. {
  24098. int versionBits[4];
  24099. int n = 0;
  24100. while (v != 0)
  24101. {
  24102. versionBits [n++] = (v & 0xff);
  24103. v >>= 8;
  24104. }
  24105. s << 'V';
  24106. while (n > 0)
  24107. {
  24108. s << versionBits [--n];
  24109. if (n > 0)
  24110. s << '.';
  24111. }
  24112. }
  24113. return s;
  24114. }
  24115. int VSTPluginInstance::getUID() const throw()
  24116. {
  24117. int uid = effect != 0 ? effect->uniqueID : 0;
  24118. if (uid == 0)
  24119. uid = module->file.hashCode();
  24120. return uid;
  24121. }
  24122. const String VSTPluginInstance::getCategory() const throw()
  24123. {
  24124. const char* result = 0;
  24125. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  24126. {
  24127. case kPlugCategEffect:
  24128. result = "Effect";
  24129. break;
  24130. case kPlugCategSynth:
  24131. result = "Synth";
  24132. break;
  24133. case kPlugCategAnalysis:
  24134. result = "Anaylsis";
  24135. break;
  24136. case kPlugCategMastering:
  24137. result = "Mastering";
  24138. break;
  24139. case kPlugCategSpacializer:
  24140. result = "Spacial";
  24141. break;
  24142. case kPlugCategRoomFx:
  24143. result = "Reverb";
  24144. break;
  24145. case kPlugSurroundFx:
  24146. result = "Surround";
  24147. break;
  24148. case kPlugCategRestoration:
  24149. result = "Restoration";
  24150. break;
  24151. case kPlugCategGenerator:
  24152. result = "Tone generation";
  24153. break;
  24154. default:
  24155. break;
  24156. }
  24157. return result;
  24158. }
  24159. float VSTPluginInstance::getParameter (int index)
  24160. {
  24161. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24162. {
  24163. try
  24164. {
  24165. const ScopedLock sl (lock);
  24166. return effect->getParameter (effect, index);
  24167. }
  24168. catch (...)
  24169. {
  24170. }
  24171. }
  24172. return 0.0f;
  24173. }
  24174. void VSTPluginInstance::setParameter (int index, float newValue)
  24175. {
  24176. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24177. {
  24178. try
  24179. {
  24180. const ScopedLock sl (lock);
  24181. if (effect->getParameter (effect, index) != newValue)
  24182. effect->setParameter (effect, index, newValue);
  24183. }
  24184. catch (...)
  24185. {
  24186. }
  24187. }
  24188. }
  24189. const String VSTPluginInstance::getParameterName (int index)
  24190. {
  24191. if (effect != 0)
  24192. {
  24193. jassert (index >= 0 && index < effect->numParams);
  24194. char nm [256];
  24195. zerostruct (nm);
  24196. dispatch (effGetParamName, index, 0, nm, 0);
  24197. return String (nm).trim();
  24198. }
  24199. return String::empty;
  24200. }
  24201. const String VSTPluginInstance::getParameterLabel (int index) const
  24202. {
  24203. if (effect != 0)
  24204. {
  24205. jassert (index >= 0 && index < effect->numParams);
  24206. char nm [256];
  24207. zerostruct (nm);
  24208. dispatch (effGetParamLabel, index, 0, nm, 0);
  24209. return String (nm).trim();
  24210. }
  24211. return String::empty;
  24212. }
  24213. const String VSTPluginInstance::getParameterText (int index)
  24214. {
  24215. if (effect != 0)
  24216. {
  24217. jassert (index >= 0 && index < effect->numParams);
  24218. char nm [256];
  24219. zerostruct (nm);
  24220. dispatch (effGetParamDisplay, index, 0, nm, 0);
  24221. return String (nm).trim();
  24222. }
  24223. return String::empty;
  24224. }
  24225. bool VSTPluginInstance::isParameterAutomatable (int index) const
  24226. {
  24227. if (effect != 0)
  24228. {
  24229. jassert (index >= 0 && index < effect->numParams);
  24230. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  24231. }
  24232. return false;
  24233. }
  24234. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  24235. {
  24236. dest.setSize (64 + 4 * getNumParameters());
  24237. dest.fillWith (0);
  24238. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  24239. float* const p = (float*) (((char*) dest.getData()) + 64);
  24240. for (int i = 0; i < getNumParameters(); ++i)
  24241. p[i] = getParameter(i);
  24242. }
  24243. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  24244. {
  24245. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  24246. float* p = (float*) (((char*) m.getData()) + 64);
  24247. for (int i = 0; i < getNumParameters(); ++i)
  24248. setParameter (i, p[i]);
  24249. }
  24250. void VSTPluginInstance::setCurrentProgram (int newIndex)
  24251. {
  24252. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  24253. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  24254. }
  24255. const String VSTPluginInstance::getProgramName (int index)
  24256. {
  24257. if (index == getCurrentProgram())
  24258. {
  24259. return getCurrentProgramName();
  24260. }
  24261. else if (effect != 0)
  24262. {
  24263. char nm [256];
  24264. zerostruct (nm);
  24265. if (dispatch (effGetProgramNameIndexed,
  24266. jlimit (0, getNumPrograms(), index),
  24267. -1, nm, 0) != 0)
  24268. {
  24269. return String (nm).trim();
  24270. }
  24271. }
  24272. return programNames [index];
  24273. }
  24274. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  24275. {
  24276. if (index == getCurrentProgram())
  24277. {
  24278. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  24279. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  24280. }
  24281. else
  24282. {
  24283. jassertfalse // xxx not implemented!
  24284. }
  24285. }
  24286. void VSTPluginInstance::updateStoredProgramNames()
  24287. {
  24288. if (effect != 0 && getNumPrograms() > 0)
  24289. {
  24290. char nm [256];
  24291. zerostruct (nm);
  24292. // only do this if the plugin can't use indexed names..
  24293. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  24294. {
  24295. const int oldProgram = getCurrentProgram();
  24296. MemoryBlock oldSettings;
  24297. createTempParameterStore (oldSettings);
  24298. for (int i = 0; i < getNumPrograms(); ++i)
  24299. {
  24300. setCurrentProgram (i);
  24301. getCurrentProgramName(); // (this updates the list)
  24302. }
  24303. setCurrentProgram (oldProgram);
  24304. restoreFromTempParameterStore (oldSettings);
  24305. }
  24306. }
  24307. }
  24308. const String VSTPluginInstance::getCurrentProgramName()
  24309. {
  24310. if (effect != 0)
  24311. {
  24312. char nm [256];
  24313. zerostruct (nm);
  24314. dispatch (effGetProgramName, 0, 0, nm, 0);
  24315. const int index = getCurrentProgram();
  24316. if (programNames[index].isEmpty())
  24317. {
  24318. while (programNames.size() < index)
  24319. programNames.add (String::empty);
  24320. programNames.set (index, String (nm).trim());
  24321. }
  24322. return String (nm).trim();
  24323. }
  24324. return String::empty;
  24325. }
  24326. const String VSTPluginInstance::getInputChannelName (const int index) const
  24327. {
  24328. if (index >= 0 && index < getNumInputChannels())
  24329. {
  24330. VstPinProperties pinProps;
  24331. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24332. return String (pinProps.label, sizeof (pinProps.label));
  24333. }
  24334. return String::empty;
  24335. }
  24336. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  24337. {
  24338. if (index < 0 || index >= getNumInputChannels())
  24339. return false;
  24340. VstPinProperties pinProps;
  24341. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24342. return (pinProps.flags & kVstPinIsStereo) != 0;
  24343. return true;
  24344. }
  24345. const String VSTPluginInstance::getOutputChannelName (const int index) const
  24346. {
  24347. if (index >= 0 && index < getNumOutputChannels())
  24348. {
  24349. VstPinProperties pinProps;
  24350. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24351. return String (pinProps.label, sizeof (pinProps.label));
  24352. }
  24353. return String::empty;
  24354. }
  24355. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  24356. {
  24357. if (index < 0 || index >= getNumOutputChannels())
  24358. return false;
  24359. VstPinProperties pinProps;
  24360. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24361. return (pinProps.flags & kVstPinIsStereo) != 0;
  24362. return true;
  24363. }
  24364. void VSTPluginInstance::setPower (const bool on)
  24365. {
  24366. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  24367. isPowerOn = on;
  24368. }
  24369. const int defaultMaxSizeMB = 64;
  24370. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  24371. {
  24372. saveToFXBFile (destData, true, defaultMaxSizeMB);
  24373. }
  24374. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24375. {
  24376. saveToFXBFile (destData, false, defaultMaxSizeMB);
  24377. }
  24378. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24379. {
  24380. loadFromFXBFile (data, sizeInBytes);
  24381. }
  24382. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24383. {
  24384. loadFromFXBFile (data, sizeInBytes);
  24385. }
  24386. VSTPluginFormat::VSTPluginFormat()
  24387. {
  24388. }
  24389. VSTPluginFormat::~VSTPluginFormat()
  24390. {
  24391. }
  24392. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24393. const File& file)
  24394. {
  24395. if (! fileMightContainThisPluginType (file))
  24396. return;
  24397. PluginDescription desc;
  24398. desc.file = file;
  24399. desc.uid = 0;
  24400. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  24401. if (instance == 0)
  24402. return;
  24403. try
  24404. {
  24405. #if JUCE_MAC
  24406. if (instance->module->resFileId != 0)
  24407. UseResFile (instance->module->resFileId);
  24408. #endif
  24409. instance->fillInPluginDescription (desc);
  24410. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  24411. if (category != kPlugCategShell)
  24412. {
  24413. // Normal plugin...
  24414. results.add (new PluginDescription (desc));
  24415. ++insideVSTCallback;
  24416. instance->dispatch (effOpen, 0, 0, 0, 0);
  24417. --insideVSTCallback;
  24418. }
  24419. else
  24420. {
  24421. // It's a shell plugin, so iterate all the subtypes...
  24422. char shellEffectName [64];
  24423. for (;;)
  24424. {
  24425. zerostruct (shellEffectName);
  24426. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  24427. if (uid == 0)
  24428. {
  24429. break;
  24430. }
  24431. else
  24432. {
  24433. desc.uid = uid;
  24434. desc.name = shellEffectName;
  24435. bool alreadyThere = false;
  24436. for (int i = results.size(); --i >= 0;)
  24437. {
  24438. PluginDescription* const d = results.getUnchecked(i);
  24439. if (d->isDuplicateOf (desc))
  24440. {
  24441. alreadyThere = true;
  24442. break;
  24443. }
  24444. }
  24445. if (! alreadyThere)
  24446. results.add (new PluginDescription (desc));
  24447. }
  24448. }
  24449. }
  24450. }
  24451. catch (...)
  24452. {
  24453. // crashed while loading...
  24454. }
  24455. deleteAndZero (instance);
  24456. }
  24457. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24458. {
  24459. VSTPluginInstance* result = 0;
  24460. if (fileMightContainThisPluginType (desc.file))
  24461. {
  24462. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  24463. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  24464. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  24465. if (module != 0)
  24466. {
  24467. shellUIDToCreate = desc.uid;
  24468. result = new VSTPluginInstance (module);
  24469. if (result->effect != 0)
  24470. {
  24471. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  24472. result->initialise();
  24473. }
  24474. else
  24475. {
  24476. deleteAndZero (result);
  24477. }
  24478. }
  24479. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  24480. }
  24481. return result;
  24482. }
  24483. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  24484. {
  24485. #if JUCE_MAC
  24486. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  24487. return true;
  24488. #if JUCE_PPC
  24489. FSRef fileRef;
  24490. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  24491. {
  24492. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  24493. if (resFileId != -1)
  24494. {
  24495. const int numEffects = Count1Resources ('aEff');
  24496. CloseResFile (resFileId);
  24497. if (numEffects > 0)
  24498. return true;
  24499. }
  24500. }
  24501. #endif
  24502. return false;
  24503. #elif JUCE_WIN32
  24504. return f.existsAsFile()
  24505. && f.hasFileExtension (T(".dll"));
  24506. #elif JUCE_LINUX
  24507. return f.existsAsFile()
  24508. && f.hasFileExtension (T(".so"));
  24509. #endif
  24510. }
  24511. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  24512. {
  24513. #if JUCE_MAC
  24514. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  24515. #elif JUCE_WIN32
  24516. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  24517. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  24518. #elif JUCE_LINUX
  24519. return FileSearchPath ("/usr/lib/vst");
  24520. #endif
  24521. }
  24522. END_JUCE_NAMESPACE
  24523. #undef log
  24524. #endif
  24525. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  24526. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  24527. BEGIN_JUCE_NAMESPACE
  24528. AudioProcessor::AudioProcessor()
  24529. : playHead (0),
  24530. activeEditor (0),
  24531. sampleRate (0),
  24532. blockSize (0),
  24533. numInputChannels (0),
  24534. numOutputChannels (0),
  24535. latencySamples (0),
  24536. suspended (false),
  24537. nonRealtime (false)
  24538. {
  24539. }
  24540. AudioProcessor::~AudioProcessor()
  24541. {
  24542. // ooh, nasty - the editor should have been deleted before the filter
  24543. // that it refers to is deleted..
  24544. jassert (activeEditor == 0);
  24545. #ifdef JUCE_DEBUG
  24546. // This will fail if you've called beginParameterChangeGesture() for one
  24547. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  24548. jassert (changingParams.countNumberOfSetBits() == 0);
  24549. #endif
  24550. }
  24551. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  24552. {
  24553. playHead = newPlayHead;
  24554. }
  24555. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  24556. {
  24557. const ScopedLock sl (listenerLock);
  24558. listeners.addIfNotAlreadyThere (newListener);
  24559. }
  24560. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  24561. {
  24562. const ScopedLock sl (listenerLock);
  24563. listeners.removeValue (listenerToRemove);
  24564. }
  24565. void AudioProcessor::setPlayConfigDetails (const int numIns,
  24566. const int numOuts,
  24567. const double sampleRate_,
  24568. const int blockSize_) throw()
  24569. {
  24570. numInputChannels = numIns;
  24571. numOutputChannels = numOuts;
  24572. sampleRate = sampleRate_;
  24573. blockSize = blockSize_;
  24574. }
  24575. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  24576. {
  24577. nonRealtime = nonRealtime_;
  24578. }
  24579. void AudioProcessor::setLatencySamples (const int newLatency)
  24580. {
  24581. if (latencySamples != newLatency)
  24582. {
  24583. latencySamples = newLatency;
  24584. updateHostDisplay();
  24585. }
  24586. }
  24587. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  24588. const float newValue)
  24589. {
  24590. setParameter (parameterIndex, newValue);
  24591. sendParamChangeMessageToListeners (parameterIndex, newValue);
  24592. }
  24593. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  24594. {
  24595. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24596. for (int i = listeners.size(); --i >= 0;)
  24597. {
  24598. listenerLock.enter();
  24599. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24600. listenerLock.exit();
  24601. if (l != 0)
  24602. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  24603. }
  24604. }
  24605. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  24606. {
  24607. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24608. #ifdef JUCE_DEBUG
  24609. // This means you've called beginParameterChangeGesture twice in succession without a matching
  24610. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  24611. jassert (! changingParams [parameterIndex]);
  24612. changingParams.setBit (parameterIndex);
  24613. #endif
  24614. for (int i = listeners.size(); --i >= 0;)
  24615. {
  24616. listenerLock.enter();
  24617. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24618. listenerLock.exit();
  24619. if (l != 0)
  24620. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  24621. }
  24622. }
  24623. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  24624. {
  24625. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24626. #ifdef JUCE_DEBUG
  24627. // This means you've called endParameterChangeGesture without having previously called
  24628. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  24629. // calls matched correctly.
  24630. jassert (changingParams [parameterIndex]);
  24631. changingParams.clearBit (parameterIndex);
  24632. #endif
  24633. for (int i = listeners.size(); --i >= 0;)
  24634. {
  24635. listenerLock.enter();
  24636. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24637. listenerLock.exit();
  24638. if (l != 0)
  24639. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  24640. }
  24641. }
  24642. void AudioProcessor::updateHostDisplay()
  24643. {
  24644. for (int i = listeners.size(); --i >= 0;)
  24645. {
  24646. listenerLock.enter();
  24647. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24648. listenerLock.exit();
  24649. if (l != 0)
  24650. l->audioProcessorChanged (this);
  24651. }
  24652. }
  24653. bool AudioProcessor::isParameterAutomatable (int /*index*/) const
  24654. {
  24655. return true;
  24656. }
  24657. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  24658. {
  24659. const ScopedLock sl (callbackLock);
  24660. suspended = shouldBeSuspended;
  24661. }
  24662. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  24663. {
  24664. const ScopedLock sl (callbackLock);
  24665. jassert (activeEditor == editor);
  24666. if (activeEditor == editor)
  24667. activeEditor = 0;
  24668. }
  24669. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  24670. {
  24671. if (activeEditor != 0)
  24672. return activeEditor;
  24673. AudioProcessorEditor* const ed = createEditor();
  24674. if (ed != 0)
  24675. {
  24676. // you must give your editor comp a size before returning it..
  24677. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  24678. const ScopedLock sl (callbackLock);
  24679. activeEditor = ed;
  24680. }
  24681. return ed;
  24682. }
  24683. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  24684. {
  24685. getStateInformation (destData);
  24686. }
  24687. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24688. {
  24689. setStateInformation (data, sizeInBytes);
  24690. }
  24691. // magic number to identify memory blocks that we've stored as XML
  24692. const uint32 magicXmlNumber = 0x21324356;
  24693. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  24694. JUCE_NAMESPACE::MemoryBlock& destData)
  24695. {
  24696. const String xmlString (xml.createDocument (String::empty, true, false));
  24697. const int stringLength = xmlString.length();
  24698. destData.setSize (stringLength + 10);
  24699. char* const d = (char*) destData.getData();
  24700. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  24701. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  24702. xmlString.copyToBuffer (d + 8, stringLength);
  24703. }
  24704. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  24705. const int sizeInBytes)
  24706. {
  24707. if (sizeInBytes > 8
  24708. && littleEndianInt ((const char*) data) == magicXmlNumber)
  24709. {
  24710. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  24711. if (stringLength > 0)
  24712. {
  24713. XmlDocument doc (String (((const char*) data) + 8,
  24714. jmin ((sizeInBytes - 8), stringLength)));
  24715. return doc.getDocumentElement();
  24716. }
  24717. }
  24718. return 0;
  24719. }
  24720. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  24721. {
  24722. }
  24723. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  24724. {
  24725. }
  24726. END_JUCE_NAMESPACE
  24727. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  24728. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  24729. BEGIN_JUCE_NAMESPACE
  24730. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  24731. : owner (owner_)
  24732. {
  24733. // the filter must be valid..
  24734. jassert (owner != 0);
  24735. }
  24736. AudioProcessorEditor::~AudioProcessorEditor()
  24737. {
  24738. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  24739. // filter for some reason..
  24740. jassert (owner->getActiveEditor() != this);
  24741. }
  24742. END_JUCE_NAMESPACE
  24743. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  24744. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  24745. BEGIN_JUCE_NAMESPACE
  24746. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  24747. AudioProcessorGraph::Node::Node (const uint32 id_,
  24748. AudioProcessor* const processor_) throw()
  24749. : id (id_),
  24750. processor (processor_),
  24751. isPrepared (false)
  24752. {
  24753. jassert (processor_ != 0);
  24754. }
  24755. AudioProcessorGraph::Node::~Node()
  24756. {
  24757. delete processor;
  24758. }
  24759. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  24760. AudioProcessorGraph* const graph)
  24761. {
  24762. if (! isPrepared)
  24763. {
  24764. isPrepared = true;
  24765. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24766. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  24767. if (ioProc != 0)
  24768. ioProc->setParentGraph (graph);
  24769. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  24770. processor->getNumOutputChannels(),
  24771. sampleRate, blockSize);
  24772. processor->prepareToPlay (sampleRate, blockSize);
  24773. }
  24774. }
  24775. void AudioProcessorGraph::Node::unprepare()
  24776. {
  24777. if (isPrepared)
  24778. {
  24779. isPrepared = false;
  24780. processor->releaseResources();
  24781. }
  24782. }
  24783. AudioProcessorGraph::AudioProcessorGraph()
  24784. : lastNodeId (0),
  24785. renderingBuffers (1, 1),
  24786. currentAudioOutputBuffer (1, 1)
  24787. {
  24788. }
  24789. AudioProcessorGraph::~AudioProcessorGraph()
  24790. {
  24791. clearRenderingSequence();
  24792. clear();
  24793. }
  24794. const String AudioProcessorGraph::getName() const
  24795. {
  24796. return "Audio Graph";
  24797. }
  24798. void AudioProcessorGraph::clear()
  24799. {
  24800. nodes.clear();
  24801. connections.clear();
  24802. triggerAsyncUpdate();
  24803. }
  24804. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  24805. {
  24806. for (int i = nodes.size(); --i >= 0;)
  24807. if (nodes.getUnchecked(i)->id == nodeId)
  24808. return nodes.getUnchecked(i);
  24809. return 0;
  24810. }
  24811. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  24812. uint32 nodeId)
  24813. {
  24814. if (newProcessor == 0)
  24815. {
  24816. jassertfalse
  24817. return 0;
  24818. }
  24819. if (nodeId == 0)
  24820. {
  24821. nodeId = ++lastNodeId;
  24822. }
  24823. else
  24824. {
  24825. // you can't add a node with an id that already exists in the graph..
  24826. jassert (getNodeForId (nodeId) == 0);
  24827. removeNode (nodeId);
  24828. }
  24829. lastNodeId = nodeId;
  24830. Node* const n = new Node (nodeId, newProcessor);
  24831. nodes.add (n);
  24832. triggerAsyncUpdate();
  24833. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24834. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  24835. if (ioProc != 0)
  24836. ioProc->setParentGraph (this);
  24837. return n;
  24838. }
  24839. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  24840. {
  24841. disconnectNode (nodeId);
  24842. for (int i = nodes.size(); --i >= 0;)
  24843. {
  24844. if (nodes.getUnchecked(i)->id == nodeId)
  24845. {
  24846. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24847. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  24848. if (ioProc != 0)
  24849. ioProc->setParentGraph (0);
  24850. nodes.remove (i);
  24851. triggerAsyncUpdate();
  24852. return true;
  24853. }
  24854. }
  24855. return false;
  24856. }
  24857. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  24858. const int sourceChannelIndex,
  24859. const uint32 destNodeId,
  24860. const int destChannelIndex) const throw()
  24861. {
  24862. for (int i = connections.size(); --i >= 0;)
  24863. {
  24864. const Connection* const c = connections.getUnchecked(i);
  24865. if (c->sourceNodeId == sourceNodeId
  24866. && c->destNodeId == destNodeId
  24867. && c->sourceChannelIndex == sourceChannelIndex
  24868. && c->destChannelIndex == destChannelIndex)
  24869. {
  24870. return c;
  24871. }
  24872. }
  24873. return 0;
  24874. }
  24875. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  24876. const uint32 possibleDestNodeId) const throw()
  24877. {
  24878. for (int i = connections.size(); --i >= 0;)
  24879. {
  24880. const Connection* const c = connections.getUnchecked(i);
  24881. if (c->sourceNodeId == possibleSourceNodeId
  24882. && c->destNodeId == possibleDestNodeId)
  24883. {
  24884. return true;
  24885. }
  24886. }
  24887. return false;
  24888. }
  24889. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  24890. const int sourceChannelIndex,
  24891. const uint32 destNodeId,
  24892. const int destChannelIndex) const throw()
  24893. {
  24894. if (sourceChannelIndex < 0
  24895. || destChannelIndex < 0
  24896. || sourceNodeId == destNodeId
  24897. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  24898. return false;
  24899. const Node* const source = getNodeForId (sourceNodeId);
  24900. if (source == 0
  24901. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  24902. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  24903. return false;
  24904. const Node* const dest = getNodeForId (destNodeId);
  24905. if (dest == 0
  24906. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  24907. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  24908. return false;
  24909. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  24910. destNodeId, destChannelIndex) == 0;
  24911. }
  24912. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  24913. const int sourceChannelIndex,
  24914. const uint32 destNodeId,
  24915. const int destChannelIndex)
  24916. {
  24917. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  24918. return false;
  24919. Connection* const c = new Connection();
  24920. c->sourceNodeId = sourceNodeId;
  24921. c->sourceChannelIndex = sourceChannelIndex;
  24922. c->destNodeId = destNodeId;
  24923. c->destChannelIndex = destChannelIndex;
  24924. connections.add (c);
  24925. triggerAsyncUpdate();
  24926. return true;
  24927. }
  24928. void AudioProcessorGraph::removeConnection (const int index)
  24929. {
  24930. connections.remove (index);
  24931. triggerAsyncUpdate();
  24932. }
  24933. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  24934. const uint32 destNodeId, const int destChannelIndex)
  24935. {
  24936. bool doneAnything = false;
  24937. for (int i = connections.size(); --i >= 0;)
  24938. {
  24939. const Connection* const c = connections.getUnchecked(i);
  24940. if (c->sourceNodeId == sourceNodeId
  24941. && c->destNodeId == destNodeId
  24942. && c->sourceChannelIndex == sourceChannelIndex
  24943. && c->destChannelIndex == destChannelIndex)
  24944. {
  24945. removeConnection (i);
  24946. doneAnything = true;
  24947. triggerAsyncUpdate();
  24948. }
  24949. }
  24950. return doneAnything;
  24951. }
  24952. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  24953. {
  24954. bool doneAnything = false;
  24955. for (int i = connections.size(); --i >= 0;)
  24956. {
  24957. const Connection* const c = connections.getUnchecked(i);
  24958. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  24959. {
  24960. removeConnection (i);
  24961. doneAnything = true;
  24962. triggerAsyncUpdate();
  24963. }
  24964. }
  24965. return doneAnything;
  24966. }
  24967. bool AudioProcessorGraph::removeIllegalConnections()
  24968. {
  24969. bool doneAnything = false;
  24970. for (int i = connections.size(); --i >= 0;)
  24971. {
  24972. const Connection* const c = connections.getUnchecked(i);
  24973. const Node* const source = getNodeForId (c->sourceNodeId);
  24974. const Node* const dest = getNodeForId (c->destNodeId);
  24975. if (source == 0 || dest == 0
  24976. || (c->sourceChannelIndex != midiChannelIndex
  24977. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  24978. || (c->sourceChannelIndex == midiChannelIndex
  24979. && ! source->processor->producesMidi())
  24980. || (c->destChannelIndex != midiChannelIndex
  24981. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  24982. || (c->destChannelIndex == midiChannelIndex
  24983. && ! dest->processor->acceptsMidi()))
  24984. {
  24985. removeConnection (i);
  24986. doneAnything = true;
  24987. triggerAsyncUpdate();
  24988. }
  24989. }
  24990. return doneAnything;
  24991. }
  24992. namespace GraphRenderingOps
  24993. {
  24994. class AudioGraphRenderingOp
  24995. {
  24996. public:
  24997. AudioGraphRenderingOp() throw() {}
  24998. virtual ~AudioGraphRenderingOp() throw() {}
  24999. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  25000. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  25001. const int numSamples) throw() = 0;
  25002. juce_UseDebuggingNewOperator
  25003. };
  25004. class ClearChannelOp : public AudioGraphRenderingOp
  25005. {
  25006. public:
  25007. ClearChannelOp (const int channelNum_) throw()
  25008. : channelNum (channelNum_)
  25009. {}
  25010. ~ClearChannelOp() throw() {}
  25011. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25012. {
  25013. sharedBufferChans.clear (channelNum, 0, numSamples);
  25014. }
  25015. private:
  25016. const int channelNum;
  25017. ClearChannelOp (const ClearChannelOp&);
  25018. const ClearChannelOp& operator= (const ClearChannelOp&);
  25019. };
  25020. class CopyChannelOp : public AudioGraphRenderingOp
  25021. {
  25022. public:
  25023. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25024. : srcChannelNum (srcChannelNum_),
  25025. dstChannelNum (dstChannelNum_)
  25026. {}
  25027. ~CopyChannelOp() throw() {}
  25028. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25029. {
  25030. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25031. }
  25032. private:
  25033. const int srcChannelNum, dstChannelNum;
  25034. CopyChannelOp (const CopyChannelOp&);
  25035. const CopyChannelOp& operator= (const CopyChannelOp&);
  25036. };
  25037. class AddChannelOp : public AudioGraphRenderingOp
  25038. {
  25039. public:
  25040. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25041. : srcChannelNum (srcChannelNum_),
  25042. dstChannelNum (dstChannelNum_)
  25043. {}
  25044. ~AddChannelOp() throw() {}
  25045. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25046. {
  25047. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25048. }
  25049. private:
  25050. const int srcChannelNum, dstChannelNum;
  25051. AddChannelOp (const AddChannelOp&);
  25052. const AddChannelOp& operator= (const AddChannelOp&);
  25053. };
  25054. class ClearMidiBufferOp : public AudioGraphRenderingOp
  25055. {
  25056. public:
  25057. ClearMidiBufferOp (const int bufferNum_) throw()
  25058. : bufferNum (bufferNum_)
  25059. {}
  25060. ~ClearMidiBufferOp() throw() {}
  25061. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25062. {
  25063. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  25064. }
  25065. private:
  25066. const int bufferNum;
  25067. ClearMidiBufferOp (const ClearMidiBufferOp&);
  25068. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  25069. };
  25070. class CopyMidiBufferOp : public AudioGraphRenderingOp
  25071. {
  25072. public:
  25073. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25074. : srcBufferNum (srcBufferNum_),
  25075. dstBufferNum (dstBufferNum_)
  25076. {}
  25077. ~CopyMidiBufferOp() throw() {}
  25078. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25079. {
  25080. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  25081. }
  25082. private:
  25083. const int srcBufferNum, dstBufferNum;
  25084. CopyMidiBufferOp (const CopyMidiBufferOp&);
  25085. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  25086. };
  25087. class AddMidiBufferOp : public AudioGraphRenderingOp
  25088. {
  25089. public:
  25090. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25091. : srcBufferNum (srcBufferNum_),
  25092. dstBufferNum (dstBufferNum_)
  25093. {}
  25094. ~AddMidiBufferOp() throw() {}
  25095. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25096. {
  25097. sharedMidiBuffers.getUnchecked (dstBufferNum)
  25098. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  25099. }
  25100. private:
  25101. const int srcBufferNum, dstBufferNum;
  25102. AddMidiBufferOp (const AddMidiBufferOp&);
  25103. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  25104. };
  25105. class ProcessBufferOp : public AudioGraphRenderingOp
  25106. {
  25107. public:
  25108. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  25109. const Array <int>& audioChannelsToUse_,
  25110. const int totalChans_,
  25111. const int midiBufferToUse_) throw()
  25112. : node (node_),
  25113. processor (node_->processor),
  25114. audioChannelsToUse (audioChannelsToUse_),
  25115. totalChans (totalChans_),
  25116. midiBufferToUse (midiBufferToUse_)
  25117. {
  25118. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  25119. }
  25120. ~ProcessBufferOp() throw()
  25121. {
  25122. juce_free (channels);
  25123. }
  25124. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25125. {
  25126. for (int i = totalChans; --i >= 0;)
  25127. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  25128. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  25129. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  25130. }
  25131. const AudioProcessorGraph::Node::Ptr node;
  25132. AudioProcessor* const processor;
  25133. private:
  25134. Array <int> audioChannelsToUse;
  25135. float** channels;
  25136. int totalChans;
  25137. int midiBufferToUse;
  25138. ProcessBufferOp (const ProcessBufferOp&);
  25139. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  25140. };
  25141. /** Used to calculate the correct sequence of rendering ops needed, based on
  25142. the best re-use of shared buffers at each stage.
  25143. */
  25144. class RenderingOpSequenceCalculator
  25145. {
  25146. public:
  25147. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  25148. const VoidArray& orderedNodes_,
  25149. VoidArray& renderingOps)
  25150. : graph (graph_),
  25151. orderedNodes (orderedNodes_)
  25152. {
  25153. nodeIds.add (-2); // first buffer is read-only zeros
  25154. channels.add (0);
  25155. midiNodeIds.add (-2);
  25156. for (int i = 0; i < orderedNodes.size(); ++i)
  25157. {
  25158. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  25159. renderingOps, i);
  25160. markAnyUnusedBuffersAsFree (i);
  25161. }
  25162. }
  25163. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  25164. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  25165. juce_UseDebuggingNewOperator
  25166. private:
  25167. AudioProcessorGraph& graph;
  25168. const VoidArray& orderedNodes;
  25169. Array <int> nodeIds, channels, midiNodeIds;
  25170. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  25171. VoidArray& renderingOps,
  25172. const int ourRenderingIndex)
  25173. {
  25174. const int numIns = node->processor->getNumInputChannels();
  25175. const int numOuts = node->processor->getNumOutputChannels();
  25176. const int totalChans = jmax (numIns, numOuts);
  25177. Array <int> audioChannelsToUse;
  25178. int midiBufferToUse = -1;
  25179. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  25180. {
  25181. // get a list of all the inputs to this node
  25182. Array <int> sourceNodes, sourceOutputChans;
  25183. for (int i = graph.getNumConnections(); --i >= 0;)
  25184. {
  25185. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25186. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  25187. {
  25188. sourceNodes.add (c->sourceNodeId);
  25189. sourceOutputChans.add (c->sourceChannelIndex);
  25190. }
  25191. }
  25192. int bufIndex = -1;
  25193. if (sourceNodes.size() == 0)
  25194. {
  25195. // unconnected input channel
  25196. if (inputChan >= numOuts)
  25197. {
  25198. bufIndex = getReadOnlyEmptyBuffer();
  25199. jassert (bufIndex >= 0);
  25200. }
  25201. else
  25202. {
  25203. bufIndex = getFreeBuffer (false);
  25204. renderingOps.add (new ClearChannelOp (bufIndex));
  25205. }
  25206. }
  25207. else if (sourceNodes.size() == 1)
  25208. {
  25209. // channel with a straightforward single input..
  25210. const int srcNode = sourceNodes.getUnchecked(0);
  25211. const int srcChan = sourceOutputChans.getUnchecked(0);
  25212. bufIndex = getBufferContaining (srcNode, srcChan);
  25213. if (bufIndex < 0)
  25214. {
  25215. // if not found, this is probably a feedback loop
  25216. bufIndex = getReadOnlyEmptyBuffer();
  25217. jassert (bufIndex >= 0);
  25218. }
  25219. if (inputChan < numOuts
  25220. && isBufferNeededLater (ourRenderingIndex,
  25221. inputChan,
  25222. srcNode, srcChan))
  25223. {
  25224. // can't mess up this channel because it's needed later by another node, so we
  25225. // need to use a copy of it..
  25226. const int newFreeBuffer = getFreeBuffer (false);
  25227. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  25228. bufIndex = newFreeBuffer;
  25229. }
  25230. }
  25231. else
  25232. {
  25233. // channel with a mix of several inputs..
  25234. // try to find a re-usable channel from our inputs..
  25235. int reusableInputIndex = -1;
  25236. for (int i = 0; i < sourceNodes.size(); ++i)
  25237. {
  25238. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  25239. sourceOutputChans.getUnchecked(i));
  25240. if (sourceBufIndex >= 0
  25241. && ! isBufferNeededLater (ourRenderingIndex,
  25242. inputChan,
  25243. sourceNodes.getUnchecked(i),
  25244. sourceOutputChans.getUnchecked(i)))
  25245. {
  25246. // we've found one of our input chans that can be re-used..
  25247. reusableInputIndex = i;
  25248. bufIndex = sourceBufIndex;
  25249. break;
  25250. }
  25251. }
  25252. if (reusableInputIndex < 0)
  25253. {
  25254. // can't re-use any of our input chans, so get a new one and copy everything into it..
  25255. bufIndex = getFreeBuffer (false);
  25256. jassert (bufIndex != 0);
  25257. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  25258. sourceOutputChans.getUnchecked (0));
  25259. if (srcIndex < 0)
  25260. {
  25261. // if not found, this is probably a feedback loop
  25262. renderingOps.add (new ClearChannelOp (bufIndex));
  25263. }
  25264. else
  25265. {
  25266. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  25267. }
  25268. reusableInputIndex = 0;
  25269. }
  25270. for (int j = 0; j < sourceNodes.size(); ++j)
  25271. {
  25272. if (j != reusableInputIndex)
  25273. {
  25274. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  25275. sourceOutputChans.getUnchecked(j));
  25276. if (srcIndex >= 0)
  25277. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  25278. }
  25279. }
  25280. }
  25281. jassert (bufIndex >= 0);
  25282. audioChannelsToUse.add (bufIndex);
  25283. if (inputChan < numOuts)
  25284. markBufferAsContaining (bufIndex, node->id, inputChan);
  25285. }
  25286. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  25287. {
  25288. const int bufIndex = getFreeBuffer (false);
  25289. jassert (bufIndex != 0);
  25290. audioChannelsToUse.add (bufIndex);
  25291. markBufferAsContaining (bufIndex, node->id, outputChan);
  25292. }
  25293. // Now the same thing for midi..
  25294. Array <int> midiSourceNodes;
  25295. for (int i = graph.getNumConnections(); --i >= 0;)
  25296. {
  25297. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25298. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  25299. midiSourceNodes.add (c->sourceNodeId);
  25300. }
  25301. if (midiSourceNodes.size() == 0)
  25302. {
  25303. // No midi inputs..
  25304. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25305. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  25306. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25307. }
  25308. else if (midiSourceNodes.size() == 1)
  25309. {
  25310. // One midi input..
  25311. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25312. AudioProcessorGraph::midiChannelIndex);
  25313. if (midiBufferToUse >= 0)
  25314. {
  25315. if (isBufferNeededLater (ourRenderingIndex,
  25316. AudioProcessorGraph::midiChannelIndex,
  25317. midiSourceNodes.getUnchecked(0),
  25318. AudioProcessorGraph::midiChannelIndex))
  25319. {
  25320. // can't mess up this channel because it's needed later by another node, so we
  25321. // need to use a copy of it..
  25322. const int newFreeBuffer = getFreeBuffer (true);
  25323. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  25324. midiBufferToUse = newFreeBuffer;
  25325. }
  25326. }
  25327. else
  25328. {
  25329. // probably a feedback loop, so just use an empty one..
  25330. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25331. }
  25332. }
  25333. else
  25334. {
  25335. // More than one midi input being mixed..
  25336. int reusableInputIndex = -1;
  25337. for (int i = 0; i < midiSourceNodes.size(); ++i)
  25338. {
  25339. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  25340. AudioProcessorGraph::midiChannelIndex);
  25341. if (sourceBufIndex >= 0
  25342. && ! isBufferNeededLater (ourRenderingIndex,
  25343. AudioProcessorGraph::midiChannelIndex,
  25344. midiSourceNodes.getUnchecked(i),
  25345. AudioProcessorGraph::midiChannelIndex))
  25346. {
  25347. // we've found one of our input buffers that can be re-used..
  25348. reusableInputIndex = i;
  25349. midiBufferToUse = sourceBufIndex;
  25350. break;
  25351. }
  25352. }
  25353. if (reusableInputIndex < 0)
  25354. {
  25355. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  25356. midiBufferToUse = getFreeBuffer (true);
  25357. jassert (midiBufferToUse >= 0);
  25358. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25359. AudioProcessorGraph::midiChannelIndex);
  25360. if (srcIndex >= 0)
  25361. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  25362. else
  25363. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25364. reusableInputIndex = 0;
  25365. }
  25366. for (int j = 0; j < midiSourceNodes.size(); ++j)
  25367. {
  25368. if (j != reusableInputIndex)
  25369. {
  25370. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  25371. AudioProcessorGraph::midiChannelIndex);
  25372. if (srcIndex >= 0)
  25373. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  25374. }
  25375. }
  25376. }
  25377. if (node->processor->producesMidi())
  25378. markBufferAsContaining (midiBufferToUse, node->id,
  25379. AudioProcessorGraph::midiChannelIndex);
  25380. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  25381. totalChans, midiBufferToUse));
  25382. }
  25383. int getFreeBuffer (const bool forMidi)
  25384. {
  25385. if (forMidi)
  25386. {
  25387. for (int i = 1; i < midiNodeIds.size(); ++i)
  25388. if (midiNodeIds.getUnchecked(i) < 0)
  25389. return i;
  25390. midiNodeIds.add (-1);
  25391. return midiNodeIds.size() - 1;
  25392. }
  25393. else
  25394. {
  25395. for (int i = 1; i < nodeIds.size(); ++i)
  25396. if (nodeIds.getUnchecked(i) < 0)
  25397. return i;
  25398. nodeIds.add (-1);
  25399. channels.add (0);
  25400. return nodeIds.size() - 1;
  25401. }
  25402. }
  25403. int getReadOnlyEmptyBuffer() const throw()
  25404. {
  25405. return 0;
  25406. }
  25407. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  25408. {
  25409. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  25410. {
  25411. for (int i = midiNodeIds.size(); --i >= 0;)
  25412. if (midiNodeIds.getUnchecked(i) == nodeId)
  25413. return i;
  25414. }
  25415. else
  25416. {
  25417. for (int i = nodeIds.size(); --i >= 0;)
  25418. if (nodeIds.getUnchecked(i) == nodeId
  25419. && channels.getUnchecked(i) == outputChannel)
  25420. return i;
  25421. }
  25422. return -1;
  25423. }
  25424. void markAnyUnusedBuffersAsFree (const int stepIndex)
  25425. {
  25426. int i;
  25427. for (i = 0; i < nodeIds.size(); ++i)
  25428. {
  25429. if (nodeIds.getUnchecked(i) >= 0
  25430. && ! isBufferNeededLater (stepIndex, -1,
  25431. nodeIds.getUnchecked(i),
  25432. channels.getUnchecked(i)))
  25433. {
  25434. nodeIds.set (i, -1);
  25435. }
  25436. }
  25437. for (i = 0; i < midiNodeIds.size(); ++i)
  25438. {
  25439. if (midiNodeIds.getUnchecked(i) >= 0
  25440. && ! isBufferNeededLater (stepIndex, -1,
  25441. midiNodeIds.getUnchecked(i),
  25442. AudioProcessorGraph::midiChannelIndex))
  25443. {
  25444. midiNodeIds.set (i, -1);
  25445. }
  25446. }
  25447. }
  25448. bool isBufferNeededLater (int stepIndexToSearchFrom,
  25449. int inputChannelOfIndexToIgnore,
  25450. const int nodeId,
  25451. const int outputChanIndex) const throw()
  25452. {
  25453. while (stepIndexToSearchFrom < orderedNodes.size())
  25454. {
  25455. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  25456. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  25457. {
  25458. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  25459. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  25460. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  25461. return true;
  25462. }
  25463. else
  25464. {
  25465. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  25466. if (i != inputChannelOfIndexToIgnore
  25467. && graph.getConnectionBetween (nodeId, outputChanIndex,
  25468. node->id, i) != 0)
  25469. return true;
  25470. }
  25471. inputChannelOfIndexToIgnore = -1;
  25472. ++stepIndexToSearchFrom;
  25473. }
  25474. return false;
  25475. }
  25476. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  25477. {
  25478. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  25479. {
  25480. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  25481. midiNodeIds.set (bufferNum, nodeId);
  25482. }
  25483. else
  25484. {
  25485. jassert (bufferNum > 0 && bufferNum < nodeIds.size());
  25486. nodeIds.set (bufferNum, nodeId);
  25487. channels.set (bufferNum, outputIndex);
  25488. }
  25489. }
  25490. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  25491. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  25492. };
  25493. }
  25494. void AudioProcessorGraph::clearRenderingSequence()
  25495. {
  25496. const ScopedLock sl (renderLock);
  25497. for (int i = renderingOps.size(); --i >= 0;)
  25498. {
  25499. GraphRenderingOps::AudioGraphRenderingOp* const r
  25500. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25501. renderingOps.remove (i);
  25502. delete r;
  25503. }
  25504. }
  25505. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  25506. const uint32 possibleDestinationId,
  25507. const int recursionCheck) const throw()
  25508. {
  25509. if (recursionCheck > 0)
  25510. {
  25511. for (int i = connections.size(); --i >= 0;)
  25512. {
  25513. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  25514. if (c->destNodeId == possibleDestinationId
  25515. && (c->sourceNodeId == possibleInputId
  25516. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  25517. return true;
  25518. }
  25519. }
  25520. return false;
  25521. }
  25522. void AudioProcessorGraph::buildRenderingSequence()
  25523. {
  25524. VoidArray newRenderingOps;
  25525. int numRenderingBuffersNeeded = 2;
  25526. int numMidiBuffersNeeded = 1;
  25527. {
  25528. MessageManagerLock mml;
  25529. VoidArray orderedNodes;
  25530. int i;
  25531. for (i = 0; i < nodes.size(); ++i)
  25532. {
  25533. Node* const node = nodes.getUnchecked(i);
  25534. node->prepare (getSampleRate(), getBlockSize(), this);
  25535. int j = 0;
  25536. for (; j < orderedNodes.size(); ++j)
  25537. if (isAnInputTo (node->id,
  25538. ((Node*) orderedNodes.getUnchecked (j))->id,
  25539. nodes.size() + 1))
  25540. break;
  25541. orderedNodes.insert (j, node);
  25542. }
  25543. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  25544. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  25545. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  25546. }
  25547. VoidArray oldRenderingOps (renderingOps);
  25548. {
  25549. // swap over to the new set of rendering sequence..
  25550. const ScopedLock sl (renderLock);
  25551. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  25552. renderingBuffers.clear();
  25553. for (int i = midiBuffers.size(); --i >= 0;)
  25554. midiBuffers.getUnchecked(i)->clear();
  25555. while (midiBuffers.size() < numMidiBuffersNeeded)
  25556. midiBuffers.add (new MidiBuffer());
  25557. renderingOps = newRenderingOps;
  25558. }
  25559. for (int i = oldRenderingOps.size(); --i >= 0;)
  25560. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  25561. }
  25562. void AudioProcessorGraph::handleAsyncUpdate()
  25563. {
  25564. buildRenderingSequence();
  25565. }
  25566. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  25567. {
  25568. currentAudioInputBuffer = 0;
  25569. currentAudioOutputBuffer.setSize (getNumOutputChannels(), estimatedSamplesPerBlock);
  25570. currentMidiInputBuffer = 0;
  25571. currentMidiOutputBuffer.clear();
  25572. clearRenderingSequence();
  25573. buildRenderingSequence();
  25574. }
  25575. void AudioProcessorGraph::releaseResources()
  25576. {
  25577. for (int i = 0; i < nodes.size(); ++i)
  25578. nodes.getUnchecked(i)->unprepare();
  25579. renderingBuffers.setSize (1, 1);
  25580. midiBuffers.clear();
  25581. currentAudioInputBuffer = 0;
  25582. currentAudioOutputBuffer.setSize (1, 1);
  25583. currentMidiInputBuffer = 0;
  25584. currentMidiOutputBuffer.clear();
  25585. }
  25586. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  25587. {
  25588. const int numSamples = buffer.getNumSamples();
  25589. const ScopedLock sl (renderLock);
  25590. currentAudioInputBuffer = &buffer;
  25591. currentAudioOutputBuffer.setSize (buffer.getNumChannels(), numSamples);
  25592. currentAudioOutputBuffer.clear();
  25593. currentMidiInputBuffer = &midiMessages;
  25594. currentMidiOutputBuffer.clear();
  25595. for (int i = 0; i < renderingOps.size(); ++i)
  25596. {
  25597. GraphRenderingOps::AudioGraphRenderingOp* const op
  25598. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25599. op->perform (renderingBuffers, midiBuffers, numSamples);
  25600. }
  25601. for (int i = 0; i < buffer.getNumChannels(); ++i)
  25602. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  25603. }
  25604. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  25605. {
  25606. return "Input " + String (channelIndex + 1);
  25607. }
  25608. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  25609. {
  25610. return "Output " + String (channelIndex + 1);
  25611. }
  25612. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  25613. {
  25614. return true;
  25615. }
  25616. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  25617. {
  25618. return true;
  25619. }
  25620. bool AudioProcessorGraph::acceptsMidi() const
  25621. {
  25622. return true;
  25623. }
  25624. bool AudioProcessorGraph::producesMidi() const
  25625. {
  25626. return true;
  25627. }
  25628. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  25629. {
  25630. }
  25631. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  25632. {
  25633. }
  25634. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  25635. : type (type_),
  25636. graph (0)
  25637. {
  25638. }
  25639. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  25640. {
  25641. }
  25642. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  25643. {
  25644. switch (type)
  25645. {
  25646. case audioOutputNode:
  25647. return "Audio Output";
  25648. case audioInputNode:
  25649. return "Audio Input";
  25650. case midiOutputNode:
  25651. return "Midi Output";
  25652. case midiInputNode:
  25653. return "Midi Input";
  25654. default:
  25655. break;
  25656. }
  25657. return String::empty;
  25658. }
  25659. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  25660. {
  25661. d.name = getName();
  25662. d.uid = d.name.hashCode();
  25663. d.category = "I/O devices";
  25664. d.pluginFormatName = "Internal";
  25665. d.manufacturerName = "Raw Material Software";
  25666. d.version = "1.0";
  25667. d.isInstrument = false;
  25668. d.numInputChannels = getNumInputChannels();
  25669. if (type == audioOutputNode && graph != 0)
  25670. d.numInputChannels = graph->getNumInputChannels();
  25671. d.numOutputChannels = getNumOutputChannels();
  25672. if (type == audioInputNode && graph != 0)
  25673. d.numOutputChannels = graph->getNumOutputChannels();
  25674. }
  25675. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  25676. {
  25677. jassert (graph != 0);
  25678. }
  25679. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  25680. {
  25681. }
  25682. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  25683. MidiBuffer& midiMessages)
  25684. {
  25685. jassert (graph != 0);
  25686. switch (type)
  25687. {
  25688. case audioOutputNode:
  25689. {
  25690. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  25691. buffer.getNumChannels()); --i >= 0;)
  25692. {
  25693. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  25694. }
  25695. break;
  25696. }
  25697. case audioInputNode:
  25698. {
  25699. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  25700. buffer.getNumChannels()); --i >= 0;)
  25701. {
  25702. buffer.addFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  25703. }
  25704. break;
  25705. }
  25706. case midiOutputNode:
  25707. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  25708. break;
  25709. case midiInputNode:
  25710. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  25711. break;
  25712. default:
  25713. break;
  25714. }
  25715. }
  25716. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  25717. {
  25718. return type == midiOutputNode;
  25719. }
  25720. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  25721. {
  25722. return type == midiInputNode;
  25723. }
  25724. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  25725. {
  25726. switch (type)
  25727. {
  25728. case audioOutputNode:
  25729. return "Output " + String (channelIndex + 1);
  25730. case midiOutputNode:
  25731. return "Midi Output";
  25732. default:
  25733. break;
  25734. }
  25735. return String::empty;
  25736. }
  25737. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  25738. {
  25739. switch (type)
  25740. {
  25741. case audioInputNode:
  25742. return "Input " + String (channelIndex + 1);
  25743. case midiInputNode:
  25744. return "Midi Input";
  25745. default:
  25746. break;
  25747. }
  25748. return String::empty;
  25749. }
  25750. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  25751. {
  25752. return type == audioInputNode || type == audioOutputNode;
  25753. }
  25754. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  25755. {
  25756. return isInputChannelStereoPair (index);
  25757. }
  25758. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  25759. {
  25760. return type == audioInputNode || type == midiInputNode;
  25761. }
  25762. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  25763. {
  25764. return type == audioOutputNode || type == midiOutputNode;
  25765. }
  25766. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  25767. {
  25768. return 0;
  25769. }
  25770. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  25771. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  25772. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  25773. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  25774. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  25775. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  25776. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  25777. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  25778. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  25779. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  25780. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  25781. {
  25782. }
  25783. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  25784. {
  25785. }
  25786. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  25787. {
  25788. graph = newGraph;
  25789. if (graph != 0)
  25790. {
  25791. setPlayConfigDetails (type == audioOutputNode ? graph->getNumInputChannels() : 0,
  25792. type == audioInputNode ? graph->getNumOutputChannels() : 0,
  25793. getSampleRate(),
  25794. getBlockSize());
  25795. updateHostDisplay();
  25796. }
  25797. }
  25798. END_JUCE_NAMESPACE
  25799. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  25800. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  25801. BEGIN_JUCE_NAMESPACE
  25802. AudioProcessorPlayer::AudioProcessorPlayer()
  25803. : processor (0),
  25804. sampleRate (0),
  25805. blockSize (0),
  25806. isPrepared (false),
  25807. numInputChans (0),
  25808. numOutputChans (0),
  25809. tempBuffer (1, 1)
  25810. {
  25811. }
  25812. AudioProcessorPlayer::~AudioProcessorPlayer()
  25813. {
  25814. setProcessor (0);
  25815. }
  25816. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  25817. {
  25818. if (processor != processorToPlay)
  25819. {
  25820. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  25821. {
  25822. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  25823. sampleRate, blockSize);
  25824. processorToPlay->prepareToPlay (sampleRate, blockSize);
  25825. }
  25826. lock.enter();
  25827. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  25828. processor = processorToPlay;
  25829. isPrepared = true;
  25830. lock.exit();
  25831. if (oldOne != 0)
  25832. oldOne->releaseResources();
  25833. }
  25834. }
  25835. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  25836. int totalNumInputChannels,
  25837. float** outputChannelData,
  25838. int totalNumOutputChannels,
  25839. int numSamples)
  25840. {
  25841. // these should have been prepared by audioDeviceAboutToStart()...
  25842. jassert (sampleRate > 0 && blockSize > 0);
  25843. incomingMidi.clear();
  25844. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  25845. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  25846. // messy stuff needed to compact the channels down into an array
  25847. // of non-zero pointers..
  25848. for (i = 0; i < totalNumInputChannels; ++i)
  25849. {
  25850. if (inputChannelData[i] != 0)
  25851. {
  25852. inputChans [numInputs++] = inputChannelData[i];
  25853. if (numInputs >= numElementsInArray (inputChans))
  25854. break;
  25855. }
  25856. }
  25857. for (i = 0; i < totalNumOutputChannels; ++i)
  25858. {
  25859. if (outputChannelData[i] != 0)
  25860. {
  25861. outputChans [numOutputs++] = outputChannelData[i];
  25862. if (numOutputs >= numElementsInArray (outputChans))
  25863. break;
  25864. }
  25865. }
  25866. if (numInputs > numOutputs)
  25867. {
  25868. // if there aren't enough output channels for the number of
  25869. // inputs, we need to create some temporary extra ones (can't
  25870. // use the input data in case it gets written to)
  25871. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  25872. false, false, true);
  25873. for (i = 0; i < numOutputs; ++i)
  25874. {
  25875. channels[numActiveChans] = outputChans[i];
  25876. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25877. ++numActiveChans;
  25878. }
  25879. for (i = numOutputs; i < numInputs; ++i)
  25880. {
  25881. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  25882. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25883. ++numActiveChans;
  25884. }
  25885. }
  25886. else
  25887. {
  25888. for (i = 0; i < numInputs; ++i)
  25889. {
  25890. channels[numActiveChans] = outputChans[i];
  25891. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25892. ++numActiveChans;
  25893. }
  25894. for (i = numInputs; i < numOutputs; ++i)
  25895. {
  25896. channels[numActiveChans] = outputChans[i];
  25897. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  25898. ++numActiveChans;
  25899. }
  25900. }
  25901. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  25902. const ScopedLock sl (lock);
  25903. if (processor != 0)
  25904. processor->processBlock (buffer, incomingMidi);
  25905. }
  25906. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  25907. {
  25908. const ScopedLock sl (lock);
  25909. sampleRate = device->getCurrentSampleRate();
  25910. blockSize = device->getCurrentBufferSizeSamples();
  25911. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  25912. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  25913. messageCollector.reset (sampleRate);
  25914. zeromem (channels, sizeof (channels));
  25915. if (processor != 0)
  25916. {
  25917. if (isPrepared)
  25918. processor->releaseResources();
  25919. AudioProcessor* const oldProcessor = processor;
  25920. setProcessor (0);
  25921. setProcessor (oldProcessor);
  25922. }
  25923. }
  25924. void AudioProcessorPlayer::audioDeviceStopped()
  25925. {
  25926. const ScopedLock sl (lock);
  25927. if (processor != 0 && isPrepared)
  25928. processor->releaseResources();
  25929. sampleRate = 0.0;
  25930. blockSize = 0;
  25931. isPrepared = false;
  25932. tempBuffer.setSize (1, 1);
  25933. }
  25934. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  25935. {
  25936. messageCollector.addMessageToQueue (message);
  25937. }
  25938. END_JUCE_NAMESPACE
  25939. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  25940. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  25941. BEGIN_JUCE_NAMESPACE
  25942. class ProcessorParameterPropertyComp : public PropertyComponent,
  25943. public AudioProcessorListener,
  25944. public AsyncUpdater
  25945. {
  25946. public:
  25947. ProcessorParameterPropertyComp (const String& name,
  25948. AudioProcessor* const owner_,
  25949. const int index_)
  25950. : PropertyComponent (name),
  25951. owner (owner_),
  25952. index (index_)
  25953. {
  25954. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  25955. owner_->addListener (this);
  25956. }
  25957. ~ProcessorParameterPropertyComp()
  25958. {
  25959. owner->removeListener (this);
  25960. deleteAllChildren();
  25961. }
  25962. void refresh()
  25963. {
  25964. slider->setValue (owner->getParameter (index), false);
  25965. }
  25966. void audioProcessorChanged (AudioProcessor*) {}
  25967. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  25968. {
  25969. if (parameterIndex == index)
  25970. triggerAsyncUpdate();
  25971. }
  25972. void handleAsyncUpdate()
  25973. {
  25974. refresh();
  25975. }
  25976. juce_UseDebuggingNewOperator
  25977. private:
  25978. AudioProcessor* const owner;
  25979. const int index;
  25980. Slider* slider;
  25981. class ParamSlider : public Slider
  25982. {
  25983. public:
  25984. ParamSlider (AudioProcessor* const owner_, const int index_)
  25985. : Slider (String::empty),
  25986. owner (owner_),
  25987. index (index_)
  25988. {
  25989. setRange (0.0, 1.0, 0.0);
  25990. setSliderStyle (Slider::LinearBar);
  25991. setTextBoxIsEditable (false);
  25992. setScrollWheelEnabled (false);
  25993. }
  25994. ~ParamSlider()
  25995. {
  25996. }
  25997. void valueChanged()
  25998. {
  25999. const float newVal = (float) getValue();
  26000. if (owner->getParameter (index) != newVal)
  26001. owner->setParameter (index, newVal);
  26002. }
  26003. const String getTextFromValue (double /*value*/)
  26004. {
  26005. return owner->getParameterText (index);
  26006. }
  26007. juce_UseDebuggingNewOperator
  26008. private:
  26009. AudioProcessor* const owner;
  26010. const int index;
  26011. };
  26012. };
  26013. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  26014. : AudioProcessorEditor (owner)
  26015. {
  26016. setOpaque (true);
  26017. addAndMakeVisible (panel = new PropertyPanel());
  26018. Array <PropertyComponent*> params;
  26019. const int numParams = owner->getNumParameters();
  26020. int totalHeight = 0;
  26021. for (int i = 0; i < numParams; ++i)
  26022. {
  26023. String name (owner->getParameterName (i));
  26024. if (name.trim().isEmpty())
  26025. name = "Unnamed";
  26026. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  26027. params.add (pc);
  26028. totalHeight += pc->getPreferredHeight();
  26029. }
  26030. panel->addProperties (params);
  26031. setSize (400, jlimit (25, 400, totalHeight));
  26032. }
  26033. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  26034. {
  26035. deleteAllChildren();
  26036. }
  26037. void GenericAudioProcessorEditor::paint (Graphics& g)
  26038. {
  26039. g.fillAll (Colours::white);
  26040. }
  26041. void GenericAudioProcessorEditor::resized()
  26042. {
  26043. panel->setSize (getWidth(), getHeight());
  26044. }
  26045. END_JUCE_NAMESPACE
  26046. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26047. /********* Start of inlined file: juce_Sampler.cpp *********/
  26048. BEGIN_JUCE_NAMESPACE
  26049. SamplerSound::SamplerSound (const String& name_,
  26050. AudioFormatReader& source,
  26051. const BitArray& midiNotes_,
  26052. const int midiNoteForNormalPitch,
  26053. const double attackTimeSecs,
  26054. const double releaseTimeSecs,
  26055. const double maxSampleLengthSeconds)
  26056. : name (name_),
  26057. midiNotes (midiNotes_),
  26058. midiRootNote (midiNoteForNormalPitch)
  26059. {
  26060. sourceSampleRate = source.sampleRate;
  26061. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  26062. {
  26063. data = 0;
  26064. length = 0;
  26065. attackSamples = 0;
  26066. releaseSamples = 0;
  26067. }
  26068. else
  26069. {
  26070. length = jmin ((int) source.lengthInSamples,
  26071. (int) (maxSampleLengthSeconds * sourceSampleRate));
  26072. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  26073. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  26074. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  26075. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  26076. }
  26077. }
  26078. SamplerSound::~SamplerSound()
  26079. {
  26080. delete data;
  26081. data = 0;
  26082. }
  26083. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  26084. {
  26085. return midiNotes [midiNoteNumber];
  26086. }
  26087. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  26088. {
  26089. return true;
  26090. }
  26091. SamplerVoice::SamplerVoice()
  26092. : pitchRatio (0.0),
  26093. sourceSamplePosition (0.0),
  26094. lgain (0.0f),
  26095. rgain (0.0f),
  26096. isInAttack (false),
  26097. isInRelease (false)
  26098. {
  26099. }
  26100. SamplerVoice::~SamplerVoice()
  26101. {
  26102. }
  26103. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  26104. {
  26105. return dynamic_cast <const SamplerSound*> (sound) != 0;
  26106. }
  26107. void SamplerVoice::startNote (const int midiNoteNumber,
  26108. const float velocity,
  26109. SynthesiserSound* s,
  26110. const int /*currentPitchWheelPosition*/)
  26111. {
  26112. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  26113. jassert (sound != 0); // this object can only play SamplerSounds!
  26114. if (sound != 0)
  26115. {
  26116. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  26117. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  26118. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  26119. sourceSamplePosition = 0.0;
  26120. lgain = velocity;
  26121. rgain = velocity;
  26122. isInAttack = (sound->attackSamples > 0);
  26123. isInRelease = false;
  26124. if (isInAttack)
  26125. {
  26126. attackReleaseLevel = 0.0f;
  26127. attackDelta = (float) (pitchRatio / sound->attackSamples);
  26128. }
  26129. else
  26130. {
  26131. attackReleaseLevel = 1.0f;
  26132. attackDelta = 0.0f;
  26133. }
  26134. if (sound->releaseSamples > 0)
  26135. {
  26136. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  26137. }
  26138. else
  26139. {
  26140. releaseDelta = 0.0f;
  26141. }
  26142. }
  26143. }
  26144. void SamplerVoice::stopNote (const bool allowTailOff)
  26145. {
  26146. if (allowTailOff)
  26147. {
  26148. isInAttack = false;
  26149. isInRelease = true;
  26150. }
  26151. else
  26152. {
  26153. clearCurrentNote();
  26154. }
  26155. }
  26156. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  26157. {
  26158. }
  26159. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  26160. const int /*newValue*/)
  26161. {
  26162. }
  26163. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  26164. {
  26165. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  26166. if (playingSound != 0)
  26167. {
  26168. const float* const inL = playingSound->data->getSampleData (0, 0);
  26169. const float* const inR = playingSound->data->getNumChannels() > 1
  26170. ? playingSound->data->getSampleData (1, 0) : 0;
  26171. float* outL = outputBuffer.getSampleData (0, startSample);
  26172. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  26173. while (--numSamples >= 0)
  26174. {
  26175. const int pos = (int) sourceSamplePosition;
  26176. const float alpha = (float) (sourceSamplePosition - pos);
  26177. const float invAlpha = 1.0f - alpha;
  26178. // just using a very simple linear interpolation here..
  26179. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  26180. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  26181. : l;
  26182. l *= lgain;
  26183. r *= rgain;
  26184. if (isInAttack)
  26185. {
  26186. l *= attackReleaseLevel;
  26187. r *= attackReleaseLevel;
  26188. attackReleaseLevel += attackDelta;
  26189. if (attackReleaseLevel >= 1.0f)
  26190. {
  26191. attackReleaseLevel = 1.0f;
  26192. isInAttack = false;
  26193. }
  26194. }
  26195. else if (isInRelease)
  26196. {
  26197. l *= attackReleaseLevel;
  26198. r *= attackReleaseLevel;
  26199. attackReleaseLevel += releaseDelta;
  26200. if (attackReleaseLevel <= 0.0f)
  26201. {
  26202. stopNote (false);
  26203. break;
  26204. }
  26205. }
  26206. if (outR != 0)
  26207. {
  26208. *outL++ += l;
  26209. *outR++ += r;
  26210. }
  26211. else
  26212. {
  26213. *outL++ += (l + r) * 0.5f;
  26214. }
  26215. sourceSamplePosition += pitchRatio;
  26216. if (sourceSamplePosition > playingSound->length)
  26217. {
  26218. stopNote (false);
  26219. break;
  26220. }
  26221. }
  26222. }
  26223. }
  26224. END_JUCE_NAMESPACE
  26225. /********* End of inlined file: juce_Sampler.cpp *********/
  26226. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  26227. BEGIN_JUCE_NAMESPACE
  26228. SynthesiserSound::SynthesiserSound()
  26229. {
  26230. }
  26231. SynthesiserSound::~SynthesiserSound()
  26232. {
  26233. }
  26234. SynthesiserVoice::SynthesiserVoice()
  26235. : currentSampleRate (44100.0),
  26236. currentlyPlayingNote (-1),
  26237. noteOnTime (0),
  26238. currentlyPlayingSound (0)
  26239. {
  26240. }
  26241. SynthesiserVoice::~SynthesiserVoice()
  26242. {
  26243. }
  26244. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  26245. {
  26246. return currentlyPlayingSound != 0
  26247. && currentlyPlayingSound->appliesToChannel (midiChannel);
  26248. }
  26249. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  26250. {
  26251. currentSampleRate = newRate;
  26252. }
  26253. void SynthesiserVoice::clearCurrentNote()
  26254. {
  26255. currentlyPlayingNote = -1;
  26256. currentlyPlayingSound = 0;
  26257. }
  26258. Synthesiser::Synthesiser()
  26259. : voices (2),
  26260. sounds (2),
  26261. sampleRate (0),
  26262. lastNoteOnCounter (0),
  26263. shouldStealNotes (true)
  26264. {
  26265. zeromem (lastPitchWheelValues, sizeof (lastPitchWheelValues));
  26266. }
  26267. Synthesiser::~Synthesiser()
  26268. {
  26269. }
  26270. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  26271. {
  26272. const ScopedLock sl (lock);
  26273. return voices [index];
  26274. }
  26275. void Synthesiser::clearVoices()
  26276. {
  26277. const ScopedLock sl (lock);
  26278. voices.clear();
  26279. }
  26280. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  26281. {
  26282. const ScopedLock sl (lock);
  26283. voices.add (newVoice);
  26284. }
  26285. void Synthesiser::removeVoice (const int index)
  26286. {
  26287. const ScopedLock sl (lock);
  26288. voices.remove (index);
  26289. }
  26290. void Synthesiser::clearSounds()
  26291. {
  26292. const ScopedLock sl (lock);
  26293. sounds.clear();
  26294. }
  26295. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  26296. {
  26297. const ScopedLock sl (lock);
  26298. sounds.add (newSound);
  26299. }
  26300. void Synthesiser::removeSound (const int index)
  26301. {
  26302. const ScopedLock sl (lock);
  26303. sounds.remove (index);
  26304. }
  26305. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  26306. {
  26307. shouldStealNotes = shouldStealNotes_;
  26308. }
  26309. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  26310. {
  26311. if (sampleRate != newRate)
  26312. {
  26313. const ScopedLock sl (lock);
  26314. allNotesOff (0, false);
  26315. sampleRate = newRate;
  26316. for (int i = voices.size(); --i >= 0;)
  26317. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  26318. }
  26319. }
  26320. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  26321. const MidiBuffer& midiData,
  26322. int startSample,
  26323. int numSamples)
  26324. {
  26325. // must set the sample rate before using this!
  26326. jassert (sampleRate != 0);
  26327. const ScopedLock sl (lock);
  26328. MidiBuffer::Iterator midiIterator (midiData);
  26329. midiIterator.setNextSamplePosition (startSample);
  26330. MidiMessage m (0xf4, 0.0);
  26331. while (numSamples > 0)
  26332. {
  26333. int midiEventPos;
  26334. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  26335. && midiEventPos < startSample + numSamples;
  26336. const int numThisTime = useEvent ? midiEventPos - startSample
  26337. : numSamples;
  26338. if (numThisTime > 0)
  26339. {
  26340. for (int i = voices.size(); --i >= 0;)
  26341. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  26342. }
  26343. if (useEvent)
  26344. {
  26345. if (m.isNoteOn())
  26346. {
  26347. const int channel = m.getChannel();
  26348. noteOn (channel,
  26349. m.getNoteNumber(),
  26350. m.getFloatVelocity());
  26351. }
  26352. else if (m.isNoteOff())
  26353. {
  26354. noteOff (m.getChannel(),
  26355. m.getNoteNumber(),
  26356. true);
  26357. }
  26358. else if (m.isAllNotesOff() || m.isAllSoundOff())
  26359. {
  26360. allNotesOff (m.getChannel(), true);
  26361. }
  26362. else if (m.isPitchWheel())
  26363. {
  26364. const int channel = m.getChannel();
  26365. const int wheelPos = m.getPitchWheelValue();
  26366. lastPitchWheelValues [channel - 1] = wheelPos;
  26367. handlePitchWheel (channel, wheelPos);
  26368. }
  26369. else if (m.isController())
  26370. {
  26371. handleController (m.getChannel(),
  26372. m.getControllerNumber(),
  26373. m.getControllerValue());
  26374. }
  26375. }
  26376. startSample += numThisTime;
  26377. numSamples -= numThisTime;
  26378. }
  26379. }
  26380. void Synthesiser::noteOn (const int midiChannel,
  26381. const int midiNoteNumber,
  26382. const float velocity)
  26383. {
  26384. const ScopedLock sl (lock);
  26385. for (int i = sounds.size(); --i >= 0;)
  26386. {
  26387. SynthesiserSound* const sound = sounds.getUnchecked(i);
  26388. if (sound->appliesToNote (midiNoteNumber)
  26389. && sound->appliesToChannel (midiChannel))
  26390. {
  26391. startVoice (findFreeVoice (sound, shouldStealNotes),
  26392. sound, midiChannel, midiNoteNumber, velocity);
  26393. }
  26394. }
  26395. }
  26396. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  26397. SynthesiserSound* const sound,
  26398. const int midiChannel,
  26399. const int midiNoteNumber,
  26400. const float velocity)
  26401. {
  26402. if (voice != 0 && sound != 0)
  26403. {
  26404. if (voice->currentlyPlayingSound != 0)
  26405. voice->stopNote (false);
  26406. voice->startNote (midiNoteNumber,
  26407. velocity,
  26408. sound,
  26409. lastPitchWheelValues [midiChannel - 1]);
  26410. voice->currentlyPlayingNote = midiNoteNumber;
  26411. voice->noteOnTime = ++lastNoteOnCounter;
  26412. voice->currentlyPlayingSound = sound;
  26413. }
  26414. }
  26415. void Synthesiser::noteOff (const int midiChannel,
  26416. const int midiNoteNumber,
  26417. const bool allowTailOff)
  26418. {
  26419. const ScopedLock sl (lock);
  26420. for (int i = voices.size(); --i >= 0;)
  26421. {
  26422. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26423. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  26424. {
  26425. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  26426. if (sound != 0
  26427. && sound->appliesToNote (midiNoteNumber)
  26428. && sound->appliesToChannel (midiChannel))
  26429. {
  26430. voice->stopNote (allowTailOff);
  26431. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  26432. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  26433. }
  26434. }
  26435. }
  26436. }
  26437. void Synthesiser::allNotesOff (const int midiChannel,
  26438. const bool allowTailOff)
  26439. {
  26440. const ScopedLock sl (lock);
  26441. for (int i = voices.size(); --i >= 0;)
  26442. {
  26443. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26444. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26445. voice->stopNote (allowTailOff);
  26446. }
  26447. }
  26448. void Synthesiser::handlePitchWheel (const int midiChannel,
  26449. const int wheelValue)
  26450. {
  26451. const ScopedLock sl (lock);
  26452. for (int i = voices.size(); --i >= 0;)
  26453. {
  26454. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26455. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26456. {
  26457. voice->pitchWheelMoved (wheelValue);
  26458. }
  26459. }
  26460. }
  26461. void Synthesiser::handleController (const int midiChannel,
  26462. const int controllerNumber,
  26463. const int controllerValue)
  26464. {
  26465. const ScopedLock sl (lock);
  26466. for (int i = voices.size(); --i >= 0;)
  26467. {
  26468. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26469. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26470. voice->controllerMoved (controllerNumber, controllerValue);
  26471. }
  26472. }
  26473. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  26474. const bool stealIfNoneAvailable) const
  26475. {
  26476. const ScopedLock sl (lock);
  26477. for (int i = voices.size(); --i >= 0;)
  26478. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  26479. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  26480. return voices.getUnchecked (i);
  26481. if (stealIfNoneAvailable)
  26482. {
  26483. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  26484. SynthesiserVoice* oldest = 0;
  26485. for (int i = voices.size(); --i >= 0;)
  26486. {
  26487. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26488. if (voice->canPlaySound (soundToPlay)
  26489. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  26490. oldest = voice;
  26491. }
  26492. jassert (oldest != 0);
  26493. return oldest;
  26494. }
  26495. return 0;
  26496. }
  26497. END_JUCE_NAMESPACE
  26498. /********* End of inlined file: juce_Synthesiser.cpp *********/
  26499. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  26500. BEGIN_JUCE_NAMESPACE
  26501. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  26502. const String& fileWildcard_,
  26503. const String& openFileDialogTitle_,
  26504. const String& saveFileDialogTitle_)
  26505. : changedSinceSave (false),
  26506. fileExtension (fileExtension_),
  26507. fileWildcard (fileWildcard_),
  26508. openFileDialogTitle (openFileDialogTitle_),
  26509. saveFileDialogTitle (saveFileDialogTitle_)
  26510. {
  26511. }
  26512. FileBasedDocument::~FileBasedDocument()
  26513. {
  26514. }
  26515. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  26516. {
  26517. changedSinceSave = hasChanged;
  26518. }
  26519. void FileBasedDocument::changed()
  26520. {
  26521. changedSinceSave = true;
  26522. sendChangeMessage (this);
  26523. }
  26524. void FileBasedDocument::setFile (const File& newFile)
  26525. {
  26526. if (documentFile != newFile)
  26527. {
  26528. documentFile = newFile;
  26529. changedSinceSave = true;
  26530. }
  26531. }
  26532. bool FileBasedDocument::loadFrom (const File& newFile,
  26533. const bool showMessageOnFailure)
  26534. {
  26535. MouseCursor::showWaitCursor();
  26536. const File oldFile (documentFile);
  26537. documentFile = newFile;
  26538. String error;
  26539. if (newFile.existsAsFile())
  26540. {
  26541. error = loadDocument (newFile);
  26542. if (error.isEmpty())
  26543. {
  26544. setChangedFlag (false);
  26545. MouseCursor::hideWaitCursor();
  26546. setLastDocumentOpened (newFile);
  26547. return true;
  26548. }
  26549. }
  26550. else
  26551. {
  26552. error = "The file doesn't exist";
  26553. }
  26554. documentFile = oldFile;
  26555. MouseCursor::hideWaitCursor();
  26556. if (showMessageOnFailure)
  26557. {
  26558. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26559. TRANS("Failed to open file..."),
  26560. TRANS("There was an error while trying to load the file:\n\n")
  26561. + newFile.getFullPathName()
  26562. + T("\n\n")
  26563. + error);
  26564. }
  26565. return false;
  26566. }
  26567. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  26568. {
  26569. FileChooser fc (openFileDialogTitle,
  26570. getLastDocumentOpened(),
  26571. fileWildcard);
  26572. if (fc.browseForFileToOpen())
  26573. return loadFrom (fc.getResult(), showMessageOnFailure);
  26574. return false;
  26575. }
  26576. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  26577. const bool showMessageOnFailure)
  26578. {
  26579. return saveAs (documentFile,
  26580. false,
  26581. askUserForFileIfNotSpecified,
  26582. showMessageOnFailure);
  26583. }
  26584. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  26585. const bool warnAboutOverwritingExistingFiles,
  26586. const bool askUserForFileIfNotSpecified,
  26587. const bool showMessageOnFailure)
  26588. {
  26589. if (newFile == File::nonexistent)
  26590. {
  26591. if (askUserForFileIfNotSpecified)
  26592. {
  26593. return saveAsInteractive (true);
  26594. }
  26595. else
  26596. {
  26597. // can't save to an unspecified file
  26598. jassertfalse
  26599. return failedToWriteToFile;
  26600. }
  26601. }
  26602. if (warnAboutOverwritingExistingFiles && newFile.exists())
  26603. {
  26604. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  26605. TRANS("File already exists"),
  26606. TRANS("There's already a file called:\n\n")
  26607. + newFile.getFullPathName()
  26608. + TRANS("\n\nAre you sure you want to overwrite it?"),
  26609. TRANS("overwrite"),
  26610. TRANS("cancel")))
  26611. {
  26612. return userCancelledSave;
  26613. }
  26614. }
  26615. MouseCursor::showWaitCursor();
  26616. const File oldFile (documentFile);
  26617. documentFile = newFile;
  26618. String error (saveDocument (newFile));
  26619. if (error.isEmpty())
  26620. {
  26621. setChangedFlag (false);
  26622. MouseCursor::hideWaitCursor();
  26623. return savedOk;
  26624. }
  26625. documentFile = oldFile;
  26626. MouseCursor::hideWaitCursor();
  26627. if (showMessageOnFailure)
  26628. {
  26629. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26630. TRANS("Error writing to file..."),
  26631. TRANS("An error occurred while trying to save \"")
  26632. + getDocumentTitle()
  26633. + TRANS("\" to the file:\n\n")
  26634. + newFile.getFullPathName()
  26635. + T("\n\n")
  26636. + error);
  26637. }
  26638. return failedToWriteToFile;
  26639. }
  26640. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  26641. {
  26642. if (! hasChangedSinceSaved())
  26643. return savedOk;
  26644. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  26645. TRANS("Closing document..."),
  26646. TRANS("Do you want to save the changes to \"")
  26647. + getDocumentTitle() + T("\"?"),
  26648. TRANS("save"),
  26649. TRANS("discard changes"),
  26650. TRANS("cancel"));
  26651. if (r == 1)
  26652. {
  26653. // save changes
  26654. return save (true, true);
  26655. }
  26656. else if (r == 2)
  26657. {
  26658. // discard changes
  26659. return savedOk;
  26660. }
  26661. return userCancelledSave;
  26662. }
  26663. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  26664. {
  26665. File f;
  26666. if (documentFile.existsAsFile())
  26667. f = documentFile;
  26668. else
  26669. f = getLastDocumentOpened();
  26670. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  26671. if (legalFilename.isEmpty())
  26672. legalFilename = "unnamed";
  26673. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  26674. f = f.getSiblingFile (legalFilename);
  26675. else
  26676. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  26677. f = f.withFileExtension (fileExtension)
  26678. .getNonexistentSibling (true);
  26679. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  26680. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  26681. {
  26682. setLastDocumentOpened (fc.getResult());
  26683. File chosen (fc.getResult());
  26684. if (chosen.getFileExtension().isEmpty())
  26685. chosen = chosen.withFileExtension (fileExtension);
  26686. return saveAs (chosen, false, false, true);
  26687. }
  26688. return userCancelledSave;
  26689. }
  26690. END_JUCE_NAMESPACE
  26691. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  26692. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26693. BEGIN_JUCE_NAMESPACE
  26694. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  26695. : maxNumberOfItems (10)
  26696. {
  26697. }
  26698. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  26699. {
  26700. }
  26701. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  26702. {
  26703. maxNumberOfItems = jmax (1, newMaxNumber);
  26704. while (getNumFiles() > maxNumberOfItems)
  26705. files.remove (getNumFiles() - 1);
  26706. }
  26707. int RecentlyOpenedFilesList::getNumFiles() const
  26708. {
  26709. return files.size();
  26710. }
  26711. const File RecentlyOpenedFilesList::getFile (const int index) const
  26712. {
  26713. return File (files [index]);
  26714. }
  26715. void RecentlyOpenedFilesList::clear()
  26716. {
  26717. files.clear();
  26718. }
  26719. void RecentlyOpenedFilesList::addFile (const File& file)
  26720. {
  26721. const String path (file.getFullPathName());
  26722. files.removeString (path, true);
  26723. files.insert (0, path);
  26724. setMaxNumberOfItems (maxNumberOfItems);
  26725. }
  26726. void RecentlyOpenedFilesList::removeNonExistentFiles()
  26727. {
  26728. for (int i = getNumFiles(); --i >= 0;)
  26729. if (! getFile(i).exists())
  26730. files.remove (i);
  26731. }
  26732. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  26733. const int baseItemId,
  26734. const bool showFullPaths,
  26735. const bool dontAddNonExistentFiles,
  26736. const File** filesToAvoid)
  26737. {
  26738. int num = 0;
  26739. for (int i = 0; i < getNumFiles(); ++i)
  26740. {
  26741. const File f (getFile(i));
  26742. if ((! dontAddNonExistentFiles) || f.exists())
  26743. {
  26744. bool needsAvoiding = false;
  26745. if (filesToAvoid != 0)
  26746. {
  26747. const File** files = filesToAvoid;
  26748. while (*files != 0)
  26749. {
  26750. if (f == **files)
  26751. {
  26752. needsAvoiding = true;
  26753. break;
  26754. }
  26755. ++files;
  26756. }
  26757. }
  26758. if (! needsAvoiding)
  26759. {
  26760. menuToAddTo.addItem (baseItemId + i,
  26761. showFullPaths ? f.getFullPathName()
  26762. : f.getFileName());
  26763. ++num;
  26764. }
  26765. }
  26766. }
  26767. return num;
  26768. }
  26769. const String RecentlyOpenedFilesList::toString() const
  26770. {
  26771. return files.joinIntoString (T("\n"));
  26772. }
  26773. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  26774. {
  26775. clear();
  26776. files.addLines (stringifiedVersion);
  26777. setMaxNumberOfItems (maxNumberOfItems);
  26778. }
  26779. END_JUCE_NAMESPACE
  26780. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26781. /********* Start of inlined file: juce_UndoManager.cpp *********/
  26782. BEGIN_JUCE_NAMESPACE
  26783. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  26784. const int minimumTransactions)
  26785. : totalUnitsStored (0),
  26786. nextIndex (0),
  26787. newTransaction (true),
  26788. reentrancyCheck (false)
  26789. {
  26790. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  26791. minimumTransactions);
  26792. }
  26793. UndoManager::~UndoManager()
  26794. {
  26795. clearUndoHistory();
  26796. }
  26797. void UndoManager::clearUndoHistory()
  26798. {
  26799. transactions.clear();
  26800. transactionNames.clear();
  26801. totalUnitsStored = 0;
  26802. nextIndex = 0;
  26803. sendChangeMessage (this);
  26804. }
  26805. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  26806. {
  26807. return totalUnitsStored;
  26808. }
  26809. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  26810. const int minimumTransactions)
  26811. {
  26812. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  26813. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  26814. }
  26815. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  26816. {
  26817. if (command != 0)
  26818. {
  26819. if (actionName.isNotEmpty())
  26820. currentTransactionName = actionName;
  26821. if (reentrancyCheck)
  26822. {
  26823. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  26824. // undo() methods, or else these actions won't actually get done.
  26825. return false;
  26826. }
  26827. else
  26828. {
  26829. bool success = false;
  26830. JUCE_TRY
  26831. {
  26832. success = command->perform();
  26833. }
  26834. JUCE_CATCH_EXCEPTION
  26835. jassert (success);
  26836. if (success)
  26837. {
  26838. if (nextIndex > 0 && ! newTransaction)
  26839. {
  26840. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  26841. jassert (commandSet != 0);
  26842. if (commandSet == 0)
  26843. return false;
  26844. commandSet->add (command);
  26845. }
  26846. else
  26847. {
  26848. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  26849. commandSet->add (command);
  26850. transactions.insert (nextIndex, commandSet);
  26851. transactionNames.insert (nextIndex, currentTransactionName);
  26852. ++nextIndex;
  26853. }
  26854. totalUnitsStored += command->getSizeInUnits();
  26855. newTransaction = false;
  26856. }
  26857. while (nextIndex < transactions.size())
  26858. {
  26859. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  26860. for (int i = lastSet->size(); --i >= 0;)
  26861. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  26862. transactions.removeLast();
  26863. transactionNames.remove (transactionNames.size() - 1);
  26864. }
  26865. while (nextIndex > 0
  26866. && totalUnitsStored > maxNumUnitsToKeep
  26867. && transactions.size() > minimumTransactionsToKeep)
  26868. {
  26869. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  26870. for (int i = firstSet->size(); --i >= 0;)
  26871. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  26872. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  26873. transactions.remove (0);
  26874. transactionNames.remove (0);
  26875. --nextIndex;
  26876. }
  26877. sendChangeMessage (this);
  26878. return success;
  26879. }
  26880. }
  26881. return false;
  26882. }
  26883. void UndoManager::beginNewTransaction (const String& actionName)
  26884. {
  26885. newTransaction = true;
  26886. currentTransactionName = actionName;
  26887. }
  26888. void UndoManager::setCurrentTransactionName (const String& newName)
  26889. {
  26890. currentTransactionName = newName;
  26891. }
  26892. bool UndoManager::canUndo() const
  26893. {
  26894. return nextIndex > 0;
  26895. }
  26896. bool UndoManager::canRedo() const
  26897. {
  26898. return nextIndex < transactions.size();
  26899. }
  26900. const String UndoManager::getUndoDescription() const
  26901. {
  26902. return transactionNames [nextIndex - 1];
  26903. }
  26904. const String UndoManager::getRedoDescription() const
  26905. {
  26906. return transactionNames [nextIndex];
  26907. }
  26908. bool UndoManager::undo()
  26909. {
  26910. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  26911. if (commandSet == 0)
  26912. return false;
  26913. reentrancyCheck = true;
  26914. bool failed = false;
  26915. for (int i = commandSet->size(); --i >= 0;)
  26916. {
  26917. if (! commandSet->getUnchecked(i)->undo())
  26918. {
  26919. jassertfalse
  26920. failed = true;
  26921. break;
  26922. }
  26923. }
  26924. reentrancyCheck = false;
  26925. if (failed)
  26926. {
  26927. clearUndoHistory();
  26928. }
  26929. else
  26930. {
  26931. --nextIndex;
  26932. }
  26933. beginNewTransaction();
  26934. sendChangeMessage (this);
  26935. return true;
  26936. }
  26937. bool UndoManager::redo()
  26938. {
  26939. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  26940. if (commandSet == 0)
  26941. return false;
  26942. reentrancyCheck = true;
  26943. bool failed = false;
  26944. for (int i = 0; i < commandSet->size(); ++i)
  26945. {
  26946. if (! commandSet->getUnchecked(i)->perform())
  26947. {
  26948. jassertfalse
  26949. failed = true;
  26950. break;
  26951. }
  26952. }
  26953. reentrancyCheck = false;
  26954. if (failed)
  26955. {
  26956. clearUndoHistory();
  26957. }
  26958. else
  26959. {
  26960. ++nextIndex;
  26961. }
  26962. beginNewTransaction();
  26963. sendChangeMessage (this);
  26964. return true;
  26965. }
  26966. bool UndoManager::undoCurrentTransactionOnly()
  26967. {
  26968. return newTransaction ? false
  26969. : undo();
  26970. }
  26971. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  26972. {
  26973. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  26974. if (commandSet != 0 && ! newTransaction)
  26975. {
  26976. for (int i = 0; i < commandSet->size(); ++i)
  26977. actionsFound.add (commandSet->getUnchecked(i));
  26978. }
  26979. }
  26980. END_JUCE_NAMESPACE
  26981. /********* End of inlined file: juce_UndoManager.cpp *********/
  26982. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  26983. BEGIN_JUCE_NAMESPACE
  26984. ActionBroadcaster::ActionBroadcaster() throw()
  26985. {
  26986. // are you trying to create this object before or after juce has been intialised??
  26987. jassert (MessageManager::instance != 0);
  26988. }
  26989. ActionBroadcaster::~ActionBroadcaster()
  26990. {
  26991. // all event-based objects must be deleted BEFORE juce is shut down!
  26992. jassert (MessageManager::instance != 0);
  26993. }
  26994. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  26995. {
  26996. actionListenerList.addActionListener (listener);
  26997. }
  26998. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  26999. {
  27000. jassert (actionListenerList.isValidMessageListener());
  27001. if (actionListenerList.isValidMessageListener())
  27002. actionListenerList.removeActionListener (listener);
  27003. }
  27004. void ActionBroadcaster::removeAllActionListeners()
  27005. {
  27006. actionListenerList.removeAllActionListeners();
  27007. }
  27008. void ActionBroadcaster::sendActionMessage (const String& message) const
  27009. {
  27010. actionListenerList.sendActionMessage (message);
  27011. }
  27012. END_JUCE_NAMESPACE
  27013. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  27014. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  27015. BEGIN_JUCE_NAMESPACE
  27016. // special message of our own with a string in it
  27017. class ActionMessage : public Message
  27018. {
  27019. public:
  27020. const String message;
  27021. ActionMessage (const String& messageText,
  27022. void* const listener_) throw()
  27023. : message (messageText)
  27024. {
  27025. pointerParameter = listener_;
  27026. }
  27027. ~ActionMessage() throw()
  27028. {
  27029. }
  27030. private:
  27031. ActionMessage (const ActionMessage&);
  27032. const ActionMessage& operator= (const ActionMessage&);
  27033. };
  27034. ActionListenerList::ActionListenerList() throw()
  27035. {
  27036. }
  27037. ActionListenerList::~ActionListenerList() throw()
  27038. {
  27039. }
  27040. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  27041. {
  27042. const ScopedLock sl (actionListenerLock_);
  27043. jassert (listener != 0);
  27044. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  27045. if (listener != 0)
  27046. actionListeners_.add (listener);
  27047. }
  27048. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  27049. {
  27050. const ScopedLock sl (actionListenerLock_);
  27051. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  27052. actionListeners_.removeValue (listener);
  27053. }
  27054. void ActionListenerList::removeAllActionListeners() throw()
  27055. {
  27056. const ScopedLock sl (actionListenerLock_);
  27057. actionListeners_.clear();
  27058. }
  27059. void ActionListenerList::sendActionMessage (const String& message) const
  27060. {
  27061. const ScopedLock sl (actionListenerLock_);
  27062. for (int i = actionListeners_.size(); --i >= 0;)
  27063. {
  27064. postMessage (new ActionMessage (message,
  27065. (ActionListener*) actionListeners_.getUnchecked(i)));
  27066. }
  27067. }
  27068. void ActionListenerList::handleMessage (const Message& message)
  27069. {
  27070. const ActionMessage& am = (const ActionMessage&) message;
  27071. if (actionListeners_.contains (am.pointerParameter))
  27072. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  27073. }
  27074. END_JUCE_NAMESPACE
  27075. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  27076. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  27077. BEGIN_JUCE_NAMESPACE
  27078. AsyncUpdater::AsyncUpdater() throw()
  27079. : asyncMessagePending (false)
  27080. {
  27081. internalAsyncHandler.owner = this;
  27082. }
  27083. AsyncUpdater::~AsyncUpdater()
  27084. {
  27085. }
  27086. void AsyncUpdater::triggerAsyncUpdate() throw()
  27087. {
  27088. if (! asyncMessagePending)
  27089. {
  27090. asyncMessagePending = true;
  27091. internalAsyncHandler.postMessage (new Message());
  27092. }
  27093. }
  27094. void AsyncUpdater::cancelPendingUpdate() throw()
  27095. {
  27096. asyncMessagePending = false;
  27097. }
  27098. void AsyncUpdater::handleUpdateNowIfNeeded()
  27099. {
  27100. if (asyncMessagePending)
  27101. {
  27102. asyncMessagePending = false;
  27103. handleAsyncUpdate();
  27104. }
  27105. }
  27106. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  27107. {
  27108. owner->handleUpdateNowIfNeeded();
  27109. }
  27110. END_JUCE_NAMESPACE
  27111. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  27112. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  27113. BEGIN_JUCE_NAMESPACE
  27114. ChangeBroadcaster::ChangeBroadcaster() throw()
  27115. {
  27116. // are you trying to create this object before or after juce has been intialised??
  27117. jassert (MessageManager::instance != 0);
  27118. }
  27119. ChangeBroadcaster::~ChangeBroadcaster()
  27120. {
  27121. // all event-based objects must be deleted BEFORE juce is shut down!
  27122. jassert (MessageManager::instance != 0);
  27123. }
  27124. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  27125. {
  27126. changeListenerList.addChangeListener (listener);
  27127. }
  27128. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  27129. {
  27130. jassert (changeListenerList.isValidMessageListener());
  27131. if (changeListenerList.isValidMessageListener())
  27132. changeListenerList.removeChangeListener (listener);
  27133. }
  27134. void ChangeBroadcaster::removeAllChangeListeners() throw()
  27135. {
  27136. changeListenerList.removeAllChangeListeners();
  27137. }
  27138. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  27139. {
  27140. changeListenerList.sendChangeMessage (objectThatHasChanged);
  27141. }
  27142. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  27143. {
  27144. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  27145. }
  27146. void ChangeBroadcaster::dispatchPendingMessages()
  27147. {
  27148. changeListenerList.dispatchPendingMessages();
  27149. }
  27150. END_JUCE_NAMESPACE
  27151. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  27152. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  27153. BEGIN_JUCE_NAMESPACE
  27154. ChangeListenerList::ChangeListenerList() throw()
  27155. : lastChangedObject (0),
  27156. messagePending (false)
  27157. {
  27158. }
  27159. ChangeListenerList::~ChangeListenerList() throw()
  27160. {
  27161. }
  27162. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  27163. {
  27164. const ScopedLock sl (lock);
  27165. jassert (listener != 0);
  27166. if (listener != 0)
  27167. listeners.add (listener);
  27168. }
  27169. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  27170. {
  27171. const ScopedLock sl (lock);
  27172. listeners.removeValue (listener);
  27173. }
  27174. void ChangeListenerList::removeAllChangeListeners() throw()
  27175. {
  27176. const ScopedLock sl (lock);
  27177. listeners.clear();
  27178. }
  27179. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  27180. {
  27181. const ScopedLock sl (lock);
  27182. if ((! messagePending) && (listeners.size() > 0))
  27183. {
  27184. lastChangedObject = objectThatHasChanged;
  27185. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  27186. messagePending = true;
  27187. }
  27188. }
  27189. void ChangeListenerList::handleMessage (const Message& message)
  27190. {
  27191. sendSynchronousChangeMessage (message.pointerParameter);
  27192. }
  27193. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  27194. {
  27195. const ScopedLock sl (lock);
  27196. messagePending = false;
  27197. for (int i = listeners.size(); --i >= 0;)
  27198. {
  27199. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  27200. {
  27201. const ScopedUnlock tempUnlocker (lock);
  27202. l->changeListenerCallback (objectThatHasChanged);
  27203. }
  27204. i = jmin (i, listeners.size());
  27205. }
  27206. }
  27207. void ChangeListenerList::dispatchPendingMessages()
  27208. {
  27209. if (messagePending)
  27210. sendSynchronousChangeMessage (lastChangedObject);
  27211. }
  27212. END_JUCE_NAMESPACE
  27213. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  27214. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  27215. BEGIN_JUCE_NAMESPACE
  27216. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27217. const uint32 magicMessageHeaderNumber)
  27218. : Thread ("Juce IPC connection"),
  27219. socket (0),
  27220. pipe (0),
  27221. callbackConnectionState (false),
  27222. useMessageThread (callbacksOnMessageThread),
  27223. magicMessageHeader (magicMessageHeaderNumber),
  27224. pipeReceiveMessageTimeout (-1)
  27225. {
  27226. }
  27227. InterprocessConnection::~InterprocessConnection()
  27228. {
  27229. callbackConnectionState = false;
  27230. disconnect();
  27231. }
  27232. bool InterprocessConnection::connectToSocket (const String& hostName,
  27233. const int portNumber,
  27234. const int timeOutMillisecs)
  27235. {
  27236. disconnect();
  27237. const ScopedLock sl (pipeAndSocketLock);
  27238. socket = new StreamingSocket();
  27239. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  27240. {
  27241. connectionMadeInt();
  27242. startThread();
  27243. return true;
  27244. }
  27245. else
  27246. {
  27247. deleteAndZero (socket);
  27248. return false;
  27249. }
  27250. }
  27251. bool InterprocessConnection::connectToPipe (const String& pipeName,
  27252. const int pipeReceiveMessageTimeoutMs)
  27253. {
  27254. disconnect();
  27255. NamedPipe* const newPipe = new NamedPipe();
  27256. if (newPipe->openExisting (pipeName))
  27257. {
  27258. const ScopedLock sl (pipeAndSocketLock);
  27259. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27260. initialiseWithPipe (newPipe);
  27261. return true;
  27262. }
  27263. else
  27264. {
  27265. delete newPipe;
  27266. return false;
  27267. }
  27268. }
  27269. bool InterprocessConnection::createPipe (const String& pipeName,
  27270. const int pipeReceiveMessageTimeoutMs)
  27271. {
  27272. disconnect();
  27273. NamedPipe* const newPipe = new NamedPipe();
  27274. if (newPipe->createNewPipe (pipeName))
  27275. {
  27276. const ScopedLock sl (pipeAndSocketLock);
  27277. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27278. initialiseWithPipe (newPipe);
  27279. return true;
  27280. }
  27281. else
  27282. {
  27283. delete newPipe;
  27284. return false;
  27285. }
  27286. }
  27287. void InterprocessConnection::disconnect()
  27288. {
  27289. if (socket != 0)
  27290. socket->close();
  27291. if (pipe != 0)
  27292. {
  27293. pipe->cancelPendingReads();
  27294. pipe->close();
  27295. }
  27296. stopThread (4000);
  27297. {
  27298. const ScopedLock sl (pipeAndSocketLock);
  27299. deleteAndZero (socket);
  27300. deleteAndZero (pipe);
  27301. }
  27302. connectionLostInt();
  27303. }
  27304. bool InterprocessConnection::isConnected() const
  27305. {
  27306. const ScopedLock sl (pipeAndSocketLock);
  27307. return ((socket != 0 && socket->isConnected())
  27308. || (pipe != 0 && pipe->isOpen()))
  27309. && isThreadRunning();
  27310. }
  27311. const String InterprocessConnection::getConnectedHostName() const
  27312. {
  27313. if (pipe != 0)
  27314. {
  27315. return "localhost";
  27316. }
  27317. else if (socket != 0)
  27318. {
  27319. if (! socket->isLocal())
  27320. return socket->getHostName();
  27321. return "localhost";
  27322. }
  27323. return String::empty;
  27324. }
  27325. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  27326. {
  27327. uint32 messageHeader[2];
  27328. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  27329. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  27330. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  27331. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  27332. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  27333. int bytesWritten = 0;
  27334. const ScopedLock sl (pipeAndSocketLock);
  27335. if (socket != 0)
  27336. {
  27337. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  27338. }
  27339. else if (pipe != 0)
  27340. {
  27341. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  27342. }
  27343. if (bytesWritten < 0)
  27344. {
  27345. // error..
  27346. return false;
  27347. }
  27348. return (bytesWritten == messageData.getSize());
  27349. }
  27350. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  27351. {
  27352. jassert (socket == 0);
  27353. socket = socket_;
  27354. connectionMadeInt();
  27355. startThread();
  27356. }
  27357. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  27358. {
  27359. jassert (pipe == 0);
  27360. pipe = pipe_;
  27361. connectionMadeInt();
  27362. startThread();
  27363. }
  27364. const int messageMagicNumber = 0xb734128b;
  27365. void InterprocessConnection::handleMessage (const Message& message)
  27366. {
  27367. if (message.intParameter1 == messageMagicNumber)
  27368. {
  27369. switch (message.intParameter2)
  27370. {
  27371. case 0:
  27372. {
  27373. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  27374. messageReceived (*data);
  27375. delete data;
  27376. break;
  27377. }
  27378. case 1:
  27379. connectionMade();
  27380. break;
  27381. case 2:
  27382. connectionLost();
  27383. break;
  27384. }
  27385. }
  27386. }
  27387. void InterprocessConnection::connectionMadeInt()
  27388. {
  27389. if (! callbackConnectionState)
  27390. {
  27391. callbackConnectionState = true;
  27392. if (useMessageThread)
  27393. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  27394. else
  27395. connectionMade();
  27396. }
  27397. }
  27398. void InterprocessConnection::connectionLostInt()
  27399. {
  27400. if (callbackConnectionState)
  27401. {
  27402. callbackConnectionState = false;
  27403. if (useMessageThread)
  27404. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  27405. else
  27406. connectionLost();
  27407. }
  27408. }
  27409. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  27410. {
  27411. jassert (callbackConnectionState);
  27412. if (useMessageThread)
  27413. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  27414. else
  27415. messageReceived (data);
  27416. }
  27417. bool InterprocessConnection::readNextMessageInt()
  27418. {
  27419. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  27420. uint32 messageHeader[2];
  27421. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  27422. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  27423. if (bytes == sizeof (messageHeader)
  27424. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  27425. {
  27426. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  27427. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  27428. {
  27429. MemoryBlock messageData (bytesInMessage, true);
  27430. int bytesRead = 0;
  27431. while (bytesRead < bytesInMessage)
  27432. {
  27433. if (threadShouldExit())
  27434. return false;
  27435. const int numThisTime = jmin (bytesInMessage, 65536);
  27436. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  27437. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  27438. pipeReceiveMessageTimeout);
  27439. if (bytesIn <= 0)
  27440. break;
  27441. bytesRead += bytesIn;
  27442. }
  27443. if (bytesRead >= 0)
  27444. deliverDataInt (messageData);
  27445. }
  27446. }
  27447. else if (bytes < 0)
  27448. {
  27449. {
  27450. const ScopedLock sl (pipeAndSocketLock);
  27451. deleteAndZero (socket);
  27452. }
  27453. connectionLostInt();
  27454. return false;
  27455. }
  27456. return true;
  27457. }
  27458. void InterprocessConnection::run()
  27459. {
  27460. while (! threadShouldExit())
  27461. {
  27462. if (socket != 0)
  27463. {
  27464. const int ready = socket->waitUntilReady (true, 0);
  27465. if (ready < 0)
  27466. {
  27467. {
  27468. const ScopedLock sl (pipeAndSocketLock);
  27469. deleteAndZero (socket);
  27470. }
  27471. connectionLostInt();
  27472. break;
  27473. }
  27474. else if (ready > 0)
  27475. {
  27476. if (! readNextMessageInt())
  27477. break;
  27478. }
  27479. else
  27480. {
  27481. Thread::sleep (2);
  27482. }
  27483. }
  27484. else if (pipe != 0)
  27485. {
  27486. if (! pipe->isOpen())
  27487. {
  27488. {
  27489. const ScopedLock sl (pipeAndSocketLock);
  27490. deleteAndZero (pipe);
  27491. }
  27492. connectionLostInt();
  27493. break;
  27494. }
  27495. else
  27496. {
  27497. if (! readNextMessageInt())
  27498. break;
  27499. }
  27500. }
  27501. else
  27502. {
  27503. break;
  27504. }
  27505. }
  27506. }
  27507. END_JUCE_NAMESPACE
  27508. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  27509. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27510. BEGIN_JUCE_NAMESPACE
  27511. InterprocessConnectionServer::InterprocessConnectionServer()
  27512. : Thread ("Juce IPC server"),
  27513. socket (0)
  27514. {
  27515. }
  27516. InterprocessConnectionServer::~InterprocessConnectionServer()
  27517. {
  27518. stop();
  27519. }
  27520. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  27521. {
  27522. stop();
  27523. socket = new StreamingSocket();
  27524. if (socket->createListener (portNumber))
  27525. {
  27526. startThread();
  27527. return true;
  27528. }
  27529. deleteAndZero (socket);
  27530. return false;
  27531. }
  27532. void InterprocessConnectionServer::stop()
  27533. {
  27534. signalThreadShouldExit();
  27535. if (socket != 0)
  27536. socket->close();
  27537. stopThread (4000);
  27538. deleteAndZero (socket);
  27539. }
  27540. void InterprocessConnectionServer::run()
  27541. {
  27542. while ((! threadShouldExit()) && socket != 0)
  27543. {
  27544. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  27545. if (clientSocket != 0)
  27546. {
  27547. InterprocessConnection* newConnection = createConnectionObject();
  27548. if (newConnection != 0)
  27549. {
  27550. newConnection->initialiseWithSocket (clientSocket);
  27551. }
  27552. else
  27553. {
  27554. delete clientSocket;
  27555. }
  27556. }
  27557. }
  27558. }
  27559. END_JUCE_NAMESPACE
  27560. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27561. /********* Start of inlined file: juce_Message.cpp *********/
  27562. BEGIN_JUCE_NAMESPACE
  27563. Message::Message() throw()
  27564. {
  27565. }
  27566. Message::~Message() throw()
  27567. {
  27568. }
  27569. Message::Message (const int intParameter1_,
  27570. const int intParameter2_,
  27571. const int intParameter3_,
  27572. void* const pointerParameter_) throw()
  27573. : intParameter1 (intParameter1_),
  27574. intParameter2 (intParameter2_),
  27575. intParameter3 (intParameter3_),
  27576. pointerParameter (pointerParameter_)
  27577. {
  27578. }
  27579. END_JUCE_NAMESPACE
  27580. /********* End of inlined file: juce_Message.cpp *********/
  27581. /********* Start of inlined file: juce_MessageListener.cpp *********/
  27582. BEGIN_JUCE_NAMESPACE
  27583. MessageListener::MessageListener() throw()
  27584. {
  27585. // are you trying to create a messagelistener before or after juce has been intialised??
  27586. jassert (MessageManager::instance != 0);
  27587. if (MessageManager::instance != 0)
  27588. MessageManager::instance->messageListeners.add (this);
  27589. }
  27590. MessageListener::~MessageListener()
  27591. {
  27592. if (MessageManager::instance != 0)
  27593. MessageManager::instance->messageListeners.removeValue (this);
  27594. }
  27595. void MessageListener::postMessage (Message* const message) const throw()
  27596. {
  27597. message->messageRecipient = const_cast <MessageListener*> (this);
  27598. if (MessageManager::instance == 0)
  27599. MessageManager::getInstance();
  27600. MessageManager::instance->postMessageToQueue (message);
  27601. }
  27602. bool MessageListener::isValidMessageListener() const throw()
  27603. {
  27604. return (MessageManager::instance != 0)
  27605. && MessageManager::instance->messageListeners.contains (this);
  27606. }
  27607. END_JUCE_NAMESPACE
  27608. /********* End of inlined file: juce_MessageListener.cpp *********/
  27609. /********* Start of inlined file: juce_MessageManager.cpp *********/
  27610. BEGIN_JUCE_NAMESPACE
  27611. // platform-specific functions..
  27612. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  27613. bool juce_postMessageToSystemQueue (void* message);
  27614. MessageManager* MessageManager::instance = 0;
  27615. static const int quitMessageId = 0xfffff321;
  27616. MessageManager::MessageManager() throw()
  27617. : broadcastListeners (0),
  27618. quitMessagePosted (false),
  27619. quitMessageReceived (false),
  27620. useMaximumForceWhenQuitting (true),
  27621. messageCounter (0),
  27622. lastMessageCounter (-1),
  27623. isInMessageDispatcher (0),
  27624. needToGetRidOfWaitCursor (false),
  27625. timeBeforeWaitCursor (0),
  27626. lastActivityCheckOkTime (0)
  27627. {
  27628. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  27629. }
  27630. MessageManager::~MessageManager() throw()
  27631. {
  27632. jassert (instance == this);
  27633. instance = 0;
  27634. deleteAndZero (broadcastListeners);
  27635. doPlatformSpecificShutdown();
  27636. }
  27637. MessageManager* MessageManager::getInstance() throw()
  27638. {
  27639. if (instance == 0)
  27640. {
  27641. instance = new MessageManager();
  27642. doPlatformSpecificInitialisation();
  27643. instance->setTimeBeforeShowingWaitCursor (500);
  27644. }
  27645. return instance;
  27646. }
  27647. void MessageManager::postMessageToQueue (Message* const message)
  27648. {
  27649. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  27650. delete message;
  27651. }
  27652. // not for public use..
  27653. void MessageManager::deliverMessage (void* message)
  27654. {
  27655. const MessageManagerLock lock;
  27656. Message* const m = (Message*) message;
  27657. MessageListener* const recipient = m->messageRecipient;
  27658. if (messageListeners.contains (recipient))
  27659. {
  27660. JUCE_TRY
  27661. {
  27662. recipient->handleMessage (*m);
  27663. }
  27664. JUCE_CATCH_EXCEPTION
  27665. if (needToGetRidOfWaitCursor)
  27666. {
  27667. needToGetRidOfWaitCursor = false;
  27668. MouseCursor::hideWaitCursor();
  27669. }
  27670. ++messageCounter;
  27671. }
  27672. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  27673. {
  27674. quitMessageReceived = true;
  27675. useMaximumForceWhenQuitting = (m->intParameter2 != 0);
  27676. }
  27677. delete m;
  27678. }
  27679. bool MessageManager::dispatchNextMessage (const bool returnImmediatelyIfNoMessages,
  27680. bool* const wasAMessageDispatched)
  27681. {
  27682. if (quitMessageReceived)
  27683. {
  27684. if (wasAMessageDispatched != 0)
  27685. *wasAMessageDispatched = false;
  27686. return false;
  27687. }
  27688. ++isInMessageDispatcher;
  27689. bool result = false;
  27690. JUCE_TRY
  27691. {
  27692. result = juce_dispatchNextMessageOnSystemQueue (returnImmediatelyIfNoMessages);
  27693. if (wasAMessageDispatched != 0)
  27694. *wasAMessageDispatched = result;
  27695. if (instance == 0)
  27696. return false;
  27697. }
  27698. JUCE_CATCH_EXCEPTION
  27699. --isInMessageDispatcher;
  27700. ++messageCounter;
  27701. return result || ! returnImmediatelyIfNoMessages;
  27702. }
  27703. void MessageManager::dispatchPendingMessages (int maxNumberOfMessagesToDispatch)
  27704. {
  27705. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27706. while (--maxNumberOfMessagesToDispatch >= 0 && ! quitMessageReceived)
  27707. {
  27708. ++isInMessageDispatcher;
  27709. bool carryOn = false;
  27710. JUCE_TRY
  27711. {
  27712. carryOn = juce_dispatchNextMessageOnSystemQueue (true);
  27713. }
  27714. JUCE_CATCH_EXCEPTION
  27715. --isInMessageDispatcher;
  27716. ++messageCounter;
  27717. if (! carryOn)
  27718. break;
  27719. }
  27720. }
  27721. bool MessageManager::runDispatchLoop()
  27722. {
  27723. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27724. while (dispatchNextMessage())
  27725. {
  27726. }
  27727. return useMaximumForceWhenQuitting;
  27728. }
  27729. void MessageManager::postQuitMessage (const bool useMaximumForce)
  27730. {
  27731. Message* const m = new Message (quitMessageId, (useMaximumForce) ? 1 : 0, 0, 0);
  27732. m->messageRecipient = 0;
  27733. postMessageToQueue (m);
  27734. quitMessagePosted = true;
  27735. }
  27736. bool MessageManager::hasQuitMessageBeenPosted() const throw()
  27737. {
  27738. return quitMessagePosted;
  27739. }
  27740. void MessageManager::deliverBroadcastMessage (const String& value)
  27741. {
  27742. if (broadcastListeners != 0)
  27743. broadcastListeners->sendActionMessage (value);
  27744. }
  27745. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  27746. {
  27747. if (broadcastListeners == 0)
  27748. broadcastListeners = new ActionListenerList();
  27749. broadcastListeners->addActionListener (listener);
  27750. }
  27751. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  27752. {
  27753. if (broadcastListeners != 0)
  27754. broadcastListeners->removeActionListener (listener);
  27755. }
  27756. // This gets called occasionally by the timer thread (to save using an extra thread
  27757. // for it).
  27758. void MessageManager::inactivityCheckCallback() throw()
  27759. {
  27760. if (instance != 0)
  27761. instance->inactivityCheckCallbackInt();
  27762. }
  27763. void MessageManager::inactivityCheckCallbackInt() throw()
  27764. {
  27765. const unsigned int now = Time::getApproximateMillisecondCounter();
  27766. if (isInMessageDispatcher > 0
  27767. && lastMessageCounter == messageCounter
  27768. && timeBeforeWaitCursor > 0
  27769. && lastActivityCheckOkTime > 0
  27770. && ! ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  27771. {
  27772. if (now >= lastActivityCheckOkTime + timeBeforeWaitCursor
  27773. && ! needToGetRidOfWaitCursor)
  27774. {
  27775. // been in the same message call too long..
  27776. MouseCursor::showWaitCursor();
  27777. needToGetRidOfWaitCursor = true;
  27778. }
  27779. }
  27780. else
  27781. {
  27782. lastActivityCheckOkTime = now;
  27783. lastMessageCounter = messageCounter;
  27784. }
  27785. }
  27786. void MessageManager::delayWaitCursor() throw()
  27787. {
  27788. if (instance != 0)
  27789. {
  27790. instance->messageCounter++;
  27791. if (instance->needToGetRidOfWaitCursor)
  27792. {
  27793. instance->needToGetRidOfWaitCursor = false;
  27794. MouseCursor::hideWaitCursor();
  27795. }
  27796. }
  27797. }
  27798. void MessageManager::setTimeBeforeShowingWaitCursor (const int millisecs) throw()
  27799. {
  27800. // if this is a bit too small you'll get a lot of unwanted hourglass cursors..
  27801. jassert (millisecs <= 0 || millisecs > 200);
  27802. timeBeforeWaitCursor = millisecs;
  27803. if (millisecs > 0)
  27804. startTimer (millisecs / 2); // (see timerCallback() for explanation of this)
  27805. else
  27806. stopTimer();
  27807. }
  27808. void MessageManager::timerCallback()
  27809. {
  27810. // dummy callback - the message manager is just a Timer to ensure that there are always
  27811. // some events coming in - otherwise it'll show the egg-timer/beachball-of-death.
  27812. ++messageCounter;
  27813. }
  27814. int MessageManager::getTimeBeforeShowingWaitCursor() const throw()
  27815. {
  27816. return timeBeforeWaitCursor;
  27817. }
  27818. bool MessageManager::isThisTheMessageThread() const throw()
  27819. {
  27820. return Thread::getCurrentThreadId() == messageThreadId;
  27821. }
  27822. void MessageManager::setCurrentMessageThread (const int threadId) throw()
  27823. {
  27824. messageThreadId = threadId;
  27825. }
  27826. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  27827. {
  27828. return Thread::getCurrentThreadId() == currentLockingThreadId;
  27829. }
  27830. MessageManagerLock::MessageManagerLock() throw()
  27831. : locked (false)
  27832. {
  27833. if (MessageManager::instance != 0)
  27834. {
  27835. MessageManager::instance->messageDispatchLock.enter();
  27836. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  27837. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  27838. locked = true;
  27839. }
  27840. }
  27841. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  27842. : locked (false)
  27843. {
  27844. jassert (thread != 0); // This will only work if you give it a valid thread!
  27845. if (MessageManager::instance != 0)
  27846. {
  27847. for (;;)
  27848. {
  27849. if (MessageManager::instance->messageDispatchLock.tryEnter())
  27850. {
  27851. locked = true;
  27852. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  27853. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  27854. break;
  27855. }
  27856. if (thread != 0 && thread->threadShouldExit())
  27857. break;
  27858. Thread::sleep (1);
  27859. }
  27860. }
  27861. }
  27862. MessageManagerLock::~MessageManagerLock() throw()
  27863. {
  27864. if (locked && MessageManager::instance != 0)
  27865. {
  27866. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  27867. MessageManager::instance->messageDispatchLock.exit();
  27868. }
  27869. }
  27870. END_JUCE_NAMESPACE
  27871. /********* End of inlined file: juce_MessageManager.cpp *********/
  27872. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  27873. BEGIN_JUCE_NAMESPACE
  27874. class InternalMultiTimerCallback : public Timer
  27875. {
  27876. public:
  27877. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  27878. : timerId (timerId_),
  27879. owner (owner_)
  27880. {
  27881. }
  27882. ~InternalMultiTimerCallback()
  27883. {
  27884. }
  27885. void timerCallback()
  27886. {
  27887. owner.timerCallback (timerId);
  27888. }
  27889. const int timerId;
  27890. private:
  27891. MultiTimer& owner;
  27892. };
  27893. MultiTimer::MultiTimer() throw()
  27894. {
  27895. }
  27896. MultiTimer::MultiTimer (const MultiTimer&) throw()
  27897. {
  27898. }
  27899. MultiTimer::~MultiTimer()
  27900. {
  27901. const ScopedLock sl (timerListLock);
  27902. for (int i = timers.size(); --i >= 0;)
  27903. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27904. timers.clear();
  27905. }
  27906. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  27907. {
  27908. const ScopedLock sl (timerListLock);
  27909. for (int i = timers.size(); --i >= 0;)
  27910. {
  27911. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27912. if (t->timerId == timerId)
  27913. {
  27914. t->startTimer (intervalInMilliseconds);
  27915. return;
  27916. }
  27917. }
  27918. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  27919. timers.add (newTimer);
  27920. newTimer->startTimer (intervalInMilliseconds);
  27921. }
  27922. void MultiTimer::stopTimer (const int timerId) throw()
  27923. {
  27924. const ScopedLock sl (timerListLock);
  27925. for (int i = timers.size(); --i >= 0;)
  27926. {
  27927. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27928. if (t->timerId == timerId)
  27929. t->stopTimer();
  27930. }
  27931. }
  27932. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  27933. {
  27934. const ScopedLock sl (timerListLock);
  27935. for (int i = timers.size(); --i >= 0;)
  27936. {
  27937. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27938. if (t->timerId == timerId)
  27939. return t->isTimerRunning();
  27940. }
  27941. return false;
  27942. }
  27943. int MultiTimer::getTimerInterval (const int timerId) const throw()
  27944. {
  27945. const ScopedLock sl (timerListLock);
  27946. for (int i = timers.size(); --i >= 0;)
  27947. {
  27948. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27949. if (t->timerId == timerId)
  27950. return t->getTimerInterval();
  27951. }
  27952. return 0;
  27953. }
  27954. END_JUCE_NAMESPACE
  27955. /********* End of inlined file: juce_MultiTimer.cpp *********/
  27956. /********* Start of inlined file: juce_Timer.cpp *********/
  27957. BEGIN_JUCE_NAMESPACE
  27958. class InternalTimerThread : private Thread,
  27959. private MessageListener,
  27960. private DeletedAtShutdown,
  27961. private AsyncUpdater
  27962. {
  27963. private:
  27964. friend class Timer;
  27965. static InternalTimerThread* instance;
  27966. static CriticalSection lock;
  27967. Timer* volatile firstTimer;
  27968. bool volatile callbackNeeded;
  27969. InternalTimerThread (const InternalTimerThread&);
  27970. const InternalTimerThread& operator= (const InternalTimerThread&);
  27971. void addTimer (Timer* const t) throw()
  27972. {
  27973. #ifdef JUCE_DEBUG
  27974. Timer* tt = firstTimer;
  27975. while (tt != 0)
  27976. {
  27977. // trying to add a timer that's already here - shouldn't get to this point,
  27978. // so if you get this assertion, let me know!
  27979. jassert (tt != t);
  27980. tt = tt->next;
  27981. }
  27982. jassert (t->previous == 0 && t->next == 0);
  27983. #endif
  27984. Timer* i = firstTimer;
  27985. if (i == 0 || i->countdownMs > t->countdownMs)
  27986. {
  27987. t->next = firstTimer;
  27988. firstTimer = t;
  27989. }
  27990. else
  27991. {
  27992. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  27993. i = i->next;
  27994. jassert (i != 0);
  27995. t->next = i->next;
  27996. t->previous = i;
  27997. i->next = t;
  27998. }
  27999. if (t->next != 0)
  28000. t->next->previous = t;
  28001. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  28002. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  28003. notify();
  28004. }
  28005. void removeTimer (Timer* const t) throw()
  28006. {
  28007. #ifdef JUCE_DEBUG
  28008. Timer* tt = firstTimer;
  28009. bool found = false;
  28010. while (tt != 0)
  28011. {
  28012. if (tt == t)
  28013. {
  28014. found = true;
  28015. break;
  28016. }
  28017. tt = tt->next;
  28018. }
  28019. // trying to remove a timer that's not here - shouldn't get to this point,
  28020. // so if you get this assertion, let me know!
  28021. jassert (found);
  28022. #endif
  28023. if (t->previous != 0)
  28024. {
  28025. jassert (firstTimer != t);
  28026. t->previous->next = t->next;
  28027. }
  28028. else
  28029. {
  28030. jassert (firstTimer == t);
  28031. firstTimer = t->next;
  28032. }
  28033. if (t->next != 0)
  28034. t->next->previous = t->previous;
  28035. t->next = 0;
  28036. t->previous = 0;
  28037. }
  28038. void decrementAllCounters (const int numMillisecs) const
  28039. {
  28040. Timer* t = firstTimer;
  28041. while (t != 0)
  28042. {
  28043. t->countdownMs -= numMillisecs;
  28044. t = t->next;
  28045. }
  28046. }
  28047. void handleAsyncUpdate()
  28048. {
  28049. startThread (7);
  28050. }
  28051. public:
  28052. InternalTimerThread()
  28053. : Thread ("Juce Timer"),
  28054. firstTimer (0),
  28055. callbackNeeded (false)
  28056. {
  28057. triggerAsyncUpdate();
  28058. }
  28059. ~InternalTimerThread() throw()
  28060. {
  28061. stopThread (4000);
  28062. jassert (instance == this || instance == 0);
  28063. if (instance == this)
  28064. instance = 0;
  28065. }
  28066. void run()
  28067. {
  28068. uint32 lastTime = Time::getMillisecondCounter();
  28069. uint32 lastMessageManagerCallback = lastTime;
  28070. while (! threadShouldExit())
  28071. {
  28072. uint32 now = Time::getMillisecondCounter();
  28073. if (now <= lastTime)
  28074. {
  28075. wait (2);
  28076. continue;
  28077. }
  28078. const int elapsed = now - lastTime;
  28079. lastTime = now;
  28080. lock.enter();
  28081. decrementAllCounters (elapsed);
  28082. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  28083. : 1000;
  28084. lock.exit();
  28085. if (timeUntilFirstTimer <= 0)
  28086. {
  28087. callbackNeeded = true;
  28088. postMessage (new Message());
  28089. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  28090. // so this is how long to wait before assuming the message has been lost and trying again.
  28091. const uint32 messageDeliveryTimeout = now + 2000;
  28092. while (callbackNeeded)
  28093. {
  28094. wait (4);
  28095. if (threadShouldExit())
  28096. return;
  28097. now = Time::getMillisecondCounter();
  28098. if (now > lastMessageManagerCallback + 200)
  28099. {
  28100. lastMessageManagerCallback = now;
  28101. MessageManager::inactivityCheckCallback();
  28102. }
  28103. if (now > messageDeliveryTimeout)
  28104. break;
  28105. }
  28106. }
  28107. else
  28108. {
  28109. // don't wait for too long because running this loop also helps keep the
  28110. // Time::getApproximateMillisecondTimer value stay up-to-date
  28111. wait (jlimit (1, 50, timeUntilFirstTimer));
  28112. }
  28113. if (now > lastMessageManagerCallback + 200)
  28114. {
  28115. lastMessageManagerCallback = now;
  28116. MessageManager::inactivityCheckCallback();
  28117. }
  28118. }
  28119. }
  28120. void handleMessage (const Message&)
  28121. {
  28122. const ScopedLock sl (lock);
  28123. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  28124. {
  28125. Timer* const t = firstTimer;
  28126. t->countdownMs = t->periodMs;
  28127. removeTimer (t);
  28128. addTimer (t);
  28129. const ScopedUnlock ul (lock);
  28130. callbackNeeded = false;
  28131. JUCE_TRY
  28132. {
  28133. t->timerCallback();
  28134. }
  28135. JUCE_CATCH_EXCEPTION
  28136. }
  28137. callbackNeeded = false;
  28138. }
  28139. static void callAnyTimersSynchronously()
  28140. {
  28141. if (InternalTimerThread::instance != 0)
  28142. {
  28143. const Message m;
  28144. InternalTimerThread::instance->handleMessage (m);
  28145. }
  28146. }
  28147. static inline void add (Timer* const tim) throw()
  28148. {
  28149. if (instance == 0)
  28150. instance = new InternalTimerThread();
  28151. instance->addTimer (tim);
  28152. }
  28153. static inline void remove (Timer* const tim) throw()
  28154. {
  28155. if (instance != 0)
  28156. instance->removeTimer (tim);
  28157. }
  28158. static inline void resetCounter (Timer* const tim,
  28159. const int newCounter) throw()
  28160. {
  28161. if (instance != 0)
  28162. {
  28163. tim->countdownMs = newCounter;
  28164. tim->periodMs = newCounter;
  28165. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  28166. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  28167. {
  28168. instance->removeTimer (tim);
  28169. instance->addTimer (tim);
  28170. }
  28171. }
  28172. }
  28173. };
  28174. InternalTimerThread* InternalTimerThread::instance = 0;
  28175. CriticalSection InternalTimerThread::lock;
  28176. void juce_callAnyTimersSynchronously()
  28177. {
  28178. InternalTimerThread::callAnyTimersSynchronously();
  28179. }
  28180. #ifdef JUCE_DEBUG
  28181. static SortedSet <Timer*> activeTimers;
  28182. #endif
  28183. Timer::Timer() throw()
  28184. : countdownMs (0),
  28185. periodMs (0),
  28186. previous (0),
  28187. next (0)
  28188. {
  28189. #ifdef JUCE_DEBUG
  28190. activeTimers.add (this);
  28191. #endif
  28192. }
  28193. Timer::Timer (const Timer&) throw()
  28194. : countdownMs (0),
  28195. periodMs (0),
  28196. previous (0),
  28197. next (0)
  28198. {
  28199. #ifdef JUCE_DEBUG
  28200. activeTimers.add (this);
  28201. #endif
  28202. }
  28203. Timer::~Timer()
  28204. {
  28205. stopTimer();
  28206. #ifdef JUCE_DEBUG
  28207. activeTimers.removeValue (this);
  28208. #endif
  28209. }
  28210. void Timer::startTimer (const int interval) throw()
  28211. {
  28212. const ScopedLock sl (InternalTimerThread::lock);
  28213. #ifdef JUCE_DEBUG
  28214. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28215. jassert (activeTimers.contains (this));
  28216. #endif
  28217. if (periodMs == 0)
  28218. {
  28219. countdownMs = interval;
  28220. periodMs = jmax (1, interval);
  28221. InternalTimerThread::add (this);
  28222. }
  28223. else
  28224. {
  28225. InternalTimerThread::resetCounter (this, interval);
  28226. }
  28227. }
  28228. void Timer::stopTimer() throw()
  28229. {
  28230. const ScopedLock sl (InternalTimerThread::lock);
  28231. #ifdef JUCE_DEBUG
  28232. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28233. jassert (activeTimers.contains (this));
  28234. #endif
  28235. if (periodMs > 0)
  28236. {
  28237. InternalTimerThread::remove (this);
  28238. periodMs = 0;
  28239. }
  28240. }
  28241. END_JUCE_NAMESPACE
  28242. /********* End of inlined file: juce_Timer.cpp *********/
  28243. /********* Start of inlined file: juce_Component.cpp *********/
  28244. BEGIN_JUCE_NAMESPACE
  28245. Component* Component::componentUnderMouse = 0;
  28246. Component* Component::currentlyFocusedComponent = 0;
  28247. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  28248. static Array <int> modalReturnValues (4);
  28249. static const int customCommandMessage = 0x7fff0001;
  28250. static const int exitModalStateMessage = 0x7fff0002;
  28251. // these are also used by ComponentPeer
  28252. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  28253. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  28254. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  28255. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  28256. int juce_LastMousePosX = 0;
  28257. int juce_LastMousePosY = 0;
  28258. int juce_MouseClickCounter = 0;
  28259. bool juce_MouseHasMovedSignificantlySincePressed = false;
  28260. static int countMouseClicks() throw()
  28261. {
  28262. int numClicks = 0;
  28263. if (juce_recentMouseDownTimes[0] != 0)
  28264. {
  28265. if (! juce_MouseHasMovedSignificantlySincePressed)
  28266. ++numClicks;
  28267. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  28268. {
  28269. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  28270. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  28271. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  28272. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  28273. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  28274. {
  28275. ++numClicks;
  28276. }
  28277. else
  28278. {
  28279. break;
  28280. }
  28281. }
  28282. }
  28283. return numClicks;
  28284. }
  28285. static int unboundedMouseOffsetX = 0;
  28286. static int unboundedMouseOffsetY = 0;
  28287. static bool isUnboundedMouseModeOn = false;
  28288. static bool isCursorVisibleUntilOffscreen;
  28289. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  28290. static uint32 nextComponentUID = 0;
  28291. Component::Component() throw()
  28292. : parentComponent_ (0),
  28293. componentUID (++nextComponentUID),
  28294. numDeepMouseListeners (0),
  28295. childComponentList_ (16),
  28296. lookAndFeel_ (0),
  28297. effect_ (0),
  28298. bufferedImage_ (0),
  28299. mouseListeners_ (0),
  28300. keyListeners_ (0),
  28301. componentListeners_ (0),
  28302. propertySet_ (0),
  28303. componentFlags_ (0)
  28304. {
  28305. }
  28306. Component::Component (const String& name) throw()
  28307. : componentName_ (name),
  28308. parentComponent_ (0),
  28309. componentUID (++nextComponentUID),
  28310. numDeepMouseListeners (0),
  28311. childComponentList_ (16),
  28312. lookAndFeel_ (0),
  28313. effect_ (0),
  28314. bufferedImage_ (0),
  28315. mouseListeners_ (0),
  28316. keyListeners_ (0),
  28317. componentListeners_ (0),
  28318. propertySet_ (0),
  28319. componentFlags_ (0)
  28320. {
  28321. }
  28322. Component::~Component()
  28323. {
  28324. if (parentComponent_ != 0)
  28325. {
  28326. parentComponent_->removeChildComponent (this);
  28327. }
  28328. else if ((currentlyFocusedComponent == this)
  28329. || isParentOf (currentlyFocusedComponent))
  28330. {
  28331. giveAwayFocus();
  28332. }
  28333. if (componentUnderMouse == this)
  28334. componentUnderMouse = 0;
  28335. if (flags.hasHeavyweightPeerFlag)
  28336. removeFromDesktop();
  28337. modalComponentStack.removeValue (this);
  28338. for (int i = childComponentList_.size(); --i >= 0;)
  28339. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  28340. delete bufferedImage_;
  28341. delete mouseListeners_;
  28342. delete keyListeners_;
  28343. delete componentListeners_;
  28344. delete propertySet_;
  28345. }
  28346. void Component::setName (const String& name)
  28347. {
  28348. // if component methods are being called from threads other than the message
  28349. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28350. checkMessageManagerIsLocked
  28351. if (componentName_ != name)
  28352. {
  28353. componentName_ = name;
  28354. if (flags.hasHeavyweightPeerFlag)
  28355. {
  28356. ComponentPeer* const peer = getPeer();
  28357. jassert (peer != 0);
  28358. if (peer != 0)
  28359. peer->setTitle (name);
  28360. }
  28361. if (componentListeners_ != 0)
  28362. {
  28363. const ComponentDeletionWatcher deletionChecker (this);
  28364. for (int i = componentListeners_->size(); --i >= 0;)
  28365. {
  28366. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28367. ->componentNameChanged (*this);
  28368. if (deletionChecker.hasBeenDeleted())
  28369. return;
  28370. i = jmin (i, componentListeners_->size());
  28371. }
  28372. }
  28373. }
  28374. }
  28375. void Component::setVisible (bool shouldBeVisible)
  28376. {
  28377. if (flags.visibleFlag != shouldBeVisible)
  28378. {
  28379. // if component methods are being called from threads other than the message
  28380. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28381. checkMessageManagerIsLocked
  28382. const ComponentDeletionWatcher deletionChecker (this);
  28383. flags.visibleFlag = shouldBeVisible;
  28384. internalRepaint (0, 0, getWidth(), getHeight());
  28385. sendFakeMouseMove();
  28386. if (! shouldBeVisible)
  28387. {
  28388. if (currentlyFocusedComponent == this
  28389. || isParentOf (currentlyFocusedComponent))
  28390. {
  28391. if (parentComponent_ != 0)
  28392. parentComponent_->grabKeyboardFocus();
  28393. else
  28394. giveAwayFocus();
  28395. }
  28396. }
  28397. sendVisibilityChangeMessage();
  28398. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  28399. {
  28400. ComponentPeer* const peer = getPeer();
  28401. jassert (peer != 0);
  28402. if (peer != 0)
  28403. {
  28404. peer->setVisible (shouldBeVisible);
  28405. internalHierarchyChanged();
  28406. }
  28407. }
  28408. }
  28409. }
  28410. void Component::visibilityChanged()
  28411. {
  28412. }
  28413. void Component::sendVisibilityChangeMessage()
  28414. {
  28415. const ComponentDeletionWatcher deletionChecker (this);
  28416. visibilityChanged();
  28417. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  28418. {
  28419. for (int i = componentListeners_->size(); --i >= 0;)
  28420. {
  28421. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28422. ->componentVisibilityChanged (*this);
  28423. if (deletionChecker.hasBeenDeleted())
  28424. return;
  28425. i = jmin (i, componentListeners_->size());
  28426. }
  28427. }
  28428. }
  28429. bool Component::isShowing() const throw()
  28430. {
  28431. if (flags.visibleFlag)
  28432. {
  28433. if (parentComponent_ != 0)
  28434. {
  28435. return parentComponent_->isShowing();
  28436. }
  28437. else
  28438. {
  28439. const ComponentPeer* const peer = getPeer();
  28440. return peer != 0 && ! peer->isMinimised();
  28441. }
  28442. }
  28443. return false;
  28444. }
  28445. class FadeOutProxyComponent : public Component,
  28446. public Timer
  28447. {
  28448. public:
  28449. FadeOutProxyComponent (Component* comp,
  28450. const int fadeLengthMs,
  28451. const int deltaXToMove,
  28452. const int deltaYToMove,
  28453. const float scaleFactorAtEnd)
  28454. : lastTime (0),
  28455. alpha (1.0f),
  28456. scale (1.0f)
  28457. {
  28458. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  28459. setBounds (comp->getBounds());
  28460. comp->getParentComponent()->addAndMakeVisible (this);
  28461. toBehind (comp);
  28462. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  28463. centreX = comp->getX() + comp->getWidth() * 0.5f;
  28464. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  28465. centreY = comp->getY() + comp->getHeight() * 0.5f;
  28466. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  28467. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  28468. setInterceptsMouseClicks (false, false);
  28469. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  28470. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  28471. }
  28472. ~FadeOutProxyComponent()
  28473. {
  28474. delete image;
  28475. }
  28476. void paint (Graphics& g)
  28477. {
  28478. g.setOpacity (alpha);
  28479. g.drawImage (image,
  28480. 0, 0, getWidth(), getHeight(),
  28481. 0, 0, image->getWidth(), image->getHeight());
  28482. }
  28483. void timerCallback()
  28484. {
  28485. const uint32 now = Time::getMillisecondCounter();
  28486. if (lastTime == 0)
  28487. lastTime = now;
  28488. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  28489. lastTime = now;
  28490. alpha += alphaChangePerMs * msPassed;
  28491. if (alpha > 0)
  28492. {
  28493. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  28494. {
  28495. centreX += xChangePerMs * msPassed;
  28496. centreY += yChangePerMs * msPassed;
  28497. scale += scaleChangePerMs * msPassed;
  28498. const int w = roundFloatToInt (image->getWidth() * scale);
  28499. const int h = roundFloatToInt (image->getHeight() * scale);
  28500. setBounds (roundFloatToInt (centreX) - w / 2,
  28501. roundFloatToInt (centreY) - h / 2,
  28502. w, h);
  28503. }
  28504. repaint();
  28505. }
  28506. else
  28507. {
  28508. delete this;
  28509. }
  28510. }
  28511. juce_UseDebuggingNewOperator
  28512. private:
  28513. Image* image;
  28514. uint32 lastTime;
  28515. float alpha, alphaChangePerMs;
  28516. float centreX, xChangePerMs;
  28517. float centreY, yChangePerMs;
  28518. float scale, scaleChangePerMs;
  28519. FadeOutProxyComponent (const FadeOutProxyComponent&);
  28520. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  28521. };
  28522. void Component::fadeOutComponent (const int millisecondsToFade,
  28523. const int deltaXToMove,
  28524. const int deltaYToMove,
  28525. const float scaleFactorAtEnd)
  28526. {
  28527. //xxx won't work for comps without parents
  28528. if (isShowing() && millisecondsToFade > 0)
  28529. new FadeOutProxyComponent (this, millisecondsToFade,
  28530. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  28531. setVisible (false);
  28532. }
  28533. bool Component::isValidComponent() const throw()
  28534. {
  28535. return (this != 0) && isValidMessageListener();
  28536. }
  28537. void* Component::getWindowHandle() const throw()
  28538. {
  28539. const ComponentPeer* const peer = getPeer();
  28540. if (peer != 0)
  28541. return peer->getNativeHandle();
  28542. return 0;
  28543. }
  28544. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  28545. {
  28546. // if component methods are being called from threads other than the message
  28547. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28548. checkMessageManagerIsLocked
  28549. if (! isOpaque())
  28550. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  28551. int currentStyleFlags = 0;
  28552. // don't use getPeer(), so that we only get the peer that's specifically
  28553. // for this comp, and not for one of its parents.
  28554. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  28555. if (peer != 0)
  28556. currentStyleFlags = peer->getStyleFlags();
  28557. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  28558. {
  28559. const ComponentDeletionWatcher deletionChecker (this);
  28560. #if JUCE_LINUX
  28561. // it's wise to give the component a non-zero size before
  28562. // putting it on the desktop, as X windows get confused by this, and
  28563. // a (1, 1) minimum size is enforced here.
  28564. setSize (jmax (1, getWidth()),
  28565. jmax (1, getHeight()));
  28566. #endif
  28567. int x = 0, y = 0;
  28568. relativePositionToGlobal (x, y);
  28569. bool wasFullscreen = false;
  28570. bool wasMinimised = false;
  28571. ComponentBoundsConstrainer* currentConstainer = 0;
  28572. Rectangle oldNonFullScreenBounds;
  28573. if (peer != 0)
  28574. {
  28575. wasFullscreen = peer->isFullScreen();
  28576. wasMinimised = peer->isMinimised();
  28577. currentConstainer = peer->getConstrainer();
  28578. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  28579. removeFromDesktop();
  28580. }
  28581. if (parentComponent_ != 0)
  28582. parentComponent_->removeChildComponent (this);
  28583. if (! deletionChecker.hasBeenDeleted())
  28584. {
  28585. flags.hasHeavyweightPeerFlag = true;
  28586. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  28587. Desktop::getInstance().addDesktopComponent (this);
  28588. bounds_.setPosition (x, y);
  28589. peer->setBounds (x, y, getWidth(), getHeight(), false);
  28590. peer->setVisible (isVisible());
  28591. if (wasFullscreen)
  28592. {
  28593. peer->setFullScreen (true);
  28594. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  28595. }
  28596. if (wasMinimised)
  28597. peer->setMinimised (true);
  28598. if (isAlwaysOnTop())
  28599. peer->setAlwaysOnTop (true);
  28600. peer->setConstrainer (currentConstainer);
  28601. repaint();
  28602. }
  28603. internalHierarchyChanged();
  28604. }
  28605. }
  28606. void Component::removeFromDesktop()
  28607. {
  28608. // if component methods are being called from threads other than the message
  28609. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28610. checkMessageManagerIsLocked
  28611. if (flags.hasHeavyweightPeerFlag)
  28612. {
  28613. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28614. flags.hasHeavyweightPeerFlag = false;
  28615. jassert (peer != 0);
  28616. delete peer;
  28617. Desktop::getInstance().removeDesktopComponent (this);
  28618. }
  28619. }
  28620. bool Component::isOnDesktop() const throw()
  28621. {
  28622. return flags.hasHeavyweightPeerFlag;
  28623. }
  28624. void Component::userTriedToCloseWindow()
  28625. {
  28626. /* This means that the user's trying to get rid of your window with the 'close window' system
  28627. menu option (on windows) or possibly the task manager - you should really handle this
  28628. and delete or hide your component in an appropriate way.
  28629. If you want to ignore the event and don't want to trigger this assertion, just override
  28630. this method and do nothing.
  28631. */
  28632. jassertfalse
  28633. }
  28634. void Component::minimisationStateChanged (bool)
  28635. {
  28636. }
  28637. void Component::setOpaque (const bool shouldBeOpaque) throw()
  28638. {
  28639. if (shouldBeOpaque != flags.opaqueFlag)
  28640. {
  28641. flags.opaqueFlag = shouldBeOpaque;
  28642. if (flags.hasHeavyweightPeerFlag)
  28643. {
  28644. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28645. if (peer != 0)
  28646. {
  28647. // to make it recreate the heavyweight window
  28648. addToDesktop (peer->getStyleFlags());
  28649. }
  28650. }
  28651. repaint();
  28652. }
  28653. }
  28654. bool Component::isOpaque() const throw()
  28655. {
  28656. return flags.opaqueFlag;
  28657. }
  28658. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  28659. {
  28660. if (shouldBeBuffered != flags.bufferToImageFlag)
  28661. {
  28662. deleteAndZero (bufferedImage_);
  28663. flags.bufferToImageFlag = shouldBeBuffered;
  28664. }
  28665. }
  28666. void Component::toFront (const bool setAsForeground)
  28667. {
  28668. // if component methods are being called from threads other than the message
  28669. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28670. checkMessageManagerIsLocked
  28671. if (flags.hasHeavyweightPeerFlag)
  28672. {
  28673. ComponentPeer* const peer = getPeer();
  28674. if (peer != 0)
  28675. {
  28676. peer->toFront (setAsForeground);
  28677. if (setAsForeground && ! hasKeyboardFocus (true))
  28678. grabKeyboardFocus();
  28679. }
  28680. }
  28681. else if (parentComponent_ != 0)
  28682. {
  28683. if (parentComponent_->childComponentList_.getLast() != this)
  28684. {
  28685. const int index = parentComponent_->childComponentList_.indexOf (this);
  28686. if (index >= 0)
  28687. {
  28688. int insertIndex = -1;
  28689. if (! flags.alwaysOnTopFlag)
  28690. {
  28691. insertIndex = parentComponent_->childComponentList_.size() - 1;
  28692. while (insertIndex > 0
  28693. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28694. {
  28695. --insertIndex;
  28696. }
  28697. }
  28698. if (index != insertIndex)
  28699. {
  28700. parentComponent_->childComponentList_.move (index, insertIndex);
  28701. sendFakeMouseMove();
  28702. repaintParent();
  28703. }
  28704. }
  28705. }
  28706. if (setAsForeground)
  28707. {
  28708. internalBroughtToFront();
  28709. grabKeyboardFocus();
  28710. }
  28711. }
  28712. }
  28713. void Component::toBehind (Component* const other)
  28714. {
  28715. if (other != 0)
  28716. {
  28717. // the two components must belong to the same parent..
  28718. jassert (parentComponent_ == other->parentComponent_);
  28719. if (parentComponent_ != 0)
  28720. {
  28721. const int index = parentComponent_->childComponentList_.indexOf (this);
  28722. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  28723. if (index >= 0
  28724. && otherIndex >= 0
  28725. && index != otherIndex - 1
  28726. && other != this)
  28727. {
  28728. if (index < otherIndex)
  28729. --otherIndex;
  28730. parentComponent_->childComponentList_.move (index, otherIndex);
  28731. sendFakeMouseMove();
  28732. repaintParent();
  28733. }
  28734. }
  28735. else if (isOnDesktop())
  28736. {
  28737. jassert (other->isOnDesktop());
  28738. if (other->isOnDesktop())
  28739. {
  28740. ComponentPeer* const us = getPeer();
  28741. ComponentPeer* const them = other->getPeer();
  28742. jassert (us != 0 && them != 0);
  28743. if (us != 0 && them != 0)
  28744. us->toBehind (them);
  28745. }
  28746. }
  28747. }
  28748. }
  28749. void Component::toBack()
  28750. {
  28751. if (isOnDesktop())
  28752. {
  28753. jassertfalse //xxx need to add this to native window
  28754. }
  28755. else if (parentComponent_ != 0
  28756. && parentComponent_->childComponentList_.getFirst() != this)
  28757. {
  28758. const int index = parentComponent_->childComponentList_.indexOf (this);
  28759. if (index > 0)
  28760. {
  28761. int insertIndex = 0;
  28762. if (flags.alwaysOnTopFlag)
  28763. {
  28764. while (insertIndex < parentComponent_->childComponentList_.size()
  28765. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28766. {
  28767. ++insertIndex;
  28768. }
  28769. }
  28770. if (index != insertIndex)
  28771. {
  28772. parentComponent_->childComponentList_.move (index, insertIndex);
  28773. sendFakeMouseMove();
  28774. repaintParent();
  28775. }
  28776. }
  28777. }
  28778. }
  28779. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  28780. {
  28781. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  28782. {
  28783. flags.alwaysOnTopFlag = shouldStayOnTop;
  28784. if (isOnDesktop())
  28785. {
  28786. ComponentPeer* const peer = getPeer();
  28787. jassert (peer != 0);
  28788. if (peer != 0)
  28789. {
  28790. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  28791. {
  28792. // some kinds of peer can't change their always-on-top status, so
  28793. // for these, we'll need to create a new window
  28794. const int oldFlags = peer->getStyleFlags();
  28795. removeFromDesktop();
  28796. addToDesktop (oldFlags);
  28797. }
  28798. }
  28799. }
  28800. if (shouldStayOnTop)
  28801. toFront (false);
  28802. internalHierarchyChanged();
  28803. }
  28804. }
  28805. bool Component::isAlwaysOnTop() const throw()
  28806. {
  28807. return flags.alwaysOnTopFlag;
  28808. }
  28809. int Component::proportionOfWidth (const float proportion) const throw()
  28810. {
  28811. return roundDoubleToInt (proportion * bounds_.getWidth());
  28812. }
  28813. int Component::proportionOfHeight (const float proportion) const throw()
  28814. {
  28815. return roundDoubleToInt (proportion * bounds_.getHeight());
  28816. }
  28817. int Component::getParentWidth() const throw()
  28818. {
  28819. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  28820. : getParentMonitorArea().getWidth();
  28821. }
  28822. int Component::getParentHeight() const throw()
  28823. {
  28824. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  28825. : getParentMonitorArea().getHeight();
  28826. }
  28827. int Component::getScreenX() const throw()
  28828. {
  28829. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  28830. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  28831. : getX());
  28832. }
  28833. int Component::getScreenY() const throw()
  28834. {
  28835. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  28836. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  28837. : getY());
  28838. }
  28839. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  28840. {
  28841. const Component* c = this;
  28842. do
  28843. {
  28844. if (c->flags.hasHeavyweightPeerFlag)
  28845. {
  28846. c->getPeer()->relativePositionToGlobal (x, y);
  28847. break;
  28848. }
  28849. x += c->getX();
  28850. y += c->getY();
  28851. c = c->parentComponent_;
  28852. }
  28853. while (c != 0);
  28854. }
  28855. void Component::globalPositionToRelative (int& x, int& y) const throw()
  28856. {
  28857. if (flags.hasHeavyweightPeerFlag)
  28858. {
  28859. getPeer()->globalPositionToRelative (x, y);
  28860. }
  28861. else
  28862. {
  28863. if (parentComponent_ != 0)
  28864. parentComponent_->globalPositionToRelative (x, y);
  28865. x -= getX();
  28866. y -= getY();
  28867. }
  28868. }
  28869. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  28870. {
  28871. if (targetComponent != 0)
  28872. {
  28873. const Component* c = this;
  28874. do
  28875. {
  28876. if (c == targetComponent)
  28877. return;
  28878. if (c->flags.hasHeavyweightPeerFlag)
  28879. {
  28880. c->getPeer()->relativePositionToGlobal (x, y);
  28881. break;
  28882. }
  28883. x += c->getX();
  28884. y += c->getY();
  28885. c = c->parentComponent_;
  28886. }
  28887. while (c != 0);
  28888. targetComponent->globalPositionToRelative (x, y);
  28889. }
  28890. }
  28891. void Component::setBounds (int x, int y, int w, int h)
  28892. {
  28893. // if component methods are being called from threads other than the message
  28894. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28895. checkMessageManagerIsLocked
  28896. if (w < 0) w = 0;
  28897. if (h < 0) h = 0;
  28898. const bool wasResized = (getWidth() != w || getHeight() != h);
  28899. const bool wasMoved = (getX() != x || getY() != y);
  28900. #ifdef JUCE_DEBUG
  28901. // It's a very bad idea to try to resize a window during its paint() method!
  28902. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  28903. #endif
  28904. if (wasMoved || wasResized)
  28905. {
  28906. if (flags.visibleFlag)
  28907. {
  28908. // send a fake mouse move to trigger enter/exit messages if needed..
  28909. sendFakeMouseMove();
  28910. if (! flags.hasHeavyweightPeerFlag)
  28911. repaintParent();
  28912. }
  28913. bounds_.setBounds (x, y, w, h);
  28914. if (wasResized)
  28915. repaint();
  28916. else if (! flags.hasHeavyweightPeerFlag)
  28917. repaintParent();
  28918. if (flags.hasHeavyweightPeerFlag)
  28919. {
  28920. ComponentPeer* const peer = getPeer();
  28921. if (peer != 0)
  28922. {
  28923. if (wasMoved && wasResized)
  28924. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  28925. else if (wasMoved)
  28926. peer->setPosition (getX(), getY());
  28927. else if (wasResized)
  28928. peer->setSize (getWidth(), getHeight());
  28929. }
  28930. }
  28931. sendMovedResizedMessages (wasMoved, wasResized);
  28932. }
  28933. }
  28934. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  28935. {
  28936. JUCE_TRY
  28937. {
  28938. if (wasMoved)
  28939. moved();
  28940. if (wasResized)
  28941. {
  28942. resized();
  28943. for (int i = childComponentList_.size(); --i >= 0;)
  28944. {
  28945. childComponentList_.getUnchecked(i)->parentSizeChanged();
  28946. i = jmin (i, childComponentList_.size());
  28947. }
  28948. }
  28949. if (parentComponent_ != 0)
  28950. parentComponent_->childBoundsChanged (this);
  28951. if (componentListeners_ != 0)
  28952. {
  28953. const ComponentDeletionWatcher deletionChecker (this);
  28954. for (int i = componentListeners_->size(); --i >= 0;)
  28955. {
  28956. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28957. ->componentMovedOrResized (*this, wasMoved, wasResized);
  28958. if (deletionChecker.hasBeenDeleted())
  28959. return;
  28960. i = jmin (i, componentListeners_->size());
  28961. }
  28962. }
  28963. }
  28964. JUCE_CATCH_EXCEPTION
  28965. }
  28966. void Component::setSize (const int w, const int h)
  28967. {
  28968. setBounds (getX(), getY(), w, h);
  28969. }
  28970. void Component::setTopLeftPosition (const int x, const int y)
  28971. {
  28972. setBounds (x, y, getWidth(), getHeight());
  28973. }
  28974. void Component::setTopRightPosition (const int x, const int y)
  28975. {
  28976. setTopLeftPosition (x - getWidth(), y);
  28977. }
  28978. void Component::setBounds (const Rectangle& r)
  28979. {
  28980. setBounds (r.getX(),
  28981. r.getY(),
  28982. r.getWidth(),
  28983. r.getHeight());
  28984. }
  28985. void Component::setBoundsRelative (const float x, const float y,
  28986. const float w, const float h)
  28987. {
  28988. const int pw = getParentWidth();
  28989. const int ph = getParentHeight();
  28990. setBounds (roundFloatToInt (x * pw),
  28991. roundFloatToInt (y * ph),
  28992. roundFloatToInt (w * pw),
  28993. roundFloatToInt (h * ph));
  28994. }
  28995. void Component::setCentrePosition (const int x, const int y)
  28996. {
  28997. setTopLeftPosition (x - getWidth() / 2,
  28998. y - getHeight() / 2);
  28999. }
  29000. void Component::setCentreRelative (const float x, const float y)
  29001. {
  29002. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  29003. roundFloatToInt (getParentHeight() * y));
  29004. }
  29005. void Component::centreWithSize (const int width, const int height)
  29006. {
  29007. setBounds ((getParentWidth() - width) / 2,
  29008. (getParentHeight() - height) / 2,
  29009. width,
  29010. height);
  29011. }
  29012. void Component::setBoundsInset (const BorderSize& borders)
  29013. {
  29014. setBounds (borders.getLeft(),
  29015. borders.getTop(),
  29016. getParentWidth() - (borders.getLeftAndRight()),
  29017. getParentHeight() - (borders.getTopAndBottom()));
  29018. }
  29019. void Component::setBoundsToFit (int x, int y, int width, int height,
  29020. const Justification& justification,
  29021. const bool onlyReduceInSize)
  29022. {
  29023. // it's no good calling this method unless both the component and
  29024. // target rectangle have a finite size.
  29025. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  29026. if (getWidth() > 0 && getHeight() > 0
  29027. && width > 0 && height > 0)
  29028. {
  29029. int newW, newH;
  29030. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  29031. {
  29032. newW = getWidth();
  29033. newH = getHeight();
  29034. }
  29035. else
  29036. {
  29037. const double imageRatio = getHeight() / (double) getWidth();
  29038. const double targetRatio = height / (double) width;
  29039. if (imageRatio <= targetRatio)
  29040. {
  29041. newW = width;
  29042. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  29043. }
  29044. else
  29045. {
  29046. newH = height;
  29047. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  29048. }
  29049. }
  29050. if (newW > 0 && newH > 0)
  29051. {
  29052. int newX, newY;
  29053. justification.applyToRectangle (newX, newY, newW, newH,
  29054. x, y, width, height);
  29055. setBounds (newX, newY, newW, newH);
  29056. }
  29057. }
  29058. }
  29059. bool Component::hitTest (int x, int y)
  29060. {
  29061. if (! flags.ignoresMouseClicksFlag)
  29062. return true;
  29063. if (flags.allowChildMouseClicksFlag)
  29064. {
  29065. for (int i = getNumChildComponents(); --i >= 0;)
  29066. {
  29067. Component* const c = getChildComponent (i);
  29068. if (c->isVisible()
  29069. && c->bounds_.contains (x, y)
  29070. && c->hitTest (x - c->getX(),
  29071. y - c->getY()))
  29072. {
  29073. return true;
  29074. }
  29075. }
  29076. }
  29077. return false;
  29078. }
  29079. void Component::setInterceptsMouseClicks (const bool allowClicks,
  29080. const bool allowClicksOnChildComponents) throw()
  29081. {
  29082. flags.ignoresMouseClicksFlag = ! allowClicks;
  29083. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  29084. }
  29085. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  29086. bool& allowsClicksOnChildComponents) const throw()
  29087. {
  29088. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  29089. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  29090. }
  29091. bool Component::contains (const int x, const int y)
  29092. {
  29093. if (((unsigned int) x) < (unsigned int) getWidth()
  29094. && ((unsigned int) y) < (unsigned int) getHeight()
  29095. && hitTest (x, y))
  29096. {
  29097. if (parentComponent_ != 0)
  29098. {
  29099. return parentComponent_->contains (x + getX(),
  29100. y + getY());
  29101. }
  29102. else if (flags.hasHeavyweightPeerFlag)
  29103. {
  29104. const ComponentPeer* const peer = getPeer();
  29105. if (peer != 0)
  29106. return peer->contains (x, y, true);
  29107. }
  29108. }
  29109. return false;
  29110. }
  29111. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  29112. {
  29113. if (! contains (x, y))
  29114. return false;
  29115. Component* p = this;
  29116. while (p->parentComponent_ != 0)
  29117. {
  29118. x += p->getX();
  29119. y += p->getY();
  29120. p = p->parentComponent_;
  29121. }
  29122. const Component* const c = p->getComponentAt (x, y);
  29123. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  29124. }
  29125. Component* Component::getComponentAt (const int x, const int y)
  29126. {
  29127. if (flags.visibleFlag
  29128. && ((unsigned int) x) < (unsigned int) getWidth()
  29129. && ((unsigned int) y) < (unsigned int) getHeight()
  29130. && hitTest (x, y))
  29131. {
  29132. for (int i = childComponentList_.size(); --i >= 0;)
  29133. {
  29134. Component* const child = childComponentList_.getUnchecked(i);
  29135. Component* const c = child->getComponentAt (x - child->getX(),
  29136. y - child->getY());
  29137. if (c != 0)
  29138. return c;
  29139. }
  29140. return this;
  29141. }
  29142. return 0;
  29143. }
  29144. void Component::addChildComponent (Component* const child, int zOrder)
  29145. {
  29146. // if component methods are being called from threads other than the message
  29147. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29148. checkMessageManagerIsLocked
  29149. if (child != 0 && child->parentComponent_ != this)
  29150. {
  29151. if (child->parentComponent_ != 0)
  29152. child->parentComponent_->removeChildComponent (child);
  29153. else
  29154. child->removeFromDesktop();
  29155. child->parentComponent_ = this;
  29156. if (child->isVisible())
  29157. child->repaintParent();
  29158. if (! child->isAlwaysOnTop())
  29159. {
  29160. if (zOrder < 0)
  29161. zOrder = childComponentList_.size();
  29162. while (zOrder > 0)
  29163. {
  29164. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  29165. break;
  29166. --zOrder;
  29167. }
  29168. }
  29169. childComponentList_.insert (zOrder, child);
  29170. child->internalHierarchyChanged();
  29171. internalChildrenChanged();
  29172. }
  29173. }
  29174. void Component::addAndMakeVisible (Component* const child, int zOrder)
  29175. {
  29176. if (child != 0)
  29177. {
  29178. child->setVisible (true);
  29179. addChildComponent (child, zOrder);
  29180. }
  29181. }
  29182. void Component::removeChildComponent (Component* const child)
  29183. {
  29184. removeChildComponent (childComponentList_.indexOf (child));
  29185. }
  29186. Component* Component::removeChildComponent (const int index)
  29187. {
  29188. // if component methods are being called from threads other than the message
  29189. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29190. checkMessageManagerIsLocked
  29191. Component* const child = childComponentList_ [index];
  29192. if (child != 0)
  29193. {
  29194. sendFakeMouseMove();
  29195. child->repaintParent();
  29196. childComponentList_.remove (index);
  29197. child->parentComponent_ = 0;
  29198. JUCE_TRY
  29199. {
  29200. if ((currentlyFocusedComponent == child)
  29201. || child->isParentOf (currentlyFocusedComponent))
  29202. {
  29203. // get rid first to force the grabKeyboardFocus to change to us.
  29204. giveAwayFocus();
  29205. grabKeyboardFocus();
  29206. }
  29207. }
  29208. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29209. catch (const std::exception& e)
  29210. {
  29211. currentlyFocusedComponent = 0;
  29212. Desktop::getInstance().triggerFocusCallback();
  29213. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29214. }
  29215. catch (...)
  29216. {
  29217. currentlyFocusedComponent = 0;
  29218. Desktop::getInstance().triggerFocusCallback();
  29219. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29220. }
  29221. #endif
  29222. child->internalHierarchyChanged();
  29223. internalChildrenChanged();
  29224. }
  29225. return child;
  29226. }
  29227. void Component::removeAllChildren()
  29228. {
  29229. for (int i = childComponentList_.size(); --i >= 0;)
  29230. removeChildComponent (i);
  29231. }
  29232. void Component::deleteAllChildren()
  29233. {
  29234. for (int i = childComponentList_.size(); --i >= 0;)
  29235. delete (removeChildComponent (i));
  29236. }
  29237. int Component::getNumChildComponents() const throw()
  29238. {
  29239. return childComponentList_.size();
  29240. }
  29241. Component* Component::getChildComponent (const int index) const throw()
  29242. {
  29243. return childComponentList_ [index];
  29244. }
  29245. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  29246. {
  29247. return childComponentList_.indexOf (const_cast <Component*> (child));
  29248. }
  29249. Component* Component::getTopLevelComponent() const throw()
  29250. {
  29251. const Component* comp = this;
  29252. while (comp->parentComponent_ != 0)
  29253. comp = comp->parentComponent_;
  29254. return (Component*) comp;
  29255. }
  29256. bool Component::isParentOf (const Component* possibleChild) const throw()
  29257. {
  29258. while (possibleChild->isValidComponent())
  29259. {
  29260. possibleChild = possibleChild->parentComponent_;
  29261. if (possibleChild == this)
  29262. return true;
  29263. }
  29264. return false;
  29265. }
  29266. void Component::parentHierarchyChanged()
  29267. {
  29268. }
  29269. void Component::childrenChanged()
  29270. {
  29271. }
  29272. void Component::internalChildrenChanged()
  29273. {
  29274. const ComponentDeletionWatcher deletionChecker (this);
  29275. const bool hasListeners = componentListeners_ != 0;
  29276. childrenChanged();
  29277. if (hasListeners)
  29278. {
  29279. if (deletionChecker.hasBeenDeleted())
  29280. return;
  29281. for (int i = componentListeners_->size(); --i >= 0;)
  29282. {
  29283. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29284. ->componentChildrenChanged (*this);
  29285. if (deletionChecker.hasBeenDeleted())
  29286. return;
  29287. i = jmin (i, componentListeners_->size());
  29288. }
  29289. }
  29290. }
  29291. void Component::internalHierarchyChanged()
  29292. {
  29293. parentHierarchyChanged();
  29294. const ComponentDeletionWatcher deletionChecker (this);
  29295. if (componentListeners_ != 0)
  29296. {
  29297. for (int i = componentListeners_->size(); --i >= 0;)
  29298. {
  29299. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29300. ->componentParentHierarchyChanged (*this);
  29301. if (deletionChecker.hasBeenDeleted())
  29302. return;
  29303. i = jmin (i, componentListeners_->size());
  29304. }
  29305. }
  29306. for (int i = childComponentList_.size(); --i >= 0;)
  29307. {
  29308. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  29309. // you really shouldn't delete the parent component during a callback telling you
  29310. // that it's changed..
  29311. jassert (! deletionChecker.hasBeenDeleted());
  29312. if (deletionChecker.hasBeenDeleted())
  29313. return;
  29314. i = jmin (i, childComponentList_.size());
  29315. }
  29316. }
  29317. void* Component::runModalLoopCallback (void* userData)
  29318. {
  29319. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  29320. }
  29321. int Component::runModalLoop()
  29322. {
  29323. if (! MessageManager::getInstance()->isThisTheMessageThread())
  29324. {
  29325. // use a callback so this can be called from non-gui threads
  29326. return (int) (pointer_sized_int)
  29327. MessageManager::getInstance()
  29328. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  29329. }
  29330. Component* const prevFocused = getCurrentlyFocusedComponent();
  29331. ComponentDeletionWatcher* deletionChecker = 0;
  29332. if (prevFocused != 0)
  29333. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  29334. if (! isCurrentlyModal())
  29335. enterModalState();
  29336. JUCE_TRY
  29337. {
  29338. while (flags.currentlyModalFlag && flags.visibleFlag)
  29339. {
  29340. if (! MessageManager::getInstance()->dispatchNextMessage())
  29341. break;
  29342. // check whether this component was deleted during the last message
  29343. if (! isValidMessageListener())
  29344. break;
  29345. }
  29346. }
  29347. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29348. catch (const std::exception& e)
  29349. {
  29350. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29351. return 0;
  29352. }
  29353. catch (...)
  29354. {
  29355. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29356. return 0;
  29357. }
  29358. #endif
  29359. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29360. int returnValue = 0;
  29361. if (modalIndex >= 0)
  29362. {
  29363. modalComponentReturnValueKeys.remove (modalIndex);
  29364. returnValue = modalReturnValues.remove (modalIndex);
  29365. }
  29366. modalComponentStack.removeValue (this);
  29367. if (deletionChecker != 0)
  29368. {
  29369. if (! deletionChecker->hasBeenDeleted())
  29370. prevFocused->grabKeyboardFocus();
  29371. delete deletionChecker;
  29372. }
  29373. return returnValue;
  29374. }
  29375. void Component::enterModalState (const bool takeKeyboardFocus)
  29376. {
  29377. // if component methods are being called from threads other than the message
  29378. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29379. checkMessageManagerIsLocked
  29380. // Check for an attempt to make a component modal when it already is!
  29381. // This can cause nasty problems..
  29382. jassert (! flags.currentlyModalFlag);
  29383. if (! isCurrentlyModal())
  29384. {
  29385. modalComponentStack.add (this);
  29386. modalComponentReturnValueKeys.add (this);
  29387. modalReturnValues.add (0);
  29388. flags.currentlyModalFlag = true;
  29389. setVisible (true);
  29390. if (takeKeyboardFocus)
  29391. grabKeyboardFocus();
  29392. }
  29393. }
  29394. void Component::exitModalState (const int returnValue)
  29395. {
  29396. if (isCurrentlyModal())
  29397. {
  29398. if (MessageManager::getInstance()->isThisTheMessageThread())
  29399. {
  29400. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29401. if (modalIndex >= 0)
  29402. {
  29403. modalReturnValues.set (modalIndex, returnValue);
  29404. }
  29405. else
  29406. {
  29407. modalComponentReturnValueKeys.add (this);
  29408. modalReturnValues.add (returnValue);
  29409. }
  29410. modalComponentStack.removeValue (this);
  29411. flags.currentlyModalFlag = false;
  29412. }
  29413. else
  29414. {
  29415. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  29416. }
  29417. }
  29418. }
  29419. bool Component::isCurrentlyModal() const throw()
  29420. {
  29421. return flags.currentlyModalFlag
  29422. && getCurrentlyModalComponent() == this;
  29423. }
  29424. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  29425. {
  29426. Component* const mc = getCurrentlyModalComponent();
  29427. return mc != 0
  29428. && mc != this
  29429. && (! mc->isParentOf (this))
  29430. && ! mc->canModalEventBeSentToComponent (this);
  29431. }
  29432. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  29433. {
  29434. Component* const c = (Component*) modalComponentStack.getLast();
  29435. return c->isValidComponent() ? c : 0;
  29436. }
  29437. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  29438. {
  29439. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  29440. }
  29441. bool Component::isBroughtToFrontOnMouseClick() const throw()
  29442. {
  29443. return flags.bringToFrontOnClickFlag;
  29444. }
  29445. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  29446. {
  29447. cursor_ = cursor;
  29448. if (flags.visibleFlag)
  29449. {
  29450. int mx, my;
  29451. getMouseXYRelative (mx, my);
  29452. if (flags.draggingFlag || reallyContains (mx, my, false))
  29453. {
  29454. internalUpdateMouseCursor (false);
  29455. }
  29456. }
  29457. }
  29458. const MouseCursor Component::getMouseCursor()
  29459. {
  29460. return cursor_;
  29461. }
  29462. void Component::updateMouseCursor() const throw()
  29463. {
  29464. sendFakeMouseMove();
  29465. }
  29466. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  29467. {
  29468. ComponentPeer* const peer = getPeer();
  29469. if (peer != 0)
  29470. {
  29471. MouseCursor mc (getMouseCursor());
  29472. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  29473. || unboundedMouseOffsetY != 0
  29474. || ! isCursorVisibleUntilOffscreen))
  29475. {
  29476. mc = MouseCursor::NoCursor;
  29477. }
  29478. static void* currentCursorHandle = 0;
  29479. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  29480. {
  29481. currentCursorHandle = mc.getHandle();
  29482. mc.showInWindow (peer);
  29483. }
  29484. }
  29485. }
  29486. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  29487. {
  29488. flags.repaintOnMouseActivityFlag = shouldRepaint;
  29489. }
  29490. void Component::repaintParent() throw()
  29491. {
  29492. if (flags.visibleFlag)
  29493. internalRepaint (0, 0, getWidth(), getHeight());
  29494. }
  29495. void Component::repaint() throw()
  29496. {
  29497. repaint (0, 0, getWidth(), getHeight());
  29498. }
  29499. void Component::repaint (const int x, const int y,
  29500. const int w, const int h) throw()
  29501. {
  29502. deleteAndZero (bufferedImage_);
  29503. if (flags.visibleFlag)
  29504. internalRepaint (x, y, w, h);
  29505. }
  29506. void Component::internalRepaint (int x, int y, int w, int h)
  29507. {
  29508. // if component methods are being called from threads other than the message
  29509. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29510. checkMessageManagerIsLocked
  29511. if (x < 0)
  29512. {
  29513. w += x;
  29514. x = 0;
  29515. }
  29516. if (x + w > getWidth())
  29517. w = getWidth() - x;
  29518. if (w > 0)
  29519. {
  29520. if (y < 0)
  29521. {
  29522. h += y;
  29523. y = 0;
  29524. }
  29525. if (y + h > getHeight())
  29526. h = getHeight() - y;
  29527. if (h > 0)
  29528. {
  29529. if (parentComponent_ != 0)
  29530. {
  29531. x += getX();
  29532. y += getY();
  29533. if (parentComponent_->flags.visibleFlag)
  29534. parentComponent_->internalRepaint (x, y, w, h);
  29535. }
  29536. else if (flags.hasHeavyweightPeerFlag)
  29537. {
  29538. ComponentPeer* const peer = getPeer();
  29539. if (peer != 0)
  29540. peer->repaint (x, y, w, h);
  29541. }
  29542. }
  29543. }
  29544. }
  29545. void Component::paintEntireComponent (Graphics& originalContext)
  29546. {
  29547. jassert (! originalContext.isClipEmpty());
  29548. #ifdef JUCE_DEBUG
  29549. flags.isInsidePaintCall = true;
  29550. #endif
  29551. Graphics* g = &originalContext;
  29552. Image* effectImage = 0;
  29553. if (effect_ != 0)
  29554. {
  29555. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29556. getWidth(), getHeight(),
  29557. ! flags.opaqueFlag);
  29558. g = new Graphics (*effectImage);
  29559. }
  29560. g->saveState();
  29561. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  29562. if (! g->isClipEmpty())
  29563. {
  29564. if (bufferedImage_ != 0)
  29565. {
  29566. g->setColour (Colours::black);
  29567. g->drawImageAt (bufferedImage_, 0, 0);
  29568. }
  29569. else
  29570. {
  29571. if (flags.bufferToImageFlag)
  29572. {
  29573. if (bufferedImage_ == 0)
  29574. {
  29575. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29576. getWidth(), getHeight(), ! flags.opaqueFlag);
  29577. Graphics imG (*bufferedImage_);
  29578. paint (imG);
  29579. }
  29580. g->setColour (Colours::black);
  29581. g->drawImageAt (bufferedImage_, 0, 0);
  29582. }
  29583. else
  29584. {
  29585. paint (*g);
  29586. g->resetToDefaultState();
  29587. }
  29588. }
  29589. }
  29590. g->restoreState();
  29591. for (int i = 0; i < childComponentList_.size(); ++i)
  29592. {
  29593. Component* const child = childComponentList_.getUnchecked (i);
  29594. if (child->isVisible())
  29595. {
  29596. g->saveState();
  29597. if (g->reduceClipRegion (child->getX(), child->getY(),
  29598. child->getWidth(), child->getHeight()))
  29599. {
  29600. for (int j = i + 1; j < childComponentList_.size(); ++j)
  29601. {
  29602. const Component* const sibling = childComponentList_.getUnchecked (j);
  29603. if (sibling->flags.opaqueFlag && sibling->isVisible())
  29604. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  29605. sibling->getWidth(), sibling->getHeight());
  29606. }
  29607. if (! g->isClipEmpty())
  29608. {
  29609. g->setOrigin (child->getX(), child->getY());
  29610. child->paintEntireComponent (*g);
  29611. }
  29612. }
  29613. g->restoreState();
  29614. }
  29615. }
  29616. JUCE_TRY
  29617. {
  29618. g->saveState();
  29619. paintOverChildren (*g);
  29620. g->restoreState();
  29621. }
  29622. JUCE_CATCH_EXCEPTION
  29623. if (effect_ != 0)
  29624. {
  29625. delete g;
  29626. effect_->applyEffect (*effectImage, originalContext);
  29627. delete effectImage;
  29628. }
  29629. #ifdef JUCE_DEBUG
  29630. flags.isInsidePaintCall = false;
  29631. #endif
  29632. }
  29633. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  29634. const bool clipImageToComponentBounds)
  29635. {
  29636. Rectangle r (areaToGrab);
  29637. if (clipImageToComponentBounds)
  29638. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  29639. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29640. jmax (1, r.getWidth()),
  29641. jmax (1, r.getHeight()),
  29642. true);
  29643. Graphics imageContext (*componentImage);
  29644. imageContext.setOrigin (-r.getX(),
  29645. -r.getY());
  29646. paintEntireComponent (imageContext);
  29647. return componentImage;
  29648. }
  29649. void Component::setComponentEffect (ImageEffectFilter* const effect)
  29650. {
  29651. if (effect_ != effect)
  29652. {
  29653. effect_ = effect;
  29654. repaint();
  29655. }
  29656. }
  29657. LookAndFeel& Component::getLookAndFeel() const throw()
  29658. {
  29659. const Component* c = this;
  29660. do
  29661. {
  29662. if (c->lookAndFeel_ != 0)
  29663. return *(c->lookAndFeel_);
  29664. c = c->parentComponent_;
  29665. }
  29666. while (c != 0);
  29667. return LookAndFeel::getDefaultLookAndFeel();
  29668. }
  29669. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  29670. {
  29671. if (lookAndFeel_ != newLookAndFeel)
  29672. {
  29673. lookAndFeel_ = newLookAndFeel;
  29674. sendLookAndFeelChange();
  29675. }
  29676. }
  29677. void Component::lookAndFeelChanged()
  29678. {
  29679. }
  29680. void Component::sendLookAndFeelChange()
  29681. {
  29682. repaint();
  29683. lookAndFeelChanged();
  29684. // (it's not a great idea to do anything that would delete this component
  29685. // during the lookAndFeelChanged() callback)
  29686. jassert (isValidComponent());
  29687. const ComponentDeletionWatcher deletionChecker (this);
  29688. for (int i = childComponentList_.size(); --i >= 0;)
  29689. {
  29690. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  29691. if (deletionChecker.hasBeenDeleted())
  29692. return;
  29693. i = jmin (i, childComponentList_.size());
  29694. }
  29695. }
  29696. static const String getColourPropertyName (const int colourId) throw()
  29697. {
  29698. String s;
  29699. s.preallocateStorage (18);
  29700. s << T("jcclr_") << colourId;
  29701. return s;
  29702. }
  29703. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  29704. {
  29705. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  29706. inheritFromParent,
  29707. String::empty));
  29708. if (customColour.isNotEmpty())
  29709. return Colour (customColour.getIntValue());
  29710. return getLookAndFeel().findColour (colourId);
  29711. }
  29712. bool Component::isColourSpecified (const int colourId) const throw()
  29713. {
  29714. return getComponentProperty (getColourPropertyName (colourId),
  29715. false,
  29716. String::empty).isNotEmpty();
  29717. }
  29718. void Component::removeColour (const int colourId)
  29719. {
  29720. if (isColourSpecified (colourId))
  29721. {
  29722. removeComponentProperty (getColourPropertyName (colourId));
  29723. colourChanged();
  29724. }
  29725. }
  29726. void Component::setColour (const int colourId, const Colour& colour)
  29727. {
  29728. const String colourName (getColourPropertyName (colourId));
  29729. const String customColour (getComponentProperty (colourName, false, String::empty));
  29730. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  29731. {
  29732. setComponentProperty (colourName, colour);
  29733. colourChanged();
  29734. }
  29735. }
  29736. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  29737. {
  29738. if (propertySet_ != 0)
  29739. {
  29740. const StringPairArray& props = propertySet_->getAllProperties();
  29741. const StringArray& keys = props.getAllKeys();
  29742. for (int i = 0; i < keys.size(); ++i)
  29743. {
  29744. if (keys[i].startsWith (T("jcclr_")))
  29745. {
  29746. target.setComponentProperty (keys[i],
  29747. props.getAllValues() [i]);
  29748. }
  29749. }
  29750. target.colourChanged();
  29751. }
  29752. }
  29753. void Component::colourChanged()
  29754. {
  29755. }
  29756. const Rectangle Component::getUnclippedArea() const
  29757. {
  29758. int x = 0, y = 0, w = getWidth(), h = getHeight();
  29759. Component* p = parentComponent_;
  29760. int px = getX();
  29761. int py = getY();
  29762. while (p != 0)
  29763. {
  29764. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  29765. return Rectangle();
  29766. px += p->getX();
  29767. py += p->getY();
  29768. p = p->parentComponent_;
  29769. }
  29770. return Rectangle (x, y, w, h);
  29771. }
  29772. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  29773. const int deltaX, const int deltaY) const throw()
  29774. {
  29775. for (int i = childComponentList_.size(); --i >= 0;)
  29776. {
  29777. const Component* const c = childComponentList_.getUnchecked(i);
  29778. if (c->isVisible())
  29779. {
  29780. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29781. if (! newClip.isEmpty())
  29782. {
  29783. if (c->isOpaque())
  29784. {
  29785. g.excludeClipRegion (deltaX + newClip.getX(),
  29786. deltaY + newClip.getY(),
  29787. newClip.getWidth(),
  29788. newClip.getHeight());
  29789. }
  29790. else
  29791. {
  29792. newClip.translate (-c->getX(), -c->getY());
  29793. c->clipObscuredRegions (g, newClip,
  29794. c->getX() + deltaX,
  29795. c->getY() + deltaY);
  29796. }
  29797. }
  29798. }
  29799. }
  29800. }
  29801. void Component::getVisibleArea (RectangleList& result,
  29802. const bool includeSiblings) const
  29803. {
  29804. result.clear();
  29805. const Rectangle unclipped (getUnclippedArea());
  29806. if (! unclipped.isEmpty())
  29807. {
  29808. result.add (unclipped);
  29809. if (includeSiblings)
  29810. {
  29811. const Component* const c = getTopLevelComponent();
  29812. int x = 0, y = 0;
  29813. c->relativePositionToOtherComponent (this, x, y);
  29814. c->subtractObscuredRegions (result, x, y,
  29815. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  29816. this);
  29817. }
  29818. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  29819. result.consolidate();
  29820. }
  29821. }
  29822. void Component::subtractObscuredRegions (RectangleList& result,
  29823. const int deltaX,
  29824. const int deltaY,
  29825. const Rectangle& clipRect,
  29826. const Component* const compToAvoid) const throw()
  29827. {
  29828. for (int i = childComponentList_.size(); --i >= 0;)
  29829. {
  29830. const Component* const c = childComponentList_.getUnchecked(i);
  29831. if (c != compToAvoid && c->isVisible())
  29832. {
  29833. if (c->isOpaque())
  29834. {
  29835. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  29836. childBounds.translate (deltaX, deltaY);
  29837. result.subtract (childBounds);
  29838. }
  29839. else
  29840. {
  29841. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29842. newClip.translate (-c->getX(), -c->getY());
  29843. c->subtractObscuredRegions (result,
  29844. c->getX() + deltaX,
  29845. c->getY() + deltaY,
  29846. newClip,
  29847. compToAvoid);
  29848. }
  29849. }
  29850. }
  29851. }
  29852. void Component::mouseEnter (const MouseEvent&)
  29853. {
  29854. // base class does nothing
  29855. }
  29856. void Component::mouseExit (const MouseEvent&)
  29857. {
  29858. // base class does nothing
  29859. }
  29860. void Component::mouseDown (const MouseEvent&)
  29861. {
  29862. // base class does nothing
  29863. }
  29864. void Component::mouseUp (const MouseEvent&)
  29865. {
  29866. // base class does nothing
  29867. }
  29868. void Component::mouseDrag (const MouseEvent&)
  29869. {
  29870. // base class does nothing
  29871. }
  29872. void Component::mouseMove (const MouseEvent&)
  29873. {
  29874. // base class does nothing
  29875. }
  29876. void Component::mouseDoubleClick (const MouseEvent&)
  29877. {
  29878. // base class does nothing
  29879. }
  29880. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  29881. {
  29882. // the base class just passes this event up to its parent..
  29883. if (parentComponent_ != 0)
  29884. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  29885. wheelIncrementX, wheelIncrementY);
  29886. }
  29887. void Component::resized()
  29888. {
  29889. // base class does nothing
  29890. }
  29891. void Component::moved()
  29892. {
  29893. // base class does nothing
  29894. }
  29895. void Component::childBoundsChanged (Component*)
  29896. {
  29897. // base class does nothing
  29898. }
  29899. void Component::parentSizeChanged()
  29900. {
  29901. // base class does nothing
  29902. }
  29903. void Component::addComponentListener (ComponentListener* const newListener) throw()
  29904. {
  29905. if (componentListeners_ == 0)
  29906. componentListeners_ = new VoidArray (4);
  29907. componentListeners_->addIfNotAlreadyThere (newListener);
  29908. }
  29909. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  29910. {
  29911. jassert (isValidComponent());
  29912. if (componentListeners_ != 0)
  29913. componentListeners_->removeValue (listenerToRemove);
  29914. }
  29915. void Component::inputAttemptWhenModal()
  29916. {
  29917. getTopLevelComponent()->toFront (true);
  29918. getLookAndFeel().playAlertSound();
  29919. }
  29920. bool Component::canModalEventBeSentToComponent (const Component*)
  29921. {
  29922. return false;
  29923. }
  29924. void Component::internalModalInputAttempt()
  29925. {
  29926. Component* const current = getCurrentlyModalComponent();
  29927. if (current != 0)
  29928. current->inputAttemptWhenModal();
  29929. }
  29930. void Component::paint (Graphics&)
  29931. {
  29932. // all painting is done in the subclasses
  29933. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  29934. }
  29935. void Component::paintOverChildren (Graphics&)
  29936. {
  29937. // all painting is done in the subclasses
  29938. }
  29939. void Component::handleMessage (const Message& message)
  29940. {
  29941. if (message.intParameter1 == exitModalStateMessage)
  29942. {
  29943. exitModalState (message.intParameter2);
  29944. }
  29945. else if (message.intParameter1 == customCommandMessage)
  29946. {
  29947. handleCommandMessage (message.intParameter2);
  29948. }
  29949. }
  29950. void Component::postCommandMessage (const int commandId) throw()
  29951. {
  29952. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  29953. }
  29954. void Component::handleCommandMessage (int)
  29955. {
  29956. // used by subclasses
  29957. }
  29958. void Component::addMouseListener (MouseListener* const newListener,
  29959. const bool wantsEventsForAllNestedChildComponents) throw()
  29960. {
  29961. // if component methods are being called from threads other than the message
  29962. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29963. checkMessageManagerIsLocked
  29964. if (mouseListeners_ == 0)
  29965. mouseListeners_ = new VoidArray (4);
  29966. if (! mouseListeners_->contains (newListener))
  29967. {
  29968. if (wantsEventsForAllNestedChildComponents)
  29969. {
  29970. mouseListeners_->insert (0, newListener);
  29971. ++numDeepMouseListeners;
  29972. }
  29973. else
  29974. {
  29975. mouseListeners_->add (newListener);
  29976. }
  29977. }
  29978. }
  29979. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  29980. {
  29981. // if component methods are being called from threads other than the message
  29982. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29983. checkMessageManagerIsLocked
  29984. if (mouseListeners_ != 0)
  29985. {
  29986. const int index = mouseListeners_->indexOf (listenerToRemove);
  29987. if (index >= 0)
  29988. {
  29989. if (index < numDeepMouseListeners)
  29990. --numDeepMouseListeners;
  29991. mouseListeners_->remove (index);
  29992. }
  29993. }
  29994. }
  29995. void Component::internalMouseEnter (int x, int y, int64 time)
  29996. {
  29997. if (isCurrentlyBlockedByAnotherModalComponent())
  29998. {
  29999. // if something else is modal, always just show a normal mouse cursor
  30000. if (componentUnderMouse == this)
  30001. {
  30002. ComponentPeer* const peer = getPeer();
  30003. if (peer != 0)
  30004. {
  30005. MouseCursor mc (MouseCursor::NormalCursor);
  30006. mc.showInWindow (peer);
  30007. }
  30008. }
  30009. return;
  30010. }
  30011. if (! flags.mouseInsideFlag)
  30012. {
  30013. flags.mouseInsideFlag = true;
  30014. flags.mouseOverFlag = true;
  30015. flags.draggingFlag = false;
  30016. if (isValidComponent())
  30017. {
  30018. const ComponentDeletionWatcher deletionChecker (this);
  30019. if (flags.repaintOnMouseActivityFlag)
  30020. repaint();
  30021. const MouseEvent me (x, y,
  30022. ModifierKeys::getCurrentModifiers(),
  30023. this,
  30024. Time (time),
  30025. x, y,
  30026. Time (time),
  30027. 0, false);
  30028. mouseEnter (me);
  30029. if (deletionChecker.hasBeenDeleted())
  30030. return;
  30031. Desktop::getInstance().resetTimer();
  30032. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30033. {
  30034. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  30035. if (deletionChecker.hasBeenDeleted())
  30036. return;
  30037. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30038. }
  30039. if (mouseListeners_ != 0)
  30040. {
  30041. for (int i = mouseListeners_->size(); --i >= 0;)
  30042. {
  30043. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  30044. if (deletionChecker.hasBeenDeleted())
  30045. return;
  30046. i = jmin (i, mouseListeners_->size());
  30047. }
  30048. }
  30049. const Component* p = parentComponent_;
  30050. while (p != 0)
  30051. {
  30052. const ComponentDeletionWatcher parentDeletionChecker (p);
  30053. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30054. {
  30055. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  30056. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30057. return;
  30058. i = jmin (i, p->numDeepMouseListeners);
  30059. }
  30060. p = p->parentComponent_;
  30061. }
  30062. }
  30063. }
  30064. if (componentUnderMouse == this)
  30065. internalUpdateMouseCursor (true);
  30066. }
  30067. void Component::internalMouseExit (int x, int y, int64 time)
  30068. {
  30069. const ComponentDeletionWatcher deletionChecker (this);
  30070. if (flags.draggingFlag)
  30071. {
  30072. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  30073. if (deletionChecker.hasBeenDeleted())
  30074. return;
  30075. }
  30076. enableUnboundedMouseMovement (false);
  30077. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  30078. {
  30079. flags.mouseInsideFlag = false;
  30080. flags.mouseOverFlag = false;
  30081. flags.draggingFlag = false;
  30082. if (flags.repaintOnMouseActivityFlag)
  30083. repaint();
  30084. const MouseEvent me (x, y,
  30085. ModifierKeys::getCurrentModifiers(),
  30086. this,
  30087. Time (time),
  30088. x, y,
  30089. Time (time),
  30090. 0, false);
  30091. mouseExit (me);
  30092. if (deletionChecker.hasBeenDeleted())
  30093. return;
  30094. Desktop::getInstance().resetTimer();
  30095. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30096. {
  30097. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  30098. if (deletionChecker.hasBeenDeleted())
  30099. return;
  30100. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30101. }
  30102. if (mouseListeners_ != 0)
  30103. {
  30104. for (int i = mouseListeners_->size(); --i >= 0;)
  30105. {
  30106. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  30107. if (deletionChecker.hasBeenDeleted())
  30108. return;
  30109. i = jmin (i, mouseListeners_->size());
  30110. }
  30111. }
  30112. const Component* p = parentComponent_;
  30113. while (p != 0)
  30114. {
  30115. const ComponentDeletionWatcher parentDeletionChecker (p);
  30116. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30117. {
  30118. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  30119. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30120. return;
  30121. i = jmin (i, p->numDeepMouseListeners);
  30122. }
  30123. p = p->parentComponent_;
  30124. }
  30125. }
  30126. }
  30127. class InternalDragRepeater : public Timer
  30128. {
  30129. public:
  30130. InternalDragRepeater()
  30131. {}
  30132. ~InternalDragRepeater()
  30133. {}
  30134. void timerCallback()
  30135. {
  30136. Component* const c = Component::getComponentUnderMouse();
  30137. if (c != 0 && c->isMouseButtonDown())
  30138. {
  30139. int x, y;
  30140. c->getMouseXYRelative (x, y);
  30141. // the offsets have been added on, so must be taken off before calling the
  30142. // drag.. otherwise they'll be added twice
  30143. x -= unboundedMouseOffsetX;
  30144. y -= unboundedMouseOffsetY;
  30145. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  30146. }
  30147. }
  30148. juce_UseDebuggingNewOperator
  30149. };
  30150. static InternalDragRepeater* dragRepeater = 0;
  30151. void Component::beginDragAutoRepeat (const int interval)
  30152. {
  30153. if (interval > 0)
  30154. {
  30155. if (dragRepeater == 0)
  30156. dragRepeater = new InternalDragRepeater();
  30157. if (dragRepeater->getTimerInterval() != interval)
  30158. dragRepeater->startTimer (interval);
  30159. }
  30160. else
  30161. {
  30162. deleteAndZero (dragRepeater);
  30163. }
  30164. }
  30165. void Component::internalMouseDown (const int x, const int y)
  30166. {
  30167. const ComponentDeletionWatcher deletionChecker (this);
  30168. if (isCurrentlyBlockedByAnotherModalComponent())
  30169. {
  30170. internalModalInputAttempt();
  30171. if (deletionChecker.hasBeenDeleted())
  30172. return;
  30173. // If processing the input attempt has exited the modal loop, we'll allow the event
  30174. // to be delivered..
  30175. if (isCurrentlyBlockedByAnotherModalComponent())
  30176. {
  30177. // allow blocked mouse-events to go to global listeners..
  30178. const MouseEvent me (x, y,
  30179. ModifierKeys::getCurrentModifiers(),
  30180. this,
  30181. Time (juce_recentMouseDownTimes[0]),
  30182. x, y,
  30183. Time (juce_recentMouseDownTimes[0]),
  30184. countMouseClicks(),
  30185. false);
  30186. Desktop::getInstance().resetTimer();
  30187. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30188. {
  30189. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30190. if (deletionChecker.hasBeenDeleted())
  30191. return;
  30192. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30193. }
  30194. return;
  30195. }
  30196. }
  30197. {
  30198. Component* c = this;
  30199. while (c != 0)
  30200. {
  30201. if (c->isBroughtToFrontOnMouseClick())
  30202. {
  30203. c->toFront (true);
  30204. if (deletionChecker.hasBeenDeleted())
  30205. return;
  30206. }
  30207. c = c->parentComponent_;
  30208. }
  30209. }
  30210. if (! flags.dontFocusOnMouseClickFlag)
  30211. grabFocusInternal (focusChangedByMouseClick);
  30212. if (! deletionChecker.hasBeenDeleted())
  30213. {
  30214. flags.draggingFlag = true;
  30215. flags.mouseOverFlag = true;
  30216. if (flags.repaintOnMouseActivityFlag)
  30217. repaint();
  30218. const MouseEvent me (x, y,
  30219. ModifierKeys::getCurrentModifiers(),
  30220. this,
  30221. Time (juce_recentMouseDownTimes[0]),
  30222. x, y,
  30223. Time (juce_recentMouseDownTimes[0]),
  30224. countMouseClicks(),
  30225. false);
  30226. mouseDown (me);
  30227. if (deletionChecker.hasBeenDeleted())
  30228. return;
  30229. Desktop::getInstance().resetTimer();
  30230. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30231. {
  30232. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30233. if (deletionChecker.hasBeenDeleted())
  30234. return;
  30235. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30236. }
  30237. if (mouseListeners_ != 0)
  30238. {
  30239. for (int i = mouseListeners_->size(); --i >= 0;)
  30240. {
  30241. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  30242. if (deletionChecker.hasBeenDeleted())
  30243. return;
  30244. i = jmin (i, mouseListeners_->size());
  30245. }
  30246. }
  30247. const Component* p = parentComponent_;
  30248. while (p != 0)
  30249. {
  30250. const ComponentDeletionWatcher parentDeletionChecker (p);
  30251. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30252. {
  30253. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  30254. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30255. return;
  30256. i = jmin (i, p->numDeepMouseListeners);
  30257. }
  30258. p = p->parentComponent_;
  30259. }
  30260. }
  30261. }
  30262. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  30263. {
  30264. if (isValidComponent() && flags.draggingFlag)
  30265. {
  30266. flags.draggingFlag = false;
  30267. deleteAndZero (dragRepeater);
  30268. x += unboundedMouseOffsetX;
  30269. y += unboundedMouseOffsetY;
  30270. juce_LastMousePosX = x;
  30271. juce_LastMousePosY = y;
  30272. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30273. const ComponentDeletionWatcher deletionChecker (this);
  30274. if (flags.repaintOnMouseActivityFlag)
  30275. repaint();
  30276. int mdx = juce_recentMouseDownX[0];
  30277. int mdy = juce_recentMouseDownY[0];
  30278. globalPositionToRelative (mdx, mdy);
  30279. const MouseEvent me (x, y,
  30280. oldModifiers,
  30281. this,
  30282. Time (time),
  30283. mdx, mdy,
  30284. Time (juce_recentMouseDownTimes [0]),
  30285. countMouseClicks(),
  30286. juce_MouseHasMovedSignificantlySincePressed
  30287. || juce_recentMouseDownTimes[0] + 300 < time);
  30288. mouseUp (me);
  30289. if (deletionChecker.hasBeenDeleted())
  30290. return;
  30291. Desktop::getInstance().resetTimer();
  30292. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30293. {
  30294. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  30295. if (deletionChecker.hasBeenDeleted())
  30296. return;
  30297. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30298. }
  30299. if (mouseListeners_ != 0)
  30300. {
  30301. for (int i = mouseListeners_->size(); --i >= 0;)
  30302. {
  30303. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  30304. if (deletionChecker.hasBeenDeleted())
  30305. return;
  30306. i = jmin (i, mouseListeners_->size());
  30307. }
  30308. }
  30309. {
  30310. const Component* p = parentComponent_;
  30311. while (p != 0)
  30312. {
  30313. const ComponentDeletionWatcher parentDeletionChecker (p);
  30314. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30315. {
  30316. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  30317. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30318. return;
  30319. i = jmin (i, p->numDeepMouseListeners);
  30320. }
  30321. p = p->parentComponent_;
  30322. }
  30323. }
  30324. // check for double-click
  30325. if (me.getNumberOfClicks() >= 2)
  30326. {
  30327. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  30328. mouseDoubleClick (me);
  30329. int i;
  30330. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30331. {
  30332. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  30333. if (deletionChecker.hasBeenDeleted())
  30334. return;
  30335. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30336. }
  30337. for (i = numListeners; --i >= 0;)
  30338. {
  30339. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  30340. return;
  30341. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  30342. if (ml != 0)
  30343. ml->mouseDoubleClick (me);
  30344. }
  30345. if (deletionChecker.hasBeenDeleted())
  30346. return;
  30347. const Component* p = parentComponent_;
  30348. while (p != 0)
  30349. {
  30350. const ComponentDeletionWatcher parentDeletionChecker (p);
  30351. for (i = p->numDeepMouseListeners; --i >= 0;)
  30352. {
  30353. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  30354. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30355. return;
  30356. i = jmin (i, p->numDeepMouseListeners);
  30357. }
  30358. p = p->parentComponent_;
  30359. }
  30360. }
  30361. }
  30362. enableUnboundedMouseMovement (false);
  30363. }
  30364. void Component::internalMouseDrag (int x, int y, const int64 time)
  30365. {
  30366. if (isValidComponent() && flags.draggingFlag)
  30367. {
  30368. flags.mouseOverFlag = reallyContains (x, y, false);
  30369. x += unboundedMouseOffsetX;
  30370. y += unboundedMouseOffsetY;
  30371. juce_LastMousePosX = x;
  30372. juce_LastMousePosY = y;
  30373. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30374. juce_MouseHasMovedSignificantlySincePressed
  30375. = juce_MouseHasMovedSignificantlySincePressed
  30376. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  30377. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  30378. const ComponentDeletionWatcher deletionChecker (this);
  30379. int mdx = juce_recentMouseDownX[0];
  30380. int mdy = juce_recentMouseDownY[0];
  30381. globalPositionToRelative (mdx, mdy);
  30382. const MouseEvent me (x, y,
  30383. ModifierKeys::getCurrentModifiers(),
  30384. this,
  30385. Time (time),
  30386. mdx, mdy,
  30387. Time (juce_recentMouseDownTimes[0]),
  30388. countMouseClicks(),
  30389. juce_MouseHasMovedSignificantlySincePressed
  30390. || juce_recentMouseDownTimes[0] + 300 < time);
  30391. mouseDrag (me);
  30392. if (deletionChecker.hasBeenDeleted())
  30393. return;
  30394. Desktop::getInstance().resetTimer();
  30395. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30396. {
  30397. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  30398. if (deletionChecker.hasBeenDeleted())
  30399. return;
  30400. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30401. }
  30402. if (mouseListeners_ != 0)
  30403. {
  30404. for (int i = mouseListeners_->size(); --i >= 0;)
  30405. {
  30406. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  30407. if (deletionChecker.hasBeenDeleted())
  30408. return;
  30409. i = jmin (i, mouseListeners_->size());
  30410. }
  30411. }
  30412. const Component* p = parentComponent_;
  30413. while (p != 0)
  30414. {
  30415. const ComponentDeletionWatcher parentDeletionChecker (p);
  30416. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30417. {
  30418. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  30419. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30420. return;
  30421. i = jmin (i, p->numDeepMouseListeners);
  30422. }
  30423. p = p->parentComponent_;
  30424. }
  30425. if (this == componentUnderMouse)
  30426. {
  30427. if (isUnboundedMouseModeOn)
  30428. {
  30429. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  30430. int mx, my;
  30431. Desktop::getMousePosition (mx, my);
  30432. if (! screenArea.contains (mx, my))
  30433. {
  30434. int deltaX = 0, deltaY = 0;
  30435. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  30436. deltaX = getScreenX() + getWidth() / 2 - mx;
  30437. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  30438. deltaY = getScreenY() + getHeight() / 2 - my;
  30439. unboundedMouseOffsetX -= deltaX;
  30440. unboundedMouseOffsetY -= deltaY;
  30441. Desktop::setMousePosition (mx + deltaX,
  30442. my + deltaY);
  30443. }
  30444. else if (isCursorVisibleUntilOffscreen
  30445. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  30446. && screenArea.contains (mx + unboundedMouseOffsetX,
  30447. my + unboundedMouseOffsetY))
  30448. {
  30449. mx += unboundedMouseOffsetX;
  30450. my += unboundedMouseOffsetY;
  30451. unboundedMouseOffsetX = 0;
  30452. unboundedMouseOffsetY = 0;
  30453. Desktop::setMousePosition (mx, my);
  30454. }
  30455. }
  30456. internalUpdateMouseCursor (false);
  30457. }
  30458. }
  30459. }
  30460. void Component::internalMouseMove (const int x, const int y, const int64 time)
  30461. {
  30462. const ComponentDeletionWatcher deletionChecker (this);
  30463. if (isValidComponent())
  30464. {
  30465. const MouseEvent me (x, y,
  30466. ModifierKeys::getCurrentModifiers(),
  30467. this,
  30468. Time (time),
  30469. x, y,
  30470. Time (time),
  30471. 0, false);
  30472. if (isCurrentlyBlockedByAnotherModalComponent())
  30473. {
  30474. // allow blocked mouse-events to go to global listeners..
  30475. Desktop::getInstance().sendMouseMove();
  30476. }
  30477. else
  30478. {
  30479. if (this == componentUnderMouse)
  30480. internalUpdateMouseCursor (false);
  30481. flags.mouseOverFlag = true;
  30482. mouseMove (me);
  30483. if (deletionChecker.hasBeenDeleted())
  30484. return;
  30485. Desktop::getInstance().resetTimer();
  30486. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30487. {
  30488. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  30489. if (deletionChecker.hasBeenDeleted())
  30490. return;
  30491. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30492. }
  30493. if (mouseListeners_ != 0)
  30494. {
  30495. for (int i = mouseListeners_->size(); --i >= 0;)
  30496. {
  30497. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  30498. if (deletionChecker.hasBeenDeleted())
  30499. return;
  30500. i = jmin (i, mouseListeners_->size());
  30501. }
  30502. }
  30503. const Component* p = parentComponent_;
  30504. while (p != 0)
  30505. {
  30506. const ComponentDeletionWatcher parentDeletionChecker (p);
  30507. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30508. {
  30509. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  30510. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30511. return;
  30512. i = jmin (i, p->numDeepMouseListeners);
  30513. }
  30514. p = p->parentComponent_;
  30515. }
  30516. }
  30517. }
  30518. }
  30519. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  30520. {
  30521. const ComponentDeletionWatcher deletionChecker (this);
  30522. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  30523. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  30524. int mx, my;
  30525. getMouseXYRelative (mx, my);
  30526. const MouseEvent me (mx, my,
  30527. ModifierKeys::getCurrentModifiers(),
  30528. this,
  30529. Time (time),
  30530. mx, my,
  30531. Time (time),
  30532. 0, false);
  30533. if (isCurrentlyBlockedByAnotherModalComponent())
  30534. {
  30535. // allow blocked mouse-events to go to global listeners..
  30536. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30537. {
  30538. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30539. if (deletionChecker.hasBeenDeleted())
  30540. return;
  30541. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30542. }
  30543. }
  30544. else
  30545. {
  30546. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30547. if (deletionChecker.hasBeenDeleted())
  30548. return;
  30549. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30550. {
  30551. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30552. if (deletionChecker.hasBeenDeleted())
  30553. return;
  30554. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30555. }
  30556. if (mouseListeners_ != 0)
  30557. {
  30558. for (int i = mouseListeners_->size(); --i >= 0;)
  30559. {
  30560. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30561. if (deletionChecker.hasBeenDeleted())
  30562. return;
  30563. i = jmin (i, mouseListeners_->size());
  30564. }
  30565. }
  30566. const Component* p = parentComponent_;
  30567. while (p != 0)
  30568. {
  30569. const ComponentDeletionWatcher parentDeletionChecker (p);
  30570. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30571. {
  30572. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30573. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30574. return;
  30575. i = jmin (i, p->numDeepMouseListeners);
  30576. }
  30577. p = p->parentComponent_;
  30578. }
  30579. sendFakeMouseMove();
  30580. }
  30581. }
  30582. void Component::sendFakeMouseMove() const
  30583. {
  30584. ComponentPeer* const peer = getPeer();
  30585. if (peer != 0)
  30586. peer->sendFakeMouseMove();
  30587. }
  30588. void Component::broughtToFront()
  30589. {
  30590. }
  30591. void Component::internalBroughtToFront()
  30592. {
  30593. if (isValidComponent())
  30594. {
  30595. if (flags.hasHeavyweightPeerFlag)
  30596. Desktop::getInstance().componentBroughtToFront (this);
  30597. const ComponentDeletionWatcher deletionChecker (this);
  30598. broughtToFront();
  30599. if (deletionChecker.hasBeenDeleted())
  30600. return;
  30601. if (componentListeners_ != 0)
  30602. {
  30603. for (int i = componentListeners_->size(); --i >= 0;)
  30604. {
  30605. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30606. ->componentBroughtToFront (*this);
  30607. if (deletionChecker.hasBeenDeleted())
  30608. return;
  30609. i = jmin (i, componentListeners_->size());
  30610. }
  30611. }
  30612. // when brought to the front and there's a modal component blocking this one,
  30613. // we need to bring the modal one to the front instead..
  30614. Component* const cm = getCurrentlyModalComponent();
  30615. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  30616. {
  30617. cm->getTopLevelComponent()->toFront (false);
  30618. }
  30619. }
  30620. }
  30621. void Component::focusGained (FocusChangeType)
  30622. {
  30623. // base class does nothing
  30624. }
  30625. void Component::internalFocusGain (const FocusChangeType cause)
  30626. {
  30627. const ComponentDeletionWatcher deletionChecker (this);
  30628. focusGained (cause);
  30629. if (! deletionChecker.hasBeenDeleted())
  30630. internalChildFocusChange (cause);
  30631. }
  30632. void Component::focusLost (FocusChangeType)
  30633. {
  30634. // base class does nothing
  30635. }
  30636. void Component::internalFocusLoss (const FocusChangeType cause)
  30637. {
  30638. const ComponentDeletionWatcher deletionChecker (this);
  30639. focusLost (focusChangedDirectly);
  30640. if (! deletionChecker.hasBeenDeleted())
  30641. internalChildFocusChange (cause);
  30642. }
  30643. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  30644. {
  30645. // base class does nothing
  30646. }
  30647. void Component::internalChildFocusChange (FocusChangeType cause)
  30648. {
  30649. const bool childIsNowFocused = hasKeyboardFocus (true);
  30650. if (flags.childCompFocusedFlag != childIsNowFocused)
  30651. {
  30652. flags.childCompFocusedFlag = childIsNowFocused;
  30653. const ComponentDeletionWatcher deletionChecker (this);
  30654. focusOfChildComponentChanged (cause);
  30655. if (deletionChecker.hasBeenDeleted())
  30656. return;
  30657. }
  30658. if (parentComponent_ != 0)
  30659. parentComponent_->internalChildFocusChange (cause);
  30660. }
  30661. bool Component::isEnabled() const throw()
  30662. {
  30663. return (! flags.isDisabledFlag)
  30664. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  30665. }
  30666. void Component::setEnabled (const bool shouldBeEnabled)
  30667. {
  30668. if (flags.isDisabledFlag == shouldBeEnabled)
  30669. {
  30670. flags.isDisabledFlag = ! shouldBeEnabled;
  30671. // if any parent components are disabled, setting our flag won't make a difference,
  30672. // so no need to send a change message
  30673. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  30674. sendEnablementChangeMessage();
  30675. }
  30676. }
  30677. void Component::sendEnablementChangeMessage()
  30678. {
  30679. const ComponentDeletionWatcher deletionChecker (this);
  30680. enablementChanged();
  30681. if (deletionChecker.hasBeenDeleted())
  30682. return;
  30683. for (int i = getNumChildComponents(); --i >= 0;)
  30684. {
  30685. Component* const c = getChildComponent (i);
  30686. if (c != 0)
  30687. {
  30688. c->sendEnablementChangeMessage();
  30689. if (deletionChecker.hasBeenDeleted())
  30690. return;
  30691. }
  30692. }
  30693. }
  30694. void Component::enablementChanged()
  30695. {
  30696. }
  30697. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  30698. {
  30699. flags.wantsFocusFlag = wantsFocus;
  30700. }
  30701. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  30702. {
  30703. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  30704. }
  30705. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  30706. {
  30707. return ! flags.dontFocusOnMouseClickFlag;
  30708. }
  30709. bool Component::getWantsKeyboardFocus() const throw()
  30710. {
  30711. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  30712. }
  30713. void Component::setFocusContainer (const bool isFocusContainer) throw()
  30714. {
  30715. flags.isFocusContainerFlag = isFocusContainer;
  30716. }
  30717. bool Component::isFocusContainer() const throw()
  30718. {
  30719. return flags.isFocusContainerFlag;
  30720. }
  30721. int Component::getExplicitFocusOrder() const throw()
  30722. {
  30723. return getComponentPropertyInt (T("_jexfo"), false, 0);
  30724. }
  30725. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  30726. {
  30727. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  30728. }
  30729. KeyboardFocusTraverser* Component::createFocusTraverser()
  30730. {
  30731. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  30732. return new KeyboardFocusTraverser();
  30733. return parentComponent_->createFocusTraverser();
  30734. }
  30735. void Component::takeKeyboardFocus (const FocusChangeType cause)
  30736. {
  30737. // give the focus to this component
  30738. if (currentlyFocusedComponent != this)
  30739. {
  30740. JUCE_TRY
  30741. {
  30742. // get the focus onto our desktop window
  30743. ComponentPeer* const peer = getPeer();
  30744. if (peer != 0)
  30745. {
  30746. const ComponentDeletionWatcher deletionChecker (this);
  30747. peer->grabFocus();
  30748. if (peer->isFocused() && currentlyFocusedComponent != this)
  30749. {
  30750. Component* const componentLosingFocus = currentlyFocusedComponent;
  30751. currentlyFocusedComponent = this;
  30752. Desktop::getInstance().triggerFocusCallback();
  30753. // call this after setting currentlyFocusedComponent so that the one that's
  30754. // losing it has a chance to see where focus is going
  30755. if (componentLosingFocus->isValidComponent())
  30756. componentLosingFocus->internalFocusLoss (cause);
  30757. if (currentlyFocusedComponent == this)
  30758. {
  30759. focusGained (cause);
  30760. if (! deletionChecker.hasBeenDeleted())
  30761. internalChildFocusChange (cause);
  30762. }
  30763. }
  30764. }
  30765. }
  30766. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30767. catch (const std::exception& e)
  30768. {
  30769. currentlyFocusedComponent = 0;
  30770. Desktop::getInstance().triggerFocusCallback();
  30771. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30772. }
  30773. catch (...)
  30774. {
  30775. currentlyFocusedComponent = 0;
  30776. Desktop::getInstance().triggerFocusCallback();
  30777. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30778. }
  30779. #endif
  30780. }
  30781. }
  30782. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  30783. {
  30784. if (isShowing())
  30785. {
  30786. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  30787. {
  30788. takeKeyboardFocus (cause);
  30789. }
  30790. else
  30791. {
  30792. if (isParentOf (currentlyFocusedComponent)
  30793. && currentlyFocusedComponent->isShowing())
  30794. {
  30795. // do nothing if the focused component is actually a child of ours..
  30796. }
  30797. else
  30798. {
  30799. // find the default child component..
  30800. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30801. if (traverser != 0)
  30802. {
  30803. Component* const defaultComp = traverser->getDefaultComponent (this);
  30804. delete traverser;
  30805. if (defaultComp != 0)
  30806. {
  30807. defaultComp->grabFocusInternal (cause, false);
  30808. return;
  30809. }
  30810. }
  30811. if (canTryParent && parentComponent_ != 0)
  30812. {
  30813. // if no children want it and we're allowed to try our parent comp,
  30814. // then pass up to parent, which will try our siblings.
  30815. parentComponent_->grabFocusInternal (cause, true);
  30816. }
  30817. }
  30818. }
  30819. }
  30820. }
  30821. void Component::grabKeyboardFocus()
  30822. {
  30823. // if component methods are being called from threads other than the message
  30824. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30825. checkMessageManagerIsLocked
  30826. grabFocusInternal (focusChangedDirectly);
  30827. }
  30828. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  30829. {
  30830. // if component methods are being called from threads other than the message
  30831. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30832. checkMessageManagerIsLocked
  30833. if (parentComponent_ != 0)
  30834. {
  30835. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30836. if (traverser != 0)
  30837. {
  30838. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  30839. : traverser->getPreviousComponent (this);
  30840. delete traverser;
  30841. if (nextComp != 0)
  30842. {
  30843. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  30844. {
  30845. const ComponentDeletionWatcher deletionChecker (nextComp);
  30846. internalModalInputAttempt();
  30847. if (deletionChecker.hasBeenDeleted()
  30848. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  30849. return;
  30850. }
  30851. nextComp->grabFocusInternal (focusChangedByTabKey);
  30852. return;
  30853. }
  30854. }
  30855. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  30856. }
  30857. }
  30858. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  30859. {
  30860. return (currentlyFocusedComponent == this)
  30861. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  30862. }
  30863. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  30864. {
  30865. return currentlyFocusedComponent;
  30866. }
  30867. void Component::giveAwayFocus()
  30868. {
  30869. // use a copy so we can clear the value before the call
  30870. Component* const componentLosingFocus = currentlyFocusedComponent;
  30871. currentlyFocusedComponent = 0;
  30872. Desktop::getInstance().triggerFocusCallback();
  30873. if (componentLosingFocus->isValidComponent())
  30874. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  30875. }
  30876. bool Component::isMouseOver() const throw()
  30877. {
  30878. return flags.mouseOverFlag;
  30879. }
  30880. bool Component::isMouseButtonDown() const throw()
  30881. {
  30882. return flags.draggingFlag;
  30883. }
  30884. bool Component::isMouseOverOrDragging() const throw()
  30885. {
  30886. return flags.mouseOverFlag || flags.draggingFlag;
  30887. }
  30888. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  30889. {
  30890. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  30891. }
  30892. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  30893. {
  30894. Desktop::getMousePosition (mx, my);
  30895. globalPositionToRelative (mx, my);
  30896. mx += unboundedMouseOffsetX;
  30897. my += unboundedMouseOffsetY;
  30898. }
  30899. void Component::enableUnboundedMouseMovement (bool enable,
  30900. bool keepCursorVisibleUntilOffscreen) throw()
  30901. {
  30902. enable = enable && isMouseButtonDown();
  30903. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  30904. if (enable != isUnboundedMouseModeOn)
  30905. {
  30906. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  30907. || unboundedMouseOffsetX != 0
  30908. || unboundedMouseOffsetY != 0))
  30909. {
  30910. // when released, return the mouse to within the component's bounds
  30911. int mx, my;
  30912. getMouseXYRelative (mx, my);
  30913. mx = jlimit (0, getWidth(), mx);
  30914. my = jlimit (0, getHeight(), my);
  30915. relativePositionToGlobal (mx, my);
  30916. Desktop::setMousePosition (mx, my);
  30917. }
  30918. isUnboundedMouseModeOn = enable;
  30919. unboundedMouseOffsetX = 0;
  30920. unboundedMouseOffsetY = 0;
  30921. internalUpdateMouseCursor (true);
  30922. }
  30923. }
  30924. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  30925. {
  30926. return componentUnderMouse;
  30927. }
  30928. const Rectangle Component::getParentMonitorArea() const throw()
  30929. {
  30930. int centreX = getWidth() / 2;
  30931. int centreY = getHeight() / 2;
  30932. relativePositionToGlobal (centreX, centreY);
  30933. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  30934. }
  30935. void Component::addKeyListener (KeyListener* const newListener) throw()
  30936. {
  30937. if (keyListeners_ == 0)
  30938. keyListeners_ = new VoidArray (4);
  30939. keyListeners_->addIfNotAlreadyThere (newListener);
  30940. }
  30941. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  30942. {
  30943. if (keyListeners_ != 0)
  30944. keyListeners_->removeValue (listenerToRemove);
  30945. }
  30946. bool Component::keyPressed (const KeyPress&)
  30947. {
  30948. return false;
  30949. }
  30950. bool Component::keyStateChanged()
  30951. {
  30952. return false;
  30953. }
  30954. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  30955. {
  30956. if (parentComponent_ != 0)
  30957. parentComponent_->modifierKeysChanged (modifiers);
  30958. }
  30959. void Component::internalModifierKeysChanged()
  30960. {
  30961. sendFakeMouseMove();
  30962. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  30963. }
  30964. ComponentPeer* Component::getPeer() const throw()
  30965. {
  30966. if (flags.hasHeavyweightPeerFlag)
  30967. return ComponentPeer::getPeerFor (this);
  30968. else if (parentComponent_ != 0)
  30969. return parentComponent_->getPeer();
  30970. else
  30971. return 0;
  30972. }
  30973. const String Component::getComponentProperty (const String& keyName,
  30974. const bool useParentComponentIfNotFound,
  30975. const String& defaultReturnValue) const throw()
  30976. {
  30977. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  30978. return propertySet_->getValue (keyName, defaultReturnValue);
  30979. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  30980. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  30981. return defaultReturnValue;
  30982. }
  30983. int Component::getComponentPropertyInt (const String& keyName,
  30984. const bool useParentComponentIfNotFound,
  30985. const int defaultReturnValue) const throw()
  30986. {
  30987. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  30988. return propertySet_->getIntValue (keyName, defaultReturnValue);
  30989. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  30990. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  30991. return defaultReturnValue;
  30992. }
  30993. double Component::getComponentPropertyDouble (const String& keyName,
  30994. const bool useParentComponentIfNotFound,
  30995. const double defaultReturnValue) const throw()
  30996. {
  30997. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  30998. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  30999. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31000. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  31001. return defaultReturnValue;
  31002. }
  31003. bool Component::getComponentPropertyBool (const String& keyName,
  31004. const bool useParentComponentIfNotFound,
  31005. const bool defaultReturnValue) const throw()
  31006. {
  31007. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31008. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  31009. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31010. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  31011. return defaultReturnValue;
  31012. }
  31013. const Colour Component::getComponentPropertyColour (const String& keyName,
  31014. const bool useParentComponentIfNotFound,
  31015. const Colour& defaultReturnValue) const throw()
  31016. {
  31017. return Colour ((uint32) getComponentPropertyInt (keyName,
  31018. useParentComponentIfNotFound,
  31019. defaultReturnValue.getARGB()));
  31020. }
  31021. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  31022. {
  31023. if (propertySet_ == 0)
  31024. propertySet_ = new PropertySet();
  31025. propertySet_->setValue (keyName, value);
  31026. }
  31027. void Component::setComponentProperty (const String& keyName, const int value) throw()
  31028. {
  31029. if (propertySet_ == 0)
  31030. propertySet_ = new PropertySet();
  31031. propertySet_->setValue (keyName, value);
  31032. }
  31033. void Component::setComponentProperty (const String& keyName, const double value) throw()
  31034. {
  31035. if (propertySet_ == 0)
  31036. propertySet_ = new PropertySet();
  31037. propertySet_->setValue (keyName, value);
  31038. }
  31039. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  31040. {
  31041. if (propertySet_ == 0)
  31042. propertySet_ = new PropertySet();
  31043. propertySet_->setValue (keyName, value);
  31044. }
  31045. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  31046. {
  31047. setComponentProperty (keyName, (int) colour.getARGB());
  31048. }
  31049. void Component::removeComponentProperty (const String& keyName) throw()
  31050. {
  31051. if (propertySet_ != 0)
  31052. propertySet_->removeValue (keyName);
  31053. }
  31054. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  31055. : componentToWatch (componentToWatch_),
  31056. componentUID (componentToWatch_->getComponentUID())
  31057. {
  31058. // not possible to check on an already-deleted object..
  31059. jassert (componentToWatch_->isValidComponent());
  31060. }
  31061. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  31062. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  31063. {
  31064. return ! (componentToWatch->isValidComponent()
  31065. && componentToWatch->getComponentUID() == componentUID);
  31066. }
  31067. const Component* ComponentDeletionWatcher::getComponent() const throw()
  31068. {
  31069. return hasBeenDeleted() ? 0 : componentToWatch;
  31070. }
  31071. END_JUCE_NAMESPACE
  31072. /********* End of inlined file: juce_Component.cpp *********/
  31073. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  31074. BEGIN_JUCE_NAMESPACE
  31075. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  31076. {
  31077. }
  31078. void ComponentListener::componentBroughtToFront (Component&)
  31079. {
  31080. }
  31081. void ComponentListener::componentVisibilityChanged (Component&)
  31082. {
  31083. }
  31084. void ComponentListener::componentChildrenChanged (Component&)
  31085. {
  31086. }
  31087. void ComponentListener::componentParentHierarchyChanged (Component&)
  31088. {
  31089. }
  31090. void ComponentListener::componentNameChanged (Component&)
  31091. {
  31092. }
  31093. END_JUCE_NAMESPACE
  31094. /********* End of inlined file: juce_ComponentListener.cpp *********/
  31095. /********* Start of inlined file: juce_Desktop.cpp *********/
  31096. BEGIN_JUCE_NAMESPACE
  31097. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  31098. const bool clipToWorkArea) throw();
  31099. static Desktop* juce_desktopInstance = 0;
  31100. Desktop::Desktop() throw()
  31101. : mouseListeners (2),
  31102. desktopComponents (4),
  31103. monitorCoordsClipped (2),
  31104. monitorCoordsUnclipped (2),
  31105. lastMouseX (0),
  31106. lastMouseY (0)
  31107. {
  31108. refreshMonitorSizes();
  31109. }
  31110. Desktop::~Desktop() throw()
  31111. {
  31112. jassert (juce_desktopInstance == this);
  31113. juce_desktopInstance = 0;
  31114. // doh! If you don't delete all your windows before exiting, you're going to
  31115. // be leaking memory!
  31116. jassert (desktopComponents.size() == 0);
  31117. }
  31118. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  31119. {
  31120. if (juce_desktopInstance == 0)
  31121. juce_desktopInstance = new Desktop();
  31122. return *juce_desktopInstance;
  31123. }
  31124. void Desktop::refreshMonitorSizes() throw()
  31125. {
  31126. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  31127. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  31128. monitorCoordsClipped.clear();
  31129. monitorCoordsUnclipped.clear();
  31130. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  31131. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  31132. jassert (monitorCoordsClipped.size() > 0
  31133. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  31134. if (oldClipped != monitorCoordsClipped
  31135. || oldUnclipped != monitorCoordsUnclipped)
  31136. {
  31137. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  31138. {
  31139. ComponentPeer* const p = ComponentPeer::getPeer (i);
  31140. if (p != 0)
  31141. p->handleScreenSizeChange();
  31142. }
  31143. }
  31144. }
  31145. int Desktop::getNumDisplayMonitors() const throw()
  31146. {
  31147. return monitorCoordsClipped.size();
  31148. }
  31149. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  31150. {
  31151. return clippedToWorkArea ? monitorCoordsClipped [index]
  31152. : monitorCoordsUnclipped [index];
  31153. }
  31154. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  31155. {
  31156. RectangleList rl;
  31157. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  31158. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31159. return rl;
  31160. }
  31161. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  31162. {
  31163. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  31164. }
  31165. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  31166. {
  31167. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  31168. double bestDistance = 1.0e10;
  31169. for (int i = getNumDisplayMonitors(); --i >= 0;)
  31170. {
  31171. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31172. if (rect.contains (cx, cy))
  31173. return rect;
  31174. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  31175. (double) (rect.getCentreY() - cy));
  31176. if (distance < bestDistance)
  31177. {
  31178. bestDistance = distance;
  31179. best = rect;
  31180. }
  31181. }
  31182. return best;
  31183. }
  31184. int Desktop::getNumComponents() const throw()
  31185. {
  31186. return desktopComponents.size();
  31187. }
  31188. Component* Desktop::getComponent (const int index) const throw()
  31189. {
  31190. return (Component*) desktopComponents [index];
  31191. }
  31192. Component* Desktop::findComponentAt (const int screenX,
  31193. const int screenY) const
  31194. {
  31195. for (int i = desktopComponents.size(); --i >= 0;)
  31196. {
  31197. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  31198. int x = screenX, y = screenY;
  31199. c->globalPositionToRelative (x, y);
  31200. if (c->contains (x, y))
  31201. return c->getComponentAt (x, y);
  31202. }
  31203. return 0;
  31204. }
  31205. void Desktop::addDesktopComponent (Component* const c) throw()
  31206. {
  31207. jassert (c != 0);
  31208. jassert (! desktopComponents.contains (c));
  31209. desktopComponents.addIfNotAlreadyThere (c);
  31210. }
  31211. void Desktop::removeDesktopComponent (Component* const c) throw()
  31212. {
  31213. desktopComponents.removeValue (c);
  31214. }
  31215. void Desktop::componentBroughtToFront (Component* const c) throw()
  31216. {
  31217. const int index = desktopComponents.indexOf (c);
  31218. jassert (index >= 0);
  31219. if (index >= 0)
  31220. desktopComponents.move (index, -1);
  31221. }
  31222. // from Component.cpp
  31223. extern int juce_recentMouseDownX [4];
  31224. extern int juce_recentMouseDownY [4];
  31225. extern int juce_MouseClickCounter;
  31226. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  31227. {
  31228. x = juce_recentMouseDownX [0];
  31229. y = juce_recentMouseDownY [0];
  31230. }
  31231. int Desktop::getMouseButtonClickCounter() throw()
  31232. {
  31233. return juce_MouseClickCounter;
  31234. }
  31235. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  31236. {
  31237. jassert (listener != 0);
  31238. if (listener != 0)
  31239. {
  31240. mouseListeners.add (listener);
  31241. resetTimer();
  31242. }
  31243. }
  31244. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  31245. {
  31246. mouseListeners.removeValue (listener);
  31247. resetTimer();
  31248. }
  31249. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  31250. {
  31251. jassert (listener != 0);
  31252. if (listener != 0)
  31253. focusListeners.add (listener);
  31254. }
  31255. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  31256. {
  31257. focusListeners.removeValue (listener);
  31258. }
  31259. void Desktop::triggerFocusCallback() throw()
  31260. {
  31261. triggerAsyncUpdate();
  31262. }
  31263. void Desktop::handleAsyncUpdate()
  31264. {
  31265. for (int i = focusListeners.size(); --i >= 0;)
  31266. {
  31267. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  31268. i = jmin (i, focusListeners.size());
  31269. }
  31270. }
  31271. void Desktop::timerCallback()
  31272. {
  31273. int x, y;
  31274. getMousePosition (x, y);
  31275. if (lastMouseX != x || lastMouseY != y)
  31276. sendMouseMove();
  31277. }
  31278. void Desktop::sendMouseMove()
  31279. {
  31280. if (mouseListeners.size() > 0)
  31281. {
  31282. startTimer (20);
  31283. int x, y;
  31284. getMousePosition (x, y);
  31285. lastMouseX = x;
  31286. lastMouseY = y;
  31287. Component* const target = findComponentAt (x, y);
  31288. if (target != 0)
  31289. {
  31290. target->globalPositionToRelative (x, y);
  31291. ComponentDeletionWatcher deletionChecker (target);
  31292. const MouseEvent me (x, y,
  31293. ModifierKeys::getCurrentModifiers(),
  31294. target,
  31295. Time::getCurrentTime(),
  31296. x, y,
  31297. Time::getCurrentTime(),
  31298. 0, false);
  31299. for (int i = mouseListeners.size(); --i >= 0;)
  31300. {
  31301. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  31302. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  31303. else
  31304. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  31305. if (deletionChecker.hasBeenDeleted())
  31306. return;
  31307. i = jmin (i, mouseListeners.size());
  31308. }
  31309. }
  31310. }
  31311. }
  31312. void Desktop::resetTimer() throw()
  31313. {
  31314. if (mouseListeners.size() == 0)
  31315. stopTimer();
  31316. else
  31317. startTimer (100);
  31318. getMousePosition (lastMouseX, lastMouseY);
  31319. }
  31320. END_JUCE_NAMESPACE
  31321. /********* End of inlined file: juce_Desktop.cpp *********/
  31322. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  31323. BEGIN_JUCE_NAMESPACE
  31324. ArrowButton::ArrowButton (const String& name,
  31325. float arrowDirectionInRadians,
  31326. const Colour& arrowColour)
  31327. : Button (name),
  31328. colour (arrowColour)
  31329. {
  31330. path.lineTo (0.0f, 1.0f);
  31331. path.lineTo (1.0f, 0.5f);
  31332. path.closeSubPath();
  31333. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  31334. 0.5f, 0.5f));
  31335. setComponentEffect (&shadow);
  31336. buttonStateChanged();
  31337. }
  31338. ArrowButton::~ArrowButton()
  31339. {
  31340. }
  31341. void ArrowButton::paintButton (Graphics& g,
  31342. bool /*isMouseOverButton*/,
  31343. bool /*isButtonDown*/)
  31344. {
  31345. g.setColour (colour);
  31346. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  31347. (float) offset,
  31348. (float) (getWidth() - 3),
  31349. (float) (getHeight() - 3),
  31350. false));
  31351. }
  31352. void ArrowButton::buttonStateChanged()
  31353. {
  31354. offset = (isDown()) ? 1 : 0;
  31355. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  31356. 0.3f, -1, 0);
  31357. }
  31358. END_JUCE_NAMESPACE
  31359. /********* End of inlined file: juce_ArrowButton.cpp *********/
  31360. /********* Start of inlined file: juce_Button.cpp *********/
  31361. BEGIN_JUCE_NAMESPACE
  31362. Button::Button (const String& name)
  31363. : Component (name),
  31364. shortcuts (2),
  31365. keySource (0),
  31366. text (name),
  31367. buttonListeners (2),
  31368. repeatTimer (0),
  31369. buttonPressTime (0),
  31370. lastTimeCallbackTime (0),
  31371. commandManagerToUse (0),
  31372. autoRepeatDelay (-1),
  31373. autoRepeatSpeed (0),
  31374. autoRepeatMinimumDelay (-1),
  31375. radioGroupId (0),
  31376. commandID (0),
  31377. connectedEdgeFlags (0),
  31378. buttonState (buttonNormal),
  31379. isOn (false),
  31380. clickTogglesState (false),
  31381. needsToRelease (false),
  31382. needsRepainting (false),
  31383. isKeyDown (false),
  31384. triggerOnMouseDown (false),
  31385. generateTooltip (false)
  31386. {
  31387. setWantsKeyboardFocus (true);
  31388. }
  31389. Button::~Button()
  31390. {
  31391. if (commandManagerToUse != 0)
  31392. commandManagerToUse->removeListener (this);
  31393. delete repeatTimer;
  31394. clearShortcuts();
  31395. }
  31396. void Button::setButtonText (const String& newText) throw()
  31397. {
  31398. if (text != newText)
  31399. {
  31400. text = newText;
  31401. repaint();
  31402. }
  31403. }
  31404. void Button::setTooltip (const String& newTooltip)
  31405. {
  31406. SettableTooltipClient::setTooltip (newTooltip);
  31407. generateTooltip = false;
  31408. }
  31409. const String Button::getTooltip()
  31410. {
  31411. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  31412. {
  31413. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  31414. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  31415. for (int i = 0; i < keyPresses.size(); ++i)
  31416. {
  31417. const String key (keyPresses.getReference(i).getTextDescription());
  31418. if (key.length() == 1)
  31419. tt << " [shortcut: '" << key << "']";
  31420. else
  31421. tt << " [" << key << ']';
  31422. }
  31423. return tt;
  31424. }
  31425. return SettableTooltipClient::getTooltip();
  31426. }
  31427. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  31428. {
  31429. if (connectedEdgeFlags != connectedEdgeFlags_)
  31430. {
  31431. connectedEdgeFlags = connectedEdgeFlags_;
  31432. repaint();
  31433. }
  31434. }
  31435. void Button::setToggleState (const bool shouldBeOn,
  31436. const bool sendChangeNotification)
  31437. {
  31438. if (shouldBeOn != isOn)
  31439. {
  31440. const ComponentDeletionWatcher deletionWatcher (this);
  31441. isOn = shouldBeOn;
  31442. repaint();
  31443. if (sendChangeNotification)
  31444. sendClickMessage (ModifierKeys());
  31445. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  31446. turnOffOtherButtonsInGroup (sendChangeNotification);
  31447. }
  31448. }
  31449. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  31450. {
  31451. clickTogglesState = shouldToggle;
  31452. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31453. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31454. // it is that this button represents, and the button will update its state to reflect this
  31455. // in the applicationCommandListChanged() method.
  31456. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31457. }
  31458. bool Button::getClickingTogglesState() const throw()
  31459. {
  31460. return clickTogglesState;
  31461. }
  31462. void Button::setRadioGroupId (const int newGroupId)
  31463. {
  31464. if (radioGroupId != newGroupId)
  31465. {
  31466. radioGroupId = newGroupId;
  31467. if (isOn)
  31468. turnOffOtherButtonsInGroup (true);
  31469. }
  31470. }
  31471. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  31472. {
  31473. Component* const p = getParentComponent();
  31474. if (p != 0 && radioGroupId != 0)
  31475. {
  31476. const ComponentDeletionWatcher deletionWatcher (this);
  31477. for (int i = p->getNumChildComponents(); --i >= 0;)
  31478. {
  31479. Component* const c = p->getChildComponent (i);
  31480. if (c != this)
  31481. {
  31482. Button* const b = dynamic_cast <Button*> (c);
  31483. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  31484. {
  31485. b->setToggleState (false, sendChangeNotification);
  31486. if (deletionWatcher.hasBeenDeleted())
  31487. return;
  31488. }
  31489. }
  31490. }
  31491. }
  31492. }
  31493. void Button::enablementChanged()
  31494. {
  31495. updateState (0);
  31496. repaint();
  31497. }
  31498. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  31499. {
  31500. ButtonState state = buttonNormal;
  31501. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  31502. {
  31503. int mx, my;
  31504. if (e == 0)
  31505. {
  31506. getMouseXYRelative (mx, my);
  31507. }
  31508. else
  31509. {
  31510. const MouseEvent e2 (e->getEventRelativeTo (this));
  31511. mx = e2.x;
  31512. my = e2.y;
  31513. }
  31514. const bool over = reallyContains (mx, my, true);
  31515. const bool down = isMouseButtonDown();
  31516. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  31517. state = buttonDown;
  31518. else if (over)
  31519. state = buttonOver;
  31520. }
  31521. setState (state);
  31522. return state;
  31523. }
  31524. void Button::setState (const ButtonState newState)
  31525. {
  31526. if (buttonState != newState)
  31527. {
  31528. buttonState = newState;
  31529. repaint();
  31530. if (buttonState == buttonDown)
  31531. {
  31532. buttonPressTime = Time::getApproximateMillisecondCounter();
  31533. lastTimeCallbackTime = buttonPressTime;
  31534. }
  31535. sendStateMessage();
  31536. }
  31537. }
  31538. bool Button::isDown() const throw()
  31539. {
  31540. return buttonState == buttonDown;
  31541. }
  31542. bool Button::isOver() const throw()
  31543. {
  31544. return buttonState != buttonNormal;
  31545. }
  31546. void Button::buttonStateChanged()
  31547. {
  31548. }
  31549. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  31550. {
  31551. const uint32 now = Time::getApproximateMillisecondCounter();
  31552. return now > buttonPressTime ? now - buttonPressTime : 0;
  31553. }
  31554. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  31555. {
  31556. triggerOnMouseDown = isTriggeredOnMouseDown;
  31557. }
  31558. void Button::clicked()
  31559. {
  31560. }
  31561. void Button::clicked (const ModifierKeys& /*modifiers*/)
  31562. {
  31563. clicked();
  31564. }
  31565. static const int clickMessageId = 0x2f3f4f99;
  31566. void Button::triggerClick()
  31567. {
  31568. postCommandMessage (clickMessageId);
  31569. }
  31570. void Button::internalClickCallback (const ModifierKeys& modifiers)
  31571. {
  31572. if (clickTogglesState)
  31573. setToggleState ((radioGroupId != 0) || ! isOn, false);
  31574. sendClickMessage (modifiers);
  31575. }
  31576. void Button::flashButtonState() throw()
  31577. {
  31578. if (isEnabled())
  31579. {
  31580. needsToRelease = true;
  31581. setState (buttonDown);
  31582. getRepeatTimer().startTimer (100);
  31583. }
  31584. }
  31585. void Button::handleCommandMessage (int commandId)
  31586. {
  31587. if (commandId == clickMessageId)
  31588. {
  31589. if (isEnabled())
  31590. {
  31591. flashButtonState();
  31592. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31593. }
  31594. }
  31595. else
  31596. {
  31597. Component::handleCommandMessage (commandId);
  31598. }
  31599. }
  31600. void Button::addButtonListener (ButtonListener* const newListener) throw()
  31601. {
  31602. jassert (newListener != 0);
  31603. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  31604. if (newListener != 0)
  31605. buttonListeners.add (newListener);
  31606. }
  31607. void Button::removeButtonListener (ButtonListener* const listener) throw()
  31608. {
  31609. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  31610. buttonListeners.removeValue (listener);
  31611. }
  31612. void Button::sendClickMessage (const ModifierKeys& modifiers)
  31613. {
  31614. const ComponentDeletionWatcher cdw (this);
  31615. if (commandManagerToUse != 0 && commandID != 0)
  31616. {
  31617. ApplicationCommandTarget::InvocationInfo info (commandID);
  31618. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  31619. info.originatingComponent = this;
  31620. commandManagerToUse->invoke (info, true);
  31621. }
  31622. clicked (modifiers);
  31623. if (! cdw.hasBeenDeleted())
  31624. {
  31625. for (int i = buttonListeners.size(); --i >= 0;)
  31626. {
  31627. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31628. if (bl != 0)
  31629. {
  31630. bl->buttonClicked (this);
  31631. if (cdw.hasBeenDeleted())
  31632. return;
  31633. }
  31634. }
  31635. }
  31636. }
  31637. void Button::sendStateMessage()
  31638. {
  31639. const ComponentDeletionWatcher cdw (this);
  31640. buttonStateChanged();
  31641. if (cdw.hasBeenDeleted())
  31642. return;
  31643. for (int i = buttonListeners.size(); --i >= 0;)
  31644. {
  31645. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31646. if (bl != 0)
  31647. {
  31648. bl->buttonStateChanged (this);
  31649. if (cdw.hasBeenDeleted())
  31650. return;
  31651. }
  31652. }
  31653. }
  31654. void Button::paint (Graphics& g)
  31655. {
  31656. if (needsToRelease && isEnabled())
  31657. {
  31658. needsToRelease = false;
  31659. needsRepainting = true;
  31660. }
  31661. paintButton (g, isOver(), isDown());
  31662. }
  31663. void Button::mouseEnter (const MouseEvent& e)
  31664. {
  31665. updateState (&e);
  31666. }
  31667. void Button::mouseExit (const MouseEvent& e)
  31668. {
  31669. updateState (&e);
  31670. }
  31671. void Button::mouseDown (const MouseEvent& e)
  31672. {
  31673. updateState (&e);
  31674. if (isDown())
  31675. {
  31676. if (autoRepeatDelay >= 0)
  31677. getRepeatTimer().startTimer (autoRepeatDelay);
  31678. if (triggerOnMouseDown)
  31679. internalClickCallback (e.mods);
  31680. }
  31681. }
  31682. void Button::mouseUp (const MouseEvent& e)
  31683. {
  31684. const bool wasDown = isDown();
  31685. updateState (&e);
  31686. if (wasDown && isOver() && ! triggerOnMouseDown)
  31687. internalClickCallback (e.mods);
  31688. }
  31689. void Button::mouseDrag (const MouseEvent& e)
  31690. {
  31691. const ButtonState oldState = buttonState;
  31692. updateState (&e);
  31693. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  31694. getRepeatTimer().startTimer (autoRepeatSpeed);
  31695. }
  31696. void Button::focusGained (FocusChangeType)
  31697. {
  31698. updateState (0);
  31699. repaint();
  31700. }
  31701. void Button::focusLost (FocusChangeType)
  31702. {
  31703. updateState (0);
  31704. repaint();
  31705. }
  31706. void Button::setVisible (bool shouldBeVisible)
  31707. {
  31708. if (shouldBeVisible != isVisible())
  31709. {
  31710. Component::setVisible (shouldBeVisible);
  31711. if (! shouldBeVisible)
  31712. needsToRelease = false;
  31713. updateState (0);
  31714. }
  31715. else
  31716. {
  31717. Component::setVisible (shouldBeVisible);
  31718. }
  31719. }
  31720. void Button::parentHierarchyChanged()
  31721. {
  31722. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  31723. if (newKeySource != keySource)
  31724. {
  31725. if (keySource->isValidComponent())
  31726. keySource->removeKeyListener (this);
  31727. keySource = newKeySource;
  31728. if (keySource->isValidComponent())
  31729. keySource->addKeyListener (this);
  31730. }
  31731. }
  31732. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  31733. const int commandID_,
  31734. const bool generateTooltip_)
  31735. {
  31736. commandID = commandID_;
  31737. generateTooltip = generateTooltip_;
  31738. if (commandManagerToUse != commandManagerToUse_)
  31739. {
  31740. if (commandManagerToUse != 0)
  31741. commandManagerToUse->removeListener (this);
  31742. commandManagerToUse = commandManagerToUse_;
  31743. if (commandManagerToUse != 0)
  31744. commandManagerToUse->addListener (this);
  31745. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31746. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31747. // it is that this button represents, and the button will update its state to reflect this
  31748. // in the applicationCommandListChanged() method.
  31749. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31750. }
  31751. if (commandManagerToUse != 0)
  31752. applicationCommandListChanged();
  31753. else
  31754. setEnabled (true);
  31755. }
  31756. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  31757. {
  31758. if (info.commandID == commandID
  31759. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  31760. {
  31761. flashButtonState();
  31762. }
  31763. }
  31764. void Button::applicationCommandListChanged()
  31765. {
  31766. if (commandManagerToUse != 0)
  31767. {
  31768. ApplicationCommandInfo info (0);
  31769. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  31770. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  31771. if (target != 0)
  31772. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  31773. }
  31774. }
  31775. void Button::addShortcut (const KeyPress& key)
  31776. {
  31777. if (key.isValid())
  31778. {
  31779. jassert (! isRegisteredForShortcut (key)); // already registered!
  31780. shortcuts.add (key);
  31781. parentHierarchyChanged();
  31782. }
  31783. }
  31784. void Button::clearShortcuts()
  31785. {
  31786. shortcuts.clear();
  31787. parentHierarchyChanged();
  31788. }
  31789. bool Button::isShortcutPressed() const throw()
  31790. {
  31791. if (! isCurrentlyBlockedByAnotherModalComponent())
  31792. {
  31793. for (int i = shortcuts.size(); --i >= 0;)
  31794. if (shortcuts.getReference(i).isCurrentlyDown())
  31795. return true;
  31796. }
  31797. return false;
  31798. }
  31799. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  31800. {
  31801. for (int i = shortcuts.size(); --i >= 0;)
  31802. if (key == shortcuts.getReference(i))
  31803. return true;
  31804. return false;
  31805. }
  31806. bool Button::keyStateChanged (Component*)
  31807. {
  31808. if (! isEnabled())
  31809. return false;
  31810. const bool wasDown = isKeyDown;
  31811. isKeyDown = isShortcutPressed();
  31812. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  31813. getRepeatTimer().startTimer (autoRepeatDelay);
  31814. updateState (0);
  31815. if (isEnabled() && wasDown && ! isKeyDown)
  31816. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31817. return isKeyDown || wasDown;
  31818. }
  31819. bool Button::keyPressed (const KeyPress&, Component*)
  31820. {
  31821. // returning true will avoid forwarding events for keys that we're using as shortcuts
  31822. return isShortcutPressed();
  31823. }
  31824. bool Button::keyPressed (const KeyPress& key)
  31825. {
  31826. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  31827. {
  31828. triggerClick();
  31829. return true;
  31830. }
  31831. return false;
  31832. }
  31833. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  31834. const int repeatMillisecs,
  31835. const int minimumDelayInMillisecs) throw()
  31836. {
  31837. autoRepeatDelay = initialDelayMillisecs;
  31838. autoRepeatSpeed = repeatMillisecs;
  31839. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  31840. }
  31841. void Button::repeatTimerCallback() throw()
  31842. {
  31843. if (needsRepainting)
  31844. {
  31845. getRepeatTimer().stopTimer();
  31846. updateState (0);
  31847. needsRepainting = false;
  31848. }
  31849. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  31850. {
  31851. int repeatSpeed = autoRepeatSpeed;
  31852. if (autoRepeatMinimumDelay >= 0)
  31853. {
  31854. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  31855. timeHeldDown *= timeHeldDown;
  31856. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  31857. }
  31858. repeatSpeed = jmax (1, repeatSpeed);
  31859. getRepeatTimer().startTimer (repeatSpeed);
  31860. const uint32 now = Time::getApproximateMillisecondCounter();
  31861. const int numTimesToCallback
  31862. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  31863. lastTimeCallbackTime = now;
  31864. const ComponentDeletionWatcher cdw (this);
  31865. for (int i = numTimesToCallback; --i >= 0;)
  31866. {
  31867. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31868. if (cdw.hasBeenDeleted() || ! isDown())
  31869. return;
  31870. }
  31871. }
  31872. else if (! needsToRelease)
  31873. {
  31874. getRepeatTimer().stopTimer();
  31875. }
  31876. }
  31877. class InternalButtonRepeatTimer : public Timer
  31878. {
  31879. public:
  31880. InternalButtonRepeatTimer (Button& owner_) throw()
  31881. : owner (owner_)
  31882. {
  31883. }
  31884. ~InternalButtonRepeatTimer()
  31885. {
  31886. }
  31887. void timerCallback()
  31888. {
  31889. owner.repeatTimerCallback();
  31890. }
  31891. private:
  31892. Button& owner;
  31893. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  31894. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  31895. };
  31896. Timer& Button::getRepeatTimer() throw()
  31897. {
  31898. if (repeatTimer == 0)
  31899. repeatTimer = new InternalButtonRepeatTimer (*this);
  31900. return *repeatTimer;
  31901. }
  31902. END_JUCE_NAMESPACE
  31903. /********* End of inlined file: juce_Button.cpp *********/
  31904. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  31905. BEGIN_JUCE_NAMESPACE
  31906. DrawableButton::DrawableButton (const String& name,
  31907. const DrawableButton::ButtonStyle buttonStyle)
  31908. : Button (name),
  31909. style (buttonStyle),
  31910. normalImage (0),
  31911. overImage (0),
  31912. downImage (0),
  31913. disabledImage (0),
  31914. normalImageOn (0),
  31915. overImageOn (0),
  31916. downImageOn (0),
  31917. disabledImageOn (0),
  31918. edgeIndent (3)
  31919. {
  31920. if (buttonStyle == ImageOnButtonBackground)
  31921. {
  31922. backgroundOff = Colour (0xffbbbbff);
  31923. backgroundOn = Colour (0xff3333ff);
  31924. }
  31925. else
  31926. {
  31927. backgroundOff = Colours::transparentBlack;
  31928. backgroundOn = Colour (0xaabbbbff);
  31929. }
  31930. }
  31931. DrawableButton::~DrawableButton()
  31932. {
  31933. deleteImages();
  31934. }
  31935. void DrawableButton::deleteImages()
  31936. {
  31937. deleteAndZero (normalImage);
  31938. deleteAndZero (overImage);
  31939. deleteAndZero (downImage);
  31940. deleteAndZero (disabledImage);
  31941. deleteAndZero (normalImageOn);
  31942. deleteAndZero (overImageOn);
  31943. deleteAndZero (downImageOn);
  31944. deleteAndZero (disabledImageOn);
  31945. }
  31946. void DrawableButton::setImages (const Drawable* normal,
  31947. const Drawable* over,
  31948. const Drawable* down,
  31949. const Drawable* disabled,
  31950. const Drawable* normalOn,
  31951. const Drawable* overOn,
  31952. const Drawable* downOn,
  31953. const Drawable* disabledOn)
  31954. {
  31955. deleteImages();
  31956. jassert (normal != 0); // you really need to give it at least a normal image..
  31957. if (normal != 0)
  31958. normalImage = normal->createCopy();
  31959. if (over != 0)
  31960. overImage = over->createCopy();
  31961. if (down != 0)
  31962. downImage = down->createCopy();
  31963. if (disabled != 0)
  31964. disabledImage = disabled->createCopy();
  31965. if (normalOn != 0)
  31966. normalImageOn = normalOn->createCopy();
  31967. if (overOn != 0)
  31968. overImageOn = overOn->createCopy();
  31969. if (downOn != 0)
  31970. downImageOn = downOn->createCopy();
  31971. if (disabledOn != 0)
  31972. disabledImageOn = disabledOn->createCopy();
  31973. repaint();
  31974. }
  31975. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  31976. {
  31977. if (style != newStyle)
  31978. {
  31979. style = newStyle;
  31980. repaint();
  31981. }
  31982. }
  31983. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  31984. const Colour& toggledOnColour)
  31985. {
  31986. if (backgroundOff != toggledOffColour
  31987. || backgroundOn != toggledOnColour)
  31988. {
  31989. backgroundOff = toggledOffColour;
  31990. backgroundOn = toggledOnColour;
  31991. repaint();
  31992. }
  31993. }
  31994. const Colour& DrawableButton::getBackgroundColour() const throw()
  31995. {
  31996. return getToggleState() ? backgroundOn
  31997. : backgroundOff;
  31998. }
  31999. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  32000. {
  32001. edgeIndent = numPixelsIndent;
  32002. repaint();
  32003. }
  32004. void DrawableButton::paintButton (Graphics& g,
  32005. bool isMouseOverButton,
  32006. bool isButtonDown)
  32007. {
  32008. Rectangle imageSpace;
  32009. if (style == ImageOnButtonBackground)
  32010. {
  32011. const int insetX = getWidth() / 4;
  32012. const int insetY = getHeight() / 4;
  32013. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  32014. getLookAndFeel().drawButtonBackground (g, *this,
  32015. getBackgroundColour(),
  32016. isMouseOverButton,
  32017. isButtonDown);
  32018. }
  32019. else
  32020. {
  32021. g.fillAll (getBackgroundColour());
  32022. const int textH = (style == ImageAboveTextLabel)
  32023. ? jmin (16, proportionOfHeight (0.25f))
  32024. : 0;
  32025. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  32026. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  32027. imageSpace.setBounds (indentX, indentY,
  32028. getWidth() - indentX * 2,
  32029. getHeight() - indentY * 2 - textH);
  32030. if (textH > 0)
  32031. {
  32032. g.setFont ((float) textH);
  32033. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  32034. g.drawFittedText (getName(),
  32035. 2, getHeight() - textH - 1,
  32036. getWidth() - 4, textH,
  32037. Justification::centred, 1);
  32038. }
  32039. }
  32040. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  32041. g.setOpacity (1.0f);
  32042. const Drawable* imageToDraw = 0;
  32043. if (isEnabled())
  32044. {
  32045. imageToDraw = getCurrentImage();
  32046. }
  32047. else
  32048. {
  32049. imageToDraw = getToggleState() ? disabledImageOn
  32050. : disabledImage;
  32051. if (imageToDraw == 0)
  32052. {
  32053. g.setOpacity (0.4f);
  32054. imageToDraw = getNormalImage();
  32055. }
  32056. }
  32057. if (imageToDraw != 0)
  32058. {
  32059. if (style == ImageRaw)
  32060. {
  32061. imageToDraw->draw (g);
  32062. }
  32063. else
  32064. {
  32065. imageToDraw->drawWithin (g,
  32066. imageSpace.getX(),
  32067. imageSpace.getY(),
  32068. imageSpace.getWidth(),
  32069. imageSpace.getHeight(),
  32070. RectanglePlacement::centred);
  32071. }
  32072. }
  32073. }
  32074. const Drawable* DrawableButton::getCurrentImage() const throw()
  32075. {
  32076. if (isDown())
  32077. return getDownImage();
  32078. if (isOver())
  32079. return getOverImage();
  32080. return getNormalImage();
  32081. }
  32082. const Drawable* DrawableButton::getNormalImage() const throw()
  32083. {
  32084. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  32085. : normalImage;
  32086. }
  32087. const Drawable* DrawableButton::getOverImage() const throw()
  32088. {
  32089. const Drawable* d = normalImage;
  32090. if (getToggleState())
  32091. {
  32092. if (overImageOn != 0)
  32093. d = overImageOn;
  32094. else if (normalImageOn != 0)
  32095. d = normalImageOn;
  32096. else if (overImage != 0)
  32097. d = overImage;
  32098. }
  32099. else
  32100. {
  32101. if (overImage != 0)
  32102. d = overImage;
  32103. }
  32104. return d;
  32105. }
  32106. const Drawable* DrawableButton::getDownImage() const throw()
  32107. {
  32108. const Drawable* d = normalImage;
  32109. if (getToggleState())
  32110. {
  32111. if (downImageOn != 0)
  32112. d = downImageOn;
  32113. else if (overImageOn != 0)
  32114. d = overImageOn;
  32115. else if (normalImageOn != 0)
  32116. d = normalImageOn;
  32117. else if (downImage != 0)
  32118. d = downImage;
  32119. else
  32120. d = getOverImage();
  32121. }
  32122. else
  32123. {
  32124. if (downImage != 0)
  32125. d = downImage;
  32126. else
  32127. d = getOverImage();
  32128. }
  32129. return d;
  32130. }
  32131. END_JUCE_NAMESPACE
  32132. /********* End of inlined file: juce_DrawableButton.cpp *********/
  32133. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  32134. BEGIN_JUCE_NAMESPACE
  32135. HyperlinkButton::HyperlinkButton (const String& linkText,
  32136. const URL& linkURL)
  32137. : Button (linkText),
  32138. url (linkURL),
  32139. font (14.0f, Font::underlined),
  32140. resizeFont (true),
  32141. justification (Justification::centred)
  32142. {
  32143. setMouseCursor (MouseCursor::PointingHandCursor);
  32144. setTooltip (linkURL.toString (false));
  32145. }
  32146. HyperlinkButton::~HyperlinkButton()
  32147. {
  32148. }
  32149. void HyperlinkButton::setFont (const Font& newFont,
  32150. const bool resizeToMatchComponentHeight,
  32151. const Justification& justificationType)
  32152. {
  32153. font = newFont;
  32154. resizeFont = resizeToMatchComponentHeight;
  32155. justification = justificationType;
  32156. repaint();
  32157. }
  32158. void HyperlinkButton::setURL (const URL& newURL) throw()
  32159. {
  32160. url = newURL;
  32161. setTooltip (newURL.toString (false));
  32162. }
  32163. const Font HyperlinkButton::getFontToUse() const
  32164. {
  32165. Font f (font);
  32166. if (resizeFont)
  32167. f.setHeight (getHeight() * 0.7f);
  32168. return f;
  32169. }
  32170. void HyperlinkButton::changeWidthToFitText()
  32171. {
  32172. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  32173. }
  32174. void HyperlinkButton::colourChanged()
  32175. {
  32176. repaint();
  32177. }
  32178. void HyperlinkButton::clicked()
  32179. {
  32180. if (url.isWellFormed())
  32181. url.launchInDefaultBrowser();
  32182. }
  32183. void HyperlinkButton::paintButton (Graphics& g,
  32184. bool isMouseOverButton,
  32185. bool isButtonDown)
  32186. {
  32187. const Colour textColour (findColour (textColourId));
  32188. if (isEnabled())
  32189. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  32190. : textColour);
  32191. else
  32192. g.setColour (textColour.withMultipliedAlpha (0.4f));
  32193. g.setFont (getFontToUse());
  32194. g.drawText (getButtonText(),
  32195. 2, 0, getWidth() - 2, getHeight(),
  32196. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  32197. true);
  32198. }
  32199. END_JUCE_NAMESPACE
  32200. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  32201. /********* Start of inlined file: juce_ImageButton.cpp *********/
  32202. BEGIN_JUCE_NAMESPACE
  32203. ImageButton::ImageButton (const String& text)
  32204. : Button (text),
  32205. scaleImageToFit (true),
  32206. preserveProportions (true),
  32207. alphaThreshold (0),
  32208. imageX (0),
  32209. imageY (0),
  32210. imageW (0),
  32211. imageH (0),
  32212. normalImage (0),
  32213. overImage (0),
  32214. downImage (0)
  32215. {
  32216. }
  32217. ImageButton::~ImageButton()
  32218. {
  32219. deleteImages();
  32220. }
  32221. void ImageButton::deleteImages()
  32222. {
  32223. if (normalImage != 0)
  32224. {
  32225. if (ImageCache::isImageInCache (normalImage))
  32226. ImageCache::release (normalImage);
  32227. else
  32228. delete normalImage;
  32229. }
  32230. if (overImage != 0)
  32231. {
  32232. if (ImageCache::isImageInCache (overImage))
  32233. ImageCache::release (overImage);
  32234. else
  32235. delete overImage;
  32236. }
  32237. if (downImage != 0)
  32238. {
  32239. if (ImageCache::isImageInCache (downImage))
  32240. ImageCache::release (downImage);
  32241. else
  32242. delete downImage;
  32243. }
  32244. }
  32245. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  32246. const bool rescaleImagesWhenButtonSizeChanges,
  32247. const bool preserveImageProportions,
  32248. Image* const normalImage_,
  32249. const float imageOpacityWhenNormal,
  32250. const Colour& overlayColourWhenNormal,
  32251. Image* const overImage_,
  32252. const float imageOpacityWhenOver,
  32253. const Colour& overlayColourWhenOver,
  32254. Image* const downImage_,
  32255. const float imageOpacityWhenDown,
  32256. const Colour& overlayColourWhenDown,
  32257. const float hitTestAlphaThreshold)
  32258. {
  32259. deleteImages();
  32260. normalImage = normalImage_;
  32261. overImage = overImage_;
  32262. downImage = downImage_;
  32263. if (resizeButtonNowToFitThisImage && normalImage != 0)
  32264. {
  32265. imageW = normalImage->getWidth();
  32266. imageH = normalImage->getHeight();
  32267. setSize (imageW, imageH);
  32268. }
  32269. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  32270. preserveProportions = preserveImageProportions;
  32271. normalOpacity = imageOpacityWhenNormal;
  32272. normalOverlay = overlayColourWhenNormal;
  32273. overOpacity = imageOpacityWhenOver;
  32274. overOverlay = overlayColourWhenOver;
  32275. downOpacity = imageOpacityWhenDown;
  32276. downOverlay = overlayColourWhenDown;
  32277. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  32278. repaint();
  32279. }
  32280. Image* ImageButton::getCurrentImage() const
  32281. {
  32282. if (isDown())
  32283. return getDownImage();
  32284. if (isOver())
  32285. return getOverImage();
  32286. return getNormalImage();
  32287. }
  32288. Image* ImageButton::getNormalImage() const throw()
  32289. {
  32290. return normalImage;
  32291. }
  32292. Image* ImageButton::getOverImage() const throw()
  32293. {
  32294. return (overImage != 0) ? overImage
  32295. : normalImage;
  32296. }
  32297. Image* ImageButton::getDownImage() const throw()
  32298. {
  32299. return (downImage != 0) ? downImage
  32300. : getOverImage();
  32301. }
  32302. void ImageButton::paintButton (Graphics& g,
  32303. bool isMouseOverButton,
  32304. bool isButtonDown)
  32305. {
  32306. if (! isEnabled())
  32307. {
  32308. isMouseOverButton = false;
  32309. isButtonDown = false;
  32310. }
  32311. Image* const im = getCurrentImage();
  32312. if (im != 0)
  32313. {
  32314. const int iw = im->getWidth();
  32315. const int ih = im->getHeight();
  32316. imageW = getWidth();
  32317. imageH = getHeight();
  32318. imageX = (imageW - iw) >> 1;
  32319. imageY = (imageH - ih) >> 1;
  32320. if (scaleImageToFit)
  32321. {
  32322. if (preserveProportions)
  32323. {
  32324. int newW, newH;
  32325. const float imRatio = ih / (float)iw;
  32326. const float destRatio = imageH / (float)imageW;
  32327. if (imRatio > destRatio)
  32328. {
  32329. newW = roundFloatToInt (imageH / imRatio);
  32330. newH = imageH;
  32331. }
  32332. else
  32333. {
  32334. newW = imageW;
  32335. newH = roundFloatToInt (imageW * imRatio);
  32336. }
  32337. imageX = (imageW - newW) / 2;
  32338. imageY = (imageH - newH) / 2;
  32339. imageW = newW;
  32340. imageH = newH;
  32341. }
  32342. else
  32343. {
  32344. imageX = 0;
  32345. imageY = 0;
  32346. }
  32347. }
  32348. const Colour& overlayColour = (isButtonDown) ? downOverlay
  32349. : ((isMouseOverButton) ? overOverlay
  32350. : normalOverlay);
  32351. if (! overlayColour.isOpaque())
  32352. {
  32353. g.setOpacity ((isButtonDown) ? downOpacity
  32354. : ((isMouseOverButton) ? overOpacity
  32355. : normalOpacity));
  32356. if (scaleImageToFit)
  32357. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  32358. else
  32359. g.drawImageAt (im, imageX, imageY, false);
  32360. }
  32361. if (! overlayColour.isTransparent())
  32362. {
  32363. g.setColour (overlayColour);
  32364. if (scaleImageToFit)
  32365. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  32366. else
  32367. g.drawImageAt (im, imageX, imageY, true);
  32368. }
  32369. }
  32370. }
  32371. bool ImageButton::hitTest (int x, int y)
  32372. {
  32373. if (alphaThreshold == 0)
  32374. return true;
  32375. Image* const im = getCurrentImage();
  32376. return im == 0
  32377. || (imageW > 0 && imageH > 0
  32378. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  32379. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  32380. }
  32381. END_JUCE_NAMESPACE
  32382. /********* End of inlined file: juce_ImageButton.cpp *********/
  32383. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  32384. BEGIN_JUCE_NAMESPACE
  32385. ShapeButton::ShapeButton (const String& text,
  32386. const Colour& normalColour_,
  32387. const Colour& overColour_,
  32388. const Colour& downColour_)
  32389. : Button (text),
  32390. normalColour (normalColour_),
  32391. overColour (overColour_),
  32392. downColour (downColour_),
  32393. maintainShapeProportions (false),
  32394. outlineWidth (0.0f)
  32395. {
  32396. }
  32397. ShapeButton::~ShapeButton()
  32398. {
  32399. }
  32400. void ShapeButton::setColours (const Colour& newNormalColour,
  32401. const Colour& newOverColour,
  32402. const Colour& newDownColour)
  32403. {
  32404. normalColour = newNormalColour;
  32405. overColour = newOverColour;
  32406. downColour = newDownColour;
  32407. }
  32408. void ShapeButton::setOutline (const Colour& newOutlineColour,
  32409. const float newOutlineWidth)
  32410. {
  32411. outlineColour = newOutlineColour;
  32412. outlineWidth = newOutlineWidth;
  32413. }
  32414. void ShapeButton::setShape (const Path& newShape,
  32415. const bool resizeNowToFitThisShape,
  32416. const bool maintainShapeProportions_,
  32417. const bool hasShadow)
  32418. {
  32419. shape = newShape;
  32420. maintainShapeProportions = maintainShapeProportions_;
  32421. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  32422. setComponentEffect ((hasShadow) ? &shadow : 0);
  32423. if (resizeNowToFitThisShape)
  32424. {
  32425. float x, y, w, h;
  32426. shape.getBounds (x, y, w, h);
  32427. shape.applyTransform (AffineTransform::translation (-x, -y));
  32428. if (hasShadow)
  32429. {
  32430. w += 4.0f;
  32431. h += 4.0f;
  32432. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  32433. }
  32434. setSize (1 + (int) (w + outlineWidth),
  32435. 1 + (int) (h + outlineWidth));
  32436. }
  32437. }
  32438. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  32439. {
  32440. if (! isEnabled())
  32441. {
  32442. isMouseOverButton = false;
  32443. isButtonDown = false;
  32444. }
  32445. g.setColour ((isButtonDown) ? downColour
  32446. : (isMouseOverButton) ? overColour
  32447. : normalColour);
  32448. int w = getWidth();
  32449. int h = getHeight();
  32450. if (getComponentEffect() != 0)
  32451. {
  32452. w -= 4;
  32453. h -= 4;
  32454. }
  32455. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  32456. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  32457. w - offset - outlineWidth,
  32458. h - offset - outlineWidth,
  32459. maintainShapeProportions));
  32460. g.fillPath (shape, trans);
  32461. if (outlineWidth > 0.0f)
  32462. {
  32463. g.setColour (outlineColour);
  32464. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  32465. }
  32466. }
  32467. END_JUCE_NAMESPACE
  32468. /********* End of inlined file: juce_ShapeButton.cpp *********/
  32469. /********* Start of inlined file: juce_TextButton.cpp *********/
  32470. BEGIN_JUCE_NAMESPACE
  32471. TextButton::TextButton (const String& name,
  32472. const String& toolTip)
  32473. : Button (name)
  32474. {
  32475. setTooltip (toolTip);
  32476. }
  32477. TextButton::~TextButton()
  32478. {
  32479. }
  32480. void TextButton::paintButton (Graphics& g,
  32481. bool isMouseOverButton,
  32482. bool isButtonDown)
  32483. {
  32484. getLookAndFeel().drawButtonBackground (g, *this,
  32485. findColour (getToggleState() ? buttonOnColourId
  32486. : buttonColourId),
  32487. isMouseOverButton,
  32488. isButtonDown);
  32489. getLookAndFeel().drawButtonText (g, *this,
  32490. isMouseOverButton,
  32491. isButtonDown);
  32492. }
  32493. void TextButton::colourChanged()
  32494. {
  32495. repaint();
  32496. }
  32497. const Font TextButton::getFont()
  32498. {
  32499. return Font (jmin (15.0f, getHeight() * 0.6f));
  32500. }
  32501. void TextButton::changeWidthToFitText (const int newHeight)
  32502. {
  32503. if (newHeight >= 0)
  32504. setSize (jmax (1, getWidth()), newHeight);
  32505. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  32506. getHeight());
  32507. }
  32508. END_JUCE_NAMESPACE
  32509. /********* End of inlined file: juce_TextButton.cpp *********/
  32510. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  32511. BEGIN_JUCE_NAMESPACE
  32512. ToggleButton::ToggleButton (const String& buttonText)
  32513. : Button (buttonText)
  32514. {
  32515. setClickingTogglesState (true);
  32516. }
  32517. ToggleButton::~ToggleButton()
  32518. {
  32519. }
  32520. void ToggleButton::paintButton (Graphics& g,
  32521. bool isMouseOverButton,
  32522. bool isButtonDown)
  32523. {
  32524. getLookAndFeel().drawToggleButton (g, *this,
  32525. isMouseOverButton,
  32526. isButtonDown);
  32527. }
  32528. void ToggleButton::changeWidthToFitText()
  32529. {
  32530. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  32531. }
  32532. void ToggleButton::colourChanged()
  32533. {
  32534. repaint();
  32535. }
  32536. END_JUCE_NAMESPACE
  32537. /********* End of inlined file: juce_ToggleButton.cpp *********/
  32538. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  32539. BEGIN_JUCE_NAMESPACE
  32540. ToolbarButton::ToolbarButton (const int itemId,
  32541. const String& buttonText,
  32542. Drawable* const normalImage_,
  32543. Drawable* const toggledOnImage_)
  32544. : ToolbarItemComponent (itemId, buttonText, true),
  32545. normalImage (normalImage_),
  32546. toggledOnImage (toggledOnImage_)
  32547. {
  32548. }
  32549. ToolbarButton::~ToolbarButton()
  32550. {
  32551. delete normalImage;
  32552. delete toggledOnImage;
  32553. }
  32554. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  32555. bool /*isToolbarVertical*/,
  32556. int& preferredSize,
  32557. int& minSize, int& maxSize)
  32558. {
  32559. preferredSize = minSize = maxSize = toolbarDepth;
  32560. return true;
  32561. }
  32562. void ToolbarButton::paintButtonArea (Graphics& g,
  32563. int width, int height,
  32564. bool /*isMouseOver*/,
  32565. bool /*isMouseDown*/)
  32566. {
  32567. Drawable* d = normalImage;
  32568. if (getToggleState() && toggledOnImage != 0)
  32569. d = toggledOnImage;
  32570. if (! isEnabled())
  32571. {
  32572. Image im (Image::ARGB, width, height, true);
  32573. Graphics g2 (im);
  32574. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  32575. im.desaturate();
  32576. g.drawImageAt (&im, 0, 0);
  32577. }
  32578. else
  32579. {
  32580. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  32581. }
  32582. }
  32583. void ToolbarButton::contentAreaChanged (const Rectangle&)
  32584. {
  32585. }
  32586. END_JUCE_NAMESPACE
  32587. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  32588. /********* Start of inlined file: juce_ComboBox.cpp *********/
  32589. BEGIN_JUCE_NAMESPACE
  32590. ComboBox::ComboBox (const String& name)
  32591. : Component (name),
  32592. items (4),
  32593. currentIndex (-1),
  32594. isButtonDown (false),
  32595. separatorPending (false),
  32596. menuActive (false),
  32597. listeners (2),
  32598. label (0)
  32599. {
  32600. noChoicesMessage = TRANS("(no choices)");
  32601. setRepaintsOnMouseActivity (true);
  32602. lookAndFeelChanged();
  32603. }
  32604. ComboBox::~ComboBox()
  32605. {
  32606. if (menuActive)
  32607. PopupMenu::dismissAllActiveMenus();
  32608. deleteAllChildren();
  32609. }
  32610. void ComboBox::setEditableText (const bool isEditable)
  32611. {
  32612. label->setEditable (isEditable, isEditable, false);
  32613. setWantsKeyboardFocus (! isEditable);
  32614. resized();
  32615. }
  32616. bool ComboBox::isTextEditable() const throw()
  32617. {
  32618. return label->isEditable();
  32619. }
  32620. void ComboBox::setJustificationType (const Justification& justification) throw()
  32621. {
  32622. label->setJustificationType (justification);
  32623. }
  32624. const Justification ComboBox::getJustificationType() const throw()
  32625. {
  32626. return label->getJustificationType();
  32627. }
  32628. void ComboBox::setTooltip (const String& newTooltip)
  32629. {
  32630. SettableTooltipClient::setTooltip (newTooltip);
  32631. label->setTooltip (newTooltip);
  32632. }
  32633. void ComboBox::addItem (const String& newItemText,
  32634. const int newItemId) throw()
  32635. {
  32636. // you can't add empty strings to the list..
  32637. jassert (newItemText.isNotEmpty());
  32638. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  32639. jassert (newItemId != 0);
  32640. // you shouldn't use duplicate item IDs!
  32641. jassert (getItemForId (newItemId) == 0);
  32642. if (newItemText.isNotEmpty() && newItemId != 0)
  32643. {
  32644. if (separatorPending)
  32645. {
  32646. separatorPending = false;
  32647. ItemInfo* const item = new ItemInfo();
  32648. item->itemId = 0;
  32649. item->isEnabled = false;
  32650. item->isHeading = false;
  32651. items.add (item);
  32652. }
  32653. ItemInfo* const item = new ItemInfo();
  32654. item->name = newItemText;
  32655. item->itemId = newItemId;
  32656. item->isEnabled = true;
  32657. item->isHeading = false;
  32658. items.add (item);
  32659. }
  32660. }
  32661. void ComboBox::addSeparator() throw()
  32662. {
  32663. separatorPending = (items.size() > 0);
  32664. }
  32665. void ComboBox::addSectionHeading (const String& headingName) throw()
  32666. {
  32667. // you can't add empty strings to the list..
  32668. jassert (headingName.isNotEmpty());
  32669. if (headingName.isNotEmpty())
  32670. {
  32671. if (separatorPending)
  32672. {
  32673. separatorPending = false;
  32674. ItemInfo* const item = new ItemInfo();
  32675. item->itemId = 0;
  32676. item->isEnabled = false;
  32677. item->isHeading = false;
  32678. items.add (item);
  32679. }
  32680. ItemInfo* const item = new ItemInfo();
  32681. item->name = headingName;
  32682. item->itemId = 0;
  32683. item->isEnabled = true;
  32684. item->isHeading = true;
  32685. items.add (item);
  32686. }
  32687. }
  32688. void ComboBox::setItemEnabled (const int itemId,
  32689. const bool isEnabled) throw()
  32690. {
  32691. ItemInfo* const item = getItemForId (itemId);
  32692. if (item != 0)
  32693. item->isEnabled = isEnabled;
  32694. }
  32695. void ComboBox::changeItemText (const int itemId,
  32696. const String& newText) throw()
  32697. {
  32698. ItemInfo* const item = getItemForId (itemId);
  32699. jassert (item != 0);
  32700. if (item != 0)
  32701. item->name = newText;
  32702. }
  32703. void ComboBox::clear (const bool dontSendChangeMessage)
  32704. {
  32705. items.clear();
  32706. separatorPending = false;
  32707. if (! label->isEditable())
  32708. setSelectedItemIndex (-1, dontSendChangeMessage);
  32709. }
  32710. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  32711. {
  32712. jassert (itemId != 0);
  32713. if (itemId != 0)
  32714. {
  32715. for (int i = items.size(); --i >= 0;)
  32716. if (items.getUnchecked(i)->itemId == itemId)
  32717. return items.getUnchecked(i);
  32718. }
  32719. return 0;
  32720. }
  32721. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  32722. {
  32723. int n = 0;
  32724. for (int i = 0; i < items.size(); ++i)
  32725. {
  32726. ItemInfo* const item = items.getUnchecked(i);
  32727. if (item->isRealItem())
  32728. {
  32729. if (n++ == index)
  32730. return item;
  32731. }
  32732. }
  32733. return 0;
  32734. }
  32735. int ComboBox::getNumItems() const throw()
  32736. {
  32737. int n = 0;
  32738. for (int i = items.size(); --i >= 0;)
  32739. {
  32740. ItemInfo* const item = items.getUnchecked(i);
  32741. if (item->isRealItem())
  32742. ++n;
  32743. }
  32744. return n;
  32745. }
  32746. const String ComboBox::getItemText (const int index) const throw()
  32747. {
  32748. ItemInfo* const item = getItemForIndex (index);
  32749. if (item != 0)
  32750. return item->name;
  32751. return String::empty;
  32752. }
  32753. int ComboBox::getItemId (const int index) const throw()
  32754. {
  32755. ItemInfo* const item = getItemForIndex (index);
  32756. return (item != 0) ? item->itemId : 0;
  32757. }
  32758. bool ComboBox::ItemInfo::isSeparator() const throw()
  32759. {
  32760. return name.isEmpty();
  32761. }
  32762. bool ComboBox::ItemInfo::isRealItem() const throw()
  32763. {
  32764. return ! (isHeading || name.isEmpty());
  32765. }
  32766. int ComboBox::getSelectedItemIndex() const throw()
  32767. {
  32768. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  32769. ? currentIndex
  32770. : -1;
  32771. }
  32772. void ComboBox::setSelectedItemIndex (const int index,
  32773. const bool dontSendChangeMessage) throw()
  32774. {
  32775. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  32776. {
  32777. if (((unsigned int) index) < (unsigned int) getNumItems())
  32778. currentIndex = index;
  32779. else
  32780. currentIndex = -1;
  32781. label->setText (getItemText (currentIndex), false);
  32782. if (! dontSendChangeMessage)
  32783. triggerAsyncUpdate();
  32784. }
  32785. }
  32786. void ComboBox::setSelectedId (const int newItemId,
  32787. const bool dontSendChangeMessage) throw()
  32788. {
  32789. for (int i = getNumItems(); --i >= 0;)
  32790. {
  32791. if (getItemId(i) == newItemId)
  32792. {
  32793. setSelectedItemIndex (i, dontSendChangeMessage);
  32794. break;
  32795. }
  32796. }
  32797. }
  32798. int ComboBox::getSelectedId() const throw()
  32799. {
  32800. const ItemInfo* const item = getItemForIndex (currentIndex);
  32801. return (item != 0 && getText() == item->name)
  32802. ? item->itemId
  32803. : 0;
  32804. }
  32805. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  32806. {
  32807. jassert (listener != 0);
  32808. if (listener != 0)
  32809. listeners.add (listener);
  32810. }
  32811. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  32812. {
  32813. listeners.removeValue (listener);
  32814. }
  32815. void ComboBox::handleAsyncUpdate()
  32816. {
  32817. for (int i = listeners.size(); --i >= 0;)
  32818. {
  32819. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  32820. i = jmin (i, listeners.size());
  32821. }
  32822. }
  32823. const String ComboBox::getText() const throw()
  32824. {
  32825. return label->getText();
  32826. }
  32827. void ComboBox::setText (const String& newText,
  32828. const bool dontSendChangeMessage) throw()
  32829. {
  32830. for (int i = items.size(); --i >= 0;)
  32831. {
  32832. ItemInfo* const item = items.getUnchecked(i);
  32833. if (item->isRealItem()
  32834. && item->name == newText)
  32835. {
  32836. setSelectedId (item->itemId, dontSendChangeMessage);
  32837. return;
  32838. }
  32839. }
  32840. currentIndex = -1;
  32841. if (label->getText() != newText)
  32842. {
  32843. label->setText (newText, false);
  32844. if (! dontSendChangeMessage)
  32845. triggerAsyncUpdate();
  32846. }
  32847. repaint();
  32848. }
  32849. void ComboBox::showEditor()
  32850. {
  32851. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  32852. label->showEditor();
  32853. }
  32854. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  32855. {
  32856. textWhenNothingSelected = newMessage;
  32857. repaint();
  32858. }
  32859. const String ComboBox::getTextWhenNothingSelected() const throw()
  32860. {
  32861. return textWhenNothingSelected;
  32862. }
  32863. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  32864. {
  32865. noChoicesMessage = newMessage;
  32866. }
  32867. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  32868. {
  32869. return noChoicesMessage;
  32870. }
  32871. void ComboBox::paint (Graphics& g)
  32872. {
  32873. getLookAndFeel().drawComboBox (g,
  32874. getWidth(),
  32875. getHeight(),
  32876. isButtonDown,
  32877. label->getRight(),
  32878. 0,
  32879. getWidth() - label->getRight(),
  32880. getHeight(),
  32881. *this);
  32882. if (textWhenNothingSelected.isNotEmpty()
  32883. && label->getText().isEmpty()
  32884. && ! label->isBeingEdited())
  32885. {
  32886. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  32887. g.setFont (label->getFont());
  32888. g.drawFittedText (textWhenNothingSelected,
  32889. label->getX() + 2, label->getY() + 1,
  32890. label->getWidth() - 4, label->getHeight() - 2,
  32891. label->getJustificationType(),
  32892. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  32893. }
  32894. }
  32895. void ComboBox::resized()
  32896. {
  32897. if (getHeight() > 0 && getWidth() > 0)
  32898. getLookAndFeel().positionComboBoxText (*this, *label);
  32899. }
  32900. void ComboBox::enablementChanged()
  32901. {
  32902. repaint();
  32903. }
  32904. void ComboBox::lookAndFeelChanged()
  32905. {
  32906. repaint();
  32907. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  32908. if (label != 0)
  32909. {
  32910. newLabel->setEditable (label->isEditable());
  32911. newLabel->setJustificationType (label->getJustificationType());
  32912. newLabel->setTooltip (label->getTooltip());
  32913. newLabel->setText (label->getText(), false);
  32914. }
  32915. delete label;
  32916. label = newLabel;
  32917. addAndMakeVisible (newLabel);
  32918. newLabel->addListener (this);
  32919. newLabel->addMouseListener (this, false);
  32920. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  32921. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  32922. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  32923. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  32924. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  32925. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  32926. resized();
  32927. }
  32928. void ComboBox::colourChanged()
  32929. {
  32930. lookAndFeelChanged();
  32931. }
  32932. bool ComboBox::keyPressed (const KeyPress& key)
  32933. {
  32934. bool used = false;
  32935. if (key.isKeyCode (KeyPress::upKey)
  32936. || key.isKeyCode (KeyPress::leftKey))
  32937. {
  32938. setSelectedItemIndex (jmax (0, currentIndex - 1));
  32939. used = true;
  32940. }
  32941. else if (key.isKeyCode (KeyPress::downKey)
  32942. || key.isKeyCode (KeyPress::rightKey))
  32943. {
  32944. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  32945. used = true;
  32946. }
  32947. else if (key.isKeyCode (KeyPress::returnKey))
  32948. {
  32949. showPopup();
  32950. used = true;
  32951. }
  32952. return used;
  32953. }
  32954. bool ComboBox::keyStateChanged()
  32955. {
  32956. // only forward key events that aren't used by this component
  32957. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  32958. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  32959. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  32960. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  32961. }
  32962. void ComboBox::focusGained (FocusChangeType)
  32963. {
  32964. repaint();
  32965. }
  32966. void ComboBox::focusLost (FocusChangeType)
  32967. {
  32968. repaint();
  32969. }
  32970. void ComboBox::labelTextChanged (Label*)
  32971. {
  32972. triggerAsyncUpdate();
  32973. }
  32974. void ComboBox::showPopup()
  32975. {
  32976. if (! menuActive)
  32977. {
  32978. const int currentId = getSelectedId();
  32979. ComponentDeletionWatcher deletionWatcher (this);
  32980. PopupMenu menu;
  32981. menu.setLookAndFeel (&getLookAndFeel());
  32982. for (int i = 0; i < items.size(); ++i)
  32983. {
  32984. const ItemInfo* const item = items.getUnchecked(i);
  32985. if (item->isSeparator())
  32986. menu.addSeparator();
  32987. else if (item->isHeading)
  32988. menu.addSectionHeader (item->name);
  32989. else
  32990. menu.addItem (item->itemId, item->name,
  32991. item->isEnabled, item->itemId == currentId);
  32992. }
  32993. if (items.size() == 0)
  32994. menu.addItem (1, noChoicesMessage, false);
  32995. const int itemHeight = jlimit (12, 24, getHeight());
  32996. menuActive = true;
  32997. const int resultId = menu.showAt (this, currentId,
  32998. getWidth(), 1, itemHeight);
  32999. if (deletionWatcher.hasBeenDeleted())
  33000. return;
  33001. menuActive = false;
  33002. if (resultId != 0)
  33003. setSelectedId (resultId);
  33004. }
  33005. }
  33006. void ComboBox::mouseDown (const MouseEvent& e)
  33007. {
  33008. beginDragAutoRepeat (300);
  33009. isButtonDown = isEnabled();
  33010. if (isButtonDown
  33011. && (e.eventComponent == this || ! label->isEditable()))
  33012. {
  33013. showPopup();
  33014. }
  33015. }
  33016. void ComboBox::mouseDrag (const MouseEvent& e)
  33017. {
  33018. beginDragAutoRepeat (50);
  33019. if (isButtonDown && ! e.mouseWasClicked())
  33020. showPopup();
  33021. }
  33022. void ComboBox::mouseUp (const MouseEvent& e2)
  33023. {
  33024. if (isButtonDown)
  33025. {
  33026. isButtonDown = false;
  33027. repaint();
  33028. const MouseEvent e (e2.getEventRelativeTo (this));
  33029. if (reallyContains (e.x, e.y, true)
  33030. && (e2.eventComponent == this || ! label->isEditable()))
  33031. {
  33032. showPopup();
  33033. }
  33034. }
  33035. }
  33036. END_JUCE_NAMESPACE
  33037. /********* End of inlined file: juce_ComboBox.cpp *********/
  33038. /********* Start of inlined file: juce_Label.cpp *********/
  33039. BEGIN_JUCE_NAMESPACE
  33040. Label::Label (const String& componentName,
  33041. const String& labelText)
  33042. : Component (componentName),
  33043. text (labelText),
  33044. font (15.0f),
  33045. justification (Justification::centredLeft),
  33046. editor (0),
  33047. listeners (2),
  33048. ownerComponent (0),
  33049. deletionWatcher (0),
  33050. editSingleClick (false),
  33051. editDoubleClick (false),
  33052. lossOfFocusDiscardsChanges (false)
  33053. {
  33054. setColour (TextEditor::textColourId, Colours::black);
  33055. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33056. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33057. }
  33058. Label::~Label()
  33059. {
  33060. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33061. ownerComponent->removeComponentListener (this);
  33062. deleteAndZero (deletionWatcher);
  33063. if (editor != 0)
  33064. delete editor;
  33065. }
  33066. void Label::setText (const String& newText,
  33067. const bool broadcastChangeMessage)
  33068. {
  33069. hideEditor (true);
  33070. if (text != newText)
  33071. {
  33072. text = newText;
  33073. if (broadcastChangeMessage)
  33074. triggerAsyncUpdate();
  33075. repaint();
  33076. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33077. componentMovedOrResized (*ownerComponent, true, true);
  33078. }
  33079. }
  33080. const String Label::getText (const bool returnActiveEditorContents) const throw()
  33081. {
  33082. return (returnActiveEditorContents && isBeingEdited())
  33083. ? editor->getText()
  33084. : text;
  33085. }
  33086. void Label::setFont (const Font& newFont) throw()
  33087. {
  33088. font = newFont;
  33089. repaint();
  33090. }
  33091. const Font& Label::getFont() const throw()
  33092. {
  33093. return font;
  33094. }
  33095. void Label::setEditable (const bool editOnSingleClick,
  33096. const bool editOnDoubleClick,
  33097. const bool lossOfFocusDiscardsChanges_) throw()
  33098. {
  33099. editSingleClick = editOnSingleClick;
  33100. editDoubleClick = editOnDoubleClick;
  33101. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  33102. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  33103. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  33104. }
  33105. void Label::setJustificationType (const Justification& justification_) throw()
  33106. {
  33107. justification = justification_;
  33108. repaint();
  33109. }
  33110. void Label::attachToComponent (Component* owner,
  33111. const bool onLeft)
  33112. {
  33113. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33114. ownerComponent->removeComponentListener (this);
  33115. deleteAndZero (deletionWatcher);
  33116. ownerComponent = owner;
  33117. leftOfOwnerComp = onLeft;
  33118. if (ownerComponent != 0)
  33119. {
  33120. deletionWatcher = new ComponentDeletionWatcher (owner);
  33121. setVisible (owner->isVisible());
  33122. ownerComponent->addComponentListener (this);
  33123. componentParentHierarchyChanged (*ownerComponent);
  33124. componentMovedOrResized (*ownerComponent, true, true);
  33125. }
  33126. }
  33127. void Label::componentMovedOrResized (Component& component,
  33128. bool /*wasMoved*/,
  33129. bool /*wasResized*/)
  33130. {
  33131. if (leftOfOwnerComp)
  33132. {
  33133. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  33134. component.getHeight());
  33135. setTopRightPosition (component.getX(), component.getY());
  33136. }
  33137. else
  33138. {
  33139. setSize (component.getWidth(),
  33140. 8 + roundFloatToInt (getFont().getHeight()));
  33141. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  33142. }
  33143. }
  33144. void Label::componentParentHierarchyChanged (Component& component)
  33145. {
  33146. if (component.getParentComponent() != 0)
  33147. component.getParentComponent()->addChildComponent (this);
  33148. }
  33149. void Label::componentVisibilityChanged (Component& component)
  33150. {
  33151. setVisible (component.isVisible());
  33152. }
  33153. void Label::textWasEdited()
  33154. {
  33155. }
  33156. void Label::showEditor()
  33157. {
  33158. if (editor == 0)
  33159. {
  33160. addAndMakeVisible (editor = createEditorComponent());
  33161. editor->setText (getText());
  33162. editor->addListener (this);
  33163. editor->grabKeyboardFocus();
  33164. editor->setHighlightedRegion (0, text.length());
  33165. editor->addListener (this);
  33166. resized();
  33167. repaint();
  33168. enterModalState();
  33169. editor->grabKeyboardFocus();
  33170. }
  33171. }
  33172. bool Label::updateFromTextEditorContents()
  33173. {
  33174. jassert (editor != 0);
  33175. const String newText (editor->getText());
  33176. if (text != newText)
  33177. {
  33178. text = newText;
  33179. triggerAsyncUpdate();
  33180. repaint();
  33181. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33182. componentMovedOrResized (*ownerComponent, true, true);
  33183. return true;
  33184. }
  33185. return false;
  33186. }
  33187. void Label::hideEditor (const bool discardCurrentEditorContents)
  33188. {
  33189. if (editor != 0)
  33190. {
  33191. const bool changed = (! discardCurrentEditorContents)
  33192. && updateFromTextEditorContents();
  33193. deleteAndZero (editor);
  33194. repaint();
  33195. if (changed)
  33196. textWasEdited();
  33197. exitModalState (0);
  33198. }
  33199. }
  33200. void Label::inputAttemptWhenModal()
  33201. {
  33202. if (editor != 0)
  33203. {
  33204. if (lossOfFocusDiscardsChanges)
  33205. textEditorEscapeKeyPressed (*editor);
  33206. else
  33207. textEditorReturnKeyPressed (*editor);
  33208. }
  33209. }
  33210. bool Label::isBeingEdited() const throw()
  33211. {
  33212. return editor != 0;
  33213. }
  33214. TextEditor* Label::createEditorComponent()
  33215. {
  33216. TextEditor* const ed = new TextEditor (getName());
  33217. ed->setFont (font);
  33218. // copy these colours from our own settings..
  33219. const int cols[] = { TextEditor::backgroundColourId,
  33220. TextEditor::textColourId,
  33221. TextEditor::highlightColourId,
  33222. TextEditor::highlightedTextColourId,
  33223. TextEditor::caretColourId,
  33224. TextEditor::outlineColourId,
  33225. TextEditor::focusedOutlineColourId,
  33226. TextEditor::shadowColourId };
  33227. for (int i = 0; i < numElementsInArray (cols); ++i)
  33228. ed->setColour (cols[i], findColour (cols[i]));
  33229. return ed;
  33230. }
  33231. void Label::paint (Graphics& g)
  33232. {
  33233. g.fillAll (findColour (backgroundColourId));
  33234. if (editor == 0)
  33235. {
  33236. const float alpha = isEnabled() ? 1.0f : 0.5f;
  33237. g.setColour (findColour (textColourId).withMultipliedAlpha (alpha));
  33238. g.setFont (font);
  33239. g.drawFittedText (text,
  33240. 3, 1, getWidth() - 6, getHeight() - 2,
  33241. justification,
  33242. jmax (1, (int) (getHeight() / font.getHeight())));
  33243. g.setColour (findColour (outlineColourId).withMultipliedAlpha (alpha));
  33244. g.drawRect (0, 0, getWidth(), getHeight());
  33245. }
  33246. else if (isEnabled())
  33247. {
  33248. g.setColour (editor->findColour (TextEditor::backgroundColourId)
  33249. .overlaidWith (findColour (outlineColourId)));
  33250. g.drawRect (0, 0, getWidth(), getHeight());
  33251. }
  33252. }
  33253. void Label::mouseUp (const MouseEvent& e)
  33254. {
  33255. if (editSingleClick
  33256. && e.mouseWasClicked()
  33257. && contains (e.x, e.y)
  33258. && ! e.mods.isPopupMenu())
  33259. {
  33260. showEditor();
  33261. }
  33262. }
  33263. void Label::mouseDoubleClick (const MouseEvent& e)
  33264. {
  33265. if (editDoubleClick && ! e.mods.isPopupMenu())
  33266. showEditor();
  33267. }
  33268. void Label::resized()
  33269. {
  33270. if (editor != 0)
  33271. editor->setBoundsInset (BorderSize (0));
  33272. }
  33273. void Label::focusGained (FocusChangeType cause)
  33274. {
  33275. if (editSingleClick && cause == focusChangedByTabKey)
  33276. showEditor();
  33277. }
  33278. void Label::enablementChanged()
  33279. {
  33280. repaint();
  33281. }
  33282. void Label::colourChanged()
  33283. {
  33284. repaint();
  33285. }
  33286. // We'll use a custom focus traverser here to make sure focus goes from the
  33287. // text editor to another component rather than back to the label itself.
  33288. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  33289. {
  33290. public:
  33291. LabelKeyboardFocusTraverser() {}
  33292. Component* getNextComponent (Component* current)
  33293. {
  33294. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  33295. ? current->getParentComponent() : current);
  33296. }
  33297. Component* getPreviousComponent (Component* current)
  33298. {
  33299. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  33300. ? current->getParentComponent() : current);
  33301. }
  33302. };
  33303. KeyboardFocusTraverser* Label::createFocusTraverser()
  33304. {
  33305. return new LabelKeyboardFocusTraverser();
  33306. }
  33307. void Label::addListener (LabelListener* const listener) throw()
  33308. {
  33309. jassert (listener != 0);
  33310. if (listener != 0)
  33311. listeners.add (listener);
  33312. }
  33313. void Label::removeListener (LabelListener* const listener) throw()
  33314. {
  33315. listeners.removeValue (listener);
  33316. }
  33317. void Label::handleAsyncUpdate()
  33318. {
  33319. for (int i = listeners.size(); --i >= 0;)
  33320. {
  33321. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  33322. i = jmin (i, listeners.size());
  33323. }
  33324. }
  33325. void Label::textEditorTextChanged (TextEditor& ed)
  33326. {
  33327. if (editor != 0)
  33328. {
  33329. jassert (&ed == editor);
  33330. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  33331. {
  33332. if (lossOfFocusDiscardsChanges)
  33333. textEditorEscapeKeyPressed (ed);
  33334. else
  33335. textEditorReturnKeyPressed (ed);
  33336. }
  33337. }
  33338. }
  33339. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  33340. {
  33341. if (editor != 0)
  33342. {
  33343. jassert (&ed == editor);
  33344. (void) ed;
  33345. const bool changed = updateFromTextEditorContents();
  33346. hideEditor (true);
  33347. if (changed)
  33348. textWasEdited();
  33349. }
  33350. }
  33351. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  33352. {
  33353. if (editor != 0)
  33354. {
  33355. jassert (&ed == editor);
  33356. (void) ed;
  33357. editor->setText (text, false);
  33358. hideEditor (true);
  33359. }
  33360. }
  33361. void Label::textEditorFocusLost (TextEditor& ed)
  33362. {
  33363. textEditorTextChanged (ed);
  33364. }
  33365. END_JUCE_NAMESPACE
  33366. /********* End of inlined file: juce_Label.cpp *********/
  33367. /********* Start of inlined file: juce_ListBox.cpp *********/
  33368. BEGIN_JUCE_NAMESPACE
  33369. class ListBoxRowComponent : public Component
  33370. {
  33371. public:
  33372. ListBoxRowComponent (ListBox& owner_)
  33373. : owner (owner_),
  33374. row (-1),
  33375. selected (false),
  33376. isDragging (false)
  33377. {
  33378. }
  33379. ~ListBoxRowComponent()
  33380. {
  33381. deleteAllChildren();
  33382. }
  33383. void paint (Graphics& g)
  33384. {
  33385. if (owner.getModel() != 0)
  33386. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  33387. }
  33388. void update (const int row_, const bool selected_)
  33389. {
  33390. if (row != row_ || selected != selected_)
  33391. {
  33392. repaint();
  33393. row = row_;
  33394. selected = selected_;
  33395. }
  33396. if (owner.getModel() != 0)
  33397. {
  33398. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  33399. if (customComp != 0)
  33400. {
  33401. addAndMakeVisible (customComp);
  33402. customComp->setBounds (0, 0, getWidth(), getHeight());
  33403. for (int i = getNumChildComponents(); --i >= 0;)
  33404. if (getChildComponent (i) != customComp)
  33405. delete getChildComponent (i);
  33406. }
  33407. else
  33408. {
  33409. deleteAllChildren();
  33410. }
  33411. }
  33412. }
  33413. void mouseDown (const MouseEvent& e)
  33414. {
  33415. isDragging = false;
  33416. selectRowOnMouseUp = false;
  33417. if (isEnabled())
  33418. {
  33419. if (! selected)
  33420. {
  33421. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33422. if (owner.getModel() != 0)
  33423. owner.getModel()->listBoxItemClicked (row, e);
  33424. }
  33425. else
  33426. {
  33427. selectRowOnMouseUp = true;
  33428. }
  33429. }
  33430. }
  33431. void mouseUp (const MouseEvent& e)
  33432. {
  33433. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  33434. {
  33435. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33436. if (owner.getModel() != 0)
  33437. owner.getModel()->listBoxItemClicked (row, e);
  33438. }
  33439. }
  33440. void mouseDoubleClick (const MouseEvent& e)
  33441. {
  33442. if (owner.getModel() != 0 && isEnabled())
  33443. owner.getModel()->listBoxItemDoubleClicked (row, e);
  33444. }
  33445. void mouseDrag (const MouseEvent& e)
  33446. {
  33447. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  33448. {
  33449. const SparseSet <int> selectedRows (owner.getSelectedRows());
  33450. if (selectedRows.size() > 0)
  33451. {
  33452. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  33453. if (dragDescription.isNotEmpty())
  33454. {
  33455. isDragging = true;
  33456. DragAndDropContainer* const dragContainer
  33457. = DragAndDropContainer::findParentDragContainerFor (this);
  33458. if (dragContainer != 0)
  33459. {
  33460. Image* dragImage = owner.createSnapshotOfSelectedRows();
  33461. dragImage->multiplyAllAlphas (0.6f);
  33462. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  33463. }
  33464. else
  33465. {
  33466. // to be able to do a drag-and-drop operation, the listbox needs to
  33467. // be inside a component which is also a DragAndDropContainer.
  33468. jassertfalse
  33469. }
  33470. }
  33471. }
  33472. }
  33473. }
  33474. void resized()
  33475. {
  33476. if (getNumChildComponents() > 0)
  33477. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  33478. }
  33479. juce_UseDebuggingNewOperator
  33480. bool neededFlag;
  33481. private:
  33482. ListBox& owner;
  33483. int row;
  33484. bool selected, isDragging, selectRowOnMouseUp;
  33485. ListBoxRowComponent (const ListBoxRowComponent&);
  33486. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  33487. };
  33488. class ListViewport : public Viewport
  33489. {
  33490. public:
  33491. int firstIndex, firstWholeIndex, lastWholeIndex;
  33492. bool hasUpdated;
  33493. ListViewport (ListBox& owner_)
  33494. : owner (owner_)
  33495. {
  33496. setWantsKeyboardFocus (false);
  33497. setViewedComponent (new Component());
  33498. getViewedComponent()->addMouseListener (this, false);
  33499. getViewedComponent()->setWantsKeyboardFocus (false);
  33500. }
  33501. ~ListViewport()
  33502. {
  33503. getViewedComponent()->removeMouseListener (this);
  33504. getViewedComponent()->deleteAllChildren();
  33505. }
  33506. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  33507. {
  33508. return (ListBoxRowComponent*) getViewedComponent()
  33509. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  33510. }
  33511. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  33512. {
  33513. const int index = getIndexOfChildComponent (rowComponent);
  33514. const int num = getViewedComponent()->getNumChildComponents();
  33515. for (int i = num; --i >= 0;)
  33516. if (((firstIndex + i) % jmax (1, num)) == index)
  33517. return firstIndex + i;
  33518. return -1;
  33519. }
  33520. Component* getComponentForRowIfOnscreen (const int row) const throw()
  33521. {
  33522. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  33523. ? getComponentForRow (row) : 0;
  33524. }
  33525. void visibleAreaChanged (int, int, int, int)
  33526. {
  33527. updateVisibleArea (true);
  33528. if (owner.getModel() != 0)
  33529. owner.getModel()->listWasScrolled();
  33530. }
  33531. void updateVisibleArea (const bool makeSureItUpdatesContent)
  33532. {
  33533. hasUpdated = false;
  33534. const int newX = getViewedComponent()->getX();
  33535. int newY = getViewedComponent()->getY();
  33536. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  33537. const int newH = owner.totalItems * owner.getRowHeight();
  33538. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  33539. newY = getMaximumVisibleHeight() - newH;
  33540. getViewedComponent()->setBounds (newX, newY, newW, newH);
  33541. if (makeSureItUpdatesContent && ! hasUpdated)
  33542. updateContents();
  33543. }
  33544. void updateContents()
  33545. {
  33546. hasUpdated = true;
  33547. const int rowHeight = owner.getRowHeight();
  33548. if (rowHeight > 0)
  33549. {
  33550. const int y = getViewPositionY();
  33551. const int w = getViewedComponent()->getWidth();
  33552. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  33553. while (numNeeded > getViewedComponent()->getNumChildComponents())
  33554. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  33555. jassert (numNeeded >= 0);
  33556. while (numNeeded < getViewedComponent()->getNumChildComponents())
  33557. {
  33558. Component* const rowToRemove
  33559. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  33560. delete rowToRemove;
  33561. }
  33562. firstIndex = y / rowHeight;
  33563. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  33564. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  33565. for (int i = 0; i < numNeeded; ++i)
  33566. {
  33567. const int row = i + firstIndex;
  33568. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  33569. if (rowComp != 0)
  33570. {
  33571. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  33572. rowComp->update (row, owner.isRowSelected (row));
  33573. }
  33574. }
  33575. }
  33576. if (owner.headerComponent != 0)
  33577. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  33578. owner.outlineThickness,
  33579. jmax (owner.getWidth() - owner.outlineThickness * 2,
  33580. getViewedComponent()->getWidth()),
  33581. owner.headerComponent->getHeight());
  33582. }
  33583. void paint (Graphics& g)
  33584. {
  33585. if (isOpaque())
  33586. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  33587. }
  33588. bool keyPressed (const KeyPress& key)
  33589. {
  33590. if (key.isKeyCode (KeyPress::upKey)
  33591. || key.isKeyCode (KeyPress::downKey)
  33592. || key.isKeyCode (KeyPress::pageUpKey)
  33593. || key.isKeyCode (KeyPress::pageDownKey)
  33594. || key.isKeyCode (KeyPress::homeKey)
  33595. || key.isKeyCode (KeyPress::endKey))
  33596. {
  33597. // we want to avoid these keypresses going to the viewport, and instead allow
  33598. // them to pass up to our listbox..
  33599. return false;
  33600. }
  33601. return Viewport::keyPressed (key);
  33602. }
  33603. juce_UseDebuggingNewOperator
  33604. private:
  33605. ListBox& owner;
  33606. ListViewport (const ListViewport&);
  33607. const ListViewport& operator= (const ListViewport&);
  33608. };
  33609. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  33610. : Component (name),
  33611. model (model_),
  33612. headerComponent (0),
  33613. totalItems (0),
  33614. rowHeight (22),
  33615. minimumRowWidth (0),
  33616. outlineThickness (0),
  33617. lastRowSelected (-1),
  33618. mouseMoveSelects (false),
  33619. multipleSelection (false),
  33620. hasDoneInitialUpdate (false)
  33621. {
  33622. addAndMakeVisible (viewport = new ListViewport (*this));
  33623. setWantsKeyboardFocus (true);
  33624. }
  33625. ListBox::~ListBox()
  33626. {
  33627. deleteAllChildren();
  33628. }
  33629. void ListBox::setModel (ListBoxModel* const newModel)
  33630. {
  33631. if (model != newModel)
  33632. {
  33633. model = newModel;
  33634. updateContent();
  33635. }
  33636. }
  33637. void ListBox::setMultipleSelectionEnabled (bool b)
  33638. {
  33639. multipleSelection = b;
  33640. }
  33641. void ListBox::setMouseMoveSelectsRows (bool b)
  33642. {
  33643. mouseMoveSelects = b;
  33644. if (b)
  33645. addMouseListener (this, true);
  33646. }
  33647. void ListBox::paint (Graphics& g)
  33648. {
  33649. if (! hasDoneInitialUpdate)
  33650. updateContent();
  33651. g.fillAll (findColour (backgroundColourId));
  33652. }
  33653. void ListBox::paintOverChildren (Graphics& g)
  33654. {
  33655. if (outlineThickness > 0)
  33656. {
  33657. g.setColour (findColour (outlineColourId));
  33658. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33659. }
  33660. }
  33661. void ListBox::resized()
  33662. {
  33663. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  33664. outlineThickness,
  33665. outlineThickness,
  33666. outlineThickness));
  33667. viewport->setSingleStepSizes (20, getRowHeight());
  33668. viewport->updateVisibleArea (false);
  33669. }
  33670. void ListBox::visibilityChanged()
  33671. {
  33672. viewport->updateVisibleArea (true);
  33673. }
  33674. Viewport* ListBox::getViewport() const throw()
  33675. {
  33676. return viewport;
  33677. }
  33678. void ListBox::updateContent()
  33679. {
  33680. hasDoneInitialUpdate = true;
  33681. totalItems = (model != 0) ? model->getNumRows() : 0;
  33682. bool selectionChanged = false;
  33683. if (selected [selected.size() - 1] >= totalItems)
  33684. {
  33685. selected.removeRange (totalItems, INT_MAX - totalItems);
  33686. lastRowSelected = getSelectedRow (0);
  33687. selectionChanged = true;
  33688. }
  33689. viewport->updateVisibleArea (isVisible());
  33690. viewport->resized();
  33691. if (selectionChanged && model != 0)
  33692. model->selectedRowsChanged (lastRowSelected);
  33693. }
  33694. void ListBox::selectRow (const int row,
  33695. bool dontScroll,
  33696. bool deselectOthersFirst)
  33697. {
  33698. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  33699. }
  33700. void ListBox::selectRowInternal (const int row,
  33701. bool dontScroll,
  33702. bool deselectOthersFirst,
  33703. bool isMouseClick)
  33704. {
  33705. if (! multipleSelection)
  33706. deselectOthersFirst = true;
  33707. if ((! isRowSelected (row))
  33708. || (deselectOthersFirst && getNumSelectedRows() > 1))
  33709. {
  33710. if (((unsigned int) row) < (unsigned int) totalItems)
  33711. {
  33712. if (deselectOthersFirst)
  33713. selected.clear();
  33714. selected.addRange (row, 1);
  33715. if (getHeight() == 0 || getWidth() == 0)
  33716. dontScroll = true;
  33717. viewport->hasUpdated = false;
  33718. if (row < viewport->firstWholeIndex && ! dontScroll)
  33719. {
  33720. viewport->setViewPosition (viewport->getViewPositionX(),
  33721. row * getRowHeight());
  33722. }
  33723. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  33724. {
  33725. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  33726. if (row >= lastRowSelected + rowsOnScreen
  33727. && rowsOnScreen < totalItems - 1
  33728. && ! isMouseClick)
  33729. {
  33730. viewport->setViewPosition (viewport->getViewPositionX(),
  33731. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  33732. * getRowHeight());
  33733. }
  33734. else
  33735. {
  33736. viewport->setViewPosition (viewport->getViewPositionX(),
  33737. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33738. }
  33739. }
  33740. if (! viewport->hasUpdated)
  33741. viewport->updateContents();
  33742. lastRowSelected = row;
  33743. model->selectedRowsChanged (row);
  33744. }
  33745. else
  33746. {
  33747. if (deselectOthersFirst)
  33748. deselectAllRows();
  33749. }
  33750. }
  33751. }
  33752. void ListBox::deselectRow (const int row)
  33753. {
  33754. if (selected.contains (row))
  33755. {
  33756. selected.removeRange (row, 1);
  33757. if (row == lastRowSelected)
  33758. lastRowSelected = getSelectedRow (0);
  33759. viewport->updateContents();
  33760. model->selectedRowsChanged (lastRowSelected);
  33761. }
  33762. }
  33763. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  33764. const bool sendNotificationEventToModel)
  33765. {
  33766. selected = setOfRowsToBeSelected;
  33767. selected.removeRange (totalItems, INT_MAX - totalItems);
  33768. if (! isRowSelected (lastRowSelected))
  33769. lastRowSelected = getSelectedRow (0);
  33770. viewport->updateContents();
  33771. if ((model != 0) && sendNotificationEventToModel)
  33772. model->selectedRowsChanged (lastRowSelected);
  33773. }
  33774. const SparseSet<int> ListBox::getSelectedRows() const
  33775. {
  33776. return selected;
  33777. }
  33778. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  33779. {
  33780. if (multipleSelection && (firstRow != lastRow))
  33781. {
  33782. const int numRows = totalItems - 1;
  33783. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  33784. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  33785. selected.addRange (jmin (firstRow, lastRow),
  33786. abs (firstRow - lastRow) + 1);
  33787. selected.removeRange (lastRow, 1);
  33788. }
  33789. selectRowInternal (lastRow, false, false, true);
  33790. }
  33791. void ListBox::flipRowSelection (const int row)
  33792. {
  33793. if (isRowSelected (row))
  33794. deselectRow (row);
  33795. else
  33796. selectRowInternal (row, false, false, true);
  33797. }
  33798. void ListBox::deselectAllRows()
  33799. {
  33800. if (! selected.isEmpty())
  33801. {
  33802. selected.clear();
  33803. lastRowSelected = -1;
  33804. viewport->updateContents();
  33805. if (model != 0)
  33806. model->selectedRowsChanged (lastRowSelected);
  33807. }
  33808. }
  33809. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  33810. const ModifierKeys& mods)
  33811. {
  33812. if (multipleSelection && mods.isCommandDown())
  33813. {
  33814. flipRowSelection (row);
  33815. }
  33816. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  33817. {
  33818. selectRangeOfRows (lastRowSelected, row);
  33819. }
  33820. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  33821. {
  33822. selectRowInternal (row, false, true, true);
  33823. }
  33824. }
  33825. int ListBox::getNumSelectedRows() const
  33826. {
  33827. return selected.size();
  33828. }
  33829. int ListBox::getSelectedRow (const int index) const
  33830. {
  33831. return (((unsigned int) index) < (unsigned int) selected.size())
  33832. ? selected [index] : -1;
  33833. }
  33834. bool ListBox::isRowSelected (const int row) const
  33835. {
  33836. return selected.contains (row);
  33837. }
  33838. int ListBox::getLastRowSelected() const
  33839. {
  33840. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  33841. }
  33842. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  33843. {
  33844. if (((unsigned int) x) < (unsigned int) getWidth())
  33845. {
  33846. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  33847. if (((unsigned int) row) < (unsigned int) totalItems)
  33848. return row;
  33849. }
  33850. return -1;
  33851. }
  33852. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  33853. {
  33854. if (((unsigned int) x) < (unsigned int) getWidth())
  33855. {
  33856. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  33857. return jlimit (0, totalItems, row);
  33858. }
  33859. return -1;
  33860. }
  33861. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  33862. {
  33863. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  33864. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  33865. }
  33866. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  33867. {
  33868. return viewport->getRowNumberOfComponent (rowComponent);
  33869. }
  33870. const Rectangle ListBox::getRowPosition (const int rowNumber,
  33871. const bool relativeToComponentTopLeft) const throw()
  33872. {
  33873. const int rowHeight = getRowHeight();
  33874. int y = viewport->getY() + rowHeight * rowNumber;
  33875. if (relativeToComponentTopLeft)
  33876. y -= viewport->getViewPositionY();
  33877. return Rectangle (viewport->getX(), y,
  33878. viewport->getViewedComponent()->getWidth(), rowHeight);
  33879. }
  33880. void ListBox::setVerticalPosition (const double proportion)
  33881. {
  33882. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  33883. viewport->setViewPosition (viewport->getViewPositionX(),
  33884. jmax (0, roundDoubleToInt (proportion * offscreen)));
  33885. }
  33886. double ListBox::getVerticalPosition() const
  33887. {
  33888. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  33889. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  33890. : 0;
  33891. }
  33892. int ListBox::getVisibleRowWidth() const throw()
  33893. {
  33894. return viewport->getViewWidth();
  33895. }
  33896. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  33897. {
  33898. if (row < viewport->firstWholeIndex)
  33899. {
  33900. viewport->setViewPosition (viewport->getViewPositionX(),
  33901. row * getRowHeight());
  33902. }
  33903. else if (row >= viewport->lastWholeIndex)
  33904. {
  33905. viewport->setViewPosition (viewport->getViewPositionX(),
  33906. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33907. }
  33908. }
  33909. bool ListBox::keyPressed (const KeyPress& key)
  33910. {
  33911. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  33912. const bool multiple = multipleSelection
  33913. && (lastRowSelected >= 0)
  33914. && (key.getModifiers().isShiftDown()
  33915. || key.getModifiers().isCtrlDown()
  33916. || key.getModifiers().isCommandDown());
  33917. if (key.isKeyCode (KeyPress::upKey))
  33918. {
  33919. if (multiple)
  33920. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  33921. else
  33922. selectRow (jmax (0, lastRowSelected - 1));
  33923. }
  33924. else if (key.isKeyCode (KeyPress::returnKey)
  33925. && isRowSelected (lastRowSelected))
  33926. {
  33927. if (model != 0)
  33928. model->returnKeyPressed (lastRowSelected);
  33929. }
  33930. else if (key.isKeyCode (KeyPress::pageUpKey))
  33931. {
  33932. if (multiple)
  33933. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  33934. else
  33935. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  33936. }
  33937. else if (key.isKeyCode (KeyPress::pageDownKey))
  33938. {
  33939. if (multiple)
  33940. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  33941. else
  33942. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  33943. }
  33944. else if (key.isKeyCode (KeyPress::homeKey))
  33945. {
  33946. if (multiple && key.getModifiers().isShiftDown())
  33947. selectRangeOfRows (lastRowSelected, 0);
  33948. else
  33949. selectRow (0);
  33950. }
  33951. else if (key.isKeyCode (KeyPress::endKey))
  33952. {
  33953. if (multiple && key.getModifiers().isShiftDown())
  33954. selectRangeOfRows (lastRowSelected, totalItems - 1);
  33955. else
  33956. selectRow (totalItems - 1);
  33957. }
  33958. else if (key.isKeyCode (KeyPress::downKey))
  33959. {
  33960. if (multiple)
  33961. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  33962. else
  33963. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  33964. }
  33965. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  33966. && isRowSelected (lastRowSelected))
  33967. {
  33968. if (model != 0)
  33969. model->deleteKeyPressed (lastRowSelected);
  33970. }
  33971. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  33972. {
  33973. selectRangeOfRows (0, INT_MAX);
  33974. }
  33975. else
  33976. {
  33977. return false;
  33978. }
  33979. return true;
  33980. }
  33981. bool ListBox::keyStateChanged()
  33982. {
  33983. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  33984. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  33985. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  33986. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  33987. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  33988. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  33989. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  33990. }
  33991. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33992. {
  33993. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  33994. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  33995. }
  33996. void ListBox::mouseMove (const MouseEvent& e)
  33997. {
  33998. if (mouseMoveSelects)
  33999. {
  34000. const MouseEvent e2 (e.getEventRelativeTo (this));
  34001. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  34002. lastMouseX = e2.x;
  34003. lastMouseY = e2.y;
  34004. }
  34005. }
  34006. void ListBox::mouseExit (const MouseEvent& e)
  34007. {
  34008. mouseMove (e);
  34009. }
  34010. void ListBox::mouseUp (const MouseEvent& e)
  34011. {
  34012. if (e.mouseWasClicked() && model != 0)
  34013. model->backgroundClicked();
  34014. }
  34015. void ListBox::setRowHeight (const int newHeight)
  34016. {
  34017. rowHeight = jmax (1, newHeight);
  34018. viewport->setSingleStepSizes (20, rowHeight);
  34019. updateContent();
  34020. }
  34021. int ListBox::getNumRowsOnScreen() const throw()
  34022. {
  34023. return viewport->getMaximumVisibleHeight() / rowHeight;
  34024. }
  34025. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  34026. {
  34027. minimumRowWidth = newMinimumWidth;
  34028. updateContent();
  34029. }
  34030. int ListBox::getVisibleContentWidth() const throw()
  34031. {
  34032. return viewport->getMaximumVisibleWidth();
  34033. }
  34034. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  34035. {
  34036. return viewport->getVerticalScrollBar();
  34037. }
  34038. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  34039. {
  34040. return viewport->getHorizontalScrollBar();
  34041. }
  34042. void ListBox::colourChanged()
  34043. {
  34044. setOpaque (findColour (backgroundColourId).isOpaque());
  34045. viewport->setOpaque (isOpaque());
  34046. repaint();
  34047. }
  34048. void ListBox::setOutlineThickness (const int outlineThickness_)
  34049. {
  34050. outlineThickness = outlineThickness_;
  34051. resized();
  34052. }
  34053. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  34054. {
  34055. if (headerComponent != newHeaderComponent)
  34056. {
  34057. if (headerComponent != 0)
  34058. delete headerComponent;
  34059. headerComponent = newHeaderComponent;
  34060. addAndMakeVisible (newHeaderComponent);
  34061. ListBox::resized();
  34062. }
  34063. }
  34064. void ListBox::repaintRow (const int rowNumber) throw()
  34065. {
  34066. const Rectangle r (getRowPosition (rowNumber, true));
  34067. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  34068. }
  34069. Image* ListBox::createSnapshotOfSelectedRows()
  34070. {
  34071. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  34072. Graphics g (*snapshot);
  34073. const int firstRow = getRowContainingPosition (0, 0);
  34074. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  34075. {
  34076. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  34077. if (rowComp != 0 && isRowSelected (firstRow + i))
  34078. {
  34079. g.saveState();
  34080. int x = 0, y = 0;
  34081. rowComp->relativePositionToOtherComponent (this, x, y);
  34082. g.setOrigin (x, y);
  34083. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  34084. rowComp->paintEntireComponent (g);
  34085. g.restoreState();
  34086. }
  34087. }
  34088. return snapshot;
  34089. }
  34090. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  34091. {
  34092. (void) existingComponentToUpdate;
  34093. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  34094. return 0;
  34095. }
  34096. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  34097. {
  34098. }
  34099. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  34100. {
  34101. }
  34102. void ListBoxModel::backgroundClicked()
  34103. {
  34104. }
  34105. void ListBoxModel::selectedRowsChanged (int)
  34106. {
  34107. }
  34108. void ListBoxModel::deleteKeyPressed (int)
  34109. {
  34110. }
  34111. void ListBoxModel::returnKeyPressed (int)
  34112. {
  34113. }
  34114. void ListBoxModel::listWasScrolled()
  34115. {
  34116. }
  34117. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  34118. {
  34119. return String::empty;
  34120. }
  34121. END_JUCE_NAMESPACE
  34122. /********* End of inlined file: juce_ListBox.cpp *********/
  34123. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  34124. BEGIN_JUCE_NAMESPACE
  34125. ProgressBar::ProgressBar (double& progress_)
  34126. : progress (progress_),
  34127. displayPercentage (true)
  34128. {
  34129. currentValue = jlimit (0.0, 1.0, progress);
  34130. }
  34131. ProgressBar::~ProgressBar()
  34132. {
  34133. }
  34134. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  34135. {
  34136. displayPercentage = shouldDisplayPercentage;
  34137. repaint();
  34138. }
  34139. void ProgressBar::setTextToDisplay (const String& text)
  34140. {
  34141. displayPercentage = false;
  34142. displayedMessage = text;
  34143. }
  34144. void ProgressBar::lookAndFeelChanged()
  34145. {
  34146. setOpaque (findColour (backgroundColourId).isOpaque());
  34147. }
  34148. void ProgressBar::colourChanged()
  34149. {
  34150. lookAndFeelChanged();
  34151. }
  34152. void ProgressBar::paint (Graphics& g)
  34153. {
  34154. String text;
  34155. if (displayPercentage)
  34156. {
  34157. if (currentValue >= 0 && currentValue <= 1.0)
  34158. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  34159. }
  34160. else
  34161. {
  34162. text = displayedMessage;
  34163. }
  34164. getLookAndFeel().drawProgressBar (g, *this,
  34165. getWidth(), getHeight(),
  34166. currentValue, text);
  34167. }
  34168. void ProgressBar::visibilityChanged()
  34169. {
  34170. if (isVisible())
  34171. startTimer (30);
  34172. else
  34173. stopTimer();
  34174. }
  34175. void ProgressBar::timerCallback()
  34176. {
  34177. double newProgress = progress;
  34178. if (currentValue != newProgress
  34179. || newProgress < 0 || newProgress >= 1.0
  34180. || currentMessage != displayedMessage)
  34181. {
  34182. if (currentValue < newProgress
  34183. && newProgress >= 0 && newProgress < 1.0
  34184. && currentValue >= 0 && newProgress < 1.0)
  34185. {
  34186. newProgress = jmin (currentValue + 0.02, newProgress);
  34187. }
  34188. currentValue = newProgress;
  34189. currentMessage = displayedMessage;
  34190. repaint();
  34191. }
  34192. }
  34193. END_JUCE_NAMESPACE
  34194. /********* End of inlined file: juce_ProgressBar.cpp *********/
  34195. /********* Start of inlined file: juce_Slider.cpp *********/
  34196. BEGIN_JUCE_NAMESPACE
  34197. class SliderPopupDisplayComponent : public BubbleComponent
  34198. {
  34199. public:
  34200. SliderPopupDisplayComponent (Slider* const owner_)
  34201. : owner (owner_),
  34202. font (15.0f, Font::bold)
  34203. {
  34204. setAlwaysOnTop (true);
  34205. }
  34206. ~SliderPopupDisplayComponent()
  34207. {
  34208. }
  34209. void paintContent (Graphics& g, int w, int h)
  34210. {
  34211. g.setFont (font);
  34212. g.setColour (Colours::black);
  34213. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  34214. }
  34215. void getContentSize (int& w, int& h)
  34216. {
  34217. w = font.getStringWidth (text) + 18;
  34218. h = (int) (font.getHeight() * 1.6f);
  34219. }
  34220. void updatePosition (const String& newText)
  34221. {
  34222. if (text != newText)
  34223. {
  34224. text = newText;
  34225. repaint();
  34226. }
  34227. BubbleComponent::setPosition (owner);
  34228. }
  34229. juce_UseDebuggingNewOperator
  34230. private:
  34231. Slider* owner;
  34232. Font font;
  34233. String text;
  34234. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  34235. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  34236. };
  34237. Slider::Slider (const String& name)
  34238. : Component (name),
  34239. listeners (2),
  34240. currentValue (0.0),
  34241. valueMin (0.0),
  34242. valueMax (0.0),
  34243. minimum (0),
  34244. maximum (10),
  34245. interval (0),
  34246. skewFactor (1.0),
  34247. velocityModeSensitivity (1.0),
  34248. velocityModeOffset (0.0),
  34249. velocityModeThreshold (1),
  34250. rotaryStart (float_Pi * 1.2f),
  34251. rotaryEnd (float_Pi * 2.8f),
  34252. numDecimalPlaces (7),
  34253. sliderRegionStart (0),
  34254. sliderRegionSize (1),
  34255. pixelsForFullDragExtent (250),
  34256. style (LinearHorizontal),
  34257. textBoxPos (TextBoxLeft),
  34258. textBoxWidth (80),
  34259. textBoxHeight (20),
  34260. incDecButtonMode (incDecButtonsNotDraggable),
  34261. editableText (true),
  34262. doubleClickToValue (false),
  34263. isVelocityBased (false),
  34264. userKeyOverridesVelocity (true),
  34265. rotaryStop (true),
  34266. incDecButtonsSideBySide (false),
  34267. sendChangeOnlyOnRelease (false),
  34268. popupDisplayEnabled (false),
  34269. menuEnabled (false),
  34270. menuShown (false),
  34271. scrollWheelEnabled (true),
  34272. snapsToMousePos (true),
  34273. valueBox (0),
  34274. incButton (0),
  34275. decButton (0),
  34276. popupDisplay (0),
  34277. parentForPopupDisplay (0)
  34278. {
  34279. setWantsKeyboardFocus (false);
  34280. setRepaintsOnMouseActivity (true);
  34281. lookAndFeelChanged();
  34282. updateText();
  34283. }
  34284. Slider::~Slider()
  34285. {
  34286. deleteAndZero (popupDisplay);
  34287. deleteAllChildren();
  34288. }
  34289. void Slider::handleAsyncUpdate()
  34290. {
  34291. cancelPendingUpdate();
  34292. for (int i = listeners.size(); --i >= 0;)
  34293. {
  34294. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  34295. i = jmin (i, listeners.size());
  34296. }
  34297. }
  34298. void Slider::sendDragStart()
  34299. {
  34300. startedDragging();
  34301. for (int i = listeners.size(); --i >= 0;)
  34302. {
  34303. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  34304. i = jmin (i, listeners.size());
  34305. }
  34306. }
  34307. void Slider::sendDragEnd()
  34308. {
  34309. stoppedDragging();
  34310. for (int i = listeners.size(); --i >= 0;)
  34311. {
  34312. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  34313. i = jmin (i, listeners.size());
  34314. }
  34315. }
  34316. void Slider::addListener (SliderListener* const listener) throw()
  34317. {
  34318. jassert (listener != 0);
  34319. if (listener != 0)
  34320. listeners.add (listener);
  34321. }
  34322. void Slider::removeListener (SliderListener* const listener) throw()
  34323. {
  34324. listeners.removeValue (listener);
  34325. }
  34326. void Slider::setSliderStyle (const SliderStyle newStyle)
  34327. {
  34328. if (style != newStyle)
  34329. {
  34330. style = newStyle;
  34331. repaint();
  34332. lookAndFeelChanged();
  34333. }
  34334. }
  34335. void Slider::setRotaryParameters (const float startAngleRadians,
  34336. const float endAngleRadians,
  34337. const bool stopAtEnd)
  34338. {
  34339. // make sure the values are sensible..
  34340. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  34341. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  34342. jassert (rotaryStart < rotaryEnd);
  34343. rotaryStart = startAngleRadians;
  34344. rotaryEnd = endAngleRadians;
  34345. rotaryStop = stopAtEnd;
  34346. }
  34347. void Slider::setVelocityBasedMode (const bool velBased) throw()
  34348. {
  34349. isVelocityBased = velBased;
  34350. }
  34351. void Slider::setVelocityModeParameters (const double sensitivity,
  34352. const int threshold,
  34353. const double offset,
  34354. const bool userCanPressKeyToSwapMode) throw()
  34355. {
  34356. jassert (threshold >= 0);
  34357. jassert (sensitivity > 0);
  34358. jassert (offset >= 0);
  34359. velocityModeSensitivity = sensitivity;
  34360. velocityModeOffset = offset;
  34361. velocityModeThreshold = threshold;
  34362. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  34363. }
  34364. void Slider::setSkewFactor (const double factor) throw()
  34365. {
  34366. skewFactor = factor;
  34367. }
  34368. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  34369. {
  34370. if (maximum > minimum)
  34371. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  34372. / (maximum - minimum));
  34373. }
  34374. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  34375. {
  34376. jassert (distanceForFullScaleDrag > 0);
  34377. pixelsForFullDragExtent = distanceForFullScaleDrag;
  34378. }
  34379. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  34380. {
  34381. if (incDecButtonMode != mode)
  34382. {
  34383. incDecButtonMode = mode;
  34384. lookAndFeelChanged();
  34385. }
  34386. }
  34387. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34388. const bool isReadOnly,
  34389. const int textEntryBoxWidth,
  34390. const int textEntryBoxHeight)
  34391. {
  34392. textBoxPos = newPosition;
  34393. editableText = ! isReadOnly;
  34394. textBoxWidth = textEntryBoxWidth;
  34395. textBoxHeight = textEntryBoxHeight;
  34396. repaint();
  34397. lookAndFeelChanged();
  34398. }
  34399. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  34400. {
  34401. editableText = shouldBeEditable;
  34402. if (valueBox != 0)
  34403. valueBox->setEditable (shouldBeEditable && isEnabled());
  34404. }
  34405. void Slider::showTextBox()
  34406. {
  34407. jassert (editableText); // this should probably be avoided in read-only sliders.
  34408. if (valueBox != 0)
  34409. valueBox->showEditor();
  34410. }
  34411. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  34412. {
  34413. if (valueBox != 0)
  34414. {
  34415. valueBox->hideEditor (discardCurrentEditorContents);
  34416. if (discardCurrentEditorContents)
  34417. updateText();
  34418. }
  34419. }
  34420. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  34421. {
  34422. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  34423. }
  34424. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  34425. {
  34426. snapsToMousePos = shouldSnapToMouse;
  34427. }
  34428. void Slider::setPopupDisplayEnabled (const bool enabled,
  34429. Component* const parentComponentToUse) throw()
  34430. {
  34431. popupDisplayEnabled = enabled;
  34432. parentForPopupDisplay = parentComponentToUse;
  34433. }
  34434. void Slider::colourChanged()
  34435. {
  34436. lookAndFeelChanged();
  34437. }
  34438. void Slider::lookAndFeelChanged()
  34439. {
  34440. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  34441. : getTextFromValue (currentValue));
  34442. deleteAllChildren();
  34443. valueBox = 0;
  34444. LookAndFeel& lf = getLookAndFeel();
  34445. if (textBoxPos != NoTextBox)
  34446. {
  34447. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  34448. valueBox->setWantsKeyboardFocus (false);
  34449. valueBox->setText (previousTextBoxContent, false);
  34450. valueBox->setEditable (editableText && isEnabled());
  34451. valueBox->addListener (this);
  34452. if (style == LinearBar)
  34453. valueBox->addMouseListener (this, false);
  34454. }
  34455. if (style == IncDecButtons)
  34456. {
  34457. addAndMakeVisible (incButton = lf.createSliderButton (true));
  34458. incButton->addButtonListener (this);
  34459. addAndMakeVisible (decButton = lf.createSliderButton (false));
  34460. decButton->addButtonListener (this);
  34461. if (incDecButtonMode != incDecButtonsNotDraggable)
  34462. {
  34463. incButton->addMouseListener (this, false);
  34464. decButton->addMouseListener (this, false);
  34465. }
  34466. else
  34467. {
  34468. incButton->setRepeatSpeed (300, 100, 20);
  34469. incButton->addMouseListener (decButton, false);
  34470. decButton->setRepeatSpeed (300, 100, 20);
  34471. decButton->addMouseListener (incButton, false);
  34472. }
  34473. }
  34474. setComponentEffect (lf.getSliderEffect());
  34475. resized();
  34476. repaint();
  34477. }
  34478. void Slider::setRange (const double newMin,
  34479. const double newMax,
  34480. const double newInt)
  34481. {
  34482. if (minimum != newMin
  34483. || maximum != newMax
  34484. || interval != newInt)
  34485. {
  34486. minimum = newMin;
  34487. maximum = newMax;
  34488. interval = newInt;
  34489. // figure out the number of DPs needed to display all values at this
  34490. // interval setting.
  34491. numDecimalPlaces = 7;
  34492. if (newInt != 0)
  34493. {
  34494. int v = abs ((int) (newInt * 10000000));
  34495. while ((v % 10) == 0)
  34496. {
  34497. --numDecimalPlaces;
  34498. v /= 10;
  34499. }
  34500. }
  34501. // keep the current values inside the new range..
  34502. if (style != TwoValueHorizontal && style != TwoValueVertical)
  34503. {
  34504. setValue (currentValue, false, false);
  34505. }
  34506. else
  34507. {
  34508. setMinValue (getMinValue(), false, false);
  34509. setMaxValue (getMaxValue(), false, false);
  34510. }
  34511. updateText();
  34512. }
  34513. }
  34514. void Slider::triggerChangeMessage (const bool synchronous)
  34515. {
  34516. if (synchronous)
  34517. handleAsyncUpdate();
  34518. else
  34519. triggerAsyncUpdate();
  34520. valueChanged();
  34521. }
  34522. double Slider::getValue() const throw()
  34523. {
  34524. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  34525. // methods to get the two values.
  34526. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34527. return currentValue;
  34528. }
  34529. void Slider::setValue (double newValue,
  34530. const bool sendUpdateMessage,
  34531. const bool sendMessageSynchronously)
  34532. {
  34533. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  34534. // methods to set the two values.
  34535. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34536. newValue = constrainedValue (newValue);
  34537. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34538. {
  34539. jassert (valueMin <= valueMax);
  34540. newValue = jlimit (valueMin, valueMax, newValue);
  34541. }
  34542. if (currentValue != newValue)
  34543. {
  34544. if (valueBox != 0)
  34545. valueBox->hideEditor (true);
  34546. currentValue = newValue;
  34547. updateText();
  34548. repaint();
  34549. if (popupDisplay != 0)
  34550. {
  34551. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  34552. popupDisplay->repaint();
  34553. }
  34554. if (sendUpdateMessage)
  34555. triggerChangeMessage (sendMessageSynchronously);
  34556. }
  34557. }
  34558. double Slider::getMinValue() const throw()
  34559. {
  34560. // The minimum value only applies to sliders that are in two- or three-value mode.
  34561. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34562. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34563. return valueMin;
  34564. }
  34565. double Slider::getMaxValue() const throw()
  34566. {
  34567. // The maximum value only applies to sliders that are in two- or three-value mode.
  34568. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34569. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34570. return valueMax;
  34571. }
  34572. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34573. {
  34574. // The minimum value only applies to sliders that are in two- or three-value mode.
  34575. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34576. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34577. newValue = constrainedValue (newValue);
  34578. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34579. newValue = jmin (valueMax, newValue);
  34580. else
  34581. newValue = jmin (currentValue, newValue);
  34582. if (valueMin != newValue)
  34583. {
  34584. valueMin = newValue;
  34585. repaint();
  34586. if (popupDisplay != 0)
  34587. {
  34588. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  34589. popupDisplay->repaint();
  34590. }
  34591. if (sendUpdateMessage)
  34592. triggerChangeMessage (sendMessageSynchronously);
  34593. }
  34594. }
  34595. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34596. {
  34597. // The maximum value only applies to sliders that are in two- or three-value mode.
  34598. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34599. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34600. newValue = constrainedValue (newValue);
  34601. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34602. newValue = jmax (valueMin, newValue);
  34603. else
  34604. newValue = jmax (currentValue, newValue);
  34605. if (valueMax != newValue)
  34606. {
  34607. valueMax = newValue;
  34608. repaint();
  34609. if (popupDisplay != 0)
  34610. {
  34611. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  34612. popupDisplay->repaint();
  34613. }
  34614. if (sendUpdateMessage)
  34615. triggerChangeMessage (sendMessageSynchronously);
  34616. }
  34617. }
  34618. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34619. const double valueToSetOnDoubleClick) throw()
  34620. {
  34621. doubleClickToValue = isDoubleClickEnabled;
  34622. doubleClickReturnValue = valueToSetOnDoubleClick;
  34623. }
  34624. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  34625. {
  34626. isEnabled_ = doubleClickToValue;
  34627. return doubleClickReturnValue;
  34628. }
  34629. void Slider::updateText()
  34630. {
  34631. if (valueBox != 0)
  34632. valueBox->setText (getTextFromValue (currentValue), false);
  34633. }
  34634. void Slider::setTextValueSuffix (const String& suffix)
  34635. {
  34636. if (textSuffix != suffix)
  34637. {
  34638. textSuffix = suffix;
  34639. updateText();
  34640. }
  34641. }
  34642. const String Slider::getTextFromValue (double v)
  34643. {
  34644. if (numDecimalPlaces > 0)
  34645. return String (v, numDecimalPlaces) + textSuffix;
  34646. else
  34647. return String (roundDoubleToInt (v)) + textSuffix;
  34648. }
  34649. double Slider::getValueFromText (const String& text)
  34650. {
  34651. String t (text.trimStart());
  34652. if (t.endsWith (textSuffix))
  34653. t = t.substring (0, t.length() - textSuffix.length());
  34654. while (t.startsWithChar (T('+')))
  34655. t = t.substring (1).trimStart();
  34656. return t.initialSectionContainingOnly (T("0123456789.,-"))
  34657. .getDoubleValue();
  34658. }
  34659. double Slider::proportionOfLengthToValue (double proportion)
  34660. {
  34661. if (skewFactor != 1.0 && proportion > 0.0)
  34662. proportion = exp (log (proportion) / skewFactor);
  34663. return minimum + (maximum - minimum) * proportion;
  34664. }
  34665. double Slider::valueToProportionOfLength (double value)
  34666. {
  34667. const double n = (value - minimum) / (maximum - minimum);
  34668. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  34669. }
  34670. double Slider::snapValue (double attemptedValue, const bool)
  34671. {
  34672. return attemptedValue;
  34673. }
  34674. void Slider::startedDragging()
  34675. {
  34676. }
  34677. void Slider::stoppedDragging()
  34678. {
  34679. }
  34680. void Slider::valueChanged()
  34681. {
  34682. }
  34683. void Slider::enablementChanged()
  34684. {
  34685. repaint();
  34686. }
  34687. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  34688. {
  34689. menuEnabled = menuEnabled_;
  34690. }
  34691. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  34692. {
  34693. scrollWheelEnabled = enabled;
  34694. }
  34695. void Slider::labelTextChanged (Label* label)
  34696. {
  34697. const double newValue = snapValue (getValueFromText (label->getText()), false);
  34698. if (getValue() != newValue)
  34699. {
  34700. sendDragStart();
  34701. setValue (newValue, true, true);
  34702. sendDragEnd();
  34703. }
  34704. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  34705. }
  34706. void Slider::buttonClicked (Button* button)
  34707. {
  34708. if (style == IncDecButtons)
  34709. {
  34710. sendDragStart();
  34711. if (button == incButton)
  34712. setValue (snapValue (getValue() + interval, false), true, true);
  34713. else if (button == decButton)
  34714. setValue (snapValue (getValue() - interval, false), true, true);
  34715. sendDragEnd();
  34716. }
  34717. }
  34718. double Slider::constrainedValue (double value) const throw()
  34719. {
  34720. if (interval > 0)
  34721. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  34722. if (value <= minimum || maximum <= minimum)
  34723. value = minimum;
  34724. else if (value >= maximum)
  34725. value = maximum;
  34726. return value;
  34727. }
  34728. float Slider::getLinearSliderPos (const double value)
  34729. {
  34730. double sliderPosProportional;
  34731. if (maximum > minimum)
  34732. {
  34733. if (value < minimum)
  34734. {
  34735. sliderPosProportional = 0.0;
  34736. }
  34737. else if (value > maximum)
  34738. {
  34739. sliderPosProportional = 1.0;
  34740. }
  34741. else
  34742. {
  34743. sliderPosProportional = valueToProportionOfLength (value);
  34744. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  34745. }
  34746. }
  34747. else
  34748. {
  34749. sliderPosProportional = 0.5;
  34750. }
  34751. if (style == LinearVertical || style == IncDecButtons)
  34752. sliderPosProportional = 1.0 - sliderPosProportional;
  34753. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  34754. }
  34755. bool Slider::isHorizontal() const throw()
  34756. {
  34757. return style == LinearHorizontal
  34758. || style == LinearBar
  34759. || style == TwoValueHorizontal
  34760. || style == ThreeValueHorizontal;
  34761. }
  34762. bool Slider::isVertical() const throw()
  34763. {
  34764. return style == LinearVertical
  34765. || style == TwoValueVertical
  34766. || style == ThreeValueVertical;
  34767. }
  34768. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  34769. {
  34770. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  34771. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  34772. }
  34773. float Slider::getPositionOfValue (const double value)
  34774. {
  34775. if (isHorizontal() || isVertical())
  34776. {
  34777. return getLinearSliderPos (value);
  34778. }
  34779. else
  34780. {
  34781. jassertfalse // not a valid call on a slider that doesn't work linearly!
  34782. return 0.0f;
  34783. }
  34784. }
  34785. void Slider::paint (Graphics& g)
  34786. {
  34787. if (style != IncDecButtons)
  34788. {
  34789. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34790. {
  34791. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  34792. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  34793. getLookAndFeel().drawRotarySlider (g,
  34794. sliderRect.getX(),
  34795. sliderRect.getY(),
  34796. sliderRect.getWidth(),
  34797. sliderRect.getHeight(),
  34798. sliderPos,
  34799. rotaryStart, rotaryEnd,
  34800. *this);
  34801. }
  34802. else
  34803. {
  34804. getLookAndFeel().drawLinearSlider (g,
  34805. sliderRect.getX(),
  34806. sliderRect.getY(),
  34807. sliderRect.getWidth(),
  34808. sliderRect.getHeight(),
  34809. getLinearSliderPos (currentValue),
  34810. getLinearSliderPos (valueMin),
  34811. getLinearSliderPos (valueMax),
  34812. style,
  34813. *this);
  34814. }
  34815. if (style == LinearBar && valueBox == 0)
  34816. {
  34817. g.setColour (findColour (Slider::textBoxOutlineColourId));
  34818. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  34819. }
  34820. }
  34821. }
  34822. void Slider::resized()
  34823. {
  34824. int minXSpace = 0;
  34825. int minYSpace = 0;
  34826. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  34827. minXSpace = 30;
  34828. else
  34829. minYSpace = 15;
  34830. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  34831. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  34832. if (style == LinearBar)
  34833. {
  34834. if (valueBox != 0)
  34835. valueBox->setBounds (0, 0, getWidth(), getHeight());
  34836. }
  34837. else
  34838. {
  34839. if (textBoxPos == NoTextBox)
  34840. {
  34841. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  34842. }
  34843. else if (textBoxPos == TextBoxLeft)
  34844. {
  34845. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  34846. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  34847. }
  34848. else if (textBoxPos == TextBoxRight)
  34849. {
  34850. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  34851. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  34852. }
  34853. else if (textBoxPos == TextBoxAbove)
  34854. {
  34855. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  34856. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  34857. }
  34858. else if (textBoxPos == TextBoxBelow)
  34859. {
  34860. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  34861. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  34862. }
  34863. }
  34864. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  34865. if (style == LinearBar)
  34866. {
  34867. const int barIndent = 1;
  34868. sliderRegionStart = barIndent;
  34869. sliderRegionSize = getWidth() - barIndent * 2;
  34870. sliderRect.setBounds (sliderRegionStart, barIndent,
  34871. sliderRegionSize, getHeight() - barIndent * 2);
  34872. }
  34873. else if (isHorizontal())
  34874. {
  34875. sliderRegionStart = sliderRect.getX() + indent;
  34876. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  34877. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  34878. sliderRegionSize, sliderRect.getHeight());
  34879. }
  34880. else if (isVertical())
  34881. {
  34882. sliderRegionStart = sliderRect.getY() + indent;
  34883. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  34884. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  34885. sliderRect.getWidth(), sliderRegionSize);
  34886. }
  34887. else
  34888. {
  34889. sliderRegionStart = 0;
  34890. sliderRegionSize = 100;
  34891. }
  34892. if (style == IncDecButtons)
  34893. {
  34894. Rectangle buttonRect (sliderRect);
  34895. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  34896. buttonRect.expand (-2, 0);
  34897. else
  34898. buttonRect.expand (0, -2);
  34899. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  34900. if (incDecButtonsSideBySide)
  34901. {
  34902. decButton->setBounds (buttonRect.getX(),
  34903. buttonRect.getY(),
  34904. buttonRect.getWidth() / 2,
  34905. buttonRect.getHeight());
  34906. decButton->setConnectedEdges (Button::ConnectedOnRight);
  34907. incButton->setBounds (buttonRect.getCentreX(),
  34908. buttonRect.getY(),
  34909. buttonRect.getWidth() / 2,
  34910. buttonRect.getHeight());
  34911. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  34912. }
  34913. else
  34914. {
  34915. incButton->setBounds (buttonRect.getX(),
  34916. buttonRect.getY(),
  34917. buttonRect.getWidth(),
  34918. buttonRect.getHeight() / 2);
  34919. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  34920. decButton->setBounds (buttonRect.getX(),
  34921. buttonRect.getCentreY(),
  34922. buttonRect.getWidth(),
  34923. buttonRect.getHeight() / 2);
  34924. decButton->setConnectedEdges (Button::ConnectedOnTop);
  34925. }
  34926. }
  34927. }
  34928. void Slider::focusOfChildComponentChanged (FocusChangeType)
  34929. {
  34930. repaint();
  34931. }
  34932. void Slider::mouseDown (const MouseEvent& e)
  34933. {
  34934. mouseWasHidden = false;
  34935. incDecDragged = false;
  34936. if (isEnabled())
  34937. {
  34938. if (e.mods.isPopupMenu() && menuEnabled)
  34939. {
  34940. menuShown = true;
  34941. PopupMenu m;
  34942. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  34943. m.addSeparator();
  34944. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34945. {
  34946. PopupMenu rotaryMenu;
  34947. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  34948. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  34949. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  34950. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  34951. }
  34952. const int r = m.show();
  34953. if (r == 1)
  34954. {
  34955. setVelocityBasedMode (! isVelocityBased);
  34956. }
  34957. else if (r == 2)
  34958. {
  34959. setSliderStyle (Rotary);
  34960. }
  34961. else if (r == 3)
  34962. {
  34963. setSliderStyle (RotaryHorizontalDrag);
  34964. }
  34965. else if (r == 4)
  34966. {
  34967. setSliderStyle (RotaryVerticalDrag);
  34968. }
  34969. }
  34970. else if (maximum > minimum)
  34971. {
  34972. menuShown = false;
  34973. if (valueBox != 0)
  34974. valueBox->hideEditor (true);
  34975. sliderBeingDragged = 0;
  34976. if (style == TwoValueHorizontal
  34977. || style == TwoValueVertical
  34978. || style == ThreeValueHorizontal
  34979. || style == ThreeValueVertical)
  34980. {
  34981. const float mousePos = (float) (isVertical() ? e.y : e.x);
  34982. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  34983. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  34984. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  34985. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34986. {
  34987. if (maxPosDistance <= minPosDistance)
  34988. sliderBeingDragged = 2;
  34989. else
  34990. sliderBeingDragged = 1;
  34991. }
  34992. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34993. {
  34994. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  34995. sliderBeingDragged = 1;
  34996. else if (normalPosDistance >= maxPosDistance)
  34997. sliderBeingDragged = 2;
  34998. }
  34999. }
  35000. minMaxDiff = valueMax - valueMin;
  35001. mouseXWhenLastDragged = e.x;
  35002. mouseYWhenLastDragged = e.y;
  35003. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  35004. * valueToProportionOfLength (currentValue);
  35005. if (sliderBeingDragged == 2)
  35006. valueWhenLastDragged = valueMax;
  35007. else if (sliderBeingDragged == 1)
  35008. valueWhenLastDragged = valueMin;
  35009. else
  35010. valueWhenLastDragged = currentValue;
  35011. valueOnMouseDown = valueWhenLastDragged;
  35012. if (popupDisplayEnabled)
  35013. {
  35014. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  35015. popupDisplay = popup;
  35016. if (parentForPopupDisplay != 0)
  35017. {
  35018. parentForPopupDisplay->addChildComponent (popup);
  35019. }
  35020. else
  35021. {
  35022. popup->addToDesktop (0);
  35023. }
  35024. popup->setVisible (true);
  35025. }
  35026. sendDragStart();
  35027. mouseDrag (e);
  35028. }
  35029. }
  35030. }
  35031. void Slider::mouseUp (const MouseEvent&)
  35032. {
  35033. if (isEnabled()
  35034. && (! menuShown)
  35035. && (maximum > minimum)
  35036. && (style != IncDecButtons || incDecDragged))
  35037. {
  35038. restoreMouseIfHidden();
  35039. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  35040. triggerChangeMessage (false);
  35041. sendDragEnd();
  35042. deleteAndZero (popupDisplay);
  35043. if (style == IncDecButtons)
  35044. {
  35045. incButton->setState (Button::buttonNormal);
  35046. decButton->setState (Button::buttonNormal);
  35047. }
  35048. }
  35049. }
  35050. void Slider::restoreMouseIfHidden()
  35051. {
  35052. if (mouseWasHidden)
  35053. {
  35054. mouseWasHidden = false;
  35055. Component* c = Component::getComponentUnderMouse();
  35056. if (c == 0)
  35057. c = this;
  35058. c->enableUnboundedMouseMovement (false);
  35059. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  35060. : ((sliderBeingDragged == 1) ? getMinValue()
  35061. : currentValue);
  35062. const int pixelPos = (int) getLinearSliderPos (pos);
  35063. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  35064. int y = isVertical() ? pixelPos : (getHeight() / 2);
  35065. relativePositionToGlobal (x, y);
  35066. Desktop::setMousePosition (x, y);
  35067. }
  35068. }
  35069. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  35070. {
  35071. if (isEnabled()
  35072. && style != IncDecButtons
  35073. && style != Rotary
  35074. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  35075. {
  35076. restoreMouseIfHidden();
  35077. }
  35078. }
  35079. static double smallestAngleBetween (double a1, double a2)
  35080. {
  35081. return jmin (fabs (a1 - a2),
  35082. fabs (a1 + double_Pi * 2.0 - a2),
  35083. fabs (a2 + double_Pi * 2.0 - a1));
  35084. }
  35085. void Slider::mouseDrag (const MouseEvent& e)
  35086. {
  35087. if (isEnabled()
  35088. && (! menuShown)
  35089. && (maximum > minimum))
  35090. {
  35091. if (style == Rotary)
  35092. {
  35093. int dx = e.x - sliderRect.getCentreX();
  35094. int dy = e.y - sliderRect.getCentreY();
  35095. if (dx * dx + dy * dy > 25)
  35096. {
  35097. double angle = atan2 ((double) dx, (double) -dy);
  35098. while (angle < 0.0)
  35099. angle += double_Pi * 2.0;
  35100. if (rotaryStop && ! e.mouseWasClicked())
  35101. {
  35102. if (fabs (angle - lastAngle) > double_Pi)
  35103. {
  35104. if (angle >= lastAngle)
  35105. angle -= double_Pi * 2.0;
  35106. else
  35107. angle += double_Pi * 2.0;
  35108. }
  35109. if (angle >= lastAngle)
  35110. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  35111. else
  35112. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  35113. }
  35114. else
  35115. {
  35116. while (angle < rotaryStart)
  35117. angle += double_Pi * 2.0;
  35118. if (angle > rotaryEnd)
  35119. {
  35120. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  35121. angle = rotaryStart;
  35122. else
  35123. angle = rotaryEnd;
  35124. }
  35125. }
  35126. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  35127. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  35128. lastAngle = angle;
  35129. }
  35130. }
  35131. else
  35132. {
  35133. if (style == LinearBar && e.mouseWasClicked()
  35134. && valueBox != 0 && valueBox->isEditable())
  35135. return;
  35136. if (style == IncDecButtons)
  35137. {
  35138. if (! incDecDragged)
  35139. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  35140. if (! incDecDragged)
  35141. return;
  35142. }
  35143. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  35144. : false))
  35145. || ((maximum - minimum) / sliderRegionSize < interval))
  35146. {
  35147. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  35148. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  35149. if (style == RotaryHorizontalDrag
  35150. || style == RotaryVerticalDrag
  35151. || style == IncDecButtons
  35152. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  35153. && ! snapsToMousePos))
  35154. {
  35155. const int mouseDiff = (style == RotaryHorizontalDrag
  35156. || style == LinearHorizontal
  35157. || style == LinearBar
  35158. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35159. ? e.getDistanceFromDragStartX()
  35160. : -e.getDistanceFromDragStartY();
  35161. double newPos = valueToProportionOfLength (valueOnMouseDown)
  35162. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  35163. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  35164. if (style == IncDecButtons)
  35165. {
  35166. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  35167. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  35168. }
  35169. }
  35170. else
  35171. {
  35172. if (style == LinearVertical)
  35173. scaledMousePos = 1.0 - scaledMousePos;
  35174. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  35175. }
  35176. }
  35177. else
  35178. {
  35179. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  35180. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35181. ? e.x - mouseXWhenLastDragged
  35182. : e.y - mouseYWhenLastDragged;
  35183. const double maxSpeed = jmax (200, sliderRegionSize);
  35184. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  35185. if (speed != 0)
  35186. {
  35187. speed = 0.2 * velocityModeSensitivity
  35188. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  35189. + jmax (0.0, (double) (speed - velocityModeThreshold))
  35190. / maxSpeed))));
  35191. if (mouseDiff < 0)
  35192. speed = -speed;
  35193. if (style == LinearVertical || style == RotaryVerticalDrag
  35194. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  35195. speed = -speed;
  35196. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  35197. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  35198. e.originalComponent->enableUnboundedMouseMovement (true, false);
  35199. mouseWasHidden = true;
  35200. }
  35201. }
  35202. }
  35203. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  35204. if (sliderBeingDragged == 0)
  35205. {
  35206. setValue (snapValue (valueWhenLastDragged, true),
  35207. ! sendChangeOnlyOnRelease, true);
  35208. }
  35209. else if (sliderBeingDragged == 1)
  35210. {
  35211. setMinValue (snapValue (valueWhenLastDragged, true),
  35212. ! sendChangeOnlyOnRelease, false);
  35213. if (e.mods.isShiftDown())
  35214. setMaxValue (getMinValue() + minMaxDiff, false);
  35215. else
  35216. minMaxDiff = valueMax - valueMin;
  35217. }
  35218. else
  35219. {
  35220. jassert (sliderBeingDragged == 2);
  35221. setMaxValue (snapValue (valueWhenLastDragged, true),
  35222. ! sendChangeOnlyOnRelease, false);
  35223. if (e.mods.isShiftDown())
  35224. setMinValue (getMaxValue() - minMaxDiff, false);
  35225. else
  35226. minMaxDiff = valueMax - valueMin;
  35227. }
  35228. mouseXWhenLastDragged = e.x;
  35229. mouseYWhenLastDragged = e.y;
  35230. }
  35231. }
  35232. void Slider::mouseDoubleClick (const MouseEvent&)
  35233. {
  35234. if (doubleClickToValue
  35235. && isEnabled()
  35236. && style != IncDecButtons
  35237. && minimum <= doubleClickReturnValue
  35238. && maximum >= doubleClickReturnValue)
  35239. {
  35240. sendDragStart();
  35241. setValue (doubleClickReturnValue, true, true);
  35242. sendDragEnd();
  35243. }
  35244. }
  35245. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35246. {
  35247. if (scrollWheelEnabled && isEnabled())
  35248. {
  35249. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  35250. {
  35251. if (valueBox != 0)
  35252. valueBox->hideEditor (false);
  35253. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  35254. const double currentPos = valueToProportionOfLength (currentValue);
  35255. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  35256. double delta = (newValue != currentValue)
  35257. ? jmax (fabs (newValue - currentValue), interval) : 0;
  35258. if (currentValue > newValue)
  35259. delta = -delta;
  35260. sendDragStart();
  35261. setValue (snapValue (currentValue + delta, false), true, true);
  35262. sendDragEnd();
  35263. }
  35264. }
  35265. else
  35266. {
  35267. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  35268. }
  35269. }
  35270. void SliderListener::sliderDragStarted (Slider*)
  35271. {
  35272. }
  35273. void SliderListener::sliderDragEnded (Slider*)
  35274. {
  35275. }
  35276. END_JUCE_NAMESPACE
  35277. /********* End of inlined file: juce_Slider.cpp *********/
  35278. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  35279. BEGIN_JUCE_NAMESPACE
  35280. class DragOverlayComp : public Component
  35281. {
  35282. public:
  35283. DragOverlayComp (Image* const image_)
  35284. : image (image_)
  35285. {
  35286. image->multiplyAllAlphas (0.8f);
  35287. setAlwaysOnTop (true);
  35288. }
  35289. ~DragOverlayComp()
  35290. {
  35291. delete image;
  35292. }
  35293. void paint (Graphics& g)
  35294. {
  35295. g.drawImageAt (image, 0, 0);
  35296. }
  35297. private:
  35298. Image* image;
  35299. DragOverlayComp (const DragOverlayComp&);
  35300. const DragOverlayComp& operator= (const DragOverlayComp&);
  35301. };
  35302. TableHeaderComponent::TableHeaderComponent()
  35303. : listeners (2),
  35304. dragOverlayComp (0),
  35305. columnsChanged (false),
  35306. columnsResized (false),
  35307. sortChanged (false),
  35308. menuActive (true),
  35309. stretchToFit (false),
  35310. columnIdBeingResized (0),
  35311. columnIdBeingDragged (0),
  35312. columnIdUnderMouse (0),
  35313. lastDeliberateWidth (0)
  35314. {
  35315. }
  35316. TableHeaderComponent::~TableHeaderComponent()
  35317. {
  35318. delete dragOverlayComp;
  35319. }
  35320. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  35321. {
  35322. menuActive = hasMenu;
  35323. }
  35324. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  35325. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  35326. {
  35327. if (onlyCountVisibleColumns)
  35328. {
  35329. int num = 0;
  35330. for (int i = columns.size(); --i >= 0;)
  35331. if (columns.getUnchecked(i)->isVisible())
  35332. ++num;
  35333. return num;
  35334. }
  35335. else
  35336. {
  35337. return columns.size();
  35338. }
  35339. }
  35340. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  35341. {
  35342. const ColumnInfo* const ci = getInfoForId (columnId);
  35343. return ci != 0 ? ci->name : String::empty;
  35344. }
  35345. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  35346. {
  35347. ColumnInfo* const ci = getInfoForId (columnId);
  35348. if (ci != 0 && ci->name != newName)
  35349. {
  35350. ci->name = newName;
  35351. sendColumnsChanged();
  35352. }
  35353. }
  35354. void TableHeaderComponent::addColumn (const String& columnName,
  35355. const int columnId,
  35356. const int width,
  35357. const int minimumWidth,
  35358. const int maximumWidth,
  35359. const int propertyFlags,
  35360. const int insertIndex)
  35361. {
  35362. // can't have a duplicate or null ID!
  35363. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  35364. jassert (width > 0);
  35365. ColumnInfo* const ci = new ColumnInfo();
  35366. ci->name = columnName;
  35367. ci->id = columnId;
  35368. ci->width = width;
  35369. ci->lastDeliberateWidth = width;
  35370. ci->minimumWidth = minimumWidth;
  35371. ci->maximumWidth = maximumWidth;
  35372. if (ci->maximumWidth < 0)
  35373. ci->maximumWidth = INT_MAX;
  35374. jassert (ci->maximumWidth >= ci->minimumWidth);
  35375. ci->propertyFlags = propertyFlags;
  35376. columns.insert (insertIndex, ci);
  35377. sendColumnsChanged();
  35378. }
  35379. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  35380. {
  35381. const int index = getIndexOfColumnId (columnIdToRemove, false);
  35382. if (index >= 0)
  35383. {
  35384. columns.remove (index);
  35385. sortChanged = true;
  35386. sendColumnsChanged();
  35387. }
  35388. }
  35389. void TableHeaderComponent::removeAllColumns()
  35390. {
  35391. if (columns.size() > 0)
  35392. {
  35393. columns.clear();
  35394. sendColumnsChanged();
  35395. }
  35396. }
  35397. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  35398. {
  35399. const int currentIndex = getIndexOfColumnId (columnId, false);
  35400. newIndex = visibleIndexToTotalIndex (newIndex);
  35401. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  35402. {
  35403. columns.move (currentIndex, newIndex);
  35404. sendColumnsChanged();
  35405. }
  35406. }
  35407. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  35408. {
  35409. ColumnInfo* const ci = getInfoForId (columnId);
  35410. if (ci != 0 && ci->width != newWidth)
  35411. {
  35412. const int numColumns = getNumColumns (true);
  35413. ci->lastDeliberateWidth = ci->width
  35414. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  35415. if (stretchToFit)
  35416. {
  35417. const int index = getIndexOfColumnId (columnId, true) + 1;
  35418. if (((unsigned int) index) < (unsigned int) numColumns)
  35419. {
  35420. const int x = getColumnPosition (index).getX();
  35421. if (lastDeliberateWidth == 0)
  35422. lastDeliberateWidth = getTotalWidth();
  35423. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  35424. }
  35425. }
  35426. repaint();
  35427. columnsResized = true;
  35428. triggerAsyncUpdate();
  35429. }
  35430. }
  35431. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  35432. {
  35433. int n = 0;
  35434. for (int i = 0; i < columns.size(); ++i)
  35435. {
  35436. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  35437. {
  35438. if (columns.getUnchecked(i)->id == columnId)
  35439. return n;
  35440. ++n;
  35441. }
  35442. }
  35443. return -1;
  35444. }
  35445. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  35446. {
  35447. if (onlyCountVisibleColumns)
  35448. index = visibleIndexToTotalIndex (index);
  35449. const ColumnInfo* const ci = columns [index];
  35450. return (ci != 0) ? ci->id : 0;
  35451. }
  35452. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  35453. {
  35454. int x = 0, width = 0, n = 0;
  35455. for (int i = 0; i < columns.size(); ++i)
  35456. {
  35457. x += width;
  35458. if (columns.getUnchecked(i)->isVisible())
  35459. {
  35460. width = columns.getUnchecked(i)->width;
  35461. if (n++ == index)
  35462. break;
  35463. }
  35464. else
  35465. {
  35466. width = 0;
  35467. }
  35468. }
  35469. return Rectangle (x, 0, width, getHeight());
  35470. }
  35471. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  35472. {
  35473. if (xToFind >= 0)
  35474. {
  35475. int x = 0;
  35476. for (int i = 0; i < columns.size(); ++i)
  35477. {
  35478. const ColumnInfo* const ci = columns.getUnchecked(i);
  35479. if (ci->isVisible())
  35480. {
  35481. x += ci->width;
  35482. if (xToFind < x)
  35483. return ci->id;
  35484. }
  35485. }
  35486. }
  35487. return 0;
  35488. }
  35489. int TableHeaderComponent::getTotalWidth() const throw()
  35490. {
  35491. int w = 0;
  35492. for (int i = columns.size(); --i >= 0;)
  35493. if (columns.getUnchecked(i)->isVisible())
  35494. w += columns.getUnchecked(i)->width;
  35495. return w;
  35496. }
  35497. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  35498. {
  35499. stretchToFit = shouldStretchToFit;
  35500. lastDeliberateWidth = getTotalWidth();
  35501. resized();
  35502. }
  35503. bool TableHeaderComponent::isStretchToFitActive() const throw()
  35504. {
  35505. return stretchToFit;
  35506. }
  35507. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  35508. {
  35509. if (stretchToFit && getWidth() > 0
  35510. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  35511. {
  35512. lastDeliberateWidth = targetTotalWidth;
  35513. resizeColumnsToFit (0, targetTotalWidth);
  35514. }
  35515. }
  35516. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  35517. {
  35518. targetTotalWidth = jmax (targetTotalWidth, 0);
  35519. StretchableObjectResizer sor;
  35520. int i;
  35521. for (i = firstColumnIndex; i < columns.size(); ++i)
  35522. {
  35523. ColumnInfo* const ci = columns.getUnchecked(i);
  35524. if (ci->isVisible())
  35525. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  35526. }
  35527. sor.resizeToFit (targetTotalWidth);
  35528. int visIndex = 0;
  35529. for (i = firstColumnIndex; i < columns.size(); ++i)
  35530. {
  35531. ColumnInfo* const ci = columns.getUnchecked(i);
  35532. if (ci->isVisible())
  35533. {
  35534. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  35535. (int) floor (sor.getItemSize (visIndex++)));
  35536. if (newWidth != ci->width)
  35537. {
  35538. ci->width = newWidth;
  35539. repaint();
  35540. columnsResized = true;
  35541. triggerAsyncUpdate();
  35542. }
  35543. }
  35544. }
  35545. }
  35546. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  35547. {
  35548. ColumnInfo* const ci = getInfoForId (columnId);
  35549. if (ci != 0 && shouldBeVisible != ci->isVisible())
  35550. {
  35551. if (shouldBeVisible)
  35552. ci->propertyFlags |= visible;
  35553. else
  35554. ci->propertyFlags &= ~visible;
  35555. sendColumnsChanged();
  35556. resized();
  35557. }
  35558. }
  35559. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  35560. {
  35561. const ColumnInfo* const ci = getInfoForId (columnId);
  35562. return ci != 0 && ci->isVisible();
  35563. }
  35564. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  35565. {
  35566. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  35567. {
  35568. for (int i = columns.size(); --i >= 0;)
  35569. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  35570. ColumnInfo* const ci = getInfoForId (columnId);
  35571. if (ci != 0)
  35572. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  35573. reSortTable();
  35574. }
  35575. }
  35576. int TableHeaderComponent::getSortColumnId() const throw()
  35577. {
  35578. for (int i = columns.size(); --i >= 0;)
  35579. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35580. return columns.getUnchecked(i)->id;
  35581. return 0;
  35582. }
  35583. bool TableHeaderComponent::isSortedForwards() const throw()
  35584. {
  35585. for (int i = columns.size(); --i >= 0;)
  35586. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35587. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  35588. return true;
  35589. }
  35590. void TableHeaderComponent::reSortTable()
  35591. {
  35592. sortChanged = true;
  35593. repaint();
  35594. triggerAsyncUpdate();
  35595. }
  35596. const String TableHeaderComponent::toString() const
  35597. {
  35598. String s;
  35599. XmlElement doc (T("TABLELAYOUT"));
  35600. doc.setAttribute (T("sortedCol"), getSortColumnId());
  35601. doc.setAttribute (T("sortForwards"), isSortedForwards());
  35602. for (int i = 0; i < columns.size(); ++i)
  35603. {
  35604. const ColumnInfo* const ci = columns.getUnchecked (i);
  35605. XmlElement* const e = new XmlElement (T("COLUMN"));
  35606. doc.addChildElement (e);
  35607. e->setAttribute (T("id"), ci->id);
  35608. e->setAttribute (T("visible"), ci->isVisible());
  35609. e->setAttribute (T("width"), ci->width);
  35610. }
  35611. return doc.createDocument (String::empty, true, false);
  35612. }
  35613. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  35614. {
  35615. XmlDocument doc (storedVersion);
  35616. XmlElement* const storedXml = doc.getDocumentElement();
  35617. int index = 0;
  35618. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  35619. {
  35620. forEachXmlChildElement (*storedXml, col)
  35621. {
  35622. const int tabId = col->getIntAttribute (T("id"));
  35623. ColumnInfo* const ci = getInfoForId (tabId);
  35624. if (ci != 0)
  35625. {
  35626. columns.move (columns.indexOf (ci), index);
  35627. ci->width = col->getIntAttribute (T("width"));
  35628. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  35629. }
  35630. ++index;
  35631. }
  35632. columnsResized = true;
  35633. sendColumnsChanged();
  35634. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  35635. storedXml->getBoolAttribute (T("sortForwards"), true));
  35636. }
  35637. delete storedXml;
  35638. }
  35639. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  35640. {
  35641. listeners.addIfNotAlreadyThere (newListener);
  35642. }
  35643. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  35644. {
  35645. listeners.removeValue (listenerToRemove);
  35646. }
  35647. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  35648. {
  35649. const ColumnInfo* const ci = getInfoForId (columnId);
  35650. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  35651. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  35652. }
  35653. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  35654. {
  35655. for (int i = 0; i < columns.size(); ++i)
  35656. {
  35657. const ColumnInfo* const ci = columns.getUnchecked(i);
  35658. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  35659. menu.addItem (ci->id, ci->name,
  35660. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  35661. isColumnVisible (ci->id));
  35662. }
  35663. }
  35664. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  35665. {
  35666. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  35667. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  35668. }
  35669. void TableHeaderComponent::paint (Graphics& g)
  35670. {
  35671. LookAndFeel& lf = getLookAndFeel();
  35672. lf.drawTableHeaderBackground (g, *this);
  35673. const Rectangle clip (g.getClipBounds());
  35674. int x = 0;
  35675. for (int i = 0; i < columns.size(); ++i)
  35676. {
  35677. const ColumnInfo* const ci = columns.getUnchecked(i);
  35678. if (ci->isVisible())
  35679. {
  35680. if (x + ci->width > clip.getX()
  35681. && (ci->id != columnIdBeingDragged
  35682. || dragOverlayComp == 0
  35683. || ! dragOverlayComp->isVisible()))
  35684. {
  35685. g.saveState();
  35686. g.setOrigin (x, 0);
  35687. g.reduceClipRegion (0, 0, ci->width, getHeight());
  35688. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  35689. ci->id == columnIdUnderMouse,
  35690. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  35691. ci->propertyFlags);
  35692. g.restoreState();
  35693. }
  35694. x += ci->width;
  35695. if (x >= clip.getRight())
  35696. break;
  35697. }
  35698. }
  35699. }
  35700. void TableHeaderComponent::resized()
  35701. {
  35702. }
  35703. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  35704. {
  35705. updateColumnUnderMouse (e.x, e.y);
  35706. }
  35707. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  35708. {
  35709. updateColumnUnderMouse (e.x, e.y);
  35710. }
  35711. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  35712. {
  35713. updateColumnUnderMouse (e.x, e.y);
  35714. }
  35715. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  35716. {
  35717. repaint();
  35718. columnIdBeingResized = 0;
  35719. columnIdBeingDragged = 0;
  35720. if (columnIdUnderMouse != 0)
  35721. {
  35722. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  35723. if (e.mods.isPopupMenu())
  35724. columnClicked (columnIdUnderMouse, e.mods);
  35725. }
  35726. if (menuActive && e.mods.isPopupMenu())
  35727. showColumnChooserMenu (columnIdUnderMouse);
  35728. }
  35729. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  35730. {
  35731. if (columnIdBeingResized == 0
  35732. && columnIdBeingDragged == 0
  35733. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  35734. {
  35735. deleteAndZero (dragOverlayComp);
  35736. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  35737. if (columnIdBeingResized != 0)
  35738. {
  35739. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35740. initialColumnWidth = ci->width;
  35741. }
  35742. else
  35743. {
  35744. beginDrag (e);
  35745. }
  35746. }
  35747. if (columnIdBeingResized != 0)
  35748. {
  35749. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35750. if (ci != 0)
  35751. {
  35752. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  35753. initialColumnWidth + e.getDistanceFromDragStartX());
  35754. if (stretchToFit)
  35755. {
  35756. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  35757. int minWidthOnRight = 0;
  35758. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  35759. if (columns.getUnchecked (i)->isVisible())
  35760. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  35761. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  35762. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  35763. }
  35764. setColumnWidth (columnIdBeingResized, w);
  35765. }
  35766. }
  35767. else if (columnIdBeingDragged != 0)
  35768. {
  35769. if (e.y >= -50 && e.y < getHeight() + 50)
  35770. {
  35771. beginDrag (e);
  35772. if (dragOverlayComp != 0)
  35773. {
  35774. dragOverlayComp->setVisible (true);
  35775. dragOverlayComp->setBounds (jlimit (0,
  35776. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  35777. e.x - draggingColumnOffset),
  35778. 0,
  35779. dragOverlayComp->getWidth(),
  35780. getHeight());
  35781. for (int i = columns.size(); --i >= 0;)
  35782. {
  35783. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35784. int newIndex = currentIndex;
  35785. if (newIndex > 0)
  35786. {
  35787. // if the previous column isn't draggable, we can't move our column
  35788. // past it, because that'd change the undraggable column's position..
  35789. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  35790. if ((previous->propertyFlags & draggable) != 0)
  35791. {
  35792. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  35793. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  35794. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  35795. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  35796. {
  35797. --newIndex;
  35798. }
  35799. }
  35800. }
  35801. if (newIndex < columns.size() - 1)
  35802. {
  35803. // if the next column isn't draggable, we can't move our column
  35804. // past it, because that'd change the undraggable column's position..
  35805. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  35806. if ((nextCol->propertyFlags & draggable) != 0)
  35807. {
  35808. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  35809. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  35810. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  35811. > abs (dragOverlayComp->getRight() - rightOfNext))
  35812. {
  35813. ++newIndex;
  35814. }
  35815. }
  35816. }
  35817. if (newIndex != currentIndex)
  35818. moveColumn (columnIdBeingDragged, newIndex);
  35819. else
  35820. break;
  35821. }
  35822. }
  35823. }
  35824. else
  35825. {
  35826. endDrag (draggingColumnOriginalIndex);
  35827. }
  35828. }
  35829. }
  35830. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  35831. {
  35832. if (columnIdBeingDragged == 0)
  35833. {
  35834. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  35835. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  35836. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  35837. {
  35838. columnIdBeingDragged = 0;
  35839. }
  35840. else
  35841. {
  35842. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35843. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  35844. const int temp = columnIdBeingDragged;
  35845. columnIdBeingDragged = 0;
  35846. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  35847. columnIdBeingDragged = temp;
  35848. dragOverlayComp->setBounds (columnRect);
  35849. for (int i = listeners.size(); --i >= 0;)
  35850. {
  35851. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  35852. i = jmin (i, listeners.size() - 1);
  35853. }
  35854. }
  35855. }
  35856. }
  35857. void TableHeaderComponent::endDrag (const int finalIndex)
  35858. {
  35859. if (columnIdBeingDragged != 0)
  35860. {
  35861. moveColumn (columnIdBeingDragged, finalIndex);
  35862. columnIdBeingDragged = 0;
  35863. repaint();
  35864. for (int i = listeners.size(); --i >= 0;)
  35865. {
  35866. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  35867. i = jmin (i, listeners.size() - 1);
  35868. }
  35869. }
  35870. }
  35871. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  35872. {
  35873. mouseDrag (e);
  35874. for (int i = columns.size(); --i >= 0;)
  35875. if (columns.getUnchecked (i)->isVisible())
  35876. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  35877. columnIdBeingResized = 0;
  35878. repaint();
  35879. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  35880. updateColumnUnderMouse (e.x, e.y);
  35881. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  35882. columnClicked (columnIdUnderMouse, e.mods);
  35883. deleteAndZero (dragOverlayComp);
  35884. }
  35885. const MouseCursor TableHeaderComponent::getMouseCursor()
  35886. {
  35887. int x, y;
  35888. getMouseXYRelative (x, y);
  35889. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  35890. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  35891. return Component::getMouseCursor();
  35892. }
  35893. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  35894. {
  35895. return (propertyFlags & TableHeaderComponent::visible) != 0;
  35896. }
  35897. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  35898. {
  35899. for (int i = columns.size(); --i >= 0;)
  35900. if (columns.getUnchecked(i)->id == id)
  35901. return columns.getUnchecked(i);
  35902. return 0;
  35903. }
  35904. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  35905. {
  35906. int n = 0;
  35907. for (int i = 0; i < columns.size(); ++i)
  35908. {
  35909. if (columns.getUnchecked(i)->isVisible())
  35910. {
  35911. if (n == visibleIndex)
  35912. return i;
  35913. ++n;
  35914. }
  35915. }
  35916. return -1;
  35917. }
  35918. void TableHeaderComponent::sendColumnsChanged()
  35919. {
  35920. if (stretchToFit && lastDeliberateWidth > 0)
  35921. resizeAllColumnsToFit (lastDeliberateWidth);
  35922. repaint();
  35923. columnsChanged = true;
  35924. triggerAsyncUpdate();
  35925. }
  35926. void TableHeaderComponent::handleAsyncUpdate()
  35927. {
  35928. const bool changed = columnsChanged || sortChanged;
  35929. const bool sized = columnsResized || changed;
  35930. const bool sorted = sortChanged;
  35931. columnsChanged = false;
  35932. columnsResized = false;
  35933. sortChanged = false;
  35934. if (sorted)
  35935. {
  35936. for (int i = listeners.size(); --i >= 0;)
  35937. {
  35938. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  35939. i = jmin (i, listeners.size() - 1);
  35940. }
  35941. }
  35942. if (changed)
  35943. {
  35944. for (int i = listeners.size(); --i >= 0;)
  35945. {
  35946. listeners.getUnchecked(i)->tableColumnsChanged (this);
  35947. i = jmin (i, listeners.size() - 1);
  35948. }
  35949. }
  35950. if (sized)
  35951. {
  35952. for (int i = listeners.size(); --i >= 0;)
  35953. {
  35954. listeners.getUnchecked(i)->tableColumnsResized (this);
  35955. i = jmin (i, listeners.size() - 1);
  35956. }
  35957. }
  35958. }
  35959. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  35960. {
  35961. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  35962. {
  35963. const int draggableDistance = 3;
  35964. int x = 0;
  35965. for (int i = 0; i < columns.size(); ++i)
  35966. {
  35967. const ColumnInfo* const ci = columns.getUnchecked(i);
  35968. if (ci->isVisible())
  35969. {
  35970. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  35971. && (ci->propertyFlags & resizable) != 0)
  35972. return ci->id;
  35973. x += ci->width;
  35974. }
  35975. }
  35976. }
  35977. return 0;
  35978. }
  35979. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  35980. {
  35981. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  35982. ? getColumnIdAtX (x) : 0;
  35983. if (newCol != columnIdUnderMouse)
  35984. {
  35985. columnIdUnderMouse = newCol;
  35986. repaint();
  35987. }
  35988. }
  35989. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  35990. {
  35991. PopupMenu m;
  35992. addMenuItems (m, columnIdClicked);
  35993. if (m.getNumItems() > 0)
  35994. {
  35995. const int result = m.show();
  35996. if (result != 0)
  35997. reactToMenuItem (result, columnIdClicked);
  35998. }
  35999. }
  36000. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  36001. {
  36002. }
  36003. END_JUCE_NAMESPACE
  36004. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  36005. /********* Start of inlined file: juce_TableListBox.cpp *********/
  36006. BEGIN_JUCE_NAMESPACE
  36007. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  36008. class TableListRowComp : public Component
  36009. {
  36010. public:
  36011. TableListRowComp (TableListBox& owner_)
  36012. : owner (owner_),
  36013. row (-1),
  36014. isSelected (false)
  36015. {
  36016. }
  36017. ~TableListRowComp()
  36018. {
  36019. deleteAllChildren();
  36020. }
  36021. void paint (Graphics& g)
  36022. {
  36023. TableListBoxModel* const model = owner.getModel();
  36024. if (model != 0)
  36025. {
  36026. const TableHeaderComponent* const header = owner.getHeader();
  36027. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  36028. const int numColumns = header->getNumColumns (true);
  36029. for (int i = 0; i < numColumns; ++i)
  36030. {
  36031. if (! columnsWithComponents [i])
  36032. {
  36033. const int columnId = header->getColumnIdOfIndex (i, true);
  36034. Rectangle columnRect (header->getColumnPosition (i));
  36035. columnRect.setSize (columnRect.getWidth(), getHeight());
  36036. g.saveState();
  36037. g.reduceClipRegion (columnRect);
  36038. g.setOrigin (columnRect.getX(), 0);
  36039. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  36040. g.restoreState();
  36041. }
  36042. }
  36043. }
  36044. }
  36045. void update (const int newRow, const bool isNowSelected)
  36046. {
  36047. if (newRow != row || isNowSelected != isSelected)
  36048. {
  36049. row = newRow;
  36050. isSelected = isNowSelected;
  36051. repaint();
  36052. }
  36053. if (row < owner.getNumRows())
  36054. {
  36055. jassert (row >= 0);
  36056. const tchar* const tagPropertyName = T("_tableLastUseNum");
  36057. const int newTag = Random::getSystemRandom().nextInt();
  36058. const TableHeaderComponent* const header = owner.getHeader();
  36059. const int numColumns = header->getNumColumns (true);
  36060. int i;
  36061. columnsWithComponents.clear();
  36062. if (owner.getModel() != 0)
  36063. {
  36064. for (i = 0; i < numColumns; ++i)
  36065. {
  36066. const int columnId = header->getColumnIdOfIndex (i, true);
  36067. Component* const newComp
  36068. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  36069. findChildComponentForColumn (columnId));
  36070. if (newComp != 0)
  36071. {
  36072. addAndMakeVisible (newComp);
  36073. newComp->setComponentProperty (tagPropertyName, newTag);
  36074. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  36075. const Rectangle columnRect (header->getColumnPosition (i));
  36076. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36077. columnsWithComponents.setBit (i);
  36078. }
  36079. }
  36080. }
  36081. for (i = getNumChildComponents(); --i >= 0;)
  36082. {
  36083. Component* const c = getChildComponent (i);
  36084. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  36085. delete c;
  36086. }
  36087. }
  36088. else
  36089. {
  36090. columnsWithComponents.clear();
  36091. deleteAllChildren();
  36092. }
  36093. }
  36094. void resized()
  36095. {
  36096. for (int i = getNumChildComponents(); --i >= 0;)
  36097. {
  36098. Component* const c = getChildComponent (i);
  36099. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  36100. if (columnId != 0)
  36101. {
  36102. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  36103. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36104. }
  36105. }
  36106. }
  36107. void mouseDown (const MouseEvent& e)
  36108. {
  36109. isDragging = false;
  36110. selectRowOnMouseUp = false;
  36111. if (isEnabled())
  36112. {
  36113. if (! isSelected)
  36114. {
  36115. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36116. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36117. if (columnId != 0 && owner.getModel() != 0)
  36118. owner.getModel()->cellClicked (row, columnId, e);
  36119. }
  36120. else
  36121. {
  36122. selectRowOnMouseUp = true;
  36123. }
  36124. }
  36125. }
  36126. void mouseDrag (const MouseEvent& e)
  36127. {
  36128. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  36129. {
  36130. const SparseSet <int> selectedRows (owner.getSelectedRows());
  36131. if (selectedRows.size() > 0)
  36132. {
  36133. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  36134. if (dragDescription.isNotEmpty())
  36135. {
  36136. isDragging = true;
  36137. DragAndDropContainer* const dragContainer
  36138. = DragAndDropContainer::findParentDragContainerFor (this);
  36139. if (dragContainer != 0)
  36140. {
  36141. Image* dragImage = owner.createSnapshotOfSelectedRows();
  36142. dragImage->multiplyAllAlphas (0.6f);
  36143. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  36144. }
  36145. else
  36146. {
  36147. // to be able to do a drag-and-drop operation, the listbox needs to
  36148. // be inside a component which is also a DragAndDropContainer.
  36149. jassertfalse
  36150. }
  36151. }
  36152. }
  36153. }
  36154. }
  36155. void mouseUp (const MouseEvent& e)
  36156. {
  36157. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  36158. {
  36159. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36160. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36161. if (columnId != 0 && owner.getModel() != 0)
  36162. owner.getModel()->cellClicked (row, columnId, e);
  36163. }
  36164. }
  36165. void mouseDoubleClick (const MouseEvent& e)
  36166. {
  36167. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36168. if (columnId != 0 && owner.getModel() != 0)
  36169. owner.getModel()->cellDoubleClicked (row, columnId, e);
  36170. }
  36171. juce_UseDebuggingNewOperator
  36172. private:
  36173. TableListBox& owner;
  36174. int row;
  36175. bool isSelected, isDragging, selectRowOnMouseUp;
  36176. BitArray columnsWithComponents;
  36177. Component* findChildComponentForColumn (const int columnId) const
  36178. {
  36179. for (int i = getNumChildComponents(); --i >= 0;)
  36180. {
  36181. Component* const c = getChildComponent (i);
  36182. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  36183. return c;
  36184. }
  36185. return 0;
  36186. }
  36187. TableListRowComp (const TableListRowComp&);
  36188. const TableListRowComp& operator= (const TableListRowComp&);
  36189. };
  36190. class TableListBoxHeader : public TableHeaderComponent
  36191. {
  36192. public:
  36193. TableListBoxHeader (TableListBox& owner_)
  36194. : owner (owner_)
  36195. {
  36196. }
  36197. ~TableListBoxHeader()
  36198. {
  36199. }
  36200. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  36201. {
  36202. if (owner.isAutoSizeMenuOptionShown())
  36203. {
  36204. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  36205. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  36206. menu.addSeparator();
  36207. }
  36208. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  36209. }
  36210. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  36211. {
  36212. if (menuReturnId == 0xf836743)
  36213. {
  36214. owner.autoSizeColumn (columnIdClicked);
  36215. }
  36216. else if (menuReturnId == 0xf836744)
  36217. {
  36218. owner.autoSizeAllColumns();
  36219. }
  36220. else
  36221. {
  36222. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  36223. }
  36224. }
  36225. juce_UseDebuggingNewOperator
  36226. private:
  36227. TableListBox& owner;
  36228. TableListBoxHeader (const TableListBoxHeader&);
  36229. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  36230. };
  36231. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  36232. : ListBox (name, 0),
  36233. model (model_),
  36234. autoSizeOptionsShown (true)
  36235. {
  36236. ListBox::model = this;
  36237. header = new TableListBoxHeader (*this);
  36238. header->setSize (100, 28);
  36239. header->addListener (this);
  36240. setHeaderComponent (header);
  36241. }
  36242. TableListBox::~TableListBox()
  36243. {
  36244. deleteAllChildren();
  36245. }
  36246. void TableListBox::setModel (TableListBoxModel* const newModel)
  36247. {
  36248. if (model != newModel)
  36249. {
  36250. model = newModel;
  36251. updateContent();
  36252. }
  36253. }
  36254. int TableListBox::getHeaderHeight() const throw()
  36255. {
  36256. return header->getHeight();
  36257. }
  36258. void TableListBox::setHeaderHeight (const int newHeight)
  36259. {
  36260. header->setSize (header->getWidth(), newHeight);
  36261. resized();
  36262. }
  36263. void TableListBox::autoSizeColumn (const int columnId)
  36264. {
  36265. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  36266. if (width > 0)
  36267. header->setColumnWidth (columnId, width);
  36268. }
  36269. void TableListBox::autoSizeAllColumns()
  36270. {
  36271. for (int i = 0; i < header->getNumColumns (true); ++i)
  36272. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  36273. }
  36274. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  36275. {
  36276. autoSizeOptionsShown = shouldBeShown;
  36277. }
  36278. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  36279. {
  36280. return autoSizeOptionsShown;
  36281. }
  36282. const Rectangle TableListBox::getCellPosition (const int columnId,
  36283. const int rowNumber,
  36284. const bool relativeToComponentTopLeft) const
  36285. {
  36286. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36287. if (relativeToComponentTopLeft)
  36288. headerCell.translate (header->getX(), 0);
  36289. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  36290. return Rectangle (headerCell.getX(), row.getY(),
  36291. headerCell.getWidth(), row.getHeight());
  36292. }
  36293. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  36294. {
  36295. ScrollBar* const scrollbar = getHorizontalScrollBar();
  36296. if (scrollbar != 0)
  36297. {
  36298. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36299. double x = scrollbar->getCurrentRangeStart();
  36300. const double w = scrollbar->getCurrentRangeSize();
  36301. if (pos.getX() < x)
  36302. x = pos.getX();
  36303. else if (pos.getRight() > x + w)
  36304. x += jmax (0.0, pos.getRight() - (x + w));
  36305. scrollbar->setCurrentRangeStart (x);
  36306. }
  36307. }
  36308. int TableListBox::getNumRows()
  36309. {
  36310. return model != 0 ? model->getNumRows() : 0;
  36311. }
  36312. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  36313. {
  36314. }
  36315. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  36316. {
  36317. if (existingComponentToUpdate == 0)
  36318. existingComponentToUpdate = new TableListRowComp (*this);
  36319. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  36320. return existingComponentToUpdate;
  36321. }
  36322. void TableListBox::selectedRowsChanged (int row)
  36323. {
  36324. if (model != 0)
  36325. model->selectedRowsChanged (row);
  36326. }
  36327. void TableListBox::deleteKeyPressed (int row)
  36328. {
  36329. if (model != 0)
  36330. model->deleteKeyPressed (row);
  36331. }
  36332. void TableListBox::returnKeyPressed (int row)
  36333. {
  36334. if (model != 0)
  36335. model->returnKeyPressed (row);
  36336. }
  36337. void TableListBox::backgroundClicked()
  36338. {
  36339. if (model != 0)
  36340. model->backgroundClicked();
  36341. }
  36342. void TableListBox::listWasScrolled()
  36343. {
  36344. if (model != 0)
  36345. model->listWasScrolled();
  36346. }
  36347. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  36348. {
  36349. setMinimumContentWidth (header->getTotalWidth());
  36350. repaint();
  36351. updateColumnComponents();
  36352. }
  36353. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  36354. {
  36355. setMinimumContentWidth (header->getTotalWidth());
  36356. repaint();
  36357. updateColumnComponents();
  36358. }
  36359. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  36360. {
  36361. if (model != 0)
  36362. model->sortOrderChanged (header->getSortColumnId(),
  36363. header->isSortedForwards());
  36364. }
  36365. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  36366. {
  36367. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  36368. repaint();
  36369. }
  36370. void TableListBox::resized()
  36371. {
  36372. ListBox::resized();
  36373. header->resizeAllColumnsToFit (getVisibleContentWidth());
  36374. setMinimumContentWidth (header->getTotalWidth());
  36375. }
  36376. void TableListBox::updateColumnComponents() const
  36377. {
  36378. const int firstRow = getRowContainingPosition (0, 0);
  36379. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  36380. {
  36381. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  36382. if (rowComp != 0)
  36383. rowComp->resized();
  36384. }
  36385. }
  36386. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  36387. {
  36388. }
  36389. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  36390. {
  36391. }
  36392. void TableListBoxModel::backgroundClicked()
  36393. {
  36394. }
  36395. void TableListBoxModel::sortOrderChanged (int, const bool)
  36396. {
  36397. }
  36398. int TableListBoxModel::getColumnAutoSizeWidth (int)
  36399. {
  36400. return 0;
  36401. }
  36402. void TableListBoxModel::selectedRowsChanged (int)
  36403. {
  36404. }
  36405. void TableListBoxModel::deleteKeyPressed (int)
  36406. {
  36407. }
  36408. void TableListBoxModel::returnKeyPressed (int)
  36409. {
  36410. }
  36411. void TableListBoxModel::listWasScrolled()
  36412. {
  36413. }
  36414. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36415. {
  36416. return String::empty;
  36417. }
  36418. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  36419. {
  36420. (void) existingComponentToUpdate;
  36421. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36422. return 0;
  36423. }
  36424. END_JUCE_NAMESPACE
  36425. /********* End of inlined file: juce_TableListBox.cpp *********/
  36426. /********* Start of inlined file: juce_TextEditor.cpp *********/
  36427. BEGIN_JUCE_NAMESPACE
  36428. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  36429. // a word or space that can't be broken down any further
  36430. struct TextAtom
  36431. {
  36432. String atomText;
  36433. float width;
  36434. uint16 numChars;
  36435. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  36436. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  36437. const String getText (const tchar passwordCharacter) const throw()
  36438. {
  36439. if (passwordCharacter == 0)
  36440. return atomText;
  36441. else
  36442. return String::repeatedString (String::charToString (passwordCharacter),
  36443. atomText.length());
  36444. }
  36445. const String getTrimmedText (const tchar passwordCharacter) const throw()
  36446. {
  36447. if (passwordCharacter == 0)
  36448. return atomText.substring (0, numChars);
  36449. else if (isNewLine())
  36450. return String::empty;
  36451. else
  36452. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  36453. }
  36454. };
  36455. // a run of text with a single font and colour
  36456. class UniformTextSection
  36457. {
  36458. public:
  36459. UniformTextSection (const String& text,
  36460. const Font& font_,
  36461. const Colour& colour_,
  36462. const tchar passwordCharacter) throw()
  36463. : font (font_),
  36464. colour (colour_),
  36465. atoms (64)
  36466. {
  36467. initialiseAtoms (text, passwordCharacter);
  36468. }
  36469. UniformTextSection (const UniformTextSection& other) throw()
  36470. : font (other.font),
  36471. colour (other.colour),
  36472. atoms (64)
  36473. {
  36474. for (int i = 0; i < other.atoms.size(); ++i)
  36475. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  36476. }
  36477. ~UniformTextSection() throw()
  36478. {
  36479. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  36480. }
  36481. void clear() throw()
  36482. {
  36483. for (int i = atoms.size(); --i >= 0;)
  36484. {
  36485. TextAtom* const atom = getAtom(i);
  36486. delete atom;
  36487. }
  36488. atoms.clear();
  36489. }
  36490. int getNumAtoms() const throw()
  36491. {
  36492. return atoms.size();
  36493. }
  36494. TextAtom* getAtom (const int index) const throw()
  36495. {
  36496. return (TextAtom*) atoms.getUnchecked (index);
  36497. }
  36498. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  36499. {
  36500. if (other.atoms.size() > 0)
  36501. {
  36502. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  36503. int i = 0;
  36504. if (lastAtom != 0)
  36505. {
  36506. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  36507. {
  36508. TextAtom* const first = other.getAtom(0);
  36509. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  36510. {
  36511. lastAtom->atomText += first->atomText;
  36512. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  36513. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  36514. delete first;
  36515. ++i;
  36516. }
  36517. }
  36518. }
  36519. while (i < other.atoms.size())
  36520. {
  36521. atoms.add (other.getAtom(i));
  36522. ++i;
  36523. }
  36524. }
  36525. }
  36526. UniformTextSection* split (const int indexToBreakAt,
  36527. const tchar passwordCharacter) throw()
  36528. {
  36529. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  36530. font, colour,
  36531. passwordCharacter);
  36532. int index = 0;
  36533. for (int i = 0; i < atoms.size(); ++i)
  36534. {
  36535. TextAtom* const atom = getAtom(i);
  36536. const int nextIndex = index + atom->numChars;
  36537. if (index == indexToBreakAt)
  36538. {
  36539. int j;
  36540. for (j = i; j < atoms.size(); ++j)
  36541. section2->atoms.add (getAtom (j));
  36542. for (j = atoms.size(); --j >= i;)
  36543. atoms.remove (j);
  36544. break;
  36545. }
  36546. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  36547. {
  36548. TextAtom* const secondAtom = new TextAtom();
  36549. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  36550. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  36551. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  36552. section2->atoms.add (secondAtom);
  36553. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  36554. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36555. atom->numChars = (uint16) (indexToBreakAt - index);
  36556. int j;
  36557. for (j = i + 1; j < atoms.size(); ++j)
  36558. section2->atoms.add (getAtom (j));
  36559. for (j = atoms.size(); --j > i;)
  36560. atoms.remove (j);
  36561. break;
  36562. }
  36563. index = nextIndex;
  36564. }
  36565. return section2;
  36566. }
  36567. const String getAllText() const throw()
  36568. {
  36569. String s;
  36570. s.preallocateStorage (getTotalLength());
  36571. tchar* endOfString = (tchar*) &(s[0]);
  36572. for (int i = 0; i < atoms.size(); ++i)
  36573. {
  36574. const TextAtom* const atom = getAtom(i);
  36575. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  36576. endOfString += atom->numChars;
  36577. }
  36578. *endOfString = 0;
  36579. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  36580. return s;
  36581. }
  36582. const String getTextSubstring (const int startCharacter,
  36583. const int endCharacter) const throw()
  36584. {
  36585. int index = 0;
  36586. int totalLen = 0;
  36587. int i;
  36588. for (i = 0; i < atoms.size(); ++i)
  36589. {
  36590. const TextAtom* const atom = getAtom (i);
  36591. const int nextIndex = index + atom->numChars;
  36592. if (startCharacter < nextIndex)
  36593. {
  36594. if (endCharacter <= index)
  36595. break;
  36596. const int start = jmax (0, startCharacter - index);
  36597. const int end = jmin (endCharacter - index, atom->numChars);
  36598. jassert (end >= start);
  36599. totalLen += end - start;
  36600. }
  36601. index = nextIndex;
  36602. }
  36603. String s;
  36604. s.preallocateStorage (totalLen + 1);
  36605. tchar* psz = (tchar*) (const tchar*) s;
  36606. index = 0;
  36607. for (i = 0; i < atoms.size(); ++i)
  36608. {
  36609. const TextAtom* const atom = getAtom (i);
  36610. const int nextIndex = index + atom->numChars;
  36611. if (startCharacter < nextIndex)
  36612. {
  36613. if (endCharacter <= index)
  36614. break;
  36615. const int start = jmax (0, startCharacter - index);
  36616. const int len = jmin (endCharacter - index, atom->numChars) - start;
  36617. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  36618. psz += len;
  36619. *psz = 0;
  36620. }
  36621. index = nextIndex;
  36622. }
  36623. return s;
  36624. }
  36625. int getTotalLength() const throw()
  36626. {
  36627. int c = 0;
  36628. for (int i = atoms.size(); --i >= 0;)
  36629. c += getAtom(i)->numChars;
  36630. return c;
  36631. }
  36632. void setFont (const Font& newFont,
  36633. const tchar passwordCharacter) throw()
  36634. {
  36635. if (font != newFont)
  36636. {
  36637. font = newFont;
  36638. for (int i = atoms.size(); --i >= 0;)
  36639. {
  36640. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  36641. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  36642. }
  36643. }
  36644. }
  36645. juce_UseDebuggingNewOperator
  36646. Font font;
  36647. Colour colour;
  36648. private:
  36649. VoidArray atoms;
  36650. void initialiseAtoms (const String& textToParse,
  36651. const tchar passwordCharacter) throw()
  36652. {
  36653. int i = 0;
  36654. const int len = textToParse.length();
  36655. const tchar* const text = (const tchar*) textToParse;
  36656. while (i < len)
  36657. {
  36658. int start = i;
  36659. // create a whitespace atom unless it starts with non-ws
  36660. if (CharacterFunctions::isWhitespace (text[i])
  36661. && text[i] != T('\r')
  36662. && text[i] != T('\n'))
  36663. {
  36664. while (i < len
  36665. && CharacterFunctions::isWhitespace (text[i])
  36666. && text[i] != T('\r')
  36667. && text[i] != T('\n'))
  36668. {
  36669. ++i;
  36670. }
  36671. }
  36672. else
  36673. {
  36674. if (text[i] == T('\r'))
  36675. {
  36676. ++i;
  36677. if ((i < len) && (text[i] == T('\n')))
  36678. {
  36679. ++start;
  36680. ++i;
  36681. }
  36682. }
  36683. else if (text[i] == T('\n'))
  36684. {
  36685. ++i;
  36686. }
  36687. else
  36688. {
  36689. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  36690. ++i;
  36691. }
  36692. }
  36693. TextAtom* const atom = new TextAtom();
  36694. atom->atomText = String (text + start, i - start);
  36695. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36696. atom->numChars = (uint16) (i - start);
  36697. atoms.add (atom);
  36698. }
  36699. }
  36700. const UniformTextSection& operator= (const UniformTextSection& other);
  36701. };
  36702. class TextEditorIterator
  36703. {
  36704. public:
  36705. TextEditorIterator (const VoidArray& sections_,
  36706. const float wordWrapWidth_,
  36707. const tchar passwordCharacter_) throw()
  36708. : indexInText (0),
  36709. lineY (0),
  36710. lineHeight (0),
  36711. maxDescent (0),
  36712. atomX (0),
  36713. atomRight (0),
  36714. atom (0),
  36715. currentSection (0),
  36716. sections (sections_),
  36717. sectionIndex (0),
  36718. atomIndex (0),
  36719. wordWrapWidth (wordWrapWidth_),
  36720. passwordCharacter (passwordCharacter_)
  36721. {
  36722. jassert (wordWrapWidth_ > 0);
  36723. if (sections.size() > 0)
  36724. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36725. if (currentSection != 0)
  36726. {
  36727. lineHeight = currentSection->font.getHeight();
  36728. maxDescent = currentSection->font.getDescent();
  36729. }
  36730. }
  36731. TextEditorIterator (const TextEditorIterator& other) throw()
  36732. : indexInText (other.indexInText),
  36733. lineY (other.lineY),
  36734. lineHeight (other.lineHeight),
  36735. maxDescent (other.maxDescent),
  36736. atomX (other.atomX),
  36737. atomRight (other.atomRight),
  36738. atom (other.atom),
  36739. currentSection (other.currentSection),
  36740. sections (other.sections),
  36741. sectionIndex (other.sectionIndex),
  36742. atomIndex (other.atomIndex),
  36743. wordWrapWidth (other.wordWrapWidth),
  36744. passwordCharacter (other.passwordCharacter),
  36745. tempAtom (other.tempAtom)
  36746. {
  36747. }
  36748. ~TextEditorIterator() throw()
  36749. {
  36750. }
  36751. bool next() throw()
  36752. {
  36753. if (atom == &tempAtom)
  36754. {
  36755. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  36756. if (numRemaining > 0)
  36757. {
  36758. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  36759. atomX = 0;
  36760. if (tempAtom.numChars > 0)
  36761. lineY += lineHeight;
  36762. indexInText += tempAtom.numChars;
  36763. GlyphArrangement g;
  36764. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  36765. int split;
  36766. for (split = 0; split < g.getNumGlyphs(); ++split)
  36767. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  36768. break;
  36769. if (split > 0 && split <= numRemaining)
  36770. {
  36771. tempAtom.numChars = (uint16) split;
  36772. tempAtom.width = g.getGlyph (split - 1).getRight();
  36773. atomRight = atomX + tempAtom.width;
  36774. return true;
  36775. }
  36776. }
  36777. }
  36778. bool forceNewLine = false;
  36779. if (sectionIndex >= sections.size())
  36780. {
  36781. moveToEndOfLastAtom();
  36782. return false;
  36783. }
  36784. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  36785. {
  36786. if (atomIndex >= currentSection->getNumAtoms())
  36787. {
  36788. if (++sectionIndex >= sections.size())
  36789. {
  36790. moveToEndOfLastAtom();
  36791. return false;
  36792. }
  36793. atomIndex = 0;
  36794. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36795. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36796. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36797. }
  36798. else
  36799. {
  36800. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  36801. if (! lastAtom->isWhitespace())
  36802. {
  36803. // handle the case where the last atom in a section is actually part of the same
  36804. // word as the first atom of the next section...
  36805. float right = atomRight + lastAtom->width;
  36806. float lineHeight2 = lineHeight;
  36807. float maxDescent2 = maxDescent;
  36808. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  36809. {
  36810. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  36811. if (s->getNumAtoms() == 0)
  36812. break;
  36813. const TextAtom* const nextAtom = s->getAtom (0);
  36814. if (nextAtom->isWhitespace())
  36815. break;
  36816. right += nextAtom->width;
  36817. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  36818. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  36819. if (SHOULD_WRAP (right, wordWrapWidth))
  36820. {
  36821. lineHeight = lineHeight2;
  36822. maxDescent = maxDescent2;
  36823. forceNewLine = true;
  36824. break;
  36825. }
  36826. if (s->getNumAtoms() > 1)
  36827. break;
  36828. }
  36829. }
  36830. }
  36831. }
  36832. if (atom != 0)
  36833. {
  36834. atomX = atomRight;
  36835. indexInText += atom->numChars;
  36836. if (atom->isNewLine())
  36837. {
  36838. atomX = 0;
  36839. lineY += lineHeight;
  36840. }
  36841. }
  36842. atom = currentSection->getAtom (atomIndex);
  36843. atomRight = atomX + atom->width;
  36844. ++atomIndex;
  36845. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  36846. {
  36847. if (atom->isWhitespace())
  36848. {
  36849. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  36850. atomRight = jmin (atomRight, wordWrapWidth);
  36851. }
  36852. else
  36853. {
  36854. return wrapCurrentAtom();
  36855. }
  36856. }
  36857. return true;
  36858. }
  36859. bool wrapCurrentAtom() throw()
  36860. {
  36861. atomRight = atom->width;
  36862. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  36863. {
  36864. tempAtom = *atom;
  36865. tempAtom.width = 0;
  36866. tempAtom.numChars = 0;
  36867. atom = &tempAtom;
  36868. if (atomX > 0)
  36869. {
  36870. atomX = 0;
  36871. lineY += lineHeight;
  36872. }
  36873. return next();
  36874. }
  36875. atomX = 0;
  36876. lineY += lineHeight;
  36877. return true;
  36878. }
  36879. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  36880. {
  36881. if (passwordCharacter != 0 || ! atom->isWhitespace())
  36882. {
  36883. if (lastSection != currentSection)
  36884. {
  36885. lastSection = currentSection;
  36886. g.setColour (currentSection->colour);
  36887. g.setFont (currentSection->font);
  36888. }
  36889. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  36890. GlyphArrangement ga;
  36891. ga.addLineOfText (currentSection->font,
  36892. atom->getTrimmedText (passwordCharacter),
  36893. atomX,
  36894. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  36895. ga.draw (g);
  36896. }
  36897. }
  36898. void drawSelection (Graphics& g,
  36899. const int selectionStart,
  36900. const int selectionEnd) const throw()
  36901. {
  36902. const int startX = roundFloatToInt (indexToX (selectionStart));
  36903. const int endX = roundFloatToInt (indexToX (selectionEnd));
  36904. const int y = roundFloatToInt (lineY);
  36905. const int nextY = roundFloatToInt (lineY + lineHeight);
  36906. g.fillRect (startX, y, endX - startX, nextY - y);
  36907. }
  36908. void drawSelectedText (Graphics& g,
  36909. const int selectionStart,
  36910. const int selectionEnd,
  36911. const Colour& selectedTextColour) const throw()
  36912. {
  36913. if (passwordCharacter != 0 || ! atom->isWhitespace())
  36914. {
  36915. GlyphArrangement ga;
  36916. ga.addLineOfText (currentSection->font,
  36917. atom->getTrimmedText (passwordCharacter),
  36918. atomX,
  36919. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  36920. if (selectionEnd < indexInText + atom->numChars)
  36921. {
  36922. GlyphArrangement ga2 (ga);
  36923. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  36924. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  36925. g.setColour (currentSection->colour);
  36926. ga2.draw (g);
  36927. }
  36928. if (selectionStart > indexInText)
  36929. {
  36930. GlyphArrangement ga2 (ga);
  36931. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  36932. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  36933. g.setColour (currentSection->colour);
  36934. ga2.draw (g);
  36935. }
  36936. g.setColour (selectedTextColour);
  36937. ga.draw (g);
  36938. }
  36939. }
  36940. float indexToX (const int indexToFind) const throw()
  36941. {
  36942. if (indexToFind <= indexInText)
  36943. return atomX;
  36944. if (indexToFind >= indexInText + atom->numChars)
  36945. return atomRight;
  36946. GlyphArrangement g;
  36947. g.addLineOfText (currentSection->font,
  36948. atom->getText (passwordCharacter),
  36949. atomX, 0.0f);
  36950. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  36951. }
  36952. int xToIndex (const float xToFind) const throw()
  36953. {
  36954. if (xToFind <= atomX || atom->isNewLine())
  36955. return indexInText;
  36956. if (xToFind >= atomRight)
  36957. return indexInText + atom->numChars;
  36958. GlyphArrangement g;
  36959. g.addLineOfText (currentSection->font,
  36960. atom->getText (passwordCharacter),
  36961. atomX, 0.0f);
  36962. int j;
  36963. for (j = 0; j < atom->numChars; ++j)
  36964. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  36965. break;
  36966. return indexInText + j;
  36967. }
  36968. void updateLineHeight() throw()
  36969. {
  36970. float x = atomRight;
  36971. int tempSectionIndex = sectionIndex;
  36972. int tempAtomIndex = atomIndex;
  36973. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  36974. while (! SHOULD_WRAP (x, wordWrapWidth))
  36975. {
  36976. if (tempSectionIndex >= sections.size())
  36977. break;
  36978. bool checkSize = false;
  36979. if (tempAtomIndex >= currentSection->getNumAtoms())
  36980. {
  36981. if (++tempSectionIndex >= sections.size())
  36982. break;
  36983. tempAtomIndex = 0;
  36984. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  36985. checkSize = true;
  36986. }
  36987. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  36988. if (atom == 0)
  36989. break;
  36990. x += atom->width;
  36991. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  36992. break;
  36993. if (checkSize)
  36994. {
  36995. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36996. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36997. }
  36998. ++tempAtomIndex;
  36999. }
  37000. }
  37001. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  37002. {
  37003. while (next())
  37004. {
  37005. if (indexInText + atom->numChars >= index)
  37006. {
  37007. updateLineHeight();
  37008. if (indexInText + atom->numChars > index)
  37009. {
  37010. cx = indexToX (index);
  37011. cy = lineY;
  37012. lineHeight_ = lineHeight;
  37013. return true;
  37014. }
  37015. }
  37016. }
  37017. cx = atomX;
  37018. cy = lineY;
  37019. lineHeight_ = lineHeight;
  37020. return false;
  37021. }
  37022. juce_UseDebuggingNewOperator
  37023. int indexInText;
  37024. float lineY, lineHeight, maxDescent;
  37025. float atomX, atomRight;
  37026. const TextAtom* atom;
  37027. const UniformTextSection* currentSection;
  37028. private:
  37029. const VoidArray& sections;
  37030. int sectionIndex, atomIndex;
  37031. const float wordWrapWidth;
  37032. const tchar passwordCharacter;
  37033. TextAtom tempAtom;
  37034. const TextEditorIterator& operator= (const TextEditorIterator&);
  37035. void moveToEndOfLastAtom() throw()
  37036. {
  37037. if (atom != 0)
  37038. {
  37039. atomX = atomRight;
  37040. if (atom->isNewLine())
  37041. {
  37042. atomX = 0.0f;
  37043. lineY += lineHeight;
  37044. }
  37045. }
  37046. }
  37047. };
  37048. class TextEditorInsertAction : public UndoableAction
  37049. {
  37050. TextEditor& owner;
  37051. const String text;
  37052. const int insertIndex, oldCaretPos, newCaretPos;
  37053. const Font font;
  37054. const Colour colour;
  37055. TextEditorInsertAction (const TextEditorInsertAction&);
  37056. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  37057. public:
  37058. TextEditorInsertAction (TextEditor& owner_,
  37059. const String& text_,
  37060. const int insertIndex_,
  37061. const Font& font_,
  37062. const Colour& colour_,
  37063. const int oldCaretPos_,
  37064. const int newCaretPos_) throw()
  37065. : owner (owner_),
  37066. text (text_),
  37067. insertIndex (insertIndex_),
  37068. oldCaretPos (oldCaretPos_),
  37069. newCaretPos (newCaretPos_),
  37070. font (font_),
  37071. colour (colour_)
  37072. {
  37073. }
  37074. ~TextEditorInsertAction()
  37075. {
  37076. }
  37077. bool perform()
  37078. {
  37079. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  37080. return true;
  37081. }
  37082. bool undo()
  37083. {
  37084. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  37085. return true;
  37086. }
  37087. int getSizeInUnits()
  37088. {
  37089. return text.length() + 16;
  37090. }
  37091. };
  37092. class TextEditorRemoveAction : public UndoableAction
  37093. {
  37094. TextEditor& owner;
  37095. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  37096. VoidArray removedSections;
  37097. TextEditorRemoveAction (const TextEditorRemoveAction&);
  37098. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  37099. public:
  37100. TextEditorRemoveAction (TextEditor& owner_,
  37101. const int startIndex_,
  37102. const int endIndex_,
  37103. const int oldCaretPos_,
  37104. const int newCaretPos_,
  37105. const VoidArray& removedSections_) throw()
  37106. : owner (owner_),
  37107. startIndex (startIndex_),
  37108. endIndex (endIndex_),
  37109. oldCaretPos (oldCaretPos_),
  37110. newCaretPos (newCaretPos_),
  37111. removedSections (removedSections_)
  37112. {
  37113. }
  37114. ~TextEditorRemoveAction()
  37115. {
  37116. for (int i = removedSections.size(); --i >= 0;)
  37117. {
  37118. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37119. section->clear();
  37120. delete section;
  37121. }
  37122. }
  37123. bool perform()
  37124. {
  37125. owner.remove (startIndex, endIndex, 0, newCaretPos);
  37126. return true;
  37127. }
  37128. bool undo()
  37129. {
  37130. owner.reinsert (startIndex, removedSections);
  37131. owner.moveCursorTo (oldCaretPos, false);
  37132. return true;
  37133. }
  37134. int getSizeInUnits()
  37135. {
  37136. int n = 0;
  37137. for (int i = removedSections.size(); --i >= 0;)
  37138. {
  37139. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37140. n += section->getTotalLength();
  37141. }
  37142. return n + 16;
  37143. }
  37144. };
  37145. class TextHolderComponent : public Component,
  37146. public Timer
  37147. {
  37148. TextEditor* const owner;
  37149. TextHolderComponent (const TextHolderComponent&);
  37150. const TextHolderComponent& operator= (const TextHolderComponent&);
  37151. public:
  37152. TextHolderComponent (TextEditor* const owner_)
  37153. : owner (owner_)
  37154. {
  37155. setWantsKeyboardFocus (false);
  37156. setInterceptsMouseClicks (false, true);
  37157. }
  37158. ~TextHolderComponent()
  37159. {
  37160. }
  37161. void paint (Graphics& g)
  37162. {
  37163. owner->drawContent (g);
  37164. }
  37165. void timerCallback()
  37166. {
  37167. owner->timerCallbackInt();
  37168. }
  37169. const MouseCursor getMouseCursor()
  37170. {
  37171. return owner->getMouseCursor();
  37172. }
  37173. };
  37174. class TextEditorViewport : public Viewport
  37175. {
  37176. TextEditor* const owner;
  37177. float lastWordWrapWidth;
  37178. TextEditorViewport (const TextEditorViewport&);
  37179. const TextEditorViewport& operator= (const TextEditorViewport&);
  37180. public:
  37181. TextEditorViewport (TextEditor* const owner_)
  37182. : owner (owner_),
  37183. lastWordWrapWidth (0)
  37184. {
  37185. }
  37186. ~TextEditorViewport()
  37187. {
  37188. }
  37189. void visibleAreaChanged (int, int, int, int)
  37190. {
  37191. const float wordWrapWidth = owner->getWordWrapWidth();
  37192. if (wordWrapWidth != lastWordWrapWidth)
  37193. {
  37194. lastWordWrapWidth = wordWrapWidth;
  37195. owner->updateTextHolderSize();
  37196. }
  37197. }
  37198. };
  37199. const int flashSpeedIntervalMs = 380;
  37200. const int textChangeMessageId = 0x10003001;
  37201. const int returnKeyMessageId = 0x10003002;
  37202. const int escapeKeyMessageId = 0x10003003;
  37203. const int focusLossMessageId = 0x10003004;
  37204. TextEditor::TextEditor (const String& name,
  37205. const tchar passwordCharacter_)
  37206. : Component (name),
  37207. borderSize (1, 1, 1, 3),
  37208. readOnly (false),
  37209. multiline (false),
  37210. wordWrap (false),
  37211. returnKeyStartsNewLine (false),
  37212. caretVisible (true),
  37213. popupMenuEnabled (true),
  37214. selectAllTextWhenFocused (false),
  37215. scrollbarVisible (true),
  37216. wasFocused (false),
  37217. caretFlashState (true),
  37218. keepCursorOnScreen (true),
  37219. tabKeyUsed (false),
  37220. menuActive (false),
  37221. cursorX (0),
  37222. cursorY (0),
  37223. cursorHeight (0),
  37224. maxTextLength (0),
  37225. selectionStart (0),
  37226. selectionEnd (0),
  37227. leftIndent (4),
  37228. topIndent (4),
  37229. lastTransactionTime (0),
  37230. currentFont (14.0f),
  37231. totalNumChars (0),
  37232. caretPosition (0),
  37233. sections (8),
  37234. passwordCharacter (passwordCharacter_),
  37235. dragType (notDragging),
  37236. listeners (2)
  37237. {
  37238. setOpaque (true);
  37239. addAndMakeVisible (viewport = new TextEditorViewport (this));
  37240. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  37241. viewport->setWantsKeyboardFocus (false);
  37242. viewport->setScrollBarsShown (false, false);
  37243. setMouseCursor (MouseCursor::IBeamCursor);
  37244. setWantsKeyboardFocus (true);
  37245. }
  37246. TextEditor::~TextEditor()
  37247. {
  37248. clearInternal (0);
  37249. delete viewport;
  37250. }
  37251. void TextEditor::newTransaction() throw()
  37252. {
  37253. lastTransactionTime = Time::getApproximateMillisecondCounter();
  37254. undoManager.beginNewTransaction();
  37255. }
  37256. void TextEditor::doUndoRedo (const bool isRedo)
  37257. {
  37258. if (! isReadOnly())
  37259. {
  37260. if ((isRedo) ? undoManager.redo()
  37261. : undoManager.undo())
  37262. {
  37263. scrollToMakeSureCursorIsVisible();
  37264. repaint();
  37265. textChanged();
  37266. }
  37267. }
  37268. }
  37269. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  37270. const bool shouldWordWrap)
  37271. {
  37272. multiline = shouldBeMultiLine;
  37273. wordWrap = shouldWordWrap && shouldBeMultiLine;
  37274. setScrollbarsShown (scrollbarVisible);
  37275. viewport->setViewPosition (0, 0);
  37276. resized();
  37277. scrollToMakeSureCursorIsVisible();
  37278. }
  37279. bool TextEditor::isMultiLine() const throw()
  37280. {
  37281. return multiline;
  37282. }
  37283. void TextEditor::setScrollbarsShown (bool enabled) throw()
  37284. {
  37285. scrollbarVisible = enabled;
  37286. enabled = enabled && isMultiLine();
  37287. viewport->setScrollBarsShown (enabled, enabled);
  37288. }
  37289. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  37290. {
  37291. readOnly = shouldBeReadOnly;
  37292. enablementChanged();
  37293. }
  37294. bool TextEditor::isReadOnly() const throw()
  37295. {
  37296. return readOnly || ! isEnabled();
  37297. }
  37298. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  37299. {
  37300. returnKeyStartsNewLine = shouldStartNewLine;
  37301. }
  37302. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  37303. {
  37304. tabKeyUsed = shouldTabKeyBeUsed;
  37305. }
  37306. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  37307. {
  37308. popupMenuEnabled = b;
  37309. }
  37310. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  37311. {
  37312. selectAllTextWhenFocused = b;
  37313. }
  37314. const Font TextEditor::getFont() const throw()
  37315. {
  37316. return currentFont;
  37317. }
  37318. void TextEditor::setFont (const Font& newFont) throw()
  37319. {
  37320. currentFont = newFont;
  37321. scrollToMakeSureCursorIsVisible();
  37322. }
  37323. void TextEditor::applyFontToAllText (const Font& newFont)
  37324. {
  37325. currentFont = newFont;
  37326. const Colour overallColour (findColour (textColourId));
  37327. for (int i = sections.size(); --i >= 0;)
  37328. {
  37329. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  37330. uts->setFont (newFont, passwordCharacter);
  37331. uts->colour = overallColour;
  37332. }
  37333. coalesceSimilarSections();
  37334. updateTextHolderSize();
  37335. scrollToMakeSureCursorIsVisible();
  37336. repaint();
  37337. }
  37338. void TextEditor::colourChanged()
  37339. {
  37340. setOpaque (findColour (backgroundColourId).isOpaque());
  37341. repaint();
  37342. }
  37343. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  37344. {
  37345. caretVisible = shouldCaretBeVisible;
  37346. if (shouldCaretBeVisible)
  37347. textHolder->startTimer (flashSpeedIntervalMs);
  37348. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  37349. : MouseCursor::NormalCursor);
  37350. }
  37351. void TextEditor::setInputRestrictions (const int maxLen,
  37352. const String& chars) throw()
  37353. {
  37354. maxTextLength = jmax (0, maxLen);
  37355. allowedCharacters = chars;
  37356. }
  37357. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  37358. {
  37359. textToShowWhenEmpty = text;
  37360. colourForTextWhenEmpty = colourToUse;
  37361. }
  37362. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  37363. {
  37364. if (passwordCharacter != newPasswordCharacter)
  37365. {
  37366. passwordCharacter = newPasswordCharacter;
  37367. resized();
  37368. repaint();
  37369. }
  37370. }
  37371. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  37372. {
  37373. viewport->setScrollBarThickness (newThicknessPixels);
  37374. }
  37375. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  37376. {
  37377. viewport->setScrollBarButtonVisibility (buttonsVisible);
  37378. }
  37379. void TextEditor::clear()
  37380. {
  37381. clearInternal (0);
  37382. updateTextHolderSize();
  37383. undoManager.clearUndoHistory();
  37384. }
  37385. void TextEditor::setText (const String& newText,
  37386. const bool sendTextChangeMessage)
  37387. {
  37388. const int newLength = newText.length();
  37389. if (newLength != getTotalNumChars() || getText() != newText)
  37390. {
  37391. const int oldCursorPos = caretPosition;
  37392. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  37393. clearInternal (0);
  37394. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  37395. // if you're adding text with line-feeds to a single-line text editor, it
  37396. // ain't gonna look right!
  37397. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  37398. if (cursorWasAtEnd && ! isMultiLine())
  37399. moveCursorTo (getTotalNumChars(), false);
  37400. else
  37401. moveCursorTo (oldCursorPos, false);
  37402. if (sendTextChangeMessage)
  37403. textChanged();
  37404. repaint();
  37405. }
  37406. updateTextHolderSize();
  37407. scrollToMakeSureCursorIsVisible();
  37408. undoManager.clearUndoHistory();
  37409. }
  37410. void TextEditor::textChanged() throw()
  37411. {
  37412. updateTextHolderSize();
  37413. postCommandMessage (textChangeMessageId);
  37414. }
  37415. void TextEditor::returnPressed()
  37416. {
  37417. postCommandMessage (returnKeyMessageId);
  37418. }
  37419. void TextEditor::escapePressed()
  37420. {
  37421. postCommandMessage (escapeKeyMessageId);
  37422. }
  37423. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  37424. {
  37425. jassert (newListener != 0)
  37426. if (newListener != 0)
  37427. listeners.add (newListener);
  37428. }
  37429. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  37430. {
  37431. listeners.removeValue (listenerToRemove);
  37432. }
  37433. void TextEditor::timerCallbackInt()
  37434. {
  37435. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  37436. if (caretFlashState != newState)
  37437. {
  37438. caretFlashState = newState;
  37439. if (caretFlashState)
  37440. wasFocused = true;
  37441. if (caretVisible
  37442. && hasKeyboardFocus (false)
  37443. && ! isReadOnly())
  37444. {
  37445. repaintCaret();
  37446. }
  37447. }
  37448. const unsigned int now = Time::getApproximateMillisecondCounter();
  37449. if (now > lastTransactionTime + 200)
  37450. newTransaction();
  37451. }
  37452. void TextEditor::repaintCaret()
  37453. {
  37454. if (! findColour (caretColourId).isTransparent())
  37455. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  37456. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  37457. 4,
  37458. roundFloatToInt (cursorHeight) + 2);
  37459. }
  37460. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  37461. {
  37462. if (textStartIndex > textEndIndex && textEndIndex > 0)
  37463. swapVariables (textStartIndex, textEndIndex);
  37464. float x = 0, y = 0, lh = currentFont.getHeight();
  37465. const float wordWrapWidth = getWordWrapWidth();
  37466. if (wordWrapWidth > 0)
  37467. {
  37468. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37469. i.getCharPosition (textStartIndex, x, y, lh);
  37470. const int y1 = (int) y;
  37471. int y2;
  37472. if (textEndIndex >= 0)
  37473. {
  37474. i.getCharPosition (textEndIndex, x, y, lh);
  37475. y2 = (int) (y + lh * 2.0f);
  37476. }
  37477. else
  37478. {
  37479. y2 = textHolder->getHeight();
  37480. }
  37481. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  37482. }
  37483. }
  37484. void TextEditor::moveCaret (int newCaretPos) throw()
  37485. {
  37486. if (newCaretPos < 0)
  37487. newCaretPos = 0;
  37488. else if (newCaretPos > getTotalNumChars())
  37489. newCaretPos = getTotalNumChars();
  37490. if (newCaretPos != getCaretPosition())
  37491. {
  37492. repaintCaret();
  37493. caretFlashState = true;
  37494. caretPosition = newCaretPos;
  37495. textHolder->startTimer (flashSpeedIntervalMs);
  37496. scrollToMakeSureCursorIsVisible();
  37497. repaintCaret();
  37498. }
  37499. }
  37500. void TextEditor::setCaretPosition (const int newIndex) throw()
  37501. {
  37502. moveCursorTo (newIndex, false);
  37503. }
  37504. int TextEditor::getCaretPosition() const throw()
  37505. {
  37506. return caretPosition;
  37507. }
  37508. float TextEditor::getWordWrapWidth() const throw()
  37509. {
  37510. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  37511. : 1.0e10f;
  37512. }
  37513. void TextEditor::updateTextHolderSize() throw()
  37514. {
  37515. const float wordWrapWidth = getWordWrapWidth();
  37516. if (wordWrapWidth > 0)
  37517. {
  37518. float maxWidth = 0.0f;
  37519. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37520. while (i.next())
  37521. maxWidth = jmax (maxWidth, i.atomRight);
  37522. const int w = leftIndent + roundFloatToInt (maxWidth);
  37523. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  37524. currentFont.getHeight()));
  37525. textHolder->setSize (w + 1, h + 1);
  37526. }
  37527. }
  37528. int TextEditor::getTextWidth() const throw()
  37529. {
  37530. return textHolder->getWidth();
  37531. }
  37532. int TextEditor::getTextHeight() const throw()
  37533. {
  37534. return textHolder->getHeight();
  37535. }
  37536. void TextEditor::setIndents (const int newLeftIndent,
  37537. const int newTopIndent) throw()
  37538. {
  37539. leftIndent = newLeftIndent;
  37540. topIndent = newTopIndent;
  37541. }
  37542. void TextEditor::setBorder (const BorderSize& border) throw()
  37543. {
  37544. borderSize = border;
  37545. resized();
  37546. }
  37547. const BorderSize TextEditor::getBorder() const throw()
  37548. {
  37549. return borderSize;
  37550. }
  37551. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  37552. {
  37553. keepCursorOnScreen = shouldScrollToShowCursor;
  37554. }
  37555. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  37556. {
  37557. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  37558. getCharPosition (caretPosition,
  37559. cursorX, cursorY,
  37560. cursorHeight);
  37561. if (keepCursorOnScreen)
  37562. {
  37563. int x = viewport->getViewPositionX();
  37564. int y = viewport->getViewPositionY();
  37565. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  37566. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  37567. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  37568. {
  37569. x += relativeCursorX - proportionOfWidth (0.2f);
  37570. }
  37571. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37572. {
  37573. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37574. }
  37575. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  37576. if (! isMultiLine())
  37577. {
  37578. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  37579. }
  37580. else
  37581. {
  37582. const int curH = roundFloatToInt (cursorHeight);
  37583. if (relativeCursorY < 0)
  37584. {
  37585. y = jmax (0, relativeCursorY + y);
  37586. }
  37587. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37588. {
  37589. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37590. }
  37591. }
  37592. viewport->setViewPosition (x, y);
  37593. }
  37594. }
  37595. void TextEditor::moveCursorTo (const int newPosition,
  37596. const bool isSelecting) throw()
  37597. {
  37598. if (isSelecting)
  37599. {
  37600. moveCaret (newPosition);
  37601. const int oldSelStart = selectionStart;
  37602. const int oldSelEnd = selectionEnd;
  37603. if (dragType == notDragging)
  37604. {
  37605. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  37606. dragType = draggingSelectionStart;
  37607. else
  37608. dragType = draggingSelectionEnd;
  37609. }
  37610. if (dragType == draggingSelectionStart)
  37611. {
  37612. selectionStart = getCaretPosition();
  37613. if (selectionEnd < selectionStart)
  37614. {
  37615. swapVariables (selectionStart, selectionEnd);
  37616. dragType = draggingSelectionEnd;
  37617. }
  37618. }
  37619. else
  37620. {
  37621. selectionEnd = getCaretPosition();
  37622. if (selectionEnd < selectionStart)
  37623. {
  37624. swapVariables (selectionStart, selectionEnd);
  37625. dragType = draggingSelectionStart;
  37626. }
  37627. }
  37628. jassert (selectionStart <= selectionEnd);
  37629. jassert (oldSelStart <= oldSelEnd);
  37630. repaintText (jmin (oldSelStart, selectionStart),
  37631. jmax (oldSelEnd, selectionEnd));
  37632. }
  37633. else
  37634. {
  37635. dragType = notDragging;
  37636. if (selectionEnd > selectionStart)
  37637. repaintText (selectionStart, selectionEnd);
  37638. moveCaret (newPosition);
  37639. selectionStart = getCaretPosition();
  37640. selectionEnd = getCaretPosition();
  37641. }
  37642. }
  37643. int TextEditor::getTextIndexAt (const int x,
  37644. const int y) throw()
  37645. {
  37646. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  37647. (float) (y + viewport->getViewPositionY() - topIndent));
  37648. }
  37649. void TextEditor::insertTextAtCursor (String newText)
  37650. {
  37651. if (allowedCharacters.isNotEmpty())
  37652. newText = newText.retainCharacters (allowedCharacters);
  37653. if (! isMultiLine())
  37654. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  37655. else
  37656. newText = newText.replace (T("\r\n"), T("\n"));
  37657. const int newCaretPos = selectionStart + newText.length();
  37658. const int insertIndex = selectionStart;
  37659. remove (selectionStart, selectionEnd,
  37660. &undoManager,
  37661. newCaretPos);
  37662. if (maxTextLength > 0)
  37663. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  37664. if (newText.isNotEmpty())
  37665. insert (newText,
  37666. insertIndex,
  37667. currentFont,
  37668. findColour (textColourId),
  37669. &undoManager,
  37670. newCaretPos);
  37671. textChanged();
  37672. }
  37673. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  37674. {
  37675. moveCursorTo (startPos, false);
  37676. moveCursorTo (startPos + numChars, true);
  37677. }
  37678. void TextEditor::copy()
  37679. {
  37680. const String selection (getTextSubstring (selectionStart, selectionEnd));
  37681. if (selection.isNotEmpty())
  37682. SystemClipboard::copyTextToClipboard (selection);
  37683. }
  37684. void TextEditor::paste()
  37685. {
  37686. if (! isReadOnly())
  37687. {
  37688. const String clip (SystemClipboard::getTextFromClipboard());
  37689. if (clip.isNotEmpty())
  37690. insertTextAtCursor (clip);
  37691. }
  37692. }
  37693. void TextEditor::cut()
  37694. {
  37695. if (! isReadOnly())
  37696. {
  37697. moveCaret (selectionEnd);
  37698. insertTextAtCursor (String::empty);
  37699. }
  37700. }
  37701. void TextEditor::drawContent (Graphics& g)
  37702. {
  37703. const float wordWrapWidth = getWordWrapWidth();
  37704. if (wordWrapWidth > 0)
  37705. {
  37706. g.setOrigin (leftIndent, topIndent);
  37707. const Rectangle clip (g.getClipBounds());
  37708. Colour selectedTextColour;
  37709. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37710. while (i.lineY + 200.0 < clip.getY() && i.next())
  37711. {}
  37712. if (selectionStart < selectionEnd)
  37713. {
  37714. g.setColour (findColour (highlightColourId)
  37715. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  37716. selectedTextColour = findColour (highlightedTextColourId);
  37717. TextEditorIterator i2 (i);
  37718. while (i2.next() && i2.lineY < clip.getBottom())
  37719. {
  37720. i2.updateLineHeight();
  37721. if (i2.lineY + i2.lineHeight >= clip.getY()
  37722. && selectionEnd >= i2.indexInText
  37723. && selectionStart <= i2.indexInText + i2.atom->numChars)
  37724. {
  37725. i2.drawSelection (g, selectionStart, selectionEnd);
  37726. }
  37727. }
  37728. }
  37729. const UniformTextSection* lastSection = 0;
  37730. while (i.next() && i.lineY < clip.getBottom())
  37731. {
  37732. i.updateLineHeight();
  37733. if (i.lineY + i.lineHeight >= clip.getY())
  37734. {
  37735. if (selectionEnd >= i.indexInText
  37736. && selectionStart <= i.indexInText + i.atom->numChars)
  37737. {
  37738. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  37739. lastSection = 0;
  37740. }
  37741. else
  37742. {
  37743. i.draw (g, lastSection);
  37744. }
  37745. }
  37746. }
  37747. }
  37748. }
  37749. void TextEditor::paint (Graphics& g)
  37750. {
  37751. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  37752. }
  37753. void TextEditor::paintOverChildren (Graphics& g)
  37754. {
  37755. if (caretFlashState
  37756. && hasKeyboardFocus (false)
  37757. && caretVisible
  37758. && ! isReadOnly())
  37759. {
  37760. g.setColour (findColour (caretColourId));
  37761. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  37762. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  37763. 2.0f, cursorHeight);
  37764. }
  37765. if (textToShowWhenEmpty.isNotEmpty()
  37766. && (! hasKeyboardFocus (false))
  37767. && getTotalNumChars() == 0)
  37768. {
  37769. g.setColour (colourForTextWhenEmpty);
  37770. g.setFont (getFont());
  37771. if (isMultiLine())
  37772. {
  37773. g.drawText (textToShowWhenEmpty,
  37774. 0, 0, getWidth(), getHeight(),
  37775. Justification::centred, true);
  37776. }
  37777. else
  37778. {
  37779. g.drawText (textToShowWhenEmpty,
  37780. leftIndent, topIndent,
  37781. viewport->getWidth() - leftIndent,
  37782. viewport->getHeight() - topIndent,
  37783. Justification::centredLeft, true);
  37784. }
  37785. }
  37786. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  37787. }
  37788. void TextEditor::mouseDown (const MouseEvent& e)
  37789. {
  37790. beginDragAutoRepeat (100);
  37791. newTransaction();
  37792. if (wasFocused || ! selectAllTextWhenFocused)
  37793. {
  37794. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37795. {
  37796. moveCursorTo (getTextIndexAt (e.x, e.y),
  37797. e.mods.isShiftDown());
  37798. }
  37799. else
  37800. {
  37801. PopupMenu m;
  37802. addPopupMenuItems (m, &e);
  37803. menuActive = true;
  37804. const int result = m.show();
  37805. menuActive = false;
  37806. if (result != 0)
  37807. performPopupMenuAction (result);
  37808. }
  37809. }
  37810. }
  37811. void TextEditor::mouseDrag (const MouseEvent& e)
  37812. {
  37813. if (wasFocused || ! selectAllTextWhenFocused)
  37814. {
  37815. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37816. {
  37817. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  37818. }
  37819. }
  37820. }
  37821. void TextEditor::mouseUp (const MouseEvent& e)
  37822. {
  37823. newTransaction();
  37824. textHolder->startTimer (flashSpeedIntervalMs);
  37825. if (wasFocused || ! selectAllTextWhenFocused)
  37826. {
  37827. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37828. {
  37829. moveCaret (getTextIndexAt (e.x, e.y));
  37830. }
  37831. }
  37832. wasFocused = true;
  37833. }
  37834. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  37835. {
  37836. int tokenEnd = getTextIndexAt (e.x, e.y);
  37837. int tokenStart = tokenEnd;
  37838. if (e.getNumberOfClicks() > 3)
  37839. {
  37840. tokenStart = 0;
  37841. tokenEnd = getTotalNumChars();
  37842. }
  37843. else
  37844. {
  37845. const String t (getText());
  37846. const int totalLength = getTotalNumChars();
  37847. while (tokenEnd < totalLength)
  37848. {
  37849. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  37850. ++tokenEnd;
  37851. else
  37852. break;
  37853. }
  37854. tokenStart = tokenEnd;
  37855. while (tokenStart > 0)
  37856. {
  37857. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  37858. --tokenStart;
  37859. else
  37860. break;
  37861. }
  37862. if (e.getNumberOfClicks() > 2)
  37863. {
  37864. while (tokenEnd < totalLength)
  37865. {
  37866. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  37867. ++tokenEnd;
  37868. else
  37869. break;
  37870. }
  37871. while (tokenStart > 0)
  37872. {
  37873. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  37874. --tokenStart;
  37875. else
  37876. break;
  37877. }
  37878. }
  37879. }
  37880. moveCursorTo (tokenEnd, false);
  37881. moveCursorTo (tokenStart, true);
  37882. }
  37883. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37884. {
  37885. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  37886. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37887. }
  37888. bool TextEditor::keyPressed (const KeyPress& key)
  37889. {
  37890. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  37891. return false;
  37892. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37893. if (key.isKeyCode (KeyPress::leftKey)
  37894. || key.isKeyCode (KeyPress::upKey))
  37895. {
  37896. newTransaction();
  37897. int newPos;
  37898. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  37899. newPos = indexAtPosition (cursorX, cursorY - 1);
  37900. else if (moveInWholeWordSteps)
  37901. newPos = findWordBreakBefore (getCaretPosition());
  37902. else
  37903. newPos = getCaretPosition() - 1;
  37904. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  37905. }
  37906. else if (key.isKeyCode (KeyPress::rightKey)
  37907. || key.isKeyCode (KeyPress::downKey))
  37908. {
  37909. newTransaction();
  37910. int newPos;
  37911. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  37912. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  37913. else if (moveInWholeWordSteps)
  37914. newPos = findWordBreakAfter (getCaretPosition());
  37915. else
  37916. newPos = getCaretPosition() + 1;
  37917. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  37918. }
  37919. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  37920. {
  37921. newTransaction();
  37922. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  37923. key.getModifiers().isShiftDown());
  37924. }
  37925. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  37926. {
  37927. newTransaction();
  37928. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  37929. key.getModifiers().isShiftDown());
  37930. }
  37931. else if (key.isKeyCode (KeyPress::homeKey))
  37932. {
  37933. newTransaction();
  37934. if (isMultiLine() && ! moveInWholeWordSteps)
  37935. moveCursorTo (indexAtPosition (0.0f, cursorY),
  37936. key.getModifiers().isShiftDown());
  37937. else
  37938. moveCursorTo (0, key.getModifiers().isShiftDown());
  37939. }
  37940. else if (key.isKeyCode (KeyPress::endKey))
  37941. {
  37942. newTransaction();
  37943. if (isMultiLine() && ! moveInWholeWordSteps)
  37944. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  37945. key.getModifiers().isShiftDown());
  37946. else
  37947. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  37948. }
  37949. else if (key.isKeyCode (KeyPress::backspaceKey))
  37950. {
  37951. if (moveInWholeWordSteps)
  37952. {
  37953. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  37954. }
  37955. else
  37956. {
  37957. if (selectionStart == selectionEnd && selectionStart > 0)
  37958. --selectionStart;
  37959. }
  37960. cut();
  37961. }
  37962. else if (key.isKeyCode (KeyPress::deleteKey))
  37963. {
  37964. if (key.getModifiers().isShiftDown())
  37965. copy();
  37966. if (selectionStart == selectionEnd
  37967. && selectionEnd < getTotalNumChars())
  37968. {
  37969. ++selectionEnd;
  37970. }
  37971. cut();
  37972. }
  37973. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  37974. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  37975. {
  37976. newTransaction();
  37977. copy();
  37978. }
  37979. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  37980. {
  37981. newTransaction();
  37982. copy();
  37983. cut();
  37984. }
  37985. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  37986. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  37987. {
  37988. newTransaction();
  37989. paste();
  37990. }
  37991. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  37992. {
  37993. newTransaction();
  37994. doUndoRedo (false);
  37995. }
  37996. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  37997. {
  37998. newTransaction();
  37999. doUndoRedo (true);
  38000. }
  38001. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  38002. {
  38003. newTransaction();
  38004. moveCursorTo (getTotalNumChars(), false);
  38005. moveCursorTo (0, true);
  38006. }
  38007. else if (key == KeyPress::returnKey)
  38008. {
  38009. newTransaction();
  38010. if (returnKeyStartsNewLine)
  38011. insertTextAtCursor (T("\n"));
  38012. else
  38013. returnPressed();
  38014. }
  38015. else if (key.isKeyCode (KeyPress::escapeKey))
  38016. {
  38017. newTransaction();
  38018. moveCursorTo (getCaretPosition(), false);
  38019. escapePressed();
  38020. }
  38021. else if (key.getTextCharacter() >= ' '
  38022. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  38023. {
  38024. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  38025. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38026. }
  38027. else
  38028. {
  38029. return false;
  38030. }
  38031. return true;
  38032. }
  38033. bool TextEditor::keyStateChanged()
  38034. {
  38035. // (overridden to avoid forwarding key events to the parent)
  38036. return true;
  38037. }
  38038. const int baseMenuItemID = 0x7fff0000;
  38039. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  38040. {
  38041. const bool writable = ! isReadOnly();
  38042. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  38043. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  38044. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  38045. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  38046. m.addSeparator();
  38047. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  38048. m.addSeparator();
  38049. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  38050. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  38051. }
  38052. void TextEditor::performPopupMenuAction (const int menuItemID)
  38053. {
  38054. switch (menuItemID)
  38055. {
  38056. case baseMenuItemID + 1:
  38057. copy();
  38058. cut();
  38059. break;
  38060. case baseMenuItemID + 2:
  38061. copy();
  38062. break;
  38063. case baseMenuItemID + 3:
  38064. paste();
  38065. break;
  38066. case baseMenuItemID + 4:
  38067. cut();
  38068. break;
  38069. case baseMenuItemID + 5:
  38070. moveCursorTo (getTotalNumChars(), false);
  38071. moveCursorTo (0, true);
  38072. break;
  38073. case baseMenuItemID + 6:
  38074. doUndoRedo (false);
  38075. break;
  38076. case baseMenuItemID + 7:
  38077. doUndoRedo (true);
  38078. break;
  38079. default:
  38080. break;
  38081. }
  38082. }
  38083. void TextEditor::focusGained (FocusChangeType)
  38084. {
  38085. newTransaction();
  38086. caretFlashState = true;
  38087. if (selectAllTextWhenFocused)
  38088. {
  38089. moveCursorTo (0, false);
  38090. moveCursorTo (getTotalNumChars(), true);
  38091. }
  38092. repaint();
  38093. if (caretVisible)
  38094. textHolder->startTimer (flashSpeedIntervalMs);
  38095. }
  38096. void TextEditor::focusLost (FocusChangeType)
  38097. {
  38098. newTransaction();
  38099. wasFocused = false;
  38100. textHolder->stopTimer();
  38101. caretFlashState = false;
  38102. postCommandMessage (focusLossMessageId);
  38103. repaint();
  38104. }
  38105. void TextEditor::resized()
  38106. {
  38107. viewport->setBoundsInset (borderSize);
  38108. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  38109. updateTextHolderSize();
  38110. if (! isMultiLine())
  38111. {
  38112. scrollToMakeSureCursorIsVisible();
  38113. }
  38114. else
  38115. {
  38116. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  38117. getCharPosition (caretPosition,
  38118. cursorX, cursorY,
  38119. cursorHeight);
  38120. }
  38121. }
  38122. void TextEditor::handleCommandMessage (const int commandId)
  38123. {
  38124. const ComponentDeletionWatcher deletionChecker (this);
  38125. for (int i = listeners.size(); --i >= 0;)
  38126. {
  38127. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  38128. if (tl != 0)
  38129. {
  38130. switch (commandId)
  38131. {
  38132. case textChangeMessageId:
  38133. tl->textEditorTextChanged (*this);
  38134. break;
  38135. case returnKeyMessageId:
  38136. tl->textEditorReturnKeyPressed (*this);
  38137. break;
  38138. case escapeKeyMessageId:
  38139. tl->textEditorEscapeKeyPressed (*this);
  38140. break;
  38141. case focusLossMessageId:
  38142. tl->textEditorFocusLost (*this);
  38143. break;
  38144. default:
  38145. jassertfalse
  38146. break;
  38147. }
  38148. if (i > 0 && deletionChecker.hasBeenDeleted())
  38149. return;
  38150. }
  38151. }
  38152. }
  38153. void TextEditor::enablementChanged()
  38154. {
  38155. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  38156. : MouseCursor::IBeamCursor));
  38157. repaint();
  38158. }
  38159. void TextEditor::clearInternal (UndoManager* const um) throw()
  38160. {
  38161. remove (0, getTotalNumChars(), um, caretPosition);
  38162. }
  38163. void TextEditor::insert (const String& text,
  38164. const int insertIndex,
  38165. const Font& font,
  38166. const Colour& colour,
  38167. UndoManager* const um,
  38168. const int caretPositionToMoveTo) throw()
  38169. {
  38170. if (text.isNotEmpty())
  38171. {
  38172. if (um != 0)
  38173. {
  38174. um->perform (new TextEditorInsertAction (*this,
  38175. text,
  38176. insertIndex,
  38177. font,
  38178. colour,
  38179. caretPosition,
  38180. caretPositionToMoveTo));
  38181. }
  38182. else
  38183. {
  38184. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  38185. // a line gets moved due to word wrap
  38186. int index = 0;
  38187. int nextIndex = 0;
  38188. for (int i = 0; i < sections.size(); ++i)
  38189. {
  38190. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38191. if (insertIndex == index)
  38192. {
  38193. sections.insert (i, new UniformTextSection (text,
  38194. font, colour,
  38195. passwordCharacter));
  38196. break;
  38197. }
  38198. else if (insertIndex > index && insertIndex < nextIndex)
  38199. {
  38200. splitSection (i, insertIndex - index);
  38201. sections.insert (i + 1, new UniformTextSection (text,
  38202. font, colour,
  38203. passwordCharacter));
  38204. break;
  38205. }
  38206. index = nextIndex;
  38207. }
  38208. if (nextIndex == insertIndex)
  38209. sections.add (new UniformTextSection (text,
  38210. font, colour,
  38211. passwordCharacter));
  38212. coalesceSimilarSections();
  38213. totalNumChars = -1;
  38214. moveCursorTo (caretPositionToMoveTo, false);
  38215. repaintText (insertIndex, -1);
  38216. }
  38217. }
  38218. }
  38219. void TextEditor::reinsert (const int insertIndex,
  38220. const VoidArray& sectionsToInsert) throw()
  38221. {
  38222. int index = 0;
  38223. int nextIndex = 0;
  38224. for (int i = 0; i < sections.size(); ++i)
  38225. {
  38226. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38227. if (insertIndex == index)
  38228. {
  38229. for (int j = sectionsToInsert.size(); --j >= 0;)
  38230. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38231. break;
  38232. }
  38233. else if (insertIndex > index && insertIndex < nextIndex)
  38234. {
  38235. splitSection (i, insertIndex - index);
  38236. for (int j = sectionsToInsert.size(); --j >= 0;)
  38237. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38238. break;
  38239. }
  38240. index = nextIndex;
  38241. }
  38242. if (nextIndex == insertIndex)
  38243. {
  38244. for (int j = 0; j < sectionsToInsert.size(); ++j)
  38245. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38246. }
  38247. coalesceSimilarSections();
  38248. totalNumChars = -1;
  38249. }
  38250. void TextEditor::remove (const int startIndex,
  38251. int endIndex,
  38252. UndoManager* const um,
  38253. const int caretPositionToMoveTo) throw()
  38254. {
  38255. if (endIndex > startIndex)
  38256. {
  38257. int index = 0;
  38258. for (int i = 0; i < sections.size(); ++i)
  38259. {
  38260. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  38261. if (startIndex > index && startIndex < nextIndex)
  38262. {
  38263. splitSection (i, startIndex - index);
  38264. --i;
  38265. }
  38266. else if (endIndex > index && endIndex < nextIndex)
  38267. {
  38268. splitSection (i, endIndex - index);
  38269. --i;
  38270. }
  38271. else
  38272. {
  38273. index = nextIndex;
  38274. if (index > endIndex)
  38275. break;
  38276. }
  38277. }
  38278. index = 0;
  38279. if (um != 0)
  38280. {
  38281. VoidArray removedSections;
  38282. for (int i = 0; i < sections.size(); ++i)
  38283. {
  38284. if (endIndex <= startIndex)
  38285. break;
  38286. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38287. const int nextIndex = index + section->getTotalLength();
  38288. if (startIndex <= index && endIndex >= nextIndex)
  38289. removedSections.add (new UniformTextSection (*section));
  38290. index = nextIndex;
  38291. }
  38292. um->perform (new TextEditorRemoveAction (*this,
  38293. startIndex,
  38294. endIndex,
  38295. caretPosition,
  38296. caretPositionToMoveTo,
  38297. removedSections));
  38298. }
  38299. else
  38300. {
  38301. for (int i = 0; i < sections.size(); ++i)
  38302. {
  38303. if (endIndex <= startIndex)
  38304. break;
  38305. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38306. const int nextIndex = index + section->getTotalLength();
  38307. if (startIndex <= index && endIndex >= nextIndex)
  38308. {
  38309. sections.remove(i);
  38310. endIndex -= (nextIndex - index);
  38311. section->clear();
  38312. delete section;
  38313. --i;
  38314. }
  38315. else
  38316. {
  38317. index = nextIndex;
  38318. }
  38319. }
  38320. coalesceSimilarSections();
  38321. totalNumChars = -1;
  38322. moveCursorTo (caretPositionToMoveTo, false);
  38323. repaintText (startIndex, -1);
  38324. }
  38325. }
  38326. }
  38327. const String TextEditor::getText() const throw()
  38328. {
  38329. String t;
  38330. for (int i = 0; i < sections.size(); ++i)
  38331. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  38332. return t;
  38333. }
  38334. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  38335. {
  38336. String t;
  38337. int index = 0;
  38338. for (int i = 0; i < sections.size(); ++i)
  38339. {
  38340. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  38341. const int nextIndex = index + s->getTotalLength();
  38342. if (startCharacter < nextIndex)
  38343. {
  38344. if (endCharacter <= index)
  38345. break;
  38346. const int start = jmax (index, startCharacter);
  38347. t += s->getTextSubstring (start - index, endCharacter - index);
  38348. }
  38349. index = nextIndex;
  38350. }
  38351. return t;
  38352. }
  38353. const String TextEditor::getHighlightedText() const throw()
  38354. {
  38355. return getTextSubstring (getHighlightedRegionStart(),
  38356. getHighlightedRegionStart() + getHighlightedRegionLength());
  38357. }
  38358. int TextEditor::getTotalNumChars() throw()
  38359. {
  38360. if (totalNumChars < 0)
  38361. {
  38362. totalNumChars = 0;
  38363. for (int i = sections.size(); --i >= 0;)
  38364. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38365. }
  38366. return totalNumChars;
  38367. }
  38368. bool TextEditor::isEmpty() const throw()
  38369. {
  38370. if (totalNumChars != 0)
  38371. {
  38372. for (int i = sections.size(); --i >= 0;)
  38373. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  38374. return false;
  38375. }
  38376. return true;
  38377. }
  38378. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  38379. {
  38380. const float wordWrapWidth = getWordWrapWidth();
  38381. if (wordWrapWidth > 0 && sections.size() > 0)
  38382. {
  38383. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38384. i.getCharPosition (index, cx, cy, lineHeight);
  38385. }
  38386. else
  38387. {
  38388. cx = cy = 0;
  38389. lineHeight = currentFont.getHeight();
  38390. }
  38391. }
  38392. int TextEditor::indexAtPosition (const float x, const float y) throw()
  38393. {
  38394. const float wordWrapWidth = getWordWrapWidth();
  38395. if (wordWrapWidth > 0)
  38396. {
  38397. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38398. while (i.next())
  38399. {
  38400. if (i.lineY + getHeight() > y)
  38401. i.updateLineHeight();
  38402. if (i.lineY + i.lineHeight > y)
  38403. {
  38404. if (i.lineY > y)
  38405. return jmax (0, i.indexInText - 1);
  38406. if (i.atomX >= x)
  38407. return i.indexInText;
  38408. if (x < i.atomRight)
  38409. return i.xToIndex (x);
  38410. }
  38411. }
  38412. }
  38413. return getTotalNumChars();
  38414. }
  38415. static int getCharacterCategory (const tchar character) throw()
  38416. {
  38417. return CharacterFunctions::isLetterOrDigit (character)
  38418. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  38419. }
  38420. int TextEditor::findWordBreakAfter (const int position) const throw()
  38421. {
  38422. const String t (getTextSubstring (position, position + 512));
  38423. const int totalLength = t.length();
  38424. int i = 0;
  38425. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38426. ++i;
  38427. const int type = getCharacterCategory (t[i]);
  38428. while (i < totalLength && type == getCharacterCategory (t[i]))
  38429. ++i;
  38430. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38431. ++i;
  38432. return position + i;
  38433. }
  38434. int TextEditor::findWordBreakBefore (const int position) const throw()
  38435. {
  38436. if (position <= 0)
  38437. return 0;
  38438. const int startOfBuffer = jmax (0, position - 512);
  38439. const String t (getTextSubstring (startOfBuffer, position));
  38440. int i = position - startOfBuffer;
  38441. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  38442. --i;
  38443. if (i > 0)
  38444. {
  38445. const int type = getCharacterCategory (t [i - 1]);
  38446. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  38447. --i;
  38448. }
  38449. jassert (startOfBuffer + i >= 0);
  38450. return startOfBuffer + i;
  38451. }
  38452. void TextEditor::splitSection (const int sectionIndex,
  38453. const int charToSplitAt) throw()
  38454. {
  38455. jassert (sections[sectionIndex] != 0);
  38456. sections.insert (sectionIndex + 1,
  38457. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  38458. ->split (charToSplitAt, passwordCharacter));
  38459. }
  38460. void TextEditor::coalesceSimilarSections() throw()
  38461. {
  38462. for (int i = 0; i < sections.size() - 1; ++i)
  38463. {
  38464. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  38465. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  38466. if (s1->font == s2->font
  38467. && s1->colour == s2->colour)
  38468. {
  38469. s1->append (*s2, passwordCharacter);
  38470. sections.remove (i + 1);
  38471. delete s2;
  38472. --i;
  38473. }
  38474. }
  38475. }
  38476. END_JUCE_NAMESPACE
  38477. /********* End of inlined file: juce_TextEditor.cpp *********/
  38478. /********* Start of inlined file: juce_Toolbar.cpp *********/
  38479. BEGIN_JUCE_NAMESPACE
  38480. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  38481. class ToolbarSpacerComp : public ToolbarItemComponent
  38482. {
  38483. public:
  38484. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  38485. : ToolbarItemComponent (itemId, String::empty, false),
  38486. fixedSize (fixedSize_),
  38487. drawBar (drawBar_)
  38488. {
  38489. }
  38490. ~ToolbarSpacerComp()
  38491. {
  38492. }
  38493. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  38494. int& preferredSize, int& minSize, int& maxSize)
  38495. {
  38496. if (fixedSize <= 0)
  38497. {
  38498. preferredSize = toolbarThickness * 2;
  38499. minSize = 4;
  38500. maxSize = 32768;
  38501. }
  38502. else
  38503. {
  38504. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  38505. minSize = drawBar ? maxSize : jmin (4, maxSize);
  38506. preferredSize = maxSize;
  38507. if (getEditingMode() == editableOnPalette)
  38508. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  38509. }
  38510. return true;
  38511. }
  38512. void paintButtonArea (Graphics&, int, int, bool, bool)
  38513. {
  38514. }
  38515. void contentAreaChanged (const Rectangle&)
  38516. {
  38517. }
  38518. int getResizeOrder() const throw()
  38519. {
  38520. return fixedSize <= 0 ? 0 : 1;
  38521. }
  38522. void paint (Graphics& g)
  38523. {
  38524. const int w = getWidth();
  38525. const int h = getHeight();
  38526. if (drawBar)
  38527. {
  38528. g.setColour (findColour (Toolbar::separatorColourId, true));
  38529. const float thickness = 0.2f;
  38530. if (isToolbarVertical())
  38531. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  38532. else
  38533. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  38534. }
  38535. if (getEditingMode() != normalMode && ! drawBar)
  38536. {
  38537. g.setColour (findColour (Toolbar::separatorColourId, true));
  38538. const int indentX = jmin (2, (w - 3) / 2);
  38539. const int indentY = jmin (2, (h - 3) / 2);
  38540. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  38541. if (fixedSize <= 0)
  38542. {
  38543. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  38544. if (isToolbarVertical())
  38545. {
  38546. x1 = w * 0.5f;
  38547. y1 = h * 0.4f;
  38548. x2 = x1;
  38549. y2 = indentX * 2.0f;
  38550. x3 = x1;
  38551. y3 = h * 0.6f;
  38552. x4 = x1;
  38553. y4 = h - y2;
  38554. hw = w * 0.15f;
  38555. hl = w * 0.2f;
  38556. }
  38557. else
  38558. {
  38559. x1 = w * 0.4f;
  38560. y1 = h * 0.5f;
  38561. x2 = indentX * 2.0f;
  38562. y2 = y1;
  38563. x3 = w * 0.6f;
  38564. y3 = y1;
  38565. x4 = w - x2;
  38566. y4 = y1;
  38567. hw = h * 0.15f;
  38568. hl = h * 0.2f;
  38569. }
  38570. Path p;
  38571. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  38572. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  38573. g.fillPath (p);
  38574. }
  38575. }
  38576. }
  38577. juce_UseDebuggingNewOperator
  38578. private:
  38579. const float fixedSize;
  38580. const bool drawBar;
  38581. ToolbarSpacerComp (const ToolbarSpacerComp&);
  38582. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  38583. };
  38584. class MissingItemsComponent : public PopupMenuCustomComponent
  38585. {
  38586. public:
  38587. MissingItemsComponent (Toolbar& owner_, const int height_)
  38588. : PopupMenuCustomComponent (true),
  38589. owner (owner_),
  38590. height (height_)
  38591. {
  38592. for (int i = owner_.getNumChildComponents(); --i >= 0;)
  38593. {
  38594. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (owner_.getChildComponent (i));
  38595. if (tc != 0 && dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  38596. {
  38597. oldIndexes.insert (0, i);
  38598. addAndMakeVisible (tc, 0);
  38599. }
  38600. }
  38601. layout (400);
  38602. }
  38603. ~MissingItemsComponent()
  38604. {
  38605. // deleting the toolbar while its menu it open??
  38606. jassert (owner.isValidComponent());
  38607. for (int i = 0; i < getNumChildComponents(); ++i)
  38608. {
  38609. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38610. if (tc != 0)
  38611. {
  38612. tc->setVisible (false);
  38613. owner.addChildComponent (tc, oldIndexes.remove (i));
  38614. --i;
  38615. }
  38616. }
  38617. owner.resized();
  38618. }
  38619. void layout (const int preferredWidth)
  38620. {
  38621. const int indent = 8;
  38622. int x = indent;
  38623. int y = indent;
  38624. int maxX = 0;
  38625. for (int i = 0; i < getNumChildComponents(); ++i)
  38626. {
  38627. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38628. if (tc != 0)
  38629. {
  38630. int preferredSize = 1, minSize = 1, maxSize = 1;
  38631. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  38632. {
  38633. if (x + preferredSize > preferredWidth && x > indent)
  38634. {
  38635. x = indent;
  38636. y += height;
  38637. }
  38638. tc->setBounds (x, y, preferredSize, height);
  38639. x += preferredSize;
  38640. maxX = jmax (maxX, x);
  38641. }
  38642. }
  38643. }
  38644. setSize (maxX + 8, y + height + 8);
  38645. }
  38646. void getIdealSize (int& idealWidth, int& idealHeight)
  38647. {
  38648. idealWidth = getWidth();
  38649. idealHeight = getHeight();
  38650. }
  38651. juce_UseDebuggingNewOperator
  38652. private:
  38653. Toolbar& owner;
  38654. const int height;
  38655. Array <int> oldIndexes;
  38656. MissingItemsComponent (const MissingItemsComponent&);
  38657. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  38658. };
  38659. Toolbar::Toolbar()
  38660. : vertical (false),
  38661. isEditingActive (false),
  38662. toolbarStyle (Toolbar::iconsOnly)
  38663. {
  38664. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  38665. missingItemsButton->setAlwaysOnTop (true);
  38666. missingItemsButton->addButtonListener (this);
  38667. }
  38668. Toolbar::~Toolbar()
  38669. {
  38670. animator.cancelAllAnimations (true);
  38671. deleteAllChildren();
  38672. }
  38673. void Toolbar::setVertical (const bool shouldBeVertical)
  38674. {
  38675. if (vertical != shouldBeVertical)
  38676. {
  38677. vertical = shouldBeVertical;
  38678. resized();
  38679. }
  38680. }
  38681. void Toolbar::clear()
  38682. {
  38683. for (int i = getNumChildComponents(); --i >= 0;)
  38684. {
  38685. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38686. if (tc != 0)
  38687. delete tc;
  38688. }
  38689. resized();
  38690. }
  38691. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  38692. {
  38693. if (itemId == ToolbarItemFactory::separatorBarId)
  38694. return new ToolbarSpacerComp (itemId, 0.1f, true);
  38695. else if (itemId == ToolbarItemFactory::spacerId)
  38696. return new ToolbarSpacerComp (itemId, 0.5f, false);
  38697. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  38698. return new ToolbarSpacerComp (itemId, 0, false);
  38699. return factory.createItem (itemId);
  38700. }
  38701. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  38702. const int itemId,
  38703. const int insertIndex)
  38704. {
  38705. // An ID can't be zero - this might indicate a mistake somewhere?
  38706. jassert (itemId != 0);
  38707. ToolbarItemComponent* const tc = createItem (factory, itemId);
  38708. if (tc != 0)
  38709. {
  38710. #ifdef JUCE_DEBUG
  38711. Array <int> allowedIds;
  38712. factory.getAllToolbarItemIds (allowedIds);
  38713. // If your factory can create an item for a given ID, it must also return
  38714. // that ID from its getAllToolbarItemIds() method!
  38715. jassert (allowedIds.contains (itemId));
  38716. #endif
  38717. addAndMakeVisible (tc, insertIndex);
  38718. }
  38719. }
  38720. void Toolbar::addItem (ToolbarItemFactory& factory,
  38721. const int itemId,
  38722. const int insertIndex)
  38723. {
  38724. addItemInternal (factory, itemId, insertIndex);
  38725. resized();
  38726. }
  38727. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  38728. {
  38729. Array <int> ids;
  38730. factoryToUse.getDefaultItemSet (ids);
  38731. clear();
  38732. for (int i = 0; i < ids.size(); ++i)
  38733. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  38734. resized();
  38735. }
  38736. void Toolbar::removeToolbarItem (const int itemIndex)
  38737. {
  38738. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38739. if (tc != 0)
  38740. {
  38741. delete tc;
  38742. resized();
  38743. }
  38744. }
  38745. int Toolbar::getNumItems() const throw()
  38746. {
  38747. return getNumChildComponents() - 1;
  38748. }
  38749. int Toolbar::getItemId (const int itemIndex) const throw()
  38750. {
  38751. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38752. return tc != 0 ? tc->getItemId() : 0;
  38753. }
  38754. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  38755. {
  38756. if (itemIndex < getNumItems())
  38757. return dynamic_cast <ToolbarItemComponent*> (getChildComponent (itemIndex));
  38758. return 0;
  38759. }
  38760. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  38761. {
  38762. for (;;)
  38763. {
  38764. index += delta;
  38765. ToolbarItemComponent* const tc = getItemComponent (index);
  38766. if (tc == 0)
  38767. break;
  38768. if (tc->isActive)
  38769. return tc;
  38770. }
  38771. return 0;
  38772. }
  38773. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  38774. {
  38775. if (toolbarStyle != newStyle)
  38776. {
  38777. toolbarStyle = newStyle;
  38778. updateAllItemPositions (false);
  38779. }
  38780. }
  38781. const String Toolbar::toString() const
  38782. {
  38783. String s (T("TB:"));
  38784. for (int i = 0; i < getNumItems(); ++i)
  38785. s << getItemId(i) << T(' ');
  38786. return s.trimEnd();
  38787. }
  38788. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  38789. const String& savedVersion)
  38790. {
  38791. if (! savedVersion.startsWith (T("TB:")))
  38792. return false;
  38793. StringArray tokens;
  38794. tokens.addTokens (savedVersion.substring (3), false);
  38795. clear();
  38796. for (int i = 0; i < tokens.size(); ++i)
  38797. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  38798. resized();
  38799. return true;
  38800. }
  38801. void Toolbar::paint (Graphics& g)
  38802. {
  38803. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  38804. }
  38805. int Toolbar::getThickness() const throw()
  38806. {
  38807. return vertical ? getWidth() : getHeight();
  38808. }
  38809. int Toolbar::getLength() const throw()
  38810. {
  38811. return vertical ? getHeight() : getWidth();
  38812. }
  38813. void Toolbar::setEditingActive (const bool active)
  38814. {
  38815. if (isEditingActive != active)
  38816. {
  38817. isEditingActive = active;
  38818. updateAllItemPositions (false);
  38819. }
  38820. }
  38821. void Toolbar::resized()
  38822. {
  38823. updateAllItemPositions (false);
  38824. }
  38825. void Toolbar::updateAllItemPositions (const bool animate)
  38826. {
  38827. if (getWidth() > 0 && getHeight() > 0)
  38828. {
  38829. StretchableObjectResizer resizer;
  38830. const int numComponents = getNumChildComponents();
  38831. Array <ToolbarItemComponent*> activeComps;
  38832. int i;
  38833. for (i = 0; i < numComponents; ++i)
  38834. {
  38835. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38836. // have you added a component directly to the toolbar? That's not advisable! Only use addCustomToolbarItem()!
  38837. jassert (tc != 0 || getChildComponent(i) == missingItemsButton);
  38838. if (tc != 0)
  38839. {
  38840. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  38841. : ToolbarItemComponent::normalMode);
  38842. tc->setStyle (toolbarStyle);
  38843. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  38844. int preferredSize = 1, minSize = 1, maxSize = 1;
  38845. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  38846. preferredSize, minSize, maxSize))
  38847. {
  38848. tc->isActive = true;
  38849. resizer.addItem (preferredSize, minSize, maxSize,
  38850. spacer != 0 ? spacer->getResizeOrder() : 2);
  38851. }
  38852. else
  38853. {
  38854. tc->isActive = false;
  38855. tc->setVisible (false);
  38856. }
  38857. }
  38858. }
  38859. resizer.resizeToFit (getLength());
  38860. int totalLength = 0;
  38861. for (i = 0; i < resizer.getNumItems(); ++i)
  38862. totalLength += (int) resizer.getItemSize (i);
  38863. const bool itemsOffTheEnd = totalLength > getLength();
  38864. const int extrasButtonSize = getThickness() / 2;
  38865. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  38866. missingItemsButton->setVisible (itemsOffTheEnd);
  38867. missingItemsButton->setEnabled (! isEditingActive);
  38868. if (vertical)
  38869. missingItemsButton->setCentrePosition (getWidth() / 2,
  38870. getHeight() - 4 - extrasButtonSize / 2);
  38871. else
  38872. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  38873. getHeight() / 2);
  38874. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  38875. : missingItemsButton->getX()) - 4
  38876. : getLength();
  38877. int pos = 0, activeIndex = 0;
  38878. for (i = 0; i < getNumChildComponents(); ++i)
  38879. {
  38880. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38881. if (tc != 0 && tc->isActive)
  38882. {
  38883. const int size = (int) resizer.getItemSize (activeIndex++);
  38884. Rectangle newBounds;
  38885. if (vertical)
  38886. newBounds.setBounds (0, pos, getWidth(), size);
  38887. else
  38888. newBounds.setBounds (pos, 0, size, getHeight());
  38889. if (animate)
  38890. {
  38891. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  38892. }
  38893. else
  38894. {
  38895. animator.cancelAnimation (tc, false);
  38896. tc->setBounds (newBounds);
  38897. }
  38898. pos += size;
  38899. tc->setVisible (pos <= maxLength
  38900. && ((! tc->isBeingDragged)
  38901. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  38902. }
  38903. }
  38904. }
  38905. }
  38906. void Toolbar::buttonClicked (Button*)
  38907. {
  38908. jassert (missingItemsButton->isShowing());
  38909. if (missingItemsButton->isShowing())
  38910. {
  38911. PopupMenu m;
  38912. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  38913. m.showAt (missingItemsButton);
  38914. }
  38915. }
  38916. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  38917. Component* /*sourceComponent*/)
  38918. {
  38919. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  38920. }
  38921. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  38922. {
  38923. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  38924. if (tc != 0)
  38925. {
  38926. if (getNumItems() == 0)
  38927. {
  38928. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  38929. {
  38930. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  38931. if (palette != 0)
  38932. palette->replaceComponent (tc);
  38933. }
  38934. else
  38935. {
  38936. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  38937. }
  38938. addChildComponent (tc);
  38939. updateAllItemPositions (false);
  38940. }
  38941. else
  38942. {
  38943. for (int i = getNumItems(); --i >= 0;)
  38944. {
  38945. int currentIndex = getIndexOfChildComponent (tc);
  38946. if (currentIndex < 0)
  38947. {
  38948. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  38949. {
  38950. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  38951. if (palette != 0)
  38952. palette->replaceComponent (tc);
  38953. }
  38954. else
  38955. {
  38956. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  38957. }
  38958. addChildComponent (tc);
  38959. currentIndex = getIndexOfChildComponent (tc);
  38960. updateAllItemPositions (true);
  38961. }
  38962. int newIndex = currentIndex;
  38963. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  38964. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  38965. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  38966. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  38967. if (prev != 0)
  38968. {
  38969. const Rectangle previousPos (animator.getComponentDestination (prev));
  38970. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  38971. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  38972. {
  38973. newIndex = getIndexOfChildComponent (prev);
  38974. }
  38975. }
  38976. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  38977. if (next != 0)
  38978. {
  38979. const Rectangle nextPos (animator.getComponentDestination (next));
  38980. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  38981. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  38982. {
  38983. newIndex = getIndexOfChildComponent (next) + 1;
  38984. }
  38985. }
  38986. if (newIndex != currentIndex)
  38987. {
  38988. removeChildComponent (tc);
  38989. addChildComponent (tc, newIndex);
  38990. updateAllItemPositions (true);
  38991. }
  38992. else
  38993. {
  38994. break;
  38995. }
  38996. }
  38997. }
  38998. }
  38999. }
  39000. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  39001. {
  39002. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39003. if (tc != 0)
  39004. {
  39005. if (isParentOf (tc))
  39006. {
  39007. removeChildComponent (tc);
  39008. updateAllItemPositions (true);
  39009. }
  39010. }
  39011. }
  39012. void Toolbar::itemDropped (const String&, Component*, int, int)
  39013. {
  39014. }
  39015. void Toolbar::mouseDown (const MouseEvent& e)
  39016. {
  39017. if (e.mods.isPopupMenu())
  39018. {
  39019. }
  39020. }
  39021. class ToolbarCustomisationDialog : public DialogWindow
  39022. {
  39023. public:
  39024. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  39025. Toolbar* const toolbar_,
  39026. const int optionFlags)
  39027. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  39028. toolbar (toolbar_)
  39029. {
  39030. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  39031. setResizable (true, true);
  39032. setResizeLimits (400, 300, 1500, 1000);
  39033. positionNearBar();
  39034. }
  39035. ~ToolbarCustomisationDialog()
  39036. {
  39037. setContentComponent (0, true);
  39038. }
  39039. void closeButtonPressed()
  39040. {
  39041. setVisible (false);
  39042. }
  39043. bool canModalEventBeSentToComponent (const Component* comp)
  39044. {
  39045. return toolbar->isParentOf (comp);
  39046. }
  39047. void positionNearBar()
  39048. {
  39049. const Rectangle screenSize (toolbar->getParentMonitorArea());
  39050. const int tbx = toolbar->getScreenX();
  39051. const int tby = toolbar->getScreenY();
  39052. const int gap = 8;
  39053. int x, y;
  39054. if (toolbar->isVertical())
  39055. {
  39056. y = tby;
  39057. if (tbx > screenSize.getCentreX())
  39058. x = tbx - getWidth() - gap;
  39059. else
  39060. x = tbx + toolbar->getWidth() + gap;
  39061. }
  39062. else
  39063. {
  39064. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  39065. if (tby > screenSize.getCentreY())
  39066. y = tby - getHeight() - gap;
  39067. else
  39068. y = tby + toolbar->getHeight() + gap;
  39069. }
  39070. setTopLeftPosition (x, y);
  39071. }
  39072. private:
  39073. Toolbar* const toolbar;
  39074. class CustomiserPanel : public Component,
  39075. private ComboBoxListener,
  39076. private ButtonListener
  39077. {
  39078. public:
  39079. CustomiserPanel (ToolbarItemFactory& factory_,
  39080. Toolbar* const toolbar_,
  39081. const int optionFlags)
  39082. : factory (factory_),
  39083. toolbar (toolbar_),
  39084. styleBox (0),
  39085. defaultButton (0)
  39086. {
  39087. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  39088. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  39089. | Toolbar::allowIconsWithTextChoice
  39090. | Toolbar::allowTextOnlyChoice)) != 0)
  39091. {
  39092. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  39093. styleBox->setEditableText (false);
  39094. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  39095. styleBox->addItem (TRANS("Show icons only"), 1);
  39096. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  39097. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  39098. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  39099. styleBox->addItem (TRANS("Show descriptions only"), 3);
  39100. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  39101. styleBox->setSelectedId (1);
  39102. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  39103. styleBox->setSelectedId (2);
  39104. else if (toolbar_->getStyle() == Toolbar::textOnly)
  39105. styleBox->setSelectedId (3);
  39106. styleBox->addListener (this);
  39107. }
  39108. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  39109. {
  39110. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  39111. defaultButton->addButtonListener (this);
  39112. }
  39113. addAndMakeVisible (instructions = new Label (String::empty,
  39114. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  39115. instructions->setFont (Font (13.0f));
  39116. setSize (500, 300);
  39117. }
  39118. ~CustomiserPanel()
  39119. {
  39120. deleteAllChildren();
  39121. }
  39122. void comboBoxChanged (ComboBox*)
  39123. {
  39124. if (styleBox->getSelectedId() == 1)
  39125. toolbar->setStyle (Toolbar::iconsOnly);
  39126. else if (styleBox->getSelectedId() == 2)
  39127. toolbar->setStyle (Toolbar::iconsWithText);
  39128. else if (styleBox->getSelectedId() == 3)
  39129. toolbar->setStyle (Toolbar::textOnly);
  39130. palette->resized(); // to make it update the styles
  39131. }
  39132. void buttonClicked (Button*)
  39133. {
  39134. toolbar->addDefaultItems (factory);
  39135. }
  39136. void paint (Graphics& g)
  39137. {
  39138. Colour background;
  39139. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  39140. if (dw != 0)
  39141. background = dw->getBackgroundColour();
  39142. g.setColour (background.contrasting().withAlpha (0.3f));
  39143. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  39144. }
  39145. void resized()
  39146. {
  39147. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  39148. if (styleBox != 0)
  39149. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  39150. if (defaultButton != 0)
  39151. {
  39152. defaultButton->changeWidthToFitText (22);
  39153. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  39154. }
  39155. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  39156. }
  39157. private:
  39158. ToolbarItemFactory& factory;
  39159. Toolbar* const toolbar;
  39160. Label* instructions;
  39161. ToolbarItemPalette* palette;
  39162. ComboBox* styleBox;
  39163. TextButton* defaultButton;
  39164. };
  39165. };
  39166. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  39167. {
  39168. setEditingActive (true);
  39169. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  39170. dw.runModalLoop();
  39171. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  39172. setEditingActive (false);
  39173. }
  39174. END_JUCE_NAMESPACE
  39175. /********* End of inlined file: juce_Toolbar.cpp *********/
  39176. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  39177. BEGIN_JUCE_NAMESPACE
  39178. ToolbarItemFactory::ToolbarItemFactory()
  39179. {
  39180. }
  39181. ToolbarItemFactory::~ToolbarItemFactory()
  39182. {
  39183. }
  39184. class ItemDragAndDropOverlayComponent : public Component
  39185. {
  39186. public:
  39187. ItemDragAndDropOverlayComponent()
  39188. : isDragging (false)
  39189. {
  39190. setAlwaysOnTop (true);
  39191. setRepaintsOnMouseActivity (true);
  39192. setMouseCursor (MouseCursor::DraggingHandCursor);
  39193. }
  39194. ~ItemDragAndDropOverlayComponent()
  39195. {
  39196. }
  39197. void paint (Graphics& g)
  39198. {
  39199. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39200. if (isMouseOverOrDragging()
  39201. && tc != 0
  39202. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39203. {
  39204. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  39205. g.drawRect (0, 0, getWidth(), getHeight(),
  39206. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  39207. }
  39208. }
  39209. void mouseDown (const MouseEvent& e)
  39210. {
  39211. isDragging = false;
  39212. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39213. if (tc != 0)
  39214. {
  39215. tc->dragOffsetX = e.x;
  39216. tc->dragOffsetY = e.y;
  39217. }
  39218. }
  39219. void mouseDrag (const MouseEvent& e)
  39220. {
  39221. if (! (isDragging || e.mouseWasClicked()))
  39222. {
  39223. isDragging = true;
  39224. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  39225. if (dnd != 0)
  39226. {
  39227. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  39228. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39229. if (tc != 0)
  39230. {
  39231. tc->isBeingDragged = true;
  39232. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39233. tc->setVisible (false);
  39234. }
  39235. }
  39236. }
  39237. }
  39238. void mouseUp (const MouseEvent&)
  39239. {
  39240. isDragging = false;
  39241. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39242. if (tc != 0)
  39243. {
  39244. tc->isBeingDragged = false;
  39245. Toolbar* const tb = tc->getToolbar();
  39246. if (tb != 0)
  39247. tb->updateAllItemPositions (true);
  39248. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39249. delete tc;
  39250. }
  39251. }
  39252. void parentSizeChanged()
  39253. {
  39254. setBounds (0, 0, getParentWidth(), getParentHeight());
  39255. }
  39256. juce_UseDebuggingNewOperator
  39257. private:
  39258. bool isDragging;
  39259. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  39260. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  39261. };
  39262. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  39263. const String& labelText,
  39264. const bool isBeingUsedAsAButton_)
  39265. : Button (labelText),
  39266. itemId (itemId_),
  39267. mode (normalMode),
  39268. toolbarStyle (Toolbar::iconsOnly),
  39269. overlayComp (0),
  39270. dragOffsetX (0),
  39271. dragOffsetY (0),
  39272. isActive (true),
  39273. isBeingDragged (false),
  39274. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  39275. {
  39276. // Your item ID can't be 0!
  39277. jassert (itemId_ != 0);
  39278. }
  39279. ToolbarItemComponent::~ToolbarItemComponent()
  39280. {
  39281. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39282. delete overlayComp;
  39283. }
  39284. Toolbar* ToolbarItemComponent::getToolbar() const
  39285. {
  39286. return dynamic_cast <Toolbar*> (getParentComponent());
  39287. }
  39288. bool ToolbarItemComponent::isToolbarVertical() const
  39289. {
  39290. const Toolbar* const t = getToolbar();
  39291. return t != 0 && t->isVertical();
  39292. }
  39293. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  39294. {
  39295. if (toolbarStyle != newStyle)
  39296. {
  39297. toolbarStyle = newStyle;
  39298. repaint();
  39299. resized();
  39300. }
  39301. }
  39302. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  39303. {
  39304. if (isBeingUsedAsAButton)
  39305. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  39306. isMouseOver, isMouseDown, *this);
  39307. if (toolbarStyle != Toolbar::iconsOnly)
  39308. {
  39309. const int indent = contentArea.getX();
  39310. int y = indent;
  39311. int h = getHeight() - indent * 2;
  39312. if (toolbarStyle == Toolbar::iconsWithText)
  39313. {
  39314. y = contentArea.getBottom() + indent / 2;
  39315. h -= contentArea.getHeight();
  39316. }
  39317. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  39318. getButtonText(), *this);
  39319. }
  39320. if (! contentArea.isEmpty())
  39321. {
  39322. g.saveState();
  39323. g.setOrigin (contentArea.getX(), contentArea.getY());
  39324. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  39325. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  39326. g.restoreState();
  39327. }
  39328. }
  39329. void ToolbarItemComponent::resized()
  39330. {
  39331. if (toolbarStyle != Toolbar::textOnly)
  39332. {
  39333. const int indent = jmin (proportionOfWidth (0.08f),
  39334. proportionOfHeight (0.08f));
  39335. contentArea = Rectangle (indent, indent,
  39336. getWidth() - indent * 2,
  39337. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  39338. : (getHeight() - indent * 2));
  39339. }
  39340. else
  39341. {
  39342. contentArea = Rectangle();
  39343. }
  39344. contentAreaChanged (contentArea);
  39345. }
  39346. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  39347. {
  39348. if (mode != newMode)
  39349. {
  39350. mode = newMode;
  39351. repaint();
  39352. if (mode == normalMode)
  39353. {
  39354. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39355. delete overlayComp;
  39356. overlayComp = 0;
  39357. }
  39358. else if (overlayComp == 0)
  39359. {
  39360. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  39361. overlayComp->parentSizeChanged();
  39362. }
  39363. resized();
  39364. }
  39365. }
  39366. END_JUCE_NAMESPACE
  39367. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  39368. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  39369. BEGIN_JUCE_NAMESPACE
  39370. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  39371. Toolbar* const toolbar_)
  39372. : factory (factory_),
  39373. toolbar (toolbar_)
  39374. {
  39375. Component* const itemHolder = new Component();
  39376. Array <int> allIds;
  39377. factory_.getAllToolbarItemIds (allIds);
  39378. for (int i = 0; i < allIds.size(); ++i)
  39379. {
  39380. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  39381. jassert (tc != 0);
  39382. if (tc != 0)
  39383. {
  39384. itemHolder->addAndMakeVisible (tc);
  39385. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  39386. }
  39387. }
  39388. viewport = new Viewport();
  39389. viewport->setViewedComponent (itemHolder);
  39390. addAndMakeVisible (viewport);
  39391. }
  39392. ToolbarItemPalette::~ToolbarItemPalette()
  39393. {
  39394. viewport->getViewedComponent()->deleteAllChildren();
  39395. deleteAllChildren();
  39396. }
  39397. void ToolbarItemPalette::resized()
  39398. {
  39399. viewport->setBoundsInset (BorderSize (1));
  39400. Component* const itemHolder = viewport->getViewedComponent();
  39401. const int indent = 8;
  39402. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  39403. const int height = toolbar->getThickness();
  39404. int x = indent;
  39405. int y = indent;
  39406. int maxX = 0;
  39407. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  39408. {
  39409. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  39410. if (tc != 0)
  39411. {
  39412. tc->setStyle (toolbar->getStyle());
  39413. int preferredSize = 1, minSize = 1, maxSize = 1;
  39414. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39415. {
  39416. if (x + preferredSize > preferredWidth && x > indent)
  39417. {
  39418. x = indent;
  39419. y += height;
  39420. }
  39421. tc->setBounds (x, y, preferredSize, height);
  39422. x += preferredSize + 8;
  39423. maxX = jmax (maxX, x);
  39424. }
  39425. }
  39426. }
  39427. itemHolder->setSize (maxX, y + height + 8);
  39428. }
  39429. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  39430. {
  39431. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  39432. jassert (tc != 0);
  39433. if (tc != 0)
  39434. {
  39435. tc->setBounds (comp->getBounds());
  39436. tc->setStyle (toolbar->getStyle());
  39437. tc->setEditingMode (comp->getEditingMode());
  39438. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  39439. }
  39440. }
  39441. END_JUCE_NAMESPACE
  39442. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  39443. /********* Start of inlined file: juce_TreeView.cpp *********/
  39444. BEGIN_JUCE_NAMESPACE
  39445. class TreeViewContentComponent : public Component
  39446. {
  39447. public:
  39448. TreeViewContentComponent (TreeView* const owner_)
  39449. : owner (owner_),
  39450. isDragging (false)
  39451. {
  39452. }
  39453. ~TreeViewContentComponent()
  39454. {
  39455. deleteAllChildren();
  39456. }
  39457. void mouseDown (const MouseEvent& e)
  39458. {
  39459. isDragging = false;
  39460. needSelectionOnMouseUp = false;
  39461. Rectangle pos;
  39462. TreeViewItem* const item = findItemAt (e.y, pos);
  39463. if (item != 0 && e.x >= pos.getX())
  39464. {
  39465. if (! owner->isMultiSelectEnabled())
  39466. item->setSelected (true, true);
  39467. else if (item->isSelected())
  39468. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  39469. else
  39470. selectBasedOnModifiers (item, e.mods);
  39471. MouseEvent e2 (e);
  39472. e2.x -= pos.getX();
  39473. e2.y -= pos.getY();
  39474. item->itemClicked (e2);
  39475. }
  39476. }
  39477. void mouseUp (const MouseEvent& e)
  39478. {
  39479. Rectangle pos;
  39480. TreeViewItem* const item = findItemAt (e.y, pos);
  39481. if (item != 0 && e.mouseWasClicked())
  39482. {
  39483. if (needSelectionOnMouseUp)
  39484. {
  39485. selectBasedOnModifiers (item, e.mods);
  39486. }
  39487. else if (e.mouseWasClicked())
  39488. {
  39489. if (e.x >= pos.getX() - owner->getIndentSize()
  39490. && e.x < pos.getX())
  39491. {
  39492. item->setOpen (! item->isOpen());
  39493. }
  39494. }
  39495. }
  39496. }
  39497. void mouseDoubleClick (const MouseEvent& e)
  39498. {
  39499. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  39500. {
  39501. Rectangle pos;
  39502. TreeViewItem* const item = findItemAt (e.y, pos);
  39503. if (item != 0 && e.x >= pos.getX())
  39504. {
  39505. MouseEvent e2 (e);
  39506. e2.x -= pos.getX();
  39507. e2.y -= pos.getY();
  39508. item->itemDoubleClicked (e2);
  39509. }
  39510. }
  39511. }
  39512. void mouseDrag (const MouseEvent& e)
  39513. {
  39514. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  39515. {
  39516. isDragging = true;
  39517. Rectangle pos;
  39518. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  39519. if (item != 0 && e.getMouseDownX() >= pos.getX())
  39520. {
  39521. const String dragDescription (item->getDragSourceDescription());
  39522. if (dragDescription.isNotEmpty())
  39523. {
  39524. DragAndDropContainer* const dragContainer
  39525. = DragAndDropContainer::findParentDragContainerFor (this);
  39526. if (dragContainer != 0)
  39527. {
  39528. pos.setSize (pos.getWidth(), item->itemHeight);
  39529. Image* dragImage = Component::createComponentSnapshot (pos, true);
  39530. dragImage->multiplyAllAlphas (0.6f);
  39531. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  39532. }
  39533. else
  39534. {
  39535. // to be able to do a drag-and-drop operation, the treeview needs to
  39536. // be inside a component which is also a DragAndDropContainer.
  39537. jassertfalse
  39538. }
  39539. }
  39540. }
  39541. }
  39542. }
  39543. void paint (Graphics& g);
  39544. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  39545. void updateComponents()
  39546. {
  39547. int xAdjust = 0, yAdjust = 0;
  39548. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  39549. {
  39550. yAdjust = owner->rootItem->itemHeight;
  39551. xAdjust = owner->getIndentSize();
  39552. }
  39553. const int visibleTop = -getY();
  39554. const int visibleBottom = visibleTop + getParentHeight();
  39555. BitArray itemsToKeep;
  39556. TreeViewItem* item = owner->rootItem;
  39557. int y = -yAdjust;
  39558. while (item != 0 && y < visibleBottom)
  39559. {
  39560. y += item->itemHeight;
  39561. if (y >= visibleTop)
  39562. {
  39563. const int index = rowComponentIds.indexOf (item->uid);
  39564. if (index < 0)
  39565. {
  39566. Component* const comp = item->createItemComponent();
  39567. if (comp != 0)
  39568. {
  39569. addAndMakeVisible (comp);
  39570. itemsToKeep.setBit (rowComponentItems.size());
  39571. rowComponentItems.add (item);
  39572. rowComponentIds.add (item->uid);
  39573. rowComponents.add (comp);
  39574. }
  39575. }
  39576. else
  39577. {
  39578. itemsToKeep.setBit (index);
  39579. }
  39580. }
  39581. item = item->getNextVisibleItem (true);
  39582. }
  39583. for (int i = rowComponentItems.size(); --i >= 0;)
  39584. {
  39585. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  39586. bool keep = false;
  39587. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  39588. && isParentOf (comp))
  39589. {
  39590. if (itemsToKeep[i])
  39591. {
  39592. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  39593. Rectangle pos (item->getItemPosition (false));
  39594. pos.translate (-xAdjust, -yAdjust);
  39595. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  39596. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  39597. {
  39598. keep = true;
  39599. comp->setBounds (pos);
  39600. }
  39601. }
  39602. else
  39603. {
  39604. comp->setSize (0, 0);
  39605. }
  39606. }
  39607. if (! keep)
  39608. {
  39609. delete comp;
  39610. rowComponents.remove (i);
  39611. rowComponentIds.remove (i);
  39612. rowComponentItems.remove (i);
  39613. }
  39614. }
  39615. }
  39616. void resized()
  39617. {
  39618. owner->itemsChanged();
  39619. }
  39620. juce_UseDebuggingNewOperator
  39621. private:
  39622. TreeView* const owner;
  39623. VoidArray rowComponentItems;
  39624. Array <int> rowComponentIds;
  39625. VoidArray rowComponents;
  39626. bool isDragging, needSelectionOnMouseUp;
  39627. TreeViewContentComponent (const TreeViewContentComponent&);
  39628. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  39629. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  39630. {
  39631. TreeViewItem* firstSelected = 0;
  39632. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  39633. {
  39634. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  39635. jassert (lastSelected != 0);
  39636. int rowStart = firstSelected->getRowNumberInTree();
  39637. int rowEnd = lastSelected->getRowNumberInTree();
  39638. if (rowStart > rowEnd)
  39639. swapVariables (rowStart, rowEnd);
  39640. int ourRow = item->getRowNumberInTree();
  39641. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  39642. if (ourRow > otherEnd)
  39643. swapVariables (ourRow, otherEnd);
  39644. for (int i = ourRow; i <= otherEnd; ++i)
  39645. owner->getItemOnRow (i)->setSelected (true, false);
  39646. }
  39647. else
  39648. {
  39649. const bool cmd = modifiers.isCommandDown();
  39650. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  39651. }
  39652. }
  39653. };
  39654. class TreeViewport : public Viewport
  39655. {
  39656. public:
  39657. TreeViewport() throw() {}
  39658. ~TreeViewport() throw() {}
  39659. void updateComponents()
  39660. {
  39661. if (getViewedComponent() != 0)
  39662. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  39663. repaint();
  39664. }
  39665. void visibleAreaChanged (int, int, int, int)
  39666. {
  39667. updateComponents();
  39668. }
  39669. juce_UseDebuggingNewOperator
  39670. private:
  39671. TreeViewport (const TreeViewport&);
  39672. const TreeViewport& operator= (const TreeViewport&);
  39673. };
  39674. TreeView::TreeView (const String& componentName)
  39675. : Component (componentName),
  39676. rootItem (0),
  39677. indentSize (24),
  39678. defaultOpenness (false),
  39679. needsRecalculating (true),
  39680. rootItemVisible (true),
  39681. multiSelectEnabled (false)
  39682. {
  39683. addAndMakeVisible (viewport = new TreeViewport());
  39684. viewport->setViewedComponent (new TreeViewContentComponent (this));
  39685. viewport->setWantsKeyboardFocus (false);
  39686. setWantsKeyboardFocus (true);
  39687. }
  39688. TreeView::~TreeView()
  39689. {
  39690. if (rootItem != 0)
  39691. rootItem->setOwnerView (0);
  39692. deleteAllChildren();
  39693. }
  39694. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  39695. {
  39696. if (rootItem != newRootItem)
  39697. {
  39698. if (newRootItem != 0)
  39699. {
  39700. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  39701. if (newRootItem->ownerView != 0)
  39702. newRootItem->ownerView->setRootItem (0);
  39703. }
  39704. if (rootItem != 0)
  39705. rootItem->setOwnerView (0);
  39706. rootItem = newRootItem;
  39707. if (newRootItem != 0)
  39708. newRootItem->setOwnerView (this);
  39709. needsRecalculating = true;
  39710. handleAsyncUpdate();
  39711. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39712. {
  39713. rootItem->setOpen (false); // force a re-open
  39714. rootItem->setOpen (true);
  39715. }
  39716. }
  39717. }
  39718. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  39719. {
  39720. rootItemVisible = shouldBeVisible;
  39721. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39722. {
  39723. rootItem->setOpen (false); // force a re-open
  39724. rootItem->setOpen (true);
  39725. }
  39726. itemsChanged();
  39727. }
  39728. void TreeView::colourChanged()
  39729. {
  39730. setOpaque (findColour (backgroundColourId).isOpaque());
  39731. repaint();
  39732. }
  39733. void TreeView::setIndentSize (const int newIndentSize)
  39734. {
  39735. if (indentSize != newIndentSize)
  39736. {
  39737. indentSize = newIndentSize;
  39738. resized();
  39739. }
  39740. }
  39741. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  39742. {
  39743. if (defaultOpenness != isOpenByDefault)
  39744. {
  39745. defaultOpenness = isOpenByDefault;
  39746. itemsChanged();
  39747. }
  39748. }
  39749. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  39750. {
  39751. multiSelectEnabled = canMultiSelect;
  39752. }
  39753. void TreeView::clearSelectedItems()
  39754. {
  39755. if (rootItem != 0)
  39756. rootItem->deselectAllRecursively();
  39757. }
  39758. int TreeView::getNumSelectedItems() const throw()
  39759. {
  39760. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  39761. }
  39762. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  39763. {
  39764. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  39765. }
  39766. int TreeView::getNumRowsInTree() const
  39767. {
  39768. if (rootItem != 0)
  39769. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  39770. return 0;
  39771. }
  39772. TreeViewItem* TreeView::getItemOnRow (int index) const
  39773. {
  39774. if (! rootItemVisible)
  39775. ++index;
  39776. if (rootItem != 0 && index >= 0)
  39777. return rootItem->getItemOnRow (index);
  39778. return 0;
  39779. }
  39780. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  39781. {
  39782. XmlElement* e = 0;
  39783. if (rootItem != 0)
  39784. {
  39785. e = rootItem->createXmlOpenness();
  39786. if (e != 0 && alsoIncludeScrollPosition)
  39787. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  39788. }
  39789. return e;
  39790. }
  39791. void TreeView::restoreOpennessState (const XmlElement& newState)
  39792. {
  39793. if (rootItem != 0)
  39794. {
  39795. rootItem->restoreFromXml (newState);
  39796. if (newState.hasAttribute (T("scrollPos")))
  39797. viewport->setViewPosition (viewport->getViewPositionX(),
  39798. newState.getIntAttribute (T("scrollPos")));
  39799. }
  39800. }
  39801. void TreeView::paint (Graphics& g)
  39802. {
  39803. g.fillAll (findColour (backgroundColourId));
  39804. }
  39805. void TreeView::resized()
  39806. {
  39807. viewport->setBounds (0, 0, getWidth(), getHeight());
  39808. itemsChanged();
  39809. }
  39810. void TreeView::moveSelectedRow (int delta)
  39811. {
  39812. int rowSelected = 0;
  39813. TreeViewItem* const firstSelected = getSelectedItem (0);
  39814. if (firstSelected != 0)
  39815. rowSelected = firstSelected->getRowNumberInTree();
  39816. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  39817. TreeViewItem* item = getItemOnRow (rowSelected);
  39818. if (item != 0)
  39819. {
  39820. item->setSelected (true, true);
  39821. scrollToKeepItemVisible (item);
  39822. }
  39823. }
  39824. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  39825. {
  39826. if (item != 0 && item->ownerView == this)
  39827. {
  39828. handleAsyncUpdate();
  39829. item = item->getDeepestOpenParentItem();
  39830. int y = item->y;
  39831. if (! rootItemVisible)
  39832. y -= rootItem->itemHeight;
  39833. int viewTop = viewport->getViewPositionY();
  39834. if (y < viewTop)
  39835. {
  39836. viewport->setViewPosition (viewport->getViewPositionX(), y);
  39837. }
  39838. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  39839. {
  39840. viewport->setViewPosition (viewport->getViewPositionX(),
  39841. (y + item->itemHeight) - viewport->getViewHeight());
  39842. }
  39843. }
  39844. }
  39845. bool TreeView::keyPressed (const KeyPress& key)
  39846. {
  39847. if (key.isKeyCode (KeyPress::upKey))
  39848. {
  39849. moveSelectedRow (-1);
  39850. }
  39851. else if (key.isKeyCode (KeyPress::downKey))
  39852. {
  39853. moveSelectedRow (1);
  39854. }
  39855. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  39856. {
  39857. if (rootItem != 0)
  39858. {
  39859. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  39860. if (key.isKeyCode (KeyPress::pageUpKey))
  39861. rowsOnScreen = -rowsOnScreen;
  39862. moveSelectedRow (rowsOnScreen);
  39863. }
  39864. }
  39865. else if (key.isKeyCode (KeyPress::homeKey))
  39866. {
  39867. moveSelectedRow (-0x3fffffff);
  39868. }
  39869. else if (key.isKeyCode (KeyPress::endKey))
  39870. {
  39871. moveSelectedRow (0x3fffffff);
  39872. }
  39873. else if (key.isKeyCode (KeyPress::returnKey))
  39874. {
  39875. TreeViewItem* const firstSelected = getSelectedItem (0);
  39876. if (firstSelected != 0)
  39877. firstSelected->setOpen (! firstSelected->isOpen());
  39878. }
  39879. else if (key.isKeyCode (KeyPress::leftKey))
  39880. {
  39881. TreeViewItem* const firstSelected = getSelectedItem (0);
  39882. if (firstSelected != 0)
  39883. {
  39884. if (firstSelected->isOpen())
  39885. {
  39886. firstSelected->setOpen (false);
  39887. }
  39888. else
  39889. {
  39890. TreeViewItem* parent = firstSelected->parentItem;
  39891. if ((! rootItemVisible) && parent == rootItem)
  39892. parent = 0;
  39893. if (parent != 0)
  39894. {
  39895. parent->setSelected (true, true);
  39896. scrollToKeepItemVisible (parent);
  39897. }
  39898. }
  39899. }
  39900. }
  39901. else if (key.isKeyCode (KeyPress::rightKey))
  39902. {
  39903. TreeViewItem* const firstSelected = getSelectedItem (0);
  39904. if (firstSelected != 0)
  39905. {
  39906. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  39907. moveSelectedRow (1);
  39908. else
  39909. firstSelected->setOpen (true);
  39910. }
  39911. }
  39912. else
  39913. {
  39914. return false;
  39915. }
  39916. return true;
  39917. }
  39918. void TreeView::itemsChanged() throw()
  39919. {
  39920. needsRecalculating = true;
  39921. repaint();
  39922. triggerAsyncUpdate();
  39923. }
  39924. void TreeView::handleAsyncUpdate()
  39925. {
  39926. if (needsRecalculating)
  39927. {
  39928. needsRecalculating = false;
  39929. const ScopedLock sl (nodeAlterationLock);
  39930. if (rootItem != 0)
  39931. rootItem->updatePositions (0);
  39932. ((TreeViewport*) viewport)->updateComponents();
  39933. if (rootItem != 0)
  39934. {
  39935. viewport->getViewedComponent()
  39936. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  39937. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  39938. }
  39939. else
  39940. {
  39941. viewport->getViewedComponent()->setSize (0, 0);
  39942. }
  39943. }
  39944. }
  39945. void TreeViewContentComponent::paint (Graphics& g)
  39946. {
  39947. if (owner->rootItem != 0)
  39948. {
  39949. owner->handleAsyncUpdate();
  39950. int w = getWidth();
  39951. if (! owner->rootItemVisible)
  39952. {
  39953. const int indentWidth = owner->getIndentSize();
  39954. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  39955. w += indentWidth;
  39956. }
  39957. owner->rootItem->paintRecursively (g, w);
  39958. }
  39959. }
  39960. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  39961. {
  39962. if (owner->rootItem != 0)
  39963. {
  39964. owner->handleAsyncUpdate();
  39965. if (! owner->rootItemVisible)
  39966. y += owner->rootItem->itemHeight;
  39967. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  39968. if (ti != 0)
  39969. {
  39970. itemPosition = ti->getItemPosition (false);
  39971. if (! owner->rootItemVisible)
  39972. itemPosition.translate (-owner->getIndentSize(),
  39973. -owner->rootItem->itemHeight);
  39974. }
  39975. return ti;
  39976. }
  39977. return 0;
  39978. }
  39979. #define opennessDefault 0
  39980. #define opennessClosed 1
  39981. #define opennessOpen 2
  39982. TreeViewItem::TreeViewItem()
  39983. : ownerView (0),
  39984. parentItem (0),
  39985. subItems (8),
  39986. y (0),
  39987. itemHeight (0),
  39988. totalHeight (0),
  39989. selected (false),
  39990. redrawNeeded (true),
  39991. drawLinesInside (true),
  39992. openness (opennessDefault)
  39993. {
  39994. static int nextUID = 0;
  39995. uid = nextUID++;
  39996. }
  39997. TreeViewItem::~TreeViewItem()
  39998. {
  39999. }
  40000. const String TreeViewItem::getUniqueName() const
  40001. {
  40002. return String::empty;
  40003. }
  40004. void TreeViewItem::itemOpennessChanged (bool)
  40005. {
  40006. }
  40007. int TreeViewItem::getNumSubItems() const throw()
  40008. {
  40009. return subItems.size();
  40010. }
  40011. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  40012. {
  40013. return subItems [index];
  40014. }
  40015. void TreeViewItem::clearSubItems()
  40016. {
  40017. if (subItems.size() > 0)
  40018. {
  40019. if (ownerView != 0)
  40020. {
  40021. const ScopedLock sl (ownerView->nodeAlterationLock);
  40022. subItems.clear();
  40023. treeHasChanged();
  40024. }
  40025. else
  40026. {
  40027. subItems.clear();
  40028. }
  40029. }
  40030. }
  40031. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  40032. {
  40033. if (newItem != 0)
  40034. {
  40035. newItem->parentItem = this;
  40036. newItem->setOwnerView (ownerView);
  40037. newItem->y = 0;
  40038. newItem->itemHeight = newItem->getItemHeight();
  40039. newItem->totalHeight = 0;
  40040. newItem->itemWidth = newItem->getItemWidth();
  40041. newItem->totalWidth = 0;
  40042. if (ownerView != 0)
  40043. {
  40044. const ScopedLock sl (ownerView->nodeAlterationLock);
  40045. subItems.insert (insertPosition, newItem);
  40046. treeHasChanged();
  40047. if (newItem->isOpen())
  40048. newItem->itemOpennessChanged (true);
  40049. }
  40050. else
  40051. {
  40052. subItems.insert (insertPosition, newItem);
  40053. if (newItem->isOpen())
  40054. newItem->itemOpennessChanged (true);
  40055. }
  40056. }
  40057. }
  40058. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  40059. {
  40060. if (ownerView != 0)
  40061. ownerView->nodeAlterationLock.enter();
  40062. if (((unsigned int) index) < (unsigned int) subItems.size())
  40063. {
  40064. subItems.remove (index, deleteItem);
  40065. treeHasChanged();
  40066. }
  40067. if (ownerView != 0)
  40068. ownerView->nodeAlterationLock.exit();
  40069. }
  40070. bool TreeViewItem::isOpen() const throw()
  40071. {
  40072. if (openness == opennessDefault)
  40073. return ownerView != 0 && ownerView->defaultOpenness;
  40074. else
  40075. return openness == opennessOpen;
  40076. }
  40077. void TreeViewItem::setOpen (const bool shouldBeOpen)
  40078. {
  40079. if (isOpen() != shouldBeOpen)
  40080. {
  40081. openness = shouldBeOpen ? opennessOpen
  40082. : opennessClosed;
  40083. treeHasChanged();
  40084. itemOpennessChanged (isOpen());
  40085. }
  40086. }
  40087. bool TreeViewItem::isSelected() const throw()
  40088. {
  40089. return selected;
  40090. }
  40091. void TreeViewItem::deselectAllRecursively()
  40092. {
  40093. setSelected (false, false);
  40094. for (int i = 0; i < subItems.size(); ++i)
  40095. subItems.getUnchecked(i)->deselectAllRecursively();
  40096. }
  40097. void TreeViewItem::setSelected (const bool shouldBeSelected,
  40098. const bool deselectOtherItemsFirst)
  40099. {
  40100. if (deselectOtherItemsFirst)
  40101. getTopLevelItem()->deselectAllRecursively();
  40102. if (shouldBeSelected != selected)
  40103. {
  40104. selected = shouldBeSelected;
  40105. if (ownerView != 0)
  40106. ownerView->repaint();
  40107. itemSelectionChanged (shouldBeSelected);
  40108. }
  40109. }
  40110. void TreeViewItem::paintItem (Graphics&, int, int)
  40111. {
  40112. }
  40113. void TreeViewItem::itemClicked (const MouseEvent&)
  40114. {
  40115. }
  40116. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  40117. {
  40118. if (mightContainSubItems())
  40119. setOpen (! isOpen());
  40120. }
  40121. void TreeViewItem::itemSelectionChanged (bool)
  40122. {
  40123. }
  40124. const String TreeViewItem::getDragSourceDescription()
  40125. {
  40126. return String::empty;
  40127. }
  40128. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  40129. {
  40130. const int indentX = getIndentX();
  40131. int width = itemWidth;
  40132. if (ownerView != 0 && width < 0)
  40133. width = ownerView->viewport->getViewWidth() - indentX;
  40134. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  40135. if (relativeToTreeViewTopLeft)
  40136. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  40137. r.getY() - ownerView->viewport->getViewPositionY());
  40138. return r;
  40139. }
  40140. void TreeViewItem::treeHasChanged() const throw()
  40141. {
  40142. if (ownerView != 0)
  40143. ownerView->itemsChanged();
  40144. }
  40145. void TreeViewItem::updatePositions (int newY)
  40146. {
  40147. y = newY;
  40148. itemHeight = getItemHeight();
  40149. totalHeight = itemHeight;
  40150. itemWidth = getItemWidth();
  40151. totalWidth = jmax (itemWidth, 0);
  40152. if (isOpen())
  40153. {
  40154. const int ourIndent = getIndentX();
  40155. newY += totalHeight;
  40156. for (int i = 0; i < subItems.size(); ++i)
  40157. {
  40158. TreeViewItem* const ti = subItems.getUnchecked(i);
  40159. ti->updatePositions (newY);
  40160. newY += ti->totalHeight;
  40161. totalHeight += ti->totalHeight;
  40162. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  40163. }
  40164. }
  40165. }
  40166. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  40167. {
  40168. TreeViewItem* result = this;
  40169. TreeViewItem* item = this;
  40170. while (item->parentItem != 0)
  40171. {
  40172. item = item->parentItem;
  40173. if (! item->isOpen())
  40174. result = item;
  40175. }
  40176. return result;
  40177. }
  40178. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  40179. {
  40180. ownerView = newOwner;
  40181. for (int i = subItems.size(); --i >= 0;)
  40182. subItems.getUnchecked(i)->setOwnerView (newOwner);
  40183. }
  40184. int TreeViewItem::getIndentX() const throw()
  40185. {
  40186. const int indentWidth = ownerView->getIndentSize();
  40187. int x = indentWidth;
  40188. TreeViewItem* p = parentItem;
  40189. while (p != 0)
  40190. {
  40191. x += indentWidth;
  40192. p = p->parentItem;
  40193. }
  40194. return x;
  40195. }
  40196. void TreeViewItem::paintRecursively (Graphics& g, int width)
  40197. {
  40198. jassert (ownerView != 0);
  40199. if (ownerView == 0)
  40200. return;
  40201. const int indent = getIndentX();
  40202. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  40203. g.setColour (ownerView->findColour (TreeView::linesColourId));
  40204. const float halfH = itemHeight * 0.5f;
  40205. int depth = 0;
  40206. TreeViewItem* p = parentItem;
  40207. while (p != 0)
  40208. {
  40209. ++depth;
  40210. p = p->parentItem;
  40211. }
  40212. const int indentWidth = ownerView->getIndentSize();
  40213. float x = (depth + 0.5f) * indentWidth;
  40214. if (x > 0)
  40215. {
  40216. if (depth >= 0)
  40217. {
  40218. if (parentItem != 0 && parentItem->drawLinesInside)
  40219. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  40220. if ((parentItem != 0 && parentItem->drawLinesInside)
  40221. || (parentItem == 0 && drawLinesInside))
  40222. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  40223. }
  40224. p = parentItem;
  40225. int d = depth;
  40226. while (p != 0 && --d >= 0)
  40227. {
  40228. x -= (float) indentWidth;
  40229. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  40230. && ! p->isLastOfSiblings())
  40231. {
  40232. g.drawLine (x, 0, x, (float) itemHeight);
  40233. }
  40234. p = p->parentItem;
  40235. }
  40236. if (mightContainSubItems())
  40237. {
  40238. ownerView->getLookAndFeel()
  40239. .drawTreeviewPlusMinusBox (g,
  40240. depth * indentWidth, 0,
  40241. indentWidth, itemHeight,
  40242. ! isOpen());
  40243. }
  40244. }
  40245. {
  40246. g.saveState();
  40247. g.setOrigin (indent, 0);
  40248. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  40249. paintItem (g, itemW, itemHeight);
  40250. g.restoreState();
  40251. }
  40252. if (isOpen())
  40253. {
  40254. const Rectangle clip (g.getClipBounds());
  40255. for (int i = 0; i < subItems.size(); ++i)
  40256. {
  40257. TreeViewItem* const ti = subItems.getUnchecked(i);
  40258. const int relY = ti->y - y;
  40259. if (relY >= clip.getBottom())
  40260. break;
  40261. if (relY + ti->totalHeight >= clip.getY())
  40262. {
  40263. g.saveState();
  40264. g.setOrigin (0, relY);
  40265. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  40266. ti->paintRecursively (g, width);
  40267. g.restoreState();
  40268. }
  40269. }
  40270. }
  40271. }
  40272. bool TreeViewItem::isLastOfSiblings() const throw()
  40273. {
  40274. return parentItem == 0
  40275. || parentItem->subItems.getLast() == this;
  40276. }
  40277. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  40278. {
  40279. return (parentItem == 0) ? this
  40280. : parentItem->getTopLevelItem();
  40281. }
  40282. int TreeViewItem::getNumRows() const throw()
  40283. {
  40284. int num = 1;
  40285. if (isOpen())
  40286. {
  40287. for (int i = subItems.size(); --i >= 0;)
  40288. num += subItems.getUnchecked(i)->getNumRows();
  40289. }
  40290. return num;
  40291. }
  40292. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  40293. {
  40294. if (index == 0)
  40295. return this;
  40296. if (index > 0 && isOpen())
  40297. {
  40298. --index;
  40299. for (int i = 0; i < subItems.size(); ++i)
  40300. {
  40301. TreeViewItem* const item = subItems.getUnchecked(i);
  40302. if (index == 0)
  40303. return item;
  40304. const int numRows = item->getNumRows();
  40305. if (numRows > index)
  40306. return item->getItemOnRow (index);
  40307. index -= numRows;
  40308. }
  40309. }
  40310. return 0;
  40311. }
  40312. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  40313. {
  40314. if (((unsigned int) y) < (unsigned int) totalHeight)
  40315. {
  40316. const int h = itemHeight;
  40317. if (y < h)
  40318. return this;
  40319. if (isOpen())
  40320. {
  40321. y -= h;
  40322. for (int i = 0; i < subItems.size(); ++i)
  40323. {
  40324. TreeViewItem* const ti = subItems.getUnchecked(i);
  40325. if (ti->totalHeight >= y)
  40326. return ti->findItemRecursively (y);
  40327. y -= ti->totalHeight;
  40328. }
  40329. }
  40330. }
  40331. return 0;
  40332. }
  40333. int TreeViewItem::countSelectedItemsRecursively() const throw()
  40334. {
  40335. int total = 0;
  40336. if (isSelected())
  40337. ++total;
  40338. for (int i = subItems.size(); --i >= 0;)
  40339. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  40340. return total;
  40341. }
  40342. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  40343. {
  40344. if (isSelected())
  40345. {
  40346. if (index == 0)
  40347. return this;
  40348. --index;
  40349. }
  40350. if (index >= 0)
  40351. {
  40352. for (int i = 0; i < subItems.size(); ++i)
  40353. {
  40354. TreeViewItem* const item = subItems.getUnchecked(i);
  40355. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  40356. if (found != 0)
  40357. return found;
  40358. index -= item->countSelectedItemsRecursively();
  40359. }
  40360. }
  40361. return 0;
  40362. }
  40363. int TreeViewItem::getRowNumberInTree() const throw()
  40364. {
  40365. if (parentItem != 0 && ownerView != 0)
  40366. {
  40367. int n = 1 + parentItem->getRowNumberInTree();
  40368. int ourIndex = parentItem->subItems.indexOf (this);
  40369. jassert (ourIndex >= 0);
  40370. while (--ourIndex >= 0)
  40371. n += parentItem->subItems [ourIndex]->getNumRows();
  40372. if (parentItem->parentItem == 0
  40373. && ! ownerView->rootItemVisible)
  40374. --n;
  40375. return n;
  40376. }
  40377. else
  40378. {
  40379. return 0;
  40380. }
  40381. }
  40382. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  40383. {
  40384. drawLinesInside = drawLines;
  40385. }
  40386. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  40387. {
  40388. if (recurse && isOpen() && subItems.size() > 0)
  40389. return subItems [0];
  40390. if (parentItem != 0)
  40391. {
  40392. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  40393. if (nextIndex >= parentItem->subItems.size())
  40394. return parentItem->getNextVisibleItem (false);
  40395. return parentItem->subItems [nextIndex];
  40396. }
  40397. return 0;
  40398. }
  40399. void TreeViewItem::restoreFromXml (const XmlElement& e)
  40400. {
  40401. if (e.hasTagName (T("CLOSED")))
  40402. {
  40403. setOpen (false);
  40404. }
  40405. else if (e.hasTagName (T("OPEN")))
  40406. {
  40407. setOpen (true);
  40408. forEachXmlChildElement (e, n)
  40409. {
  40410. const String id (n->getStringAttribute (T("id")));
  40411. for (int i = 0; i < subItems.size(); ++i)
  40412. {
  40413. TreeViewItem* const ti = subItems.getUnchecked(i);
  40414. if (ti->getUniqueName() == id)
  40415. {
  40416. ti->restoreFromXml (*n);
  40417. break;
  40418. }
  40419. }
  40420. }
  40421. }
  40422. }
  40423. XmlElement* TreeViewItem::createXmlOpenness() const
  40424. {
  40425. if (openness != opennessDefault)
  40426. {
  40427. const String name (getUniqueName());
  40428. if (name.isNotEmpty())
  40429. {
  40430. XmlElement* e;
  40431. if (isOpen())
  40432. {
  40433. e = new XmlElement (T("OPEN"));
  40434. for (int i = 0; i < subItems.size(); ++i)
  40435. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  40436. }
  40437. else
  40438. {
  40439. e = new XmlElement (T("CLOSED"));
  40440. }
  40441. e->setAttribute (T("id"), name);
  40442. return e;
  40443. }
  40444. else
  40445. {
  40446. // trying to save the openness for an element that has no name - this won't
  40447. // work because it needs the names to identify what to open.
  40448. jassertfalse
  40449. }
  40450. }
  40451. return 0;
  40452. }
  40453. END_JUCE_NAMESPACE
  40454. /********* End of inlined file: juce_TreeView.cpp *********/
  40455. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40456. BEGIN_JUCE_NAMESPACE
  40457. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  40458. : fileList (listToShow),
  40459. listeners (2)
  40460. {
  40461. }
  40462. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  40463. {
  40464. }
  40465. FileBrowserListener::~FileBrowserListener()
  40466. {
  40467. }
  40468. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  40469. {
  40470. jassert (listener != 0);
  40471. if (listener != 0)
  40472. listeners.add (listener);
  40473. }
  40474. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  40475. {
  40476. listeners.removeValue (listener);
  40477. }
  40478. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  40479. {
  40480. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40481. for (int i = listeners.size(); --i >= 0;)
  40482. {
  40483. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40484. if (deletionWatcher.hasBeenDeleted())
  40485. return;
  40486. i = jmin (i, listeners.size() - 1);
  40487. }
  40488. }
  40489. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  40490. {
  40491. if (fileList.getDirectory().exists())
  40492. {
  40493. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40494. for (int i = listeners.size(); --i >= 0;)
  40495. {
  40496. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  40497. if (deletionWatcher.hasBeenDeleted())
  40498. return;
  40499. i = jmin (i, listeners.size() - 1);
  40500. }
  40501. }
  40502. }
  40503. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  40504. {
  40505. if (fileList.getDirectory().exists())
  40506. {
  40507. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40508. for (int i = listeners.size(); --i >= 0;)
  40509. {
  40510. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  40511. if (deletionWatcher.hasBeenDeleted())
  40512. return;
  40513. i = jmin (i, listeners.size() - 1);
  40514. }
  40515. }
  40516. }
  40517. END_JUCE_NAMESPACE
  40518. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40519. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  40520. BEGIN_JUCE_NAMESPACE
  40521. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  40522. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  40523. Time* creationTime, bool* isReadOnly) throw();
  40524. bool juce_findFileNext (void* handle, String& resultFile,
  40525. bool* isDirectory, bool* isHidden, int64* fileSize,
  40526. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  40527. void juce_findFileClose (void* handle) throw();
  40528. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  40529. TimeSliceThread& thread_)
  40530. : fileFilter (fileFilter_),
  40531. thread (thread_),
  40532. includeDirectories (false),
  40533. includeFiles (false),
  40534. ignoreHiddenFiles (true),
  40535. fileFindHandle (0),
  40536. shouldStop (true)
  40537. {
  40538. }
  40539. DirectoryContentsList::~DirectoryContentsList()
  40540. {
  40541. clear();
  40542. }
  40543. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  40544. {
  40545. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  40546. }
  40547. const File& DirectoryContentsList::getDirectory() const throw()
  40548. {
  40549. return root;
  40550. }
  40551. void DirectoryContentsList::setDirectory (const File& directory,
  40552. const bool includeDirectories_,
  40553. const bool includeFiles_)
  40554. {
  40555. if (directory != root
  40556. || includeDirectories != includeDirectories_
  40557. || includeFiles != includeFiles_)
  40558. {
  40559. clear();
  40560. root = directory;
  40561. includeDirectories = includeDirectories_;
  40562. includeFiles = includeFiles_;
  40563. refresh();
  40564. }
  40565. }
  40566. void DirectoryContentsList::clear()
  40567. {
  40568. shouldStop = true;
  40569. thread.removeTimeSliceClient (this);
  40570. if (fileFindHandle != 0)
  40571. {
  40572. juce_findFileClose (fileFindHandle);
  40573. fileFindHandle = 0;
  40574. }
  40575. if (files.size() > 0)
  40576. {
  40577. files.clear();
  40578. changed();
  40579. }
  40580. }
  40581. void DirectoryContentsList::refresh()
  40582. {
  40583. clear();
  40584. if (root.isDirectory())
  40585. {
  40586. String fileFound;
  40587. bool fileFoundIsDir, isHidden, isReadOnly;
  40588. int64 fileSize;
  40589. Time modTime, creationTime;
  40590. String path (root.getFullPathName());
  40591. if (! path.endsWithChar (File::separator))
  40592. path += File::separator;
  40593. jassert (fileFindHandle == 0);
  40594. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  40595. &fileFoundIsDir,
  40596. &isHidden,
  40597. &fileSize,
  40598. &modTime,
  40599. &creationTime,
  40600. &isReadOnly);
  40601. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  40602. {
  40603. if (addFile (fileFound, fileFoundIsDir, isHidden,
  40604. fileSize, modTime, creationTime, isReadOnly))
  40605. {
  40606. changed();
  40607. }
  40608. }
  40609. shouldStop = false;
  40610. thread.addTimeSliceClient (this);
  40611. }
  40612. }
  40613. int DirectoryContentsList::getNumFiles() const
  40614. {
  40615. return files.size();
  40616. }
  40617. bool DirectoryContentsList::getFileInfo (const int index,
  40618. FileInfo& result) const
  40619. {
  40620. const ScopedLock sl (fileListLock);
  40621. const FileInfo* const info = files [index];
  40622. if (info != 0)
  40623. {
  40624. result = *info;
  40625. return true;
  40626. }
  40627. return false;
  40628. }
  40629. const File DirectoryContentsList::getFile (const int index) const
  40630. {
  40631. const ScopedLock sl (fileListLock);
  40632. const FileInfo* const info = files [index];
  40633. if (info != 0)
  40634. return root.getChildFile (info->filename);
  40635. return File::nonexistent;
  40636. }
  40637. bool DirectoryContentsList::isStillLoading() const
  40638. {
  40639. return fileFindHandle != 0;
  40640. }
  40641. void DirectoryContentsList::changed()
  40642. {
  40643. sendChangeMessage (this);
  40644. }
  40645. bool DirectoryContentsList::useTimeSlice()
  40646. {
  40647. const uint32 startTime = Time::getApproximateMillisecondCounter();
  40648. bool hasChanged = false;
  40649. for (int i = 100; --i >= 0;)
  40650. {
  40651. if (! checkNextFile (hasChanged))
  40652. {
  40653. if (hasChanged)
  40654. changed();
  40655. return false;
  40656. }
  40657. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  40658. break;
  40659. }
  40660. if (hasChanged)
  40661. changed();
  40662. return true;
  40663. }
  40664. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  40665. {
  40666. if (fileFindHandle != 0)
  40667. {
  40668. String fileFound;
  40669. bool fileFoundIsDir, isHidden, isReadOnly;
  40670. int64 fileSize;
  40671. Time modTime, creationTime;
  40672. if (juce_findFileNext (fileFindHandle, fileFound,
  40673. &fileFoundIsDir, &isHidden,
  40674. &fileSize,
  40675. &modTime,
  40676. &creationTime,
  40677. &isReadOnly))
  40678. {
  40679. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  40680. modTime, creationTime, isReadOnly))
  40681. {
  40682. hasChanged = true;
  40683. }
  40684. return true;
  40685. }
  40686. else
  40687. {
  40688. juce_findFileClose (fileFindHandle);
  40689. fileFindHandle = 0;
  40690. }
  40691. }
  40692. return false;
  40693. }
  40694. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  40695. const DirectoryContentsList::FileInfo* const second) throw()
  40696. {
  40697. #if JUCE_WIN32
  40698. if (first->isDirectory != second->isDirectory)
  40699. return first->isDirectory ? -1 : 1;
  40700. #endif
  40701. return first->filename.compareIgnoreCase (second->filename);
  40702. }
  40703. bool DirectoryContentsList::addFile (const String& filename,
  40704. const bool isDir,
  40705. const bool isHidden,
  40706. const int64 fileSize,
  40707. const Time& modTime,
  40708. const Time& creationTime,
  40709. const bool isReadOnly)
  40710. {
  40711. if (filename == T("..")
  40712. || filename == T(".")
  40713. || (ignoreHiddenFiles && isHidden))
  40714. return false;
  40715. const File file (root.getChildFile (filename));
  40716. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  40717. && (fileFilter == 0
  40718. || ((! isDir) && fileFilter->isFileSuitable (file))
  40719. || (isDir && fileFilter->isDirectorySuitable (file))))
  40720. {
  40721. FileInfo* const info = new FileInfo();
  40722. info->filename = filename;
  40723. info->fileSize = fileSize;
  40724. info->modificationTime = modTime;
  40725. info->creationTime = creationTime;
  40726. info->isDirectory = isDir;
  40727. info->isReadOnly = isReadOnly;
  40728. const ScopedLock sl (fileListLock);
  40729. for (int i = files.size(); --i >= 0;)
  40730. {
  40731. if (files.getUnchecked(i)->filename == info->filename)
  40732. {
  40733. delete info;
  40734. return false;
  40735. }
  40736. }
  40737. files.addSorted (*this, info);
  40738. return true;
  40739. }
  40740. return false;
  40741. }
  40742. END_JUCE_NAMESPACE
  40743. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  40744. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  40745. BEGIN_JUCE_NAMESPACE
  40746. class DirectoriesOnlyFilter : public FileFilter
  40747. {
  40748. public:
  40749. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  40750. bool isFileSuitable (const File&) const { return false; }
  40751. bool isDirectorySuitable (const File&) const { return true; }
  40752. };
  40753. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  40754. const File& initialFileOrDirectory,
  40755. const FileFilter* fileFilter,
  40756. FilePreviewComponent* previewComp_,
  40757. const bool useTreeView,
  40758. const bool filenameTextBoxIsReadOnly)
  40759. : directoriesOnlyFilter (0),
  40760. mode (mode_),
  40761. listeners (2),
  40762. previewComp (previewComp_),
  40763. thread ("Juce FileBrowser")
  40764. {
  40765. String filename;
  40766. if (initialFileOrDirectory == File::nonexistent)
  40767. {
  40768. currentRoot = File::getCurrentWorkingDirectory();
  40769. }
  40770. else if (initialFileOrDirectory.isDirectory())
  40771. {
  40772. currentRoot = initialFileOrDirectory;
  40773. }
  40774. else
  40775. {
  40776. currentRoot = initialFileOrDirectory.getParentDirectory();
  40777. filename = initialFileOrDirectory.getFileName();
  40778. }
  40779. if (mode_ == chooseDirectoryMode)
  40780. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  40781. fileList = new DirectoryContentsList (fileFilter, thread);
  40782. if (useTreeView)
  40783. {
  40784. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  40785. addAndMakeVisible (tree);
  40786. fileListComponent = tree;
  40787. }
  40788. else
  40789. {
  40790. FileListComponent* const list = new FileListComponent (*fileList);
  40791. list->setOutlineThickness (1);
  40792. addAndMakeVisible (list);
  40793. fileListComponent = list;
  40794. }
  40795. fileListComponent->addListener (this);
  40796. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  40797. currentPathBox->setEditableText (true);
  40798. StringArray rootNames, rootPaths;
  40799. const BitArray separators (getRoots (rootNames, rootPaths));
  40800. for (int i = 0; i < rootNames.size(); ++i)
  40801. {
  40802. if (separators [i])
  40803. currentPathBox->addSeparator();
  40804. currentPathBox->addItem (rootNames[i], i + 1);
  40805. }
  40806. currentPathBox->addSeparator();
  40807. currentPathBox->addListener (this);
  40808. addAndMakeVisible (filenameBox = new TextEditor());
  40809. filenameBox->setMultiLine (false);
  40810. filenameBox->setSelectAllWhenFocused (true);
  40811. filenameBox->setText (filename, false);
  40812. filenameBox->addListener (this);
  40813. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  40814. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  40815. : TRANS("file:"));
  40816. addAndMakeVisible (label);
  40817. label->attachToComponent (filenameBox, true);
  40818. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  40819. goUpButton->addButtonListener (this);
  40820. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  40821. if (previewComp != 0)
  40822. addAndMakeVisible (previewComp);
  40823. setRoot (currentRoot);
  40824. thread.startThread (4);
  40825. }
  40826. FileBrowserComponent::~FileBrowserComponent()
  40827. {
  40828. if (previewComp != 0)
  40829. removeChildComponent (previewComp);
  40830. deleteAllChildren();
  40831. deleteAndZero (fileList);
  40832. delete directoriesOnlyFilter;
  40833. thread.stopThread (10000);
  40834. }
  40835. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  40836. {
  40837. jassert (newListener != 0)
  40838. if (newListener != 0)
  40839. listeners.add (newListener);
  40840. }
  40841. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  40842. {
  40843. listeners.removeValue (listener);
  40844. }
  40845. const File FileBrowserComponent::getCurrentFile() const throw()
  40846. {
  40847. return currentRoot.getChildFile (filenameBox->getText());
  40848. }
  40849. bool FileBrowserComponent::currentFileIsValid() const
  40850. {
  40851. if (mode == saveFileMode)
  40852. return ! getCurrentFile().isDirectory();
  40853. else if (mode == loadFileMode)
  40854. return getCurrentFile().existsAsFile();
  40855. else if (mode == chooseDirectoryMode)
  40856. return getCurrentFile().isDirectory();
  40857. jassertfalse
  40858. return false;
  40859. }
  40860. const File FileBrowserComponent::getRoot() const
  40861. {
  40862. return currentRoot;
  40863. }
  40864. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  40865. {
  40866. if (currentRoot != newRootDirectory)
  40867. {
  40868. fileListComponent->scrollToTop();
  40869. if (mode == chooseDirectoryMode)
  40870. filenameBox->setText (String::empty, false);
  40871. String path (newRootDirectory.getFullPathName());
  40872. if (path.isEmpty())
  40873. path += File::separator;
  40874. StringArray rootNames, rootPaths;
  40875. getRoots (rootNames, rootPaths);
  40876. if (! rootPaths.contains (path, true))
  40877. {
  40878. bool alreadyListed = false;
  40879. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  40880. {
  40881. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  40882. {
  40883. alreadyListed = true;
  40884. break;
  40885. }
  40886. }
  40887. if (! alreadyListed)
  40888. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  40889. }
  40890. }
  40891. currentRoot = newRootDirectory;
  40892. fileList->setDirectory (currentRoot, true, true);
  40893. String currentRootName (currentRoot.getFullPathName());
  40894. if (currentRootName.isEmpty())
  40895. currentRootName += File::separator;
  40896. currentPathBox->setText (currentRootName, true);
  40897. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  40898. && currentRoot.getParentDirectory() != currentRoot);
  40899. }
  40900. void FileBrowserComponent::goUp()
  40901. {
  40902. setRoot (getRoot().getParentDirectory());
  40903. }
  40904. void FileBrowserComponent::refresh()
  40905. {
  40906. fileList->refresh();
  40907. }
  40908. const String FileBrowserComponent::getActionVerb() const
  40909. {
  40910. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  40911. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  40912. }
  40913. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  40914. {
  40915. return previewComp;
  40916. }
  40917. void FileBrowserComponent::resized()
  40918. {
  40919. getLookAndFeel()
  40920. .layoutFileBrowserComponent (*this, fileListComponent,
  40921. previewComp, currentPathBox,
  40922. filenameBox, goUpButton);
  40923. }
  40924. void FileBrowserComponent::sendListenerChangeMessage()
  40925. {
  40926. ComponentDeletionWatcher deletionWatcher (this);
  40927. if (previewComp != 0)
  40928. previewComp->selectedFileChanged (getCurrentFile());
  40929. jassert (! deletionWatcher.hasBeenDeleted());
  40930. for (int i = listeners.size(); --i >= 0;)
  40931. {
  40932. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40933. if (deletionWatcher.hasBeenDeleted())
  40934. return;
  40935. i = jmin (i, listeners.size() - 1);
  40936. }
  40937. }
  40938. void FileBrowserComponent::selectionChanged()
  40939. {
  40940. const File selected (fileListComponent->getSelectedFile());
  40941. if ((mode == chooseDirectoryMode && selected.isDirectory())
  40942. || selected.existsAsFile())
  40943. {
  40944. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  40945. }
  40946. sendListenerChangeMessage();
  40947. }
  40948. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  40949. {
  40950. ComponentDeletionWatcher deletionWatcher (this);
  40951. for (int i = listeners.size(); --i >= 0;)
  40952. {
  40953. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  40954. if (deletionWatcher.hasBeenDeleted())
  40955. return;
  40956. i = jmin (i, listeners.size() - 1);
  40957. }
  40958. }
  40959. void FileBrowserComponent::fileDoubleClicked (const File& f)
  40960. {
  40961. if (f.isDirectory())
  40962. {
  40963. setRoot (f);
  40964. }
  40965. else
  40966. {
  40967. ComponentDeletionWatcher deletionWatcher (this);
  40968. for (int i = listeners.size(); --i >= 0;)
  40969. {
  40970. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  40971. if (deletionWatcher.hasBeenDeleted())
  40972. return;
  40973. i = jmin (i, listeners.size() - 1);
  40974. }
  40975. }
  40976. }
  40977. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  40978. {
  40979. sendListenerChangeMessage();
  40980. }
  40981. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  40982. {
  40983. if (filenameBox->getText().containsChar (File::separator))
  40984. {
  40985. const File f (currentRoot.getChildFile (filenameBox->getText()));
  40986. if (f.isDirectory())
  40987. {
  40988. setRoot (f);
  40989. filenameBox->setText (String::empty);
  40990. }
  40991. else
  40992. {
  40993. setRoot (f.getParentDirectory());
  40994. filenameBox->setText (f.getFileName());
  40995. }
  40996. }
  40997. else
  40998. {
  40999. fileDoubleClicked (getCurrentFile());
  41000. }
  41001. }
  41002. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  41003. {
  41004. }
  41005. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  41006. {
  41007. if (mode != saveFileMode)
  41008. selectionChanged();
  41009. }
  41010. void FileBrowserComponent::buttonClicked (Button*)
  41011. {
  41012. goUp();
  41013. }
  41014. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  41015. {
  41016. const String newText (currentPathBox->getText().trim().unquoted());
  41017. if (newText.isNotEmpty())
  41018. {
  41019. const int index = currentPathBox->getSelectedId() - 1;
  41020. StringArray rootNames, rootPaths;
  41021. getRoots (rootNames, rootPaths);
  41022. if (rootPaths [index].isNotEmpty())
  41023. {
  41024. setRoot (File (rootPaths [index]));
  41025. }
  41026. else
  41027. {
  41028. File f (newText);
  41029. for (;;)
  41030. {
  41031. if (f.isDirectory())
  41032. {
  41033. setRoot (f);
  41034. break;
  41035. }
  41036. if (f.getParentDirectory() == f)
  41037. break;
  41038. f = f.getParentDirectory();
  41039. }
  41040. }
  41041. }
  41042. }
  41043. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  41044. {
  41045. BitArray separators;
  41046. #if JUCE_WIN32
  41047. OwnedArray<File> roots;
  41048. File::findFileSystemRoots (roots);
  41049. rootPaths.clear();
  41050. for (int i = 0; i < roots.size(); ++i)
  41051. {
  41052. const File* const drive = roots.getUnchecked(i);
  41053. String name (drive->getFullPathName());
  41054. rootPaths.add (name);
  41055. if (drive->isOnHardDisk())
  41056. {
  41057. String volume (drive->getVolumeLabel());
  41058. if (volume.isEmpty())
  41059. volume = TRANS("Hard Drive");
  41060. name << " [" << drive->getVolumeLabel() << ']';
  41061. }
  41062. else if (drive->isOnCDRomDrive())
  41063. {
  41064. name << TRANS(" [CD/DVD drive]");
  41065. }
  41066. rootNames.add (name);
  41067. }
  41068. separators.setBit (rootPaths.size());
  41069. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41070. rootNames.add ("Documents");
  41071. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41072. rootNames.add ("Desktop");
  41073. #endif
  41074. #if JUCE_MAC
  41075. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41076. rootNames.add ("Home folder");
  41077. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41078. rootNames.add ("Documents");
  41079. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41080. rootNames.add ("Desktop");
  41081. separators.setBit (rootPaths.size());
  41082. OwnedArray <File> volumes;
  41083. File vol ("/Volumes");
  41084. vol.findChildFiles (volumes, File::findDirectories, false);
  41085. for (int i = 0; i < volumes.size(); ++i)
  41086. {
  41087. const File* const volume = volumes.getUnchecked(i);
  41088. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  41089. {
  41090. rootPaths.add (volume->getFullPathName());
  41091. rootNames.add (volume->getFileName());
  41092. }
  41093. }
  41094. #endif
  41095. #if JUCE_LINUX
  41096. rootPaths.add ("/");
  41097. rootNames.add ("/");
  41098. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41099. rootNames.add ("Home folder");
  41100. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41101. rootNames.add ("Desktop");
  41102. #endif
  41103. return separators;
  41104. }
  41105. END_JUCE_NAMESPACE
  41106. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  41107. /********* Start of inlined file: juce_FileChooser.cpp *********/
  41108. BEGIN_JUCE_NAMESPACE
  41109. FileChooser::FileChooser (const String& chooserBoxTitle,
  41110. const File& currentFileOrDirectory,
  41111. const String& fileFilters,
  41112. const bool useNativeDialogBox_)
  41113. : title (chooserBoxTitle),
  41114. filters (fileFilters),
  41115. startingFile (currentFileOrDirectory),
  41116. useNativeDialogBox (useNativeDialogBox_)
  41117. {
  41118. #if JUCE_LINUX
  41119. useNativeDialogBox = false;
  41120. #endif
  41121. if (fileFilters.trim().isEmpty())
  41122. filters = T("*");
  41123. }
  41124. FileChooser::~FileChooser()
  41125. {
  41126. }
  41127. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  41128. {
  41129. return showDialog (false, false, false, false, previewComponent);
  41130. }
  41131. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  41132. {
  41133. return showDialog (false, false, false, true, previewComponent);
  41134. }
  41135. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  41136. {
  41137. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  41138. }
  41139. bool FileChooser::browseForDirectory()
  41140. {
  41141. return showDialog (true, false, false, false, 0);
  41142. }
  41143. const File FileChooser::getResult() const
  41144. {
  41145. // if you've used a multiple-file select, you should use the getResults() method
  41146. // to retrieve all the files that were chosen.
  41147. jassert (results.size() <= 1);
  41148. const File* const f = results.getFirst();
  41149. if (f != 0)
  41150. return *f;
  41151. return File::nonexistent;
  41152. }
  41153. const OwnedArray <File>& FileChooser::getResults() const
  41154. {
  41155. return results;
  41156. }
  41157. bool FileChooser::showDialog (const bool isDirectory,
  41158. const bool isSave,
  41159. const bool warnAboutOverwritingExistingFiles,
  41160. const bool selectMultipleFiles,
  41161. FilePreviewComponent* const previewComponent)
  41162. {
  41163. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  41164. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  41165. if (currentlyFocused != 0)
  41166. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  41167. results.clear();
  41168. // the preview component needs to be the right size before you pass it in here..
  41169. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  41170. && previewComponent->getHeight() > 10));
  41171. #if JUCE_WIN32
  41172. if (useNativeDialogBox)
  41173. #else
  41174. if (useNativeDialogBox && (previewComponent == 0))
  41175. #endif
  41176. {
  41177. showPlatformDialog (results, title, startingFile, filters,
  41178. isDirectory, isSave,
  41179. warnAboutOverwritingExistingFiles,
  41180. selectMultipleFiles,
  41181. previewComponent);
  41182. }
  41183. else
  41184. {
  41185. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  41186. WildcardFileFilter wildcard (filters, String::empty);
  41187. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  41188. : (isSave ? FileBrowserComponent::saveFileMode
  41189. : FileBrowserComponent::loadFileMode),
  41190. startingFile, &wildcard, previewComponent);
  41191. FileChooserDialogBox box (title, String::empty,
  41192. browserComponent,
  41193. warnAboutOverwritingExistingFiles,
  41194. browserComponent.findColour (AlertWindow::backgroundColourId));
  41195. if (box.show())
  41196. results.add (new File (browserComponent.getCurrentFile()));
  41197. }
  41198. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  41199. currentlyFocused->grabKeyboardFocus();
  41200. delete currentlyFocusedChecker;
  41201. return results.size() > 0;
  41202. }
  41203. FilePreviewComponent::FilePreviewComponent()
  41204. {
  41205. }
  41206. FilePreviewComponent::~FilePreviewComponent()
  41207. {
  41208. }
  41209. END_JUCE_NAMESPACE
  41210. /********* End of inlined file: juce_FileChooser.cpp *********/
  41211. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  41212. BEGIN_JUCE_NAMESPACE
  41213. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  41214. const String& instructions,
  41215. FileBrowserComponent& chooserComponent,
  41216. const bool warnAboutOverwritingExistingFiles_,
  41217. const Colour& backgroundColour)
  41218. : ResizableWindow (name, backgroundColour, true),
  41219. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  41220. {
  41221. content = new ContentComponent();
  41222. content->setName (name);
  41223. content->instructions = instructions;
  41224. content->chooserComponent = &chooserComponent;
  41225. content->addAndMakeVisible (&chooserComponent);
  41226. content->okButton = new TextButton (chooserComponent.getActionVerb());
  41227. content->addAndMakeVisible (content->okButton);
  41228. content->okButton->addButtonListener (this);
  41229. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  41230. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  41231. content->cancelButton = new TextButton (TRANS("Cancel"));
  41232. content->addAndMakeVisible (content->cancelButton);
  41233. content->cancelButton->addButtonListener (this);
  41234. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  41235. setContentComponent (content);
  41236. setResizable (true, true);
  41237. setResizeLimits (300, 300, 1200, 1000);
  41238. content->chooserComponent->addListener (this);
  41239. }
  41240. FileChooserDialogBox::~FileChooserDialogBox()
  41241. {
  41242. content->chooserComponent->removeListener (this);
  41243. }
  41244. bool FileChooserDialogBox::show (int w, int h)
  41245. {
  41246. if (w <= 0)
  41247. {
  41248. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  41249. if (previewComp != 0)
  41250. w = 400 + previewComp->getWidth();
  41251. else
  41252. w = 600;
  41253. }
  41254. if (h <= 0)
  41255. h = 500;
  41256. centreWithSize (w, h);
  41257. const bool ok = (runModalLoop() != 0);
  41258. setVisible (false);
  41259. return ok;
  41260. }
  41261. void FileChooserDialogBox::buttonClicked (Button* button)
  41262. {
  41263. if (button == content->okButton)
  41264. {
  41265. if (warnAboutOverwritingExistingFiles
  41266. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  41267. && content->chooserComponent->getCurrentFile().exists())
  41268. {
  41269. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  41270. TRANS("File already exists"),
  41271. TRANS("There's already a file called:\n\n")
  41272. + content->chooserComponent->getCurrentFile().getFullPathName()
  41273. + T("\n\nAre you sure you want to overwrite it?"),
  41274. TRANS("overwrite"),
  41275. TRANS("cancel")))
  41276. {
  41277. return;
  41278. }
  41279. }
  41280. exitModalState (1);
  41281. }
  41282. else if (button == content->cancelButton)
  41283. closeButtonPressed();
  41284. }
  41285. void FileChooserDialogBox::closeButtonPressed()
  41286. {
  41287. setVisible (false);
  41288. }
  41289. void FileChooserDialogBox::selectionChanged()
  41290. {
  41291. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  41292. }
  41293. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  41294. {
  41295. }
  41296. void FileChooserDialogBox::fileDoubleClicked (const File&)
  41297. {
  41298. selectionChanged();
  41299. content->okButton->triggerClick();
  41300. }
  41301. FileChooserDialogBox::ContentComponent::ContentComponent()
  41302. {
  41303. setInterceptsMouseClicks (false, true);
  41304. }
  41305. FileChooserDialogBox::ContentComponent::~ContentComponent()
  41306. {
  41307. delete okButton;
  41308. delete cancelButton;
  41309. }
  41310. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  41311. {
  41312. g.setColour (Colours::black);
  41313. text.draw (g);
  41314. }
  41315. void FileChooserDialogBox::ContentComponent::resized()
  41316. {
  41317. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  41318. float left, top, right, bottom;
  41319. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  41320. const int y = roundFloatToInt (bottom) + 10;
  41321. const int buttonHeight = 26;
  41322. const int buttonY = getHeight() - buttonHeight - 8;
  41323. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  41324. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  41325. proportionOfWidth (0.2f), buttonHeight);
  41326. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  41327. proportionOfWidth (0.2f), buttonHeight);
  41328. }
  41329. END_JUCE_NAMESPACE
  41330. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  41331. /********* Start of inlined file: juce_FileFilter.cpp *********/
  41332. BEGIN_JUCE_NAMESPACE
  41333. FileFilter::FileFilter (const String& filterDescription)
  41334. : description (filterDescription)
  41335. {
  41336. }
  41337. FileFilter::~FileFilter()
  41338. {
  41339. }
  41340. const String& FileFilter::getDescription() const throw()
  41341. {
  41342. return description;
  41343. }
  41344. END_JUCE_NAMESPACE
  41345. /********* End of inlined file: juce_FileFilter.cpp *********/
  41346. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  41347. BEGIN_JUCE_NAMESPACE
  41348. Image* juce_createIconForFile (const File& file);
  41349. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  41350. : DirectoryContentsDisplayComponent (listToShow),
  41351. ListBox (String::empty, 0)
  41352. {
  41353. setModel (this);
  41354. fileList.addChangeListener (this);
  41355. }
  41356. FileListComponent::~FileListComponent()
  41357. {
  41358. fileList.removeChangeListener (this);
  41359. deleteAllChildren();
  41360. }
  41361. const File FileListComponent::getSelectedFile() const
  41362. {
  41363. return fileList.getFile (getSelectedRow());
  41364. }
  41365. void FileListComponent::scrollToTop()
  41366. {
  41367. getVerticalScrollBar()->setCurrentRangeStart (0);
  41368. }
  41369. void FileListComponent::changeListenerCallback (void*)
  41370. {
  41371. updateContent();
  41372. }
  41373. class FileListItemComponent : public Component,
  41374. public TimeSliceClient,
  41375. public AsyncUpdater
  41376. {
  41377. public:
  41378. FileListItemComponent (FileListComponent& owner_,
  41379. TimeSliceThread& thread_) throw()
  41380. : owner (owner_),
  41381. thread (thread_),
  41382. icon (0)
  41383. {
  41384. }
  41385. ~FileListItemComponent() throw()
  41386. {
  41387. thread.removeTimeSliceClient (this);
  41388. clearIcon();
  41389. }
  41390. void paint (Graphics& g)
  41391. {
  41392. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  41393. file.getFileName(),
  41394. icon,
  41395. fileSize, modTime,
  41396. isDirectory, highlighted,
  41397. index);
  41398. }
  41399. void mouseDown (const MouseEvent& e)
  41400. {
  41401. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  41402. owner.sendMouseClickMessage (file, e);
  41403. }
  41404. void mouseDoubleClick (const MouseEvent&)
  41405. {
  41406. owner.sendDoubleClickMessage (file);
  41407. }
  41408. void update (const File& root,
  41409. const DirectoryContentsList::FileInfo* const fileInfo,
  41410. const int index_,
  41411. const bool highlighted_) throw()
  41412. {
  41413. thread.removeTimeSliceClient (this);
  41414. if (highlighted_ != highlighted
  41415. || index_ != index)
  41416. {
  41417. index = index_;
  41418. highlighted = highlighted_;
  41419. repaint();
  41420. }
  41421. File newFile;
  41422. String newFileSize;
  41423. String newModTime;
  41424. if (fileInfo != 0)
  41425. {
  41426. newFile = root.getChildFile (fileInfo->filename);
  41427. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  41428. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  41429. }
  41430. if (newFile != file
  41431. || fileSize != newFileSize
  41432. || modTime != newModTime)
  41433. {
  41434. file = newFile;
  41435. fileSize = newFileSize;
  41436. modTime = newModTime;
  41437. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  41438. repaint();
  41439. clearIcon();
  41440. }
  41441. if (file != File::nonexistent
  41442. && icon == 0 && ! isDirectory)
  41443. {
  41444. updateIcon (true);
  41445. if (icon == 0)
  41446. thread.addTimeSliceClient (this);
  41447. }
  41448. }
  41449. bool useTimeSlice()
  41450. {
  41451. updateIcon (false);
  41452. return false;
  41453. }
  41454. void handleAsyncUpdate()
  41455. {
  41456. repaint();
  41457. }
  41458. juce_UseDebuggingNewOperator
  41459. private:
  41460. FileListComponent& owner;
  41461. TimeSliceThread& thread;
  41462. bool highlighted;
  41463. int index;
  41464. File file;
  41465. String fileSize;
  41466. String modTime;
  41467. Image* icon;
  41468. bool isDirectory;
  41469. void clearIcon() throw()
  41470. {
  41471. ImageCache::release (icon);
  41472. icon = 0;
  41473. }
  41474. void updateIcon (const bool onlyUpdateIfCached) throw()
  41475. {
  41476. if (icon == 0)
  41477. {
  41478. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  41479. Image* im = ImageCache::getFromHashCode (hashCode);
  41480. if (im == 0 && ! onlyUpdateIfCached)
  41481. {
  41482. im = juce_createIconForFile (file);
  41483. if (im != 0)
  41484. ImageCache::addImageToCache (im, hashCode);
  41485. }
  41486. if (im != 0)
  41487. {
  41488. icon = im;
  41489. triggerAsyncUpdate();
  41490. }
  41491. }
  41492. }
  41493. };
  41494. int FileListComponent::getNumRows()
  41495. {
  41496. return fileList.getNumFiles();
  41497. }
  41498. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  41499. {
  41500. }
  41501. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  41502. {
  41503. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  41504. if (comp == 0)
  41505. {
  41506. delete existingComponentToUpdate;
  41507. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  41508. }
  41509. DirectoryContentsList::FileInfo fileInfo;
  41510. if (fileList.getFileInfo (row, fileInfo))
  41511. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  41512. else
  41513. comp->update (fileList.getDirectory(), 0, row, isSelected);
  41514. return comp;
  41515. }
  41516. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  41517. {
  41518. sendSelectionChangeMessage();
  41519. }
  41520. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  41521. {
  41522. }
  41523. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  41524. {
  41525. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  41526. }
  41527. END_JUCE_NAMESPACE
  41528. /********* End of inlined file: juce_FileListComponent.cpp *********/
  41529. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  41530. BEGIN_JUCE_NAMESPACE
  41531. FilenameComponent::FilenameComponent (const String& name,
  41532. const File& currentFile,
  41533. const bool canEditFilename,
  41534. const bool isDirectory,
  41535. const bool isForSaving,
  41536. const String& fileBrowserWildcard,
  41537. const String& enforcedSuffix_,
  41538. const String& textWhenNothingSelected)
  41539. : Component (name),
  41540. maxRecentFiles (30),
  41541. isDir (isDirectory),
  41542. isSaving (isForSaving),
  41543. isFileDragOver (false),
  41544. wildcard (fileBrowserWildcard),
  41545. enforcedSuffix (enforcedSuffix_)
  41546. {
  41547. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  41548. filenameBox->setEditableText (canEditFilename);
  41549. filenameBox->addListener (this);
  41550. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  41551. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  41552. browseButton = 0;
  41553. setBrowseButtonText (T("..."));
  41554. setCurrentFile (currentFile, true);
  41555. }
  41556. FilenameComponent::~FilenameComponent()
  41557. {
  41558. deleteAllChildren();
  41559. }
  41560. void FilenameComponent::paintOverChildren (Graphics& g)
  41561. {
  41562. if (isFileDragOver)
  41563. {
  41564. g.setColour (Colours::red.withAlpha (0.2f));
  41565. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  41566. }
  41567. }
  41568. void FilenameComponent::resized()
  41569. {
  41570. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  41571. }
  41572. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  41573. {
  41574. browseButtonText = newBrowseButtonText;
  41575. lookAndFeelChanged();
  41576. }
  41577. void FilenameComponent::lookAndFeelChanged()
  41578. {
  41579. deleteAndZero (browseButton);
  41580. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  41581. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  41582. resized();
  41583. browseButton->addButtonListener (this);
  41584. }
  41585. void FilenameComponent::setTooltip (const String& newTooltip)
  41586. {
  41587. SettableTooltipClient::setTooltip (newTooltip);
  41588. filenameBox->setTooltip (newTooltip);
  41589. }
  41590. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41591. {
  41592. defaultBrowseFile = newDefaultDirectory;
  41593. }
  41594. void FilenameComponent::buttonClicked (Button*)
  41595. {
  41596. FileChooser fc (TRANS("Choose a new file"),
  41597. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  41598. : getCurrentFile(),
  41599. wildcard);
  41600. if (isDir ? fc.browseForDirectory()
  41601. : (isSaving ? fc.browseForFileToSave (false)
  41602. : fc.browseForFileToOpen()))
  41603. {
  41604. setCurrentFile (fc.getResult(), true);
  41605. }
  41606. }
  41607. void FilenameComponent::comboBoxChanged (ComboBox*)
  41608. {
  41609. setCurrentFile (getCurrentFile(), true);
  41610. }
  41611. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  41612. {
  41613. return true;
  41614. }
  41615. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  41616. {
  41617. isFileDragOver = false;
  41618. repaint();
  41619. const File f (filenames[0]);
  41620. if (f.exists() && (f.isDirectory() == isDir))
  41621. setCurrentFile (f, true);
  41622. }
  41623. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  41624. {
  41625. isFileDragOver = true;
  41626. repaint();
  41627. }
  41628. void FilenameComponent::fileDragExit (const StringArray&)
  41629. {
  41630. isFileDragOver = false;
  41631. repaint();
  41632. }
  41633. const File FilenameComponent::getCurrentFile() const
  41634. {
  41635. File f (filenameBox->getText());
  41636. if (enforcedSuffix.isNotEmpty())
  41637. f = f.withFileExtension (enforcedSuffix);
  41638. return f;
  41639. }
  41640. void FilenameComponent::setCurrentFile (File newFile,
  41641. const bool addToRecentlyUsedList,
  41642. const bool sendChangeNotification)
  41643. {
  41644. if (enforcedSuffix.isNotEmpty())
  41645. newFile = newFile.withFileExtension (enforcedSuffix);
  41646. if (newFile.getFullPathName() != lastFilename)
  41647. {
  41648. lastFilename = newFile.getFullPathName();
  41649. if (addToRecentlyUsedList)
  41650. addRecentlyUsedFile (newFile);
  41651. filenameBox->setText (lastFilename, true);
  41652. if (sendChangeNotification)
  41653. triggerAsyncUpdate();
  41654. }
  41655. }
  41656. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  41657. {
  41658. filenameBox->setEditableText (shouldBeEditable);
  41659. }
  41660. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  41661. {
  41662. StringArray names;
  41663. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  41664. names.add (filenameBox->getItemText (i));
  41665. return names;
  41666. }
  41667. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  41668. {
  41669. if (filenames != getRecentlyUsedFilenames())
  41670. {
  41671. filenameBox->clear();
  41672. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  41673. filenameBox->addItem (filenames[i], i + 1);
  41674. }
  41675. }
  41676. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  41677. {
  41678. maxRecentFiles = jmax (1, newMaximum);
  41679. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  41680. }
  41681. void FilenameComponent::addRecentlyUsedFile (const File& file)
  41682. {
  41683. StringArray files (getRecentlyUsedFilenames());
  41684. if (file.getFullPathName().isNotEmpty())
  41685. {
  41686. files.removeString (file.getFullPathName(), true);
  41687. files.insert (0, file.getFullPathName());
  41688. setRecentlyUsedFilenames (files);
  41689. }
  41690. }
  41691. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  41692. {
  41693. jassert (listener != 0);
  41694. if (listener != 0)
  41695. listeners.add (listener);
  41696. }
  41697. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  41698. {
  41699. listeners.removeValue (listener);
  41700. }
  41701. void FilenameComponent::handleAsyncUpdate()
  41702. {
  41703. for (int i = listeners.size(); --i >= 0;)
  41704. {
  41705. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  41706. i = jmin (i, listeners.size());
  41707. }
  41708. }
  41709. END_JUCE_NAMESPACE
  41710. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  41711. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41712. BEGIN_JUCE_NAMESPACE
  41713. FileSearchPathListComponent::FileSearchPathListComponent()
  41714. {
  41715. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  41716. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  41717. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  41718. listBox->setOutlineThickness (1);
  41719. addAndMakeVisible (addButton = new TextButton ("+"));
  41720. addButton->addButtonListener (this);
  41721. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41722. addAndMakeVisible (removeButton = new TextButton ("-"));
  41723. removeButton->addButtonListener (this);
  41724. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41725. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  41726. changeButton->addButtonListener (this);
  41727. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41728. upButton->addButtonListener (this);
  41729. {
  41730. Path arrowPath;
  41731. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  41732. DrawablePath arrowImage;
  41733. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41734. arrowImage.setPath (arrowPath);
  41735. ((DrawableButton*) upButton)->setImages (&arrowImage);
  41736. }
  41737. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41738. downButton->addButtonListener (this);
  41739. {
  41740. Path arrowPath;
  41741. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  41742. DrawablePath arrowImage;
  41743. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41744. arrowImage.setPath (arrowPath);
  41745. ((DrawableButton*) downButton)->setImages (&arrowImage);
  41746. }
  41747. updateButtons();
  41748. }
  41749. FileSearchPathListComponent::~FileSearchPathListComponent()
  41750. {
  41751. deleteAllChildren();
  41752. }
  41753. void FileSearchPathListComponent::updateButtons() throw()
  41754. {
  41755. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  41756. removeButton->setEnabled (anythingSelected);
  41757. changeButton->setEnabled (anythingSelected);
  41758. upButton->setEnabled (anythingSelected);
  41759. downButton->setEnabled (anythingSelected);
  41760. }
  41761. void FileSearchPathListComponent::changed() throw()
  41762. {
  41763. listBox->updateContent();
  41764. listBox->repaint();
  41765. updateButtons();
  41766. }
  41767. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  41768. {
  41769. if (newPath.toString() != path.toString())
  41770. {
  41771. path = newPath;
  41772. changed();
  41773. }
  41774. }
  41775. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41776. {
  41777. defaultBrowseTarget = newDefaultDirectory;
  41778. }
  41779. int FileSearchPathListComponent::getNumRows()
  41780. {
  41781. return path.getNumPaths();
  41782. }
  41783. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  41784. {
  41785. if (rowIsSelected)
  41786. g.fillAll (findColour (TextEditor::highlightColourId));
  41787. g.setColour (findColour (ListBox::textColourId));
  41788. Font f (height * 0.7f);
  41789. f.setHorizontalScale (0.9f);
  41790. g.setFont (f);
  41791. g.drawText (path [rowNumber].getFullPathName(),
  41792. 4, 0, width - 6, height,
  41793. Justification::centredLeft, true);
  41794. }
  41795. void FileSearchPathListComponent::deleteKeyPressed (int row)
  41796. {
  41797. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  41798. {
  41799. path.remove (row);
  41800. changed();
  41801. }
  41802. }
  41803. void FileSearchPathListComponent::returnKeyPressed (int row)
  41804. {
  41805. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  41806. if (chooser.browseForDirectory())
  41807. {
  41808. path.remove (row);
  41809. path.add (chooser.getResult(), row);
  41810. changed();
  41811. }
  41812. }
  41813. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  41814. {
  41815. returnKeyPressed (row);
  41816. }
  41817. void FileSearchPathListComponent::selectedRowsChanged (int)
  41818. {
  41819. updateButtons();
  41820. }
  41821. void FileSearchPathListComponent::paint (Graphics& g)
  41822. {
  41823. g.fillAll (findColour (backgroundColourId));
  41824. }
  41825. void FileSearchPathListComponent::resized()
  41826. {
  41827. const int buttonH = 22;
  41828. const int buttonY = getHeight() - buttonH - 4;
  41829. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  41830. addButton->setBounds (2, buttonY, buttonH, buttonH);
  41831. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  41832. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  41833. downButton->setSize (buttonH * 2, buttonH);
  41834. upButton->setSize (buttonH * 2, buttonH);
  41835. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  41836. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  41837. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  41838. }
  41839. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  41840. {
  41841. return true;
  41842. }
  41843. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  41844. {
  41845. for (int i = filenames.size(); --i >= 0;)
  41846. {
  41847. const File f (filenames[i]);
  41848. if (f.isDirectory())
  41849. {
  41850. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  41851. path.add (f, row);
  41852. changed();
  41853. }
  41854. }
  41855. }
  41856. void FileSearchPathListComponent::buttonClicked (Button* button)
  41857. {
  41858. const int currentRow = listBox->getSelectedRow();
  41859. if (button == removeButton)
  41860. {
  41861. deleteKeyPressed (currentRow);
  41862. }
  41863. else if (button == addButton)
  41864. {
  41865. File start (defaultBrowseTarget);
  41866. if (start == File::nonexistent)
  41867. start = path [0];
  41868. if (start == File::nonexistent)
  41869. start = File::getCurrentWorkingDirectory();
  41870. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  41871. if (chooser.browseForDirectory())
  41872. {
  41873. path.add (chooser.getResult(), currentRow);
  41874. }
  41875. }
  41876. else if (button == changeButton)
  41877. {
  41878. returnKeyPressed (currentRow);
  41879. }
  41880. else if (button == upButton)
  41881. {
  41882. if (currentRow > 0 && currentRow < path.getNumPaths())
  41883. {
  41884. const File f (path[currentRow]);
  41885. path.remove (currentRow);
  41886. path.add (f, currentRow - 1);
  41887. listBox->selectRow (currentRow - 1);
  41888. }
  41889. }
  41890. else if (button == downButton)
  41891. {
  41892. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  41893. {
  41894. const File f (path[currentRow]);
  41895. path.remove (currentRow);
  41896. path.add (f, currentRow + 1);
  41897. listBox->selectRow (currentRow + 1);
  41898. }
  41899. }
  41900. changed();
  41901. }
  41902. END_JUCE_NAMESPACE
  41903. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41904. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  41905. BEGIN_JUCE_NAMESPACE
  41906. Image* juce_createIconForFile (const File& file);
  41907. class FileListTreeItem : public TreeViewItem,
  41908. public TimeSliceClient,
  41909. public AsyncUpdater,
  41910. public ChangeListener
  41911. {
  41912. public:
  41913. FileListTreeItem (FileTreeComponent& owner_,
  41914. DirectoryContentsList* const parentContentsList_,
  41915. const int indexInContentsList_,
  41916. const File& file_,
  41917. TimeSliceThread& thread_) throw()
  41918. : file (file_),
  41919. owner (owner_),
  41920. parentContentsList (parentContentsList_),
  41921. indexInContentsList (indexInContentsList_),
  41922. subContentsList (0),
  41923. canDeleteSubContentsList (false),
  41924. thread (thread_),
  41925. icon (0)
  41926. {
  41927. DirectoryContentsList::FileInfo fileInfo;
  41928. if (parentContentsList_ != 0
  41929. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  41930. {
  41931. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  41932. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  41933. isDirectory = fileInfo.isDirectory;
  41934. }
  41935. else
  41936. {
  41937. isDirectory = true;
  41938. }
  41939. }
  41940. ~FileListTreeItem() throw()
  41941. {
  41942. thread.removeTimeSliceClient (this);
  41943. clearSubItems();
  41944. ImageCache::release (icon);
  41945. if (canDeleteSubContentsList)
  41946. delete subContentsList;
  41947. }
  41948. bool mightContainSubItems() { return isDirectory; }
  41949. const String getUniqueName() const { return file.getFullPathName(); }
  41950. int getItemHeight() const { return 22; }
  41951. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  41952. void itemOpennessChanged (bool isNowOpen)
  41953. {
  41954. if (isNowOpen)
  41955. {
  41956. clearSubItems();
  41957. isDirectory = file.isDirectory();
  41958. if (isDirectory)
  41959. {
  41960. if (subContentsList == 0)
  41961. {
  41962. jassert (parentContentsList != 0);
  41963. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  41964. l->setDirectory (file, true, true);
  41965. setSubContentsList (l);
  41966. canDeleteSubContentsList = true;
  41967. }
  41968. changeListenerCallback (0);
  41969. }
  41970. }
  41971. }
  41972. void setSubContentsList (DirectoryContentsList* newList) throw()
  41973. {
  41974. jassert (subContentsList == 0);
  41975. subContentsList = newList;
  41976. newList->addChangeListener (this);
  41977. }
  41978. void changeListenerCallback (void*)
  41979. {
  41980. clearSubItems();
  41981. if (isOpen() && subContentsList != 0)
  41982. {
  41983. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  41984. {
  41985. FileListTreeItem* const item
  41986. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  41987. addSubItem (item);
  41988. }
  41989. }
  41990. }
  41991. void paintItem (Graphics& g, int width, int height)
  41992. {
  41993. if (file != File::nonexistent && ! isDirectory)
  41994. {
  41995. updateIcon (true);
  41996. if (icon == 0)
  41997. thread.addTimeSliceClient (this);
  41998. }
  41999. owner.getLookAndFeel()
  42000. .drawFileBrowserRow (g, width, height,
  42001. file.getFileName(),
  42002. icon,
  42003. fileSize, modTime,
  42004. isDirectory, isSelected(),
  42005. indexInContentsList);
  42006. }
  42007. void itemClicked (const MouseEvent& e)
  42008. {
  42009. owner.sendMouseClickMessage (file, e);
  42010. }
  42011. void itemDoubleClicked (const MouseEvent& e)
  42012. {
  42013. TreeViewItem::itemDoubleClicked (e);
  42014. owner.sendDoubleClickMessage (file);
  42015. }
  42016. void itemSelectionChanged (bool)
  42017. {
  42018. owner.sendSelectionChangeMessage();
  42019. }
  42020. bool useTimeSlice()
  42021. {
  42022. updateIcon (false);
  42023. thread.removeTimeSliceClient (this);
  42024. return false;
  42025. }
  42026. void handleAsyncUpdate()
  42027. {
  42028. owner.repaint();
  42029. }
  42030. const File file;
  42031. juce_UseDebuggingNewOperator
  42032. private:
  42033. FileTreeComponent& owner;
  42034. DirectoryContentsList* parentContentsList;
  42035. int indexInContentsList;
  42036. DirectoryContentsList* subContentsList;
  42037. bool isDirectory, canDeleteSubContentsList;
  42038. TimeSliceThread& thread;
  42039. Image* icon;
  42040. String fileSize;
  42041. String modTime;
  42042. void updateIcon (const bool onlyUpdateIfCached) throw()
  42043. {
  42044. if (icon == 0)
  42045. {
  42046. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42047. Image* im = ImageCache::getFromHashCode (hashCode);
  42048. if (im == 0 && ! onlyUpdateIfCached)
  42049. {
  42050. im = juce_createIconForFile (file);
  42051. if (im != 0)
  42052. ImageCache::addImageToCache (im, hashCode);
  42053. }
  42054. if (im != 0)
  42055. {
  42056. icon = im;
  42057. triggerAsyncUpdate();
  42058. }
  42059. }
  42060. }
  42061. };
  42062. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  42063. : DirectoryContentsDisplayComponent (listToShow)
  42064. {
  42065. FileListTreeItem* const root
  42066. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  42067. listToShow.getTimeSliceThread());
  42068. root->setSubContentsList (&listToShow);
  42069. setRootItemVisible (false);
  42070. setRootItem (root);
  42071. }
  42072. FileTreeComponent::~FileTreeComponent()
  42073. {
  42074. TreeViewItem* const root = getRootItem();
  42075. setRootItem (0);
  42076. delete root;
  42077. }
  42078. const File FileTreeComponent::getSelectedFile() const
  42079. {
  42080. return getSelectedFile (0);
  42081. }
  42082. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  42083. {
  42084. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  42085. if (item != 0)
  42086. return item->file;
  42087. return File::nonexistent;
  42088. }
  42089. void FileTreeComponent::scrollToTop()
  42090. {
  42091. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  42092. }
  42093. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  42094. {
  42095. dragAndDropDescription = description;
  42096. }
  42097. END_JUCE_NAMESPACE
  42098. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  42099. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  42100. BEGIN_JUCE_NAMESPACE
  42101. ImagePreviewComponent::ImagePreviewComponent()
  42102. : currentThumbnail (0)
  42103. {
  42104. }
  42105. ImagePreviewComponent::~ImagePreviewComponent()
  42106. {
  42107. delete currentThumbnail;
  42108. }
  42109. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  42110. {
  42111. const int availableW = proportionOfWidth (0.97f);
  42112. const int availableH = getHeight() - 13 * 4;
  42113. const double scale = jmin (1.0,
  42114. availableW / (double) w,
  42115. availableH / (double) h);
  42116. w = roundDoubleToInt (scale * w);
  42117. h = roundDoubleToInt (scale * h);
  42118. }
  42119. void ImagePreviewComponent::selectedFileChanged (const File& file)
  42120. {
  42121. if (fileToLoad != file)
  42122. {
  42123. fileToLoad = file;
  42124. startTimer (100);
  42125. }
  42126. }
  42127. void ImagePreviewComponent::timerCallback()
  42128. {
  42129. stopTimer();
  42130. deleteAndZero (currentThumbnail);
  42131. currentDetails = String::empty;
  42132. repaint();
  42133. FileInputStream* const in = fileToLoad.createInputStream();
  42134. if (in != 0)
  42135. {
  42136. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  42137. if (format != 0)
  42138. {
  42139. currentThumbnail = format->decodeImage (*in);
  42140. if (currentThumbnail != 0)
  42141. {
  42142. int w = currentThumbnail->getWidth();
  42143. int h = currentThumbnail->getHeight();
  42144. currentDetails
  42145. << fileToLoad.getFileName() << "\n"
  42146. << format->getFormatName() << "\n"
  42147. << w << " x " << h << " pixels\n"
  42148. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  42149. getThumbSize (w, h);
  42150. Image* const reduced = currentThumbnail->createCopy (w, h);
  42151. delete currentThumbnail;
  42152. currentThumbnail = reduced;
  42153. }
  42154. }
  42155. delete in;
  42156. }
  42157. }
  42158. void ImagePreviewComponent::paint (Graphics& g)
  42159. {
  42160. if (currentThumbnail != 0)
  42161. {
  42162. g.setFont (13.0f);
  42163. int w = currentThumbnail->getWidth();
  42164. int h = currentThumbnail->getHeight();
  42165. getThumbSize (w, h);
  42166. const int numLines = 4;
  42167. const int totalH = 13 * numLines + h + 4;
  42168. const int y = (getHeight() - totalH) / 2;
  42169. g.drawImageWithin (currentThumbnail,
  42170. (getWidth() - w) / 2, y, w, h,
  42171. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  42172. false);
  42173. g.drawFittedText (currentDetails,
  42174. 0, y + h + 4, getWidth(), 100,
  42175. Justification::centredTop, numLines);
  42176. }
  42177. }
  42178. END_JUCE_NAMESPACE
  42179. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  42180. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  42181. BEGIN_JUCE_NAMESPACE
  42182. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  42183. const String& description)
  42184. : FileFilter (description.isEmpty() ? wildcardPatterns
  42185. : (description + T(" (") + wildcardPatterns + T(")")))
  42186. {
  42187. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  42188. wildcards.trim();
  42189. wildcards.removeEmptyStrings();
  42190. // special case for *.*, because people use it to mean "any file", but it
  42191. // would actually ignore files with no extension.
  42192. for (int i = wildcards.size(); --i >= 0;)
  42193. if (wildcards[i] == T("*.*"))
  42194. wildcards.set (i, T("*"));
  42195. }
  42196. WildcardFileFilter::~WildcardFileFilter()
  42197. {
  42198. }
  42199. bool WildcardFileFilter::isFileSuitable (const File& file) const
  42200. {
  42201. const String filename (file.getFileName());
  42202. for (int i = wildcards.size(); --i >= 0;)
  42203. if (filename.matchesWildcard (wildcards[i], true))
  42204. return true;
  42205. return false;
  42206. }
  42207. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  42208. {
  42209. return true;
  42210. }
  42211. END_JUCE_NAMESPACE
  42212. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  42213. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42214. BEGIN_JUCE_NAMESPACE
  42215. KeyboardFocusTraverser::KeyboardFocusTraverser()
  42216. {
  42217. }
  42218. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  42219. {
  42220. }
  42221. // This will sort a set of components, so that they are ordered in terms of
  42222. // left-to-right and then top-to-bottom.
  42223. class ScreenPositionComparator
  42224. {
  42225. public:
  42226. ScreenPositionComparator() {}
  42227. static int compareElements (const Component* const first, const Component* const second) throw()
  42228. {
  42229. int explicitOrder1 = first->getExplicitFocusOrder();
  42230. if (explicitOrder1 <= 0)
  42231. explicitOrder1 = INT_MAX / 2;
  42232. int explicitOrder2 = second->getExplicitFocusOrder();
  42233. if (explicitOrder2 <= 0)
  42234. explicitOrder2 = INT_MAX / 2;
  42235. if (explicitOrder1 != explicitOrder2)
  42236. return explicitOrder1 - explicitOrder2;
  42237. const int diff = first->getY() - second->getY();
  42238. return (diff == 0) ? first->getX() - second->getX()
  42239. : diff;
  42240. }
  42241. };
  42242. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  42243. {
  42244. if (parent->getNumChildComponents() > 0)
  42245. {
  42246. Array <Component*> localComps;
  42247. ScreenPositionComparator comparator;
  42248. int i;
  42249. for (i = parent->getNumChildComponents(); --i >= 0;)
  42250. {
  42251. Component* const c = parent->getChildComponent (i);
  42252. if (c->isVisible() && c->isEnabled())
  42253. localComps.addSorted (comparator, c);
  42254. }
  42255. for (i = 0; i < localComps.size(); ++i)
  42256. {
  42257. Component* const c = localComps.getUnchecked (i);
  42258. if (c->getWantsKeyboardFocus())
  42259. comps.add (c);
  42260. if (! c->isFocusContainer())
  42261. findAllFocusableComponents (c, comps);
  42262. }
  42263. }
  42264. }
  42265. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  42266. {
  42267. Component* focusContainer = current->getParentComponent();
  42268. if (focusContainer != 0)
  42269. {
  42270. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  42271. focusContainer = focusContainer->getParentComponent();
  42272. if (focusContainer != 0)
  42273. {
  42274. Array <Component*> comps;
  42275. findAllFocusableComponents (focusContainer, comps);
  42276. if (comps.size() > 0)
  42277. {
  42278. const int index = comps.indexOf (current);
  42279. return comps [(index + comps.size() + delta) % comps.size()];
  42280. }
  42281. }
  42282. }
  42283. return 0;
  42284. }
  42285. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  42286. {
  42287. return getIncrementedComponent (current, 1);
  42288. }
  42289. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  42290. {
  42291. return getIncrementedComponent (current, -1);
  42292. }
  42293. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  42294. {
  42295. Array <Component*> comps;
  42296. if (parentComponent != 0)
  42297. findAllFocusableComponents (parentComponent, comps);
  42298. return comps.getFirst();
  42299. }
  42300. END_JUCE_NAMESPACE
  42301. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42302. /********* Start of inlined file: juce_KeyListener.cpp *********/
  42303. BEGIN_JUCE_NAMESPACE
  42304. bool KeyListener::keyStateChanged (Component*)
  42305. {
  42306. return false;
  42307. }
  42308. END_JUCE_NAMESPACE
  42309. /********* End of inlined file: juce_KeyListener.cpp *********/
  42310. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42311. BEGIN_JUCE_NAMESPACE
  42312. // N.B. these two includes are put here deliberately to avoid problems with
  42313. // old GCCs failing on long include paths
  42314. const int maxKeys = 3;
  42315. class KeyMappingChangeButton : public Button
  42316. {
  42317. public:
  42318. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  42319. const CommandID commandID_,
  42320. const String& keyName,
  42321. const int keyNum_)
  42322. : Button (keyName),
  42323. owner (owner_),
  42324. commandID (commandID_),
  42325. keyNum (keyNum_)
  42326. {
  42327. setWantsKeyboardFocus (false);
  42328. setTriggeredOnMouseDown (keyNum >= 0);
  42329. if (keyNum_ < 0)
  42330. setTooltip (TRANS("adds a new key-mapping"));
  42331. else
  42332. setTooltip (TRANS("click to change this key-mapping"));
  42333. }
  42334. ~KeyMappingChangeButton()
  42335. {
  42336. }
  42337. void paintButton (Graphics& g, bool isOver, bool isDown)
  42338. {
  42339. if (keyNum >= 0)
  42340. {
  42341. if (isEnabled())
  42342. {
  42343. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  42344. g.fillAll (owner->textColour.withAlpha (alpha));
  42345. g.setOpacity (0.3f);
  42346. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  42347. }
  42348. g.setColour (owner->textColour);
  42349. g.setFont (getHeight() * 0.6f);
  42350. g.drawFittedText (getName(),
  42351. 3, 0, getWidth() - 6, getHeight(),
  42352. Justification::centred, 1);
  42353. }
  42354. else
  42355. {
  42356. const float thickness = 7.0f;
  42357. const float indent = 22.0f;
  42358. Path p;
  42359. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  42360. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  42361. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  42362. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  42363. p.setUsingNonZeroWinding (false);
  42364. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  42365. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  42366. }
  42367. if (hasKeyboardFocus (false))
  42368. {
  42369. g.setColour (owner->textColour.withAlpha (0.4f));
  42370. g.drawRect (0, 0, getWidth(), getHeight());
  42371. }
  42372. }
  42373. void clicked()
  42374. {
  42375. if (keyNum >= 0)
  42376. {
  42377. // existing key clicked..
  42378. PopupMenu m;
  42379. m.addItem (1, TRANS("change this key-mapping"));
  42380. m.addSeparator();
  42381. m.addItem (2, TRANS("remove this key-mapping"));
  42382. const int res = m.show();
  42383. if (res == 1)
  42384. {
  42385. owner->assignNewKey (commandID, keyNum);
  42386. }
  42387. else if (res == 2)
  42388. {
  42389. owner->getMappings()->removeKeyPress (commandID, keyNum);
  42390. }
  42391. }
  42392. else
  42393. {
  42394. // + button pressed..
  42395. owner->assignNewKey (commandID, -1);
  42396. }
  42397. }
  42398. void fitToContent (const int h) throw()
  42399. {
  42400. if (keyNum < 0)
  42401. {
  42402. setSize (h, h);
  42403. }
  42404. else
  42405. {
  42406. Font f (h * 0.6f);
  42407. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  42408. }
  42409. }
  42410. juce_UseDebuggingNewOperator
  42411. private:
  42412. KeyMappingEditorComponent* const owner;
  42413. const CommandID commandID;
  42414. const int keyNum;
  42415. KeyMappingChangeButton (const KeyMappingChangeButton&);
  42416. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  42417. };
  42418. class KeyMappingItemComponent : public Component
  42419. {
  42420. public:
  42421. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  42422. const CommandID commandID_)
  42423. : owner (owner_),
  42424. commandID (commandID_)
  42425. {
  42426. setInterceptsMouseClicks (false, true);
  42427. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  42428. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  42429. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  42430. {
  42431. KeyMappingChangeButton* const kb
  42432. = new KeyMappingChangeButton (owner_, commandID,
  42433. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  42434. kb->setEnabled (! isReadOnly);
  42435. addAndMakeVisible (kb);
  42436. }
  42437. KeyMappingChangeButton* const kb
  42438. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  42439. addChildComponent (kb);
  42440. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  42441. }
  42442. ~KeyMappingItemComponent()
  42443. {
  42444. deleteAllChildren();
  42445. }
  42446. void paint (Graphics& g)
  42447. {
  42448. g.setFont (getHeight() * 0.7f);
  42449. g.setColour (owner->textColour);
  42450. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  42451. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  42452. Justification::centredLeft, true);
  42453. }
  42454. void resized()
  42455. {
  42456. int x = getWidth() - 4;
  42457. for (int i = getNumChildComponents(); --i >= 0;)
  42458. {
  42459. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  42460. kb->fitToContent (getHeight() - 2);
  42461. kb->setTopRightPosition (x, 1);
  42462. x -= kb->getWidth() + 5;
  42463. }
  42464. }
  42465. juce_UseDebuggingNewOperator
  42466. private:
  42467. KeyMappingEditorComponent* const owner;
  42468. const CommandID commandID;
  42469. KeyMappingItemComponent (const KeyMappingItemComponent&);
  42470. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  42471. };
  42472. class KeyMappingTreeViewItem : public TreeViewItem
  42473. {
  42474. public:
  42475. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  42476. const CommandID commandID_)
  42477. : owner (owner_),
  42478. commandID (commandID_)
  42479. {
  42480. }
  42481. ~KeyMappingTreeViewItem()
  42482. {
  42483. }
  42484. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  42485. bool mightContainSubItems() { return false; }
  42486. int getItemHeight() const { return 20; }
  42487. Component* createItemComponent()
  42488. {
  42489. return new KeyMappingItemComponent (owner, commandID);
  42490. }
  42491. juce_UseDebuggingNewOperator
  42492. private:
  42493. KeyMappingEditorComponent* const owner;
  42494. const CommandID commandID;
  42495. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  42496. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  42497. };
  42498. class KeyCategoryTreeViewItem : public TreeViewItem
  42499. {
  42500. public:
  42501. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  42502. const String& name)
  42503. : owner (owner_),
  42504. categoryName (name)
  42505. {
  42506. }
  42507. ~KeyCategoryTreeViewItem()
  42508. {
  42509. }
  42510. const String getUniqueName() const { return categoryName + "_cat"; }
  42511. bool mightContainSubItems() { return true; }
  42512. int getItemHeight() const { return 28; }
  42513. void paintItem (Graphics& g, int width, int height)
  42514. {
  42515. g.setFont (height * 0.6f, Font::bold);
  42516. g.setColour (owner->textColour);
  42517. g.drawText (categoryName,
  42518. 2, 0, width - 2, height,
  42519. Justification::centredLeft, true);
  42520. }
  42521. void itemOpennessChanged (bool isNowOpen)
  42522. {
  42523. if (isNowOpen)
  42524. {
  42525. if (getNumSubItems() == 0)
  42526. {
  42527. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  42528. for (int i = 0; i < commands.size(); ++i)
  42529. {
  42530. if (owner->shouldCommandBeIncluded (commands[i]))
  42531. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  42532. }
  42533. }
  42534. }
  42535. else
  42536. {
  42537. clearSubItems();
  42538. }
  42539. }
  42540. juce_UseDebuggingNewOperator
  42541. private:
  42542. KeyMappingEditorComponent* owner;
  42543. String categoryName;
  42544. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  42545. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  42546. };
  42547. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  42548. const bool showResetToDefaultButton)
  42549. : mappings (mappingManager),
  42550. textColour (Colours::black)
  42551. {
  42552. jassert (mappingManager != 0); // can't be null!
  42553. mappingManager->addChangeListener (this);
  42554. setLinesDrawnForSubItems (false);
  42555. resetButton = 0;
  42556. if (showResetToDefaultButton)
  42557. {
  42558. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  42559. resetButton->addButtonListener (this);
  42560. }
  42561. addAndMakeVisible (tree = new TreeView());
  42562. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42563. tree->setRootItemVisible (false);
  42564. tree->setDefaultOpenness (true);
  42565. tree->setRootItem (this);
  42566. }
  42567. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  42568. {
  42569. mappings->removeChangeListener (this);
  42570. deleteAllChildren();
  42571. }
  42572. bool KeyMappingEditorComponent::mightContainSubItems()
  42573. {
  42574. return true;
  42575. }
  42576. const String KeyMappingEditorComponent::getUniqueName() const
  42577. {
  42578. return T("keys");
  42579. }
  42580. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  42581. const Colour& textColour_)
  42582. {
  42583. backgroundColour = mainBackground;
  42584. textColour = textColour_;
  42585. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42586. }
  42587. void KeyMappingEditorComponent::parentHierarchyChanged()
  42588. {
  42589. changeListenerCallback (0);
  42590. }
  42591. void KeyMappingEditorComponent::resized()
  42592. {
  42593. int h = getHeight();
  42594. if (resetButton != 0)
  42595. {
  42596. const int buttonHeight = 20;
  42597. h -= buttonHeight + 8;
  42598. int x = getWidth() - 8;
  42599. const int y = h + 6;
  42600. resetButton->changeWidthToFitText (buttonHeight);
  42601. resetButton->setTopRightPosition (x, y);
  42602. }
  42603. tree->setBounds (0, 0, getWidth(), h);
  42604. }
  42605. void KeyMappingEditorComponent::buttonClicked (Button* button)
  42606. {
  42607. if (button == resetButton)
  42608. {
  42609. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  42610. TRANS("Reset to defaults"),
  42611. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  42612. TRANS("Reset")))
  42613. {
  42614. mappings->resetToDefaultMappings();
  42615. }
  42616. }
  42617. }
  42618. void KeyMappingEditorComponent::changeListenerCallback (void*)
  42619. {
  42620. XmlElement* openness = tree->getOpennessState (true);
  42621. clearSubItems();
  42622. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  42623. for (int i = 0; i < categories.size(); ++i)
  42624. {
  42625. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  42626. int count = 0;
  42627. for (int j = 0; j < commands.size(); ++j)
  42628. if (shouldCommandBeIncluded (commands[j]))
  42629. ++count;
  42630. if (count > 0)
  42631. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  42632. }
  42633. if (openness != 0)
  42634. {
  42635. tree->restoreOpennessState (*openness);
  42636. delete openness;
  42637. }
  42638. }
  42639. class KeyEntryWindow : public AlertWindow
  42640. {
  42641. public:
  42642. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  42643. : AlertWindow (TRANS("New key-mapping"),
  42644. TRANS("Please press a key combination now..."),
  42645. AlertWindow::NoIcon),
  42646. owner (owner_)
  42647. {
  42648. addButton (TRANS("ok"), 1);
  42649. addButton (TRANS("cancel"), 0);
  42650. // (avoid return + escape keys getting processed by the buttons..)
  42651. for (int i = getNumChildComponents(); --i >= 0;)
  42652. getChildComponent (i)->setWantsKeyboardFocus (false);
  42653. setWantsKeyboardFocus (true);
  42654. grabKeyboardFocus();
  42655. }
  42656. ~KeyEntryWindow()
  42657. {
  42658. }
  42659. bool keyPressed (const KeyPress& key)
  42660. {
  42661. lastPress = key;
  42662. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  42663. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  42664. if (previousCommand != 0)
  42665. {
  42666. message << "\n\n"
  42667. << TRANS("(Currently assigned to \"")
  42668. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  42669. << "\")";
  42670. }
  42671. setMessage (message);
  42672. return true;
  42673. }
  42674. bool keyStateChanged()
  42675. {
  42676. return true;
  42677. }
  42678. KeyPress lastPress;
  42679. juce_UseDebuggingNewOperator
  42680. private:
  42681. KeyMappingEditorComponent* owner;
  42682. KeyEntryWindow (const KeyEntryWindow&);
  42683. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  42684. };
  42685. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  42686. {
  42687. KeyEntryWindow entryWindow (this);
  42688. if (entryWindow.runModalLoop() != 0)
  42689. {
  42690. entryWindow.setVisible (false);
  42691. if (entryWindow.lastPress.isValid())
  42692. {
  42693. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  42694. if (previousCommand != 0)
  42695. {
  42696. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42697. TRANS("Change key-mapping"),
  42698. TRANS("This key is already assigned to the command \"")
  42699. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  42700. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  42701. TRANS("re-assign"),
  42702. TRANS("cancel")))
  42703. {
  42704. return;
  42705. }
  42706. }
  42707. mappings->removeKeyPress (entryWindow.lastPress);
  42708. if (index >= 0)
  42709. mappings->removeKeyPress (commandID, index);
  42710. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  42711. }
  42712. }
  42713. }
  42714. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  42715. {
  42716. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42717. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  42718. }
  42719. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  42720. {
  42721. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42722. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  42723. }
  42724. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  42725. {
  42726. return key.getTextDescription();
  42727. }
  42728. END_JUCE_NAMESPACE
  42729. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42730. /********* Start of inlined file: juce_KeyPress.cpp *********/
  42731. BEGIN_JUCE_NAMESPACE
  42732. KeyPress::KeyPress() throw()
  42733. : keyCode (0),
  42734. mods (0),
  42735. textCharacter (0)
  42736. {
  42737. }
  42738. KeyPress::KeyPress (const int keyCode_,
  42739. const ModifierKeys& mods_,
  42740. const juce_wchar textCharacter_) throw()
  42741. : keyCode (keyCode_),
  42742. mods (mods_),
  42743. textCharacter (textCharacter_)
  42744. {
  42745. }
  42746. KeyPress::KeyPress (const int keyCode_) throw()
  42747. : keyCode (keyCode_),
  42748. textCharacter (0)
  42749. {
  42750. }
  42751. KeyPress::KeyPress (const KeyPress& other) throw()
  42752. : keyCode (other.keyCode),
  42753. mods (other.mods),
  42754. textCharacter (other.textCharacter)
  42755. {
  42756. }
  42757. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  42758. {
  42759. keyCode = other.keyCode;
  42760. mods = other.mods;
  42761. textCharacter = other.textCharacter;
  42762. return *this;
  42763. }
  42764. bool KeyPress::operator== (const KeyPress& other) const throw()
  42765. {
  42766. return mods.getRawFlags() == other.mods.getRawFlags()
  42767. && (textCharacter == other.textCharacter
  42768. || textCharacter == 0
  42769. || other.textCharacter == 0)
  42770. && (keyCode == other.keyCode
  42771. || (keyCode < 256
  42772. && other.keyCode < 256
  42773. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  42774. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  42775. }
  42776. bool KeyPress::operator!= (const KeyPress& other) const throw()
  42777. {
  42778. return ! operator== (other);
  42779. }
  42780. bool KeyPress::isCurrentlyDown() const throw()
  42781. {
  42782. return isKeyCurrentlyDown (keyCode)
  42783. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  42784. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  42785. }
  42786. struct KeyNameAndCode
  42787. {
  42788. const char* name;
  42789. int code;
  42790. };
  42791. static const KeyNameAndCode keyNameTranslations[] =
  42792. {
  42793. { "spacebar", KeyPress::spaceKey },
  42794. { "return", KeyPress::returnKey },
  42795. { "escape", KeyPress::escapeKey },
  42796. { "backspace", KeyPress::backspaceKey },
  42797. { "cursor left", KeyPress::leftKey },
  42798. { "cursor right", KeyPress::rightKey },
  42799. { "cursor up", KeyPress::upKey },
  42800. { "cursor down", KeyPress::downKey },
  42801. { "page up", KeyPress::pageUpKey },
  42802. { "page down", KeyPress::pageDownKey },
  42803. { "home", KeyPress::homeKey },
  42804. { "end", KeyPress::endKey },
  42805. { "delete", KeyPress::deleteKey },
  42806. { "insert", KeyPress::insertKey },
  42807. { "tab", KeyPress::tabKey },
  42808. { "play", KeyPress::playKey },
  42809. { "stop", KeyPress::stopKey },
  42810. { "fast forward", KeyPress::fastForwardKey },
  42811. { "rewind", KeyPress::rewindKey }
  42812. };
  42813. static const tchar* const numberPadPrefix = T("numpad ");
  42814. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  42815. {
  42816. int modifiers = 0;
  42817. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  42818. || desc.containsWholeWordIgnoreCase (T("control"))
  42819. || desc.containsWholeWordIgnoreCase (T("ctl")))
  42820. modifiers |= ModifierKeys::ctrlModifier;
  42821. if (desc.containsWholeWordIgnoreCase (T("shift"))
  42822. || desc.containsWholeWordIgnoreCase (T("shft")))
  42823. modifiers |= ModifierKeys::shiftModifier;
  42824. if (desc.containsWholeWordIgnoreCase (T("alt"))
  42825. || desc.containsWholeWordIgnoreCase (T("option")))
  42826. modifiers |= ModifierKeys::altModifier;
  42827. if (desc.containsWholeWordIgnoreCase (T("command"))
  42828. || desc.containsWholeWordIgnoreCase (T("cmd")))
  42829. modifiers |= ModifierKeys::commandModifier;
  42830. int key = 0;
  42831. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  42832. {
  42833. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  42834. {
  42835. key = keyNameTranslations[i].code;
  42836. break;
  42837. }
  42838. }
  42839. if (key == 0)
  42840. {
  42841. // see if it's a numpad key..
  42842. if (desc.containsIgnoreCase (numberPadPrefix))
  42843. {
  42844. const tchar lastChar = desc.trimEnd().getLastCharacter();
  42845. if (lastChar >= T('0') && lastChar <= T('9'))
  42846. key = numberPad0 + lastChar - T('0');
  42847. else if (lastChar == T('+'))
  42848. key = numberPadAdd;
  42849. else if (lastChar == T('-'))
  42850. key = numberPadSubtract;
  42851. else if (lastChar == T('*'))
  42852. key = numberPadMultiply;
  42853. else if (lastChar == T('/'))
  42854. key = numberPadDivide;
  42855. else if (lastChar == T('.'))
  42856. key = numberPadDecimalPoint;
  42857. else if (lastChar == T('='))
  42858. key = numberPadEquals;
  42859. else if (desc.endsWith (T("separator")))
  42860. key = numberPadSeparator;
  42861. else if (desc.endsWith (T("delete")))
  42862. key = numberPadDelete;
  42863. }
  42864. if (key == 0)
  42865. {
  42866. // see if it's a function key..
  42867. for (int i = 1; i <= 12; ++i)
  42868. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  42869. key = F1Key + i - 1;
  42870. if (key == 0)
  42871. {
  42872. // give up and use the hex code..
  42873. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  42874. .toLowerCase()
  42875. .retainCharacters (T("0123456789abcdef"))
  42876. .getHexValue32();
  42877. if (hexCode > 0)
  42878. key = hexCode;
  42879. else
  42880. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  42881. }
  42882. }
  42883. }
  42884. return KeyPress (key, ModifierKeys (modifiers), 0);
  42885. }
  42886. const String KeyPress::getTextDescription() const throw()
  42887. {
  42888. String desc;
  42889. if (keyCode > 0)
  42890. {
  42891. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  42892. // want to store it as being a slash, not shift+whatever.
  42893. if (textCharacter == T('/'))
  42894. return "/";
  42895. if (mods.isCtrlDown())
  42896. desc << "ctrl + ";
  42897. if (mods.isShiftDown())
  42898. desc << "shift + ";
  42899. #if JUCE_MAC
  42900. // only do this on the mac, because on Windows ctrl and command are the same,
  42901. // and this would get confusing
  42902. if (mods.isCommandDown())
  42903. desc << "command + ";
  42904. if (mods.isAltDown())
  42905. desc << "option + ";
  42906. #else
  42907. if (mods.isAltDown())
  42908. desc << "alt + ";
  42909. #endif
  42910. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  42911. if (keyCode == keyNameTranslations[i].code)
  42912. return desc + keyNameTranslations[i].name;
  42913. if (keyCode >= F1Key && keyCode <= F16Key)
  42914. desc << 'F' << (1 + keyCode - F1Key);
  42915. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  42916. desc << numberPadPrefix << (keyCode - numberPad0);
  42917. else if (keyCode >= 33 && keyCode < 176)
  42918. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  42919. else if (keyCode == numberPadAdd)
  42920. desc << numberPadPrefix << '+';
  42921. else if (keyCode == numberPadSubtract)
  42922. desc << numberPadPrefix << '-';
  42923. else if (keyCode == numberPadMultiply)
  42924. desc << numberPadPrefix << '*';
  42925. else if (keyCode == numberPadDivide)
  42926. desc << numberPadPrefix << '/';
  42927. else if (keyCode == numberPadSeparator)
  42928. desc << numberPadPrefix << "separator";
  42929. else if (keyCode == numberPadDecimalPoint)
  42930. desc << numberPadPrefix << '.';
  42931. else if (keyCode == numberPadDelete)
  42932. desc << numberPadPrefix << "delete";
  42933. else
  42934. desc << '#' << String::toHexString (keyCode);
  42935. }
  42936. return desc;
  42937. }
  42938. END_JUCE_NAMESPACE
  42939. /********* End of inlined file: juce_KeyPress.cpp *********/
  42940. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  42941. BEGIN_JUCE_NAMESPACE
  42942. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  42943. : commandManager (commandManager_)
  42944. {
  42945. // A manager is needed to get the descriptions of commands, and will be called when
  42946. // a command is invoked. So you can't leave this null..
  42947. jassert (commandManager_ != 0);
  42948. Desktop::getInstance().addFocusChangeListener (this);
  42949. }
  42950. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  42951. : commandManager (other.commandManager)
  42952. {
  42953. Desktop::getInstance().addFocusChangeListener (this);
  42954. }
  42955. KeyPressMappingSet::~KeyPressMappingSet()
  42956. {
  42957. Desktop::getInstance().removeFocusChangeListener (this);
  42958. }
  42959. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  42960. {
  42961. for (int i = 0; i < mappings.size(); ++i)
  42962. if (mappings.getUnchecked(i)->commandID == commandID)
  42963. return mappings.getUnchecked (i)->keypresses;
  42964. return Array <KeyPress> ();
  42965. }
  42966. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  42967. const KeyPress& newKeyPress,
  42968. int insertIndex) throw()
  42969. {
  42970. if (findCommandForKeyPress (newKeyPress) != commandID)
  42971. {
  42972. removeKeyPress (newKeyPress);
  42973. if (newKeyPress.isValid())
  42974. {
  42975. for (int i = mappings.size(); --i >= 0;)
  42976. {
  42977. if (mappings.getUnchecked(i)->commandID == commandID)
  42978. {
  42979. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  42980. sendChangeMessage (this);
  42981. return;
  42982. }
  42983. }
  42984. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  42985. if (ci != 0)
  42986. {
  42987. CommandMapping* const cm = new CommandMapping();
  42988. cm->commandID = commandID;
  42989. cm->keypresses.add (newKeyPress);
  42990. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  42991. mappings.add (cm);
  42992. sendChangeMessage (this);
  42993. }
  42994. }
  42995. }
  42996. }
  42997. void KeyPressMappingSet::resetToDefaultMappings() throw()
  42998. {
  42999. mappings.clear();
  43000. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  43001. {
  43002. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  43003. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43004. {
  43005. addKeyPress (ci->commandID,
  43006. ci->defaultKeypresses.getReference (j));
  43007. }
  43008. }
  43009. sendChangeMessage (this);
  43010. }
  43011. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  43012. {
  43013. clearAllKeyPresses (commandID);
  43014. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43015. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43016. {
  43017. addKeyPress (ci->commandID,
  43018. ci->defaultKeypresses.getReference (j));
  43019. }
  43020. }
  43021. void KeyPressMappingSet::clearAllKeyPresses() throw()
  43022. {
  43023. if (mappings.size() > 0)
  43024. {
  43025. sendChangeMessage (this);
  43026. mappings.clear();
  43027. }
  43028. }
  43029. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  43030. {
  43031. for (int i = mappings.size(); --i >= 0;)
  43032. {
  43033. if (mappings.getUnchecked(i)->commandID == commandID)
  43034. {
  43035. mappings.remove (i);
  43036. sendChangeMessage (this);
  43037. }
  43038. }
  43039. }
  43040. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  43041. {
  43042. if (keypress.isValid())
  43043. {
  43044. for (int i = mappings.size(); --i >= 0;)
  43045. {
  43046. CommandMapping* const cm = mappings.getUnchecked(i);
  43047. for (int j = cm->keypresses.size(); --j >= 0;)
  43048. {
  43049. if (keypress == cm->keypresses [j])
  43050. {
  43051. cm->keypresses.remove (j);
  43052. sendChangeMessage (this);
  43053. }
  43054. }
  43055. }
  43056. }
  43057. }
  43058. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  43059. const int keyPressIndex) throw()
  43060. {
  43061. for (int i = mappings.size(); --i >= 0;)
  43062. {
  43063. if (mappings.getUnchecked(i)->commandID == commandID)
  43064. {
  43065. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  43066. sendChangeMessage (this);
  43067. break;
  43068. }
  43069. }
  43070. }
  43071. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  43072. {
  43073. for (int i = 0; i < mappings.size(); ++i)
  43074. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  43075. return mappings.getUnchecked(i)->commandID;
  43076. return 0;
  43077. }
  43078. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  43079. const KeyPress& keyPress) const throw()
  43080. {
  43081. for (int i = mappings.size(); --i >= 0;)
  43082. if (mappings.getUnchecked(i)->commandID == commandID)
  43083. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  43084. return false;
  43085. }
  43086. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  43087. const KeyPress& key,
  43088. const bool isKeyDown,
  43089. const int millisecsSinceKeyPressed,
  43090. Component* const originatingComponent) const
  43091. {
  43092. ApplicationCommandTarget::InvocationInfo info (commandID);
  43093. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  43094. info.isKeyDown = isKeyDown;
  43095. info.keyPress = key;
  43096. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  43097. info.originatingComponent = originatingComponent;
  43098. commandManager->invoke (info, false);
  43099. }
  43100. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  43101. {
  43102. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  43103. {
  43104. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  43105. {
  43106. // if the XML was created as a set of differences from the default mappings,
  43107. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  43108. resetToDefaultMappings();
  43109. }
  43110. else
  43111. {
  43112. // if the XML was created calling createXml (false), then we need to clear all
  43113. // the keys and treat the xml as describing the entire set of mappings.
  43114. clearAllKeyPresses();
  43115. }
  43116. forEachXmlChildElement (xmlVersion, map)
  43117. {
  43118. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  43119. if (commandId != 0)
  43120. {
  43121. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  43122. if (map->hasTagName (T("MAPPING")))
  43123. {
  43124. addKeyPress (commandId, key);
  43125. }
  43126. else if (map->hasTagName (T("UNMAPPING")))
  43127. {
  43128. if (containsMapping (commandId, key))
  43129. removeKeyPress (key);
  43130. }
  43131. }
  43132. }
  43133. return true;
  43134. }
  43135. return false;
  43136. }
  43137. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  43138. {
  43139. KeyPressMappingSet* defaultSet = 0;
  43140. if (saveDifferencesFromDefaultSet)
  43141. {
  43142. defaultSet = new KeyPressMappingSet (commandManager);
  43143. defaultSet->resetToDefaultMappings();
  43144. }
  43145. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  43146. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  43147. int i;
  43148. for (i = 0; i < mappings.size(); ++i)
  43149. {
  43150. const CommandMapping* const cm = mappings.getUnchecked(i);
  43151. for (int j = 0; j < cm->keypresses.size(); ++j)
  43152. {
  43153. if (defaultSet == 0
  43154. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43155. {
  43156. XmlElement* const map = new XmlElement (T("MAPPING"));
  43157. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43158. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43159. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43160. doc->addChildElement (map);
  43161. }
  43162. }
  43163. }
  43164. if (defaultSet != 0)
  43165. {
  43166. for (i = 0; i < defaultSet->mappings.size(); ++i)
  43167. {
  43168. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  43169. for (int j = 0; j < cm->keypresses.size(); ++j)
  43170. {
  43171. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43172. {
  43173. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  43174. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43175. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43176. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43177. doc->addChildElement (map);
  43178. }
  43179. }
  43180. }
  43181. delete defaultSet;
  43182. }
  43183. return doc;
  43184. }
  43185. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  43186. Component* originatingComponent)
  43187. {
  43188. bool used = false;
  43189. const CommandID commandID = findCommandForKeyPress (key);
  43190. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43191. if (ci != 0
  43192. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  43193. {
  43194. ApplicationCommandInfo info (0);
  43195. if (commandManager->getTargetForCommand (commandID, info) != 0
  43196. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  43197. {
  43198. invokeCommand (commandID, key, true, 0, originatingComponent);
  43199. used = true;
  43200. }
  43201. else
  43202. {
  43203. if (originatingComponent != 0)
  43204. originatingComponent->getLookAndFeel().playAlertSound();
  43205. }
  43206. }
  43207. return used;
  43208. }
  43209. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  43210. {
  43211. bool used = false;
  43212. const uint32 now = Time::getMillisecondCounter();
  43213. for (int i = mappings.size(); --i >= 0;)
  43214. {
  43215. CommandMapping* const cm = mappings.getUnchecked(i);
  43216. if (cm->wantsKeyUpDownCallbacks)
  43217. {
  43218. for (int j = cm->keypresses.size(); --j >= 0;)
  43219. {
  43220. const KeyPress key (cm->keypresses.getReference (j));
  43221. const bool isDown = key.isCurrentlyDown();
  43222. int keyPressEntryIndex = 0;
  43223. bool wasDown = false;
  43224. for (int k = keysDown.size(); --k >= 0;)
  43225. {
  43226. if (key == keysDown.getUnchecked(k)->key)
  43227. {
  43228. keyPressEntryIndex = k;
  43229. wasDown = true;
  43230. break;
  43231. }
  43232. }
  43233. if (isDown != wasDown)
  43234. {
  43235. int millisecs = 0;
  43236. if (isDown)
  43237. {
  43238. KeyPressTime* const k = new KeyPressTime();
  43239. k->key = key;
  43240. k->timeWhenPressed = now;
  43241. keysDown.add (k);
  43242. }
  43243. else
  43244. {
  43245. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  43246. if (now > pressTime)
  43247. millisecs = now - pressTime;
  43248. keysDown.remove (keyPressEntryIndex);
  43249. }
  43250. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  43251. used = true;
  43252. }
  43253. }
  43254. }
  43255. }
  43256. return used;
  43257. }
  43258. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  43259. {
  43260. if (focusedComponent != 0)
  43261. focusedComponent->keyStateChanged();
  43262. }
  43263. END_JUCE_NAMESPACE
  43264. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  43265. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  43266. BEGIN_JUCE_NAMESPACE
  43267. ModifierKeys::ModifierKeys (const int flags_) throw()
  43268. : flags (flags_)
  43269. {
  43270. }
  43271. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  43272. : flags (other.flags)
  43273. {
  43274. }
  43275. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  43276. {
  43277. flags = other.flags;
  43278. return *this;
  43279. }
  43280. int ModifierKeys::currentModifierFlags = 0;
  43281. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  43282. {
  43283. return ModifierKeys (currentModifierFlags);
  43284. }
  43285. END_JUCE_NAMESPACE
  43286. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  43287. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  43288. BEGIN_JUCE_NAMESPACE
  43289. struct AnimationTask
  43290. {
  43291. AnimationTask (Component* const comp)
  43292. : component (comp),
  43293. watcher (comp)
  43294. {
  43295. }
  43296. Component* component;
  43297. ComponentDeletionWatcher watcher;
  43298. Rectangle destination;
  43299. int msElapsed, msTotal;
  43300. double startSpeed, midSpeed, endSpeed, lastProgress;
  43301. double left, top, right, bottom;
  43302. bool useTimeslice (const int elapsed)
  43303. {
  43304. if (watcher.hasBeenDeleted())
  43305. return false;
  43306. msElapsed += elapsed;
  43307. double newProgress = msElapsed / (double) msTotal;
  43308. if (newProgress >= 0 && newProgress < 1.0)
  43309. {
  43310. newProgress = timeToDistance (newProgress);
  43311. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  43312. jassert (newProgress >= lastProgress);
  43313. lastProgress = newProgress;
  43314. left += (destination.getX() - left) * delta;
  43315. top += (destination.getY() - top) * delta;
  43316. right += (destination.getRight() - right) * delta;
  43317. bottom += (destination.getBottom() - bottom) * delta;
  43318. if (delta < 1.0)
  43319. {
  43320. const Rectangle newBounds (roundDoubleToInt (left),
  43321. roundDoubleToInt (top),
  43322. roundDoubleToInt (right - left),
  43323. roundDoubleToInt (bottom - top));
  43324. if (newBounds != destination)
  43325. {
  43326. component->setBounds (newBounds);
  43327. return true;
  43328. }
  43329. }
  43330. }
  43331. component->setBounds (destination);
  43332. return false;
  43333. }
  43334. void moveToFinalDestination()
  43335. {
  43336. if (! watcher.hasBeenDeleted())
  43337. component->setBounds (destination);
  43338. }
  43339. private:
  43340. inline double timeToDistance (const double time) const
  43341. {
  43342. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  43343. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  43344. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  43345. }
  43346. };
  43347. ComponentAnimator::ComponentAnimator()
  43348. : lastTime (0)
  43349. {
  43350. }
  43351. ComponentAnimator::~ComponentAnimator()
  43352. {
  43353. cancelAllAnimations (false);
  43354. jassert (tasks.size() == 0);
  43355. }
  43356. void* ComponentAnimator::findTaskFor (Component* const component) const
  43357. {
  43358. for (int i = tasks.size(); --i >= 0;)
  43359. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  43360. return tasks.getUnchecked(i);
  43361. return 0;
  43362. }
  43363. void ComponentAnimator::animateComponent (Component* const component,
  43364. const Rectangle& finalPosition,
  43365. const int millisecondsToSpendMoving,
  43366. const double startSpeed,
  43367. const double endSpeed)
  43368. {
  43369. if (component != 0)
  43370. {
  43371. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  43372. if (at == 0)
  43373. {
  43374. at = new AnimationTask (component);
  43375. tasks.add (at);
  43376. }
  43377. at->msElapsed = 0;
  43378. at->lastProgress = 0;
  43379. at->msTotal = jmax (1, millisecondsToSpendMoving);
  43380. at->destination = finalPosition;
  43381. // the speeds must be 0 or greater!
  43382. jassert (startSpeed >= 0 && endSpeed >= 0)
  43383. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  43384. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  43385. at->midSpeed = invTotalDistance;
  43386. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  43387. at->left = component->getX();
  43388. at->top = component->getY();
  43389. at->right = component->getRight();
  43390. at->bottom = component->getBottom();
  43391. if (! isTimerRunning())
  43392. {
  43393. lastTime = Time::getMillisecondCounter();
  43394. startTimer (1000 / 50);
  43395. }
  43396. }
  43397. }
  43398. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  43399. {
  43400. for (int i = tasks.size(); --i >= 0;)
  43401. {
  43402. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43403. if (moveComponentsToTheirFinalPositions)
  43404. at->moveToFinalDestination();
  43405. delete at;
  43406. tasks.remove (i);
  43407. }
  43408. }
  43409. void ComponentAnimator::cancelAnimation (Component* const component,
  43410. const bool moveComponentToItsFinalPosition)
  43411. {
  43412. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43413. if (at != 0)
  43414. {
  43415. if (moveComponentToItsFinalPosition)
  43416. at->moveToFinalDestination();
  43417. tasks.removeValue (at);
  43418. delete at;
  43419. }
  43420. }
  43421. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  43422. {
  43423. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43424. if (at != 0)
  43425. return at->destination;
  43426. else if (component != 0)
  43427. return component->getBounds();
  43428. return Rectangle();
  43429. }
  43430. void ComponentAnimator::timerCallback()
  43431. {
  43432. const uint32 timeNow = Time::getMillisecondCounter();
  43433. if (lastTime == 0 || lastTime == timeNow)
  43434. lastTime = timeNow;
  43435. const int elapsed = timeNow - lastTime;
  43436. for (int i = tasks.size(); --i >= 0;)
  43437. {
  43438. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43439. if (! at->useTimeslice (elapsed))
  43440. {
  43441. tasks.remove (i);
  43442. delete at;
  43443. }
  43444. }
  43445. lastTime = timeNow;
  43446. if (tasks.size() == 0)
  43447. stopTimer();
  43448. }
  43449. END_JUCE_NAMESPACE
  43450. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  43451. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43452. BEGIN_JUCE_NAMESPACE
  43453. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  43454. : minW (0),
  43455. maxW (0x3fffffff),
  43456. minH (0),
  43457. maxH (0x3fffffff),
  43458. minOffTop (0),
  43459. minOffLeft (0),
  43460. minOffBottom (0),
  43461. minOffRight (0),
  43462. aspectRatio (0.0)
  43463. {
  43464. }
  43465. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  43466. {
  43467. }
  43468. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  43469. {
  43470. minW = minimumWidth;
  43471. }
  43472. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  43473. {
  43474. maxW = maximumWidth;
  43475. }
  43476. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  43477. {
  43478. minH = minimumHeight;
  43479. }
  43480. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  43481. {
  43482. maxH = maximumHeight;
  43483. }
  43484. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  43485. {
  43486. jassert (maxW >= minimumWidth);
  43487. jassert (maxH >= minimumHeight);
  43488. jassert (minimumWidth > 0 && minimumHeight > 0);
  43489. minW = minimumWidth;
  43490. minH = minimumHeight;
  43491. if (minW > maxW)
  43492. maxW = minW;
  43493. if (minH > maxH)
  43494. maxH = minH;
  43495. }
  43496. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  43497. {
  43498. jassert (maximumWidth >= minW);
  43499. jassert (maximumHeight >= minH);
  43500. jassert (maximumWidth > 0 && maximumHeight > 0);
  43501. maxW = jmax (minW, maximumWidth);
  43502. maxH = jmax (minH, maximumHeight);
  43503. }
  43504. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  43505. const int minimumHeight,
  43506. const int maximumWidth,
  43507. const int maximumHeight) throw()
  43508. {
  43509. jassert (maximumWidth >= minimumWidth);
  43510. jassert (maximumHeight >= minimumHeight);
  43511. jassert (maximumWidth > 0 && maximumHeight > 0);
  43512. jassert (minimumWidth > 0 && minimumHeight > 0);
  43513. minW = jmax (0, minimumWidth);
  43514. minH = jmax (0, minimumHeight);
  43515. maxW = jmax (minW, maximumWidth);
  43516. maxH = jmax (minH, maximumHeight);
  43517. }
  43518. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  43519. const int minimumWhenOffTheLeft,
  43520. const int minimumWhenOffTheBottom,
  43521. const int minimumWhenOffTheRight) throw()
  43522. {
  43523. minOffTop = minimumWhenOffTheTop;
  43524. minOffLeft = minimumWhenOffTheLeft;
  43525. minOffBottom = minimumWhenOffTheBottom;
  43526. minOffRight = minimumWhenOffTheRight;
  43527. }
  43528. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  43529. {
  43530. aspectRatio = jmax (0.0, widthOverHeight);
  43531. }
  43532. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  43533. {
  43534. return aspectRatio;
  43535. }
  43536. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  43537. int x, int y, int w, int h,
  43538. const bool isStretchingTop,
  43539. const bool isStretchingLeft,
  43540. const bool isStretchingBottom,
  43541. const bool isStretchingRight)
  43542. {
  43543. jassert (component != 0);
  43544. Rectangle limits;
  43545. Component* const p = component->getParentComponent();
  43546. if (p == 0)
  43547. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  43548. else
  43549. limits.setSize (p->getWidth(), p->getHeight());
  43550. if (component->isOnDesktop())
  43551. {
  43552. ComponentPeer* const peer = component->getPeer();
  43553. const BorderSize border (peer->getFrameSize());
  43554. x -= border.getLeft();
  43555. y -= border.getTop();
  43556. w += border.getLeftAndRight();
  43557. h += border.getTopAndBottom();
  43558. checkBounds (x, y, w, h,
  43559. border.addedTo (component->getBounds()), limits,
  43560. isStretchingTop, isStretchingLeft,
  43561. isStretchingBottom, isStretchingRight);
  43562. x += border.getLeft();
  43563. y += border.getTop();
  43564. w -= border.getLeftAndRight();
  43565. h -= border.getTopAndBottom();
  43566. }
  43567. else
  43568. {
  43569. checkBounds (x, y, w, h,
  43570. component->getBounds(), limits,
  43571. isStretchingTop, isStretchingLeft,
  43572. isStretchingBottom, isStretchingRight);
  43573. }
  43574. applyBoundsToComponent (component, x, y, w, h);
  43575. }
  43576. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  43577. int x, int y, int w, int h)
  43578. {
  43579. component->setBounds (x, y, w, h);
  43580. }
  43581. void ComponentBoundsConstrainer::resizeStart()
  43582. {
  43583. }
  43584. void ComponentBoundsConstrainer::resizeEnd()
  43585. {
  43586. }
  43587. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  43588. const Rectangle& old,
  43589. const Rectangle& limits,
  43590. const bool isStretchingTop,
  43591. const bool isStretchingLeft,
  43592. const bool isStretchingBottom,
  43593. const bool isStretchingRight)
  43594. {
  43595. // constrain the size if it's being stretched..
  43596. if (isStretchingLeft)
  43597. {
  43598. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  43599. w = old.getRight() - x;
  43600. }
  43601. if (isStretchingRight)
  43602. {
  43603. w = jlimit (minW, maxW, w);
  43604. }
  43605. if (isStretchingTop)
  43606. {
  43607. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  43608. h = old.getBottom() - y;
  43609. }
  43610. if (isStretchingBottom)
  43611. {
  43612. h = jlimit (minH, maxH, h);
  43613. }
  43614. // constrain the aspect ratio if one has been specified..
  43615. if (aspectRatio > 0.0 && w > 0 && h > 0)
  43616. {
  43617. bool adjustWidth;
  43618. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43619. {
  43620. adjustWidth = true;
  43621. }
  43622. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43623. {
  43624. adjustWidth = false;
  43625. }
  43626. else
  43627. {
  43628. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  43629. const double newRatio = fabs (w / (double) h);
  43630. adjustWidth = (oldRatio > newRatio);
  43631. }
  43632. if (adjustWidth)
  43633. {
  43634. w = roundDoubleToInt (h * aspectRatio);
  43635. if (w > maxW || w < minW)
  43636. {
  43637. w = jlimit (minW, maxW, w);
  43638. h = roundDoubleToInt (w / aspectRatio);
  43639. }
  43640. }
  43641. else
  43642. {
  43643. h = roundDoubleToInt (w / aspectRatio);
  43644. if (h > maxH || h < minH)
  43645. {
  43646. h = jlimit (minH, maxH, h);
  43647. w = roundDoubleToInt (h * aspectRatio);
  43648. }
  43649. }
  43650. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43651. {
  43652. x = old.getX() + (old.getWidth() - w) / 2;
  43653. }
  43654. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43655. {
  43656. y = old.getY() + (old.getHeight() - h) / 2;
  43657. }
  43658. else
  43659. {
  43660. if (isStretchingLeft)
  43661. x = old.getRight() - w;
  43662. if (isStretchingTop)
  43663. y = old.getBottom() - h;
  43664. }
  43665. }
  43666. // ...and constrain the position if limits have been set for that.
  43667. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  43668. {
  43669. if (minOffTop > 0)
  43670. {
  43671. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  43672. if (y < limit)
  43673. {
  43674. if (isStretchingTop)
  43675. h -= (limit - y);
  43676. y = limit;
  43677. }
  43678. }
  43679. if (minOffLeft > 0)
  43680. {
  43681. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  43682. if (x < limit)
  43683. {
  43684. if (isStretchingLeft)
  43685. w -= (limit - x);
  43686. x = limit;
  43687. }
  43688. }
  43689. if (minOffBottom > 0)
  43690. {
  43691. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  43692. if (y > limit)
  43693. {
  43694. if (isStretchingBottom)
  43695. h += (limit - y);
  43696. else
  43697. y = limit;
  43698. }
  43699. }
  43700. if (minOffRight > 0)
  43701. {
  43702. const int limit = limits.getRight() - jmin (minOffRight, w);
  43703. if (x > limit)
  43704. {
  43705. if (isStretchingRight)
  43706. w += (limit - x);
  43707. else
  43708. x = limit;
  43709. }
  43710. }
  43711. }
  43712. jassert (w >= 0 && h >= 0);
  43713. }
  43714. END_JUCE_NAMESPACE
  43715. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43716. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43717. BEGIN_JUCE_NAMESPACE
  43718. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  43719. : component (component_),
  43720. lastPeer (0),
  43721. registeredParentComps (4),
  43722. reentrant (false)
  43723. {
  43724. jassert (component != 0); // can't use this with a null pointer..
  43725. #ifdef JUCE_DEBUG
  43726. deletionWatcher = new ComponentDeletionWatcher (component_);
  43727. #endif
  43728. component->addComponentListener (this);
  43729. registerWithParentComps();
  43730. }
  43731. ComponentMovementWatcher::~ComponentMovementWatcher()
  43732. {
  43733. component->removeComponentListener (this);
  43734. unregister();
  43735. #ifdef JUCE_DEBUG
  43736. delete deletionWatcher;
  43737. #endif
  43738. }
  43739. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  43740. {
  43741. #ifdef JUCE_DEBUG
  43742. // agh! don't delete the target component without deleting this object first!
  43743. jassert (! deletionWatcher->hasBeenDeleted());
  43744. #endif
  43745. if (! reentrant)
  43746. {
  43747. reentrant = true;
  43748. ComponentPeer* const peer = component->getPeer();
  43749. if (peer != lastPeer)
  43750. {
  43751. ComponentDeletionWatcher watcher (component);
  43752. componentPeerChanged();
  43753. if (watcher.hasBeenDeleted())
  43754. return;
  43755. lastPeer = peer;
  43756. }
  43757. unregister();
  43758. registerWithParentComps();
  43759. reentrant = false;
  43760. componentMovedOrResized (*component, true, true);
  43761. }
  43762. }
  43763. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  43764. {
  43765. #ifdef JUCE_DEBUG
  43766. // agh! don't delete the target component without deleting this object first!
  43767. jassert (! deletionWatcher->hasBeenDeleted());
  43768. #endif
  43769. if (wasMoved)
  43770. {
  43771. int x = 0, y = 0;
  43772. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  43773. wasMoved = (lastX != x || lastY != y);
  43774. lastX = x;
  43775. lastY = y;
  43776. }
  43777. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  43778. lastWidth = component->getWidth();
  43779. lastHeight = component->getHeight();
  43780. if (wasMoved || wasResized)
  43781. componentMovedOrResized (wasMoved, wasResized);
  43782. }
  43783. void ComponentMovementWatcher::registerWithParentComps() throw()
  43784. {
  43785. Component* p = component->getParentComponent();
  43786. while (p != 0)
  43787. {
  43788. p->addComponentListener (this);
  43789. registeredParentComps.add (p);
  43790. p = p->getParentComponent();
  43791. }
  43792. }
  43793. void ComponentMovementWatcher::unregister() throw()
  43794. {
  43795. for (int i = registeredParentComps.size(); --i >= 0;)
  43796. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  43797. registeredParentComps.clear();
  43798. }
  43799. END_JUCE_NAMESPACE
  43800. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43801. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  43802. BEGIN_JUCE_NAMESPACE
  43803. GroupComponent::GroupComponent (const String& componentName,
  43804. const String& labelText)
  43805. : Component (componentName),
  43806. text (labelText),
  43807. justification (Justification::left)
  43808. {
  43809. setInterceptsMouseClicks (false, true);
  43810. }
  43811. GroupComponent::~GroupComponent()
  43812. {
  43813. }
  43814. void GroupComponent::setText (const String& newText) throw()
  43815. {
  43816. if (text != newText)
  43817. {
  43818. text = newText;
  43819. repaint();
  43820. }
  43821. }
  43822. const String GroupComponent::getText() const throw()
  43823. {
  43824. return text;
  43825. }
  43826. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  43827. {
  43828. if (justification.getFlags() != newJustification.getFlags())
  43829. {
  43830. justification = newJustification;
  43831. repaint();
  43832. }
  43833. }
  43834. void GroupComponent::paint (Graphics& g)
  43835. {
  43836. getLookAndFeel()
  43837. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  43838. text, justification,
  43839. *this);
  43840. }
  43841. void GroupComponent::enablementChanged()
  43842. {
  43843. repaint();
  43844. }
  43845. void GroupComponent::colourChanged()
  43846. {
  43847. repaint();
  43848. }
  43849. END_JUCE_NAMESPACE
  43850. /********* End of inlined file: juce_GroupComponent.cpp *********/
  43851. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  43852. BEGIN_JUCE_NAMESPACE
  43853. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  43854. : DocumentWindow (String::empty, backgroundColour,
  43855. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  43856. {
  43857. }
  43858. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  43859. {
  43860. }
  43861. void MultiDocumentPanelWindow::maximiseButtonPressed()
  43862. {
  43863. MultiDocumentPanel* const owner = getOwner();
  43864. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  43865. if (owner != 0)
  43866. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  43867. }
  43868. void MultiDocumentPanelWindow::closeButtonPressed()
  43869. {
  43870. MultiDocumentPanel* const owner = getOwner();
  43871. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  43872. if (owner != 0)
  43873. owner->closeDocument (getContentComponent(), true);
  43874. }
  43875. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  43876. {
  43877. DocumentWindow::activeWindowStatusChanged();
  43878. updateOrder();
  43879. }
  43880. void MultiDocumentPanelWindow::broughtToFront()
  43881. {
  43882. DocumentWindow::broughtToFront();
  43883. updateOrder();
  43884. }
  43885. void MultiDocumentPanelWindow::updateOrder()
  43886. {
  43887. MultiDocumentPanel* const owner = getOwner();
  43888. if (owner != 0)
  43889. owner->updateOrder();
  43890. }
  43891. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  43892. {
  43893. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  43894. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  43895. }
  43896. class MDITabbedComponentInternal : public TabbedComponent
  43897. {
  43898. public:
  43899. MDITabbedComponentInternal()
  43900. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  43901. {
  43902. }
  43903. ~MDITabbedComponentInternal()
  43904. {
  43905. }
  43906. void currentTabChanged (const int, const String&)
  43907. {
  43908. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  43909. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  43910. if (owner != 0)
  43911. owner->updateOrder();
  43912. }
  43913. };
  43914. MultiDocumentPanel::MultiDocumentPanel()
  43915. : mode (MaximisedWindowsWithTabs),
  43916. tabComponent (0),
  43917. backgroundColour (Colours::lightblue),
  43918. maximumNumDocuments (0),
  43919. numDocsBeforeTabsUsed (0)
  43920. {
  43921. setOpaque (true);
  43922. }
  43923. MultiDocumentPanel::~MultiDocumentPanel()
  43924. {
  43925. closeAllDocuments (false);
  43926. }
  43927. static bool shouldDeleteComp (Component* const c)
  43928. {
  43929. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  43930. }
  43931. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  43932. {
  43933. while (components.size() > 0)
  43934. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  43935. return false;
  43936. return true;
  43937. }
  43938. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  43939. {
  43940. return new MultiDocumentPanelWindow (backgroundColour);
  43941. }
  43942. void MultiDocumentPanel::addWindow (Component* component)
  43943. {
  43944. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  43945. dw->setResizable (true, false);
  43946. dw->setContentComponent (component, false, true);
  43947. dw->setName (component->getName());
  43948. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  43949. int x = 4;
  43950. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  43951. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  43952. x += 16;
  43953. dw->setTopLeftPosition (x, x);
  43954. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  43955. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  43956. addAndMakeVisible (dw);
  43957. dw->toFront (true);
  43958. }
  43959. bool MultiDocumentPanel::addDocument (Component* const component,
  43960. const Colour& backgroundColour,
  43961. const bool deleteWhenRemoved)
  43962. {
  43963. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  43964. // with a frame-within-a-frame! Just pass in the bare content component.
  43965. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  43966. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  43967. return false;
  43968. components.add (component);
  43969. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  43970. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  43971. component->addComponentListener (this);
  43972. if (mode == FloatingWindows)
  43973. {
  43974. if (isFullscreenWhenOneDocument())
  43975. {
  43976. if (components.size() == 1)
  43977. {
  43978. addAndMakeVisible (component);
  43979. }
  43980. else
  43981. {
  43982. if (components.size() == 2)
  43983. addWindow (components.getFirst());
  43984. addWindow (component);
  43985. }
  43986. }
  43987. else
  43988. {
  43989. addWindow (component);
  43990. }
  43991. }
  43992. else
  43993. {
  43994. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  43995. {
  43996. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  43997. Array <Component*> temp (components);
  43998. for (int i = 0; i < temp.size(); ++i)
  43999. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  44000. resized();
  44001. }
  44002. else
  44003. {
  44004. if (tabComponent != 0)
  44005. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  44006. else
  44007. addAndMakeVisible (component);
  44008. }
  44009. setActiveDocument (component);
  44010. }
  44011. resized();
  44012. activeDocumentChanged();
  44013. return true;
  44014. }
  44015. bool MultiDocumentPanel::closeDocument (Component* component,
  44016. const bool checkItsOkToCloseFirst)
  44017. {
  44018. if (components.contains (component))
  44019. {
  44020. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  44021. return false;
  44022. component->removeComponentListener (this);
  44023. const bool shouldDelete = shouldDeleteComp (component);
  44024. component->removeComponentProperty (T("mdiDocumentDelete_"));
  44025. component->removeComponentProperty (T("mdiDocumentBkg_"));
  44026. if (mode == FloatingWindows)
  44027. {
  44028. for (int i = getNumChildComponents(); --i >= 0;)
  44029. {
  44030. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44031. if (dw != 0 && dw->getContentComponent() == component)
  44032. {
  44033. dw->setContentComponent (0, false);
  44034. delete dw;
  44035. break;
  44036. }
  44037. }
  44038. if (shouldDelete)
  44039. delete component;
  44040. components.removeValue (component);
  44041. if (isFullscreenWhenOneDocument() && components.size() == 1)
  44042. {
  44043. for (int i = getNumChildComponents(); --i >= 0;)
  44044. {
  44045. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44046. if (dw != 0)
  44047. {
  44048. dw->setContentComponent (0, false);
  44049. delete dw;
  44050. }
  44051. }
  44052. addAndMakeVisible (components.getFirst());
  44053. }
  44054. }
  44055. else
  44056. {
  44057. jassert (components.indexOf (component) >= 0);
  44058. if (tabComponent != 0)
  44059. {
  44060. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44061. if (tabComponent->getTabContentComponent (i) == component)
  44062. tabComponent->removeTab (i);
  44063. }
  44064. else
  44065. {
  44066. removeChildComponent (component);
  44067. }
  44068. if (shouldDelete)
  44069. delete component;
  44070. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  44071. deleteAndZero (tabComponent);
  44072. components.removeValue (component);
  44073. if (components.size() > 0 && tabComponent == 0)
  44074. addAndMakeVisible (components.getFirst());
  44075. }
  44076. resized();
  44077. activeDocumentChanged();
  44078. }
  44079. else
  44080. {
  44081. jassertfalse
  44082. }
  44083. return true;
  44084. }
  44085. int MultiDocumentPanel::getNumDocuments() const throw()
  44086. {
  44087. return components.size();
  44088. }
  44089. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  44090. {
  44091. return components [index];
  44092. }
  44093. Component* MultiDocumentPanel::getActiveDocument() const throw()
  44094. {
  44095. if (mode == FloatingWindows)
  44096. {
  44097. for (int i = getNumChildComponents(); --i >= 0;)
  44098. {
  44099. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44100. if (dw != 0 && dw->isActiveWindow())
  44101. return dw->getContentComponent();
  44102. }
  44103. }
  44104. return components.getLast();
  44105. }
  44106. void MultiDocumentPanel::setActiveDocument (Component* component)
  44107. {
  44108. if (mode == FloatingWindows)
  44109. {
  44110. component = getContainerComp (component);
  44111. if (component != 0)
  44112. component->toFront (true);
  44113. }
  44114. else if (tabComponent != 0)
  44115. {
  44116. jassert (components.indexOf (component) >= 0);
  44117. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44118. {
  44119. if (tabComponent->getTabContentComponent (i) == component)
  44120. {
  44121. tabComponent->setCurrentTabIndex (i);
  44122. break;
  44123. }
  44124. }
  44125. }
  44126. else
  44127. {
  44128. component->grabKeyboardFocus();
  44129. }
  44130. }
  44131. void MultiDocumentPanel::activeDocumentChanged()
  44132. {
  44133. }
  44134. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  44135. {
  44136. maximumNumDocuments = newNumber;
  44137. }
  44138. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  44139. {
  44140. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  44141. }
  44142. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  44143. {
  44144. return numDocsBeforeTabsUsed != 0;
  44145. }
  44146. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  44147. {
  44148. if (mode != newLayoutMode)
  44149. {
  44150. mode = newLayoutMode;
  44151. if (mode == FloatingWindows)
  44152. {
  44153. deleteAndZero (tabComponent);
  44154. }
  44155. else
  44156. {
  44157. for (int i = getNumChildComponents(); --i >= 0;)
  44158. {
  44159. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44160. if (dw != 0)
  44161. {
  44162. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  44163. dw->setContentComponent (0, false);
  44164. delete dw;
  44165. }
  44166. }
  44167. }
  44168. resized();
  44169. const Array <Component*> tempComps (components);
  44170. components.clear();
  44171. for (int i = 0; i < tempComps.size(); ++i)
  44172. {
  44173. Component* const c = tempComps.getUnchecked(i);
  44174. addDocument (c,
  44175. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  44176. shouldDeleteComp (c));
  44177. }
  44178. }
  44179. }
  44180. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  44181. {
  44182. if (backgroundColour != newBackgroundColour)
  44183. {
  44184. backgroundColour = newBackgroundColour;
  44185. setOpaque (newBackgroundColour.isOpaque());
  44186. repaint();
  44187. }
  44188. }
  44189. void MultiDocumentPanel::paint (Graphics& g)
  44190. {
  44191. g.fillAll (backgroundColour);
  44192. }
  44193. void MultiDocumentPanel::resized()
  44194. {
  44195. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  44196. {
  44197. for (int i = getNumChildComponents(); --i >= 0;)
  44198. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  44199. }
  44200. setWantsKeyboardFocus (components.size() == 0);
  44201. }
  44202. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  44203. {
  44204. if (mode == FloatingWindows)
  44205. {
  44206. for (int i = 0; i < getNumChildComponents(); ++i)
  44207. {
  44208. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44209. if (dw != 0 && dw->getContentComponent() == c)
  44210. {
  44211. c = dw;
  44212. break;
  44213. }
  44214. }
  44215. }
  44216. return c;
  44217. }
  44218. void MultiDocumentPanel::componentNameChanged (Component&)
  44219. {
  44220. if (mode == FloatingWindows)
  44221. {
  44222. for (int i = 0; i < getNumChildComponents(); ++i)
  44223. {
  44224. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44225. if (dw != 0)
  44226. dw->setName (dw->getContentComponent()->getName());
  44227. }
  44228. }
  44229. else if (tabComponent != 0)
  44230. {
  44231. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44232. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  44233. }
  44234. }
  44235. void MultiDocumentPanel::updateOrder()
  44236. {
  44237. const Array <Component*> oldList (components);
  44238. if (mode == FloatingWindows)
  44239. {
  44240. components.clear();
  44241. for (int i = 0; i < getNumChildComponents(); ++i)
  44242. {
  44243. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44244. if (dw != 0)
  44245. components.add (dw->getContentComponent());
  44246. }
  44247. }
  44248. else
  44249. {
  44250. if (tabComponent != 0)
  44251. {
  44252. Component* const current = tabComponent->getCurrentContentComponent();
  44253. if (current != 0)
  44254. {
  44255. components.removeValue (current);
  44256. components.add (current);
  44257. }
  44258. }
  44259. }
  44260. if (components != oldList)
  44261. activeDocumentChanged();
  44262. }
  44263. END_JUCE_NAMESPACE
  44264. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  44265. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  44266. BEGIN_JUCE_NAMESPACE
  44267. const int zoneL = 1;
  44268. const int zoneR = 2;
  44269. const int zoneT = 4;
  44270. const int zoneB = 8;
  44271. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  44272. ComponentBoundsConstrainer* const constrainer_)
  44273. : component (componentToResize),
  44274. constrainer (constrainer_),
  44275. borderSize (5),
  44276. mouseZone (0)
  44277. {
  44278. }
  44279. ResizableBorderComponent::~ResizableBorderComponent()
  44280. {
  44281. }
  44282. void ResizableBorderComponent::paint (Graphics& g)
  44283. {
  44284. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  44285. }
  44286. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  44287. {
  44288. updateMouseZone (e);
  44289. }
  44290. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  44291. {
  44292. updateMouseZone (e);
  44293. }
  44294. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  44295. {
  44296. if (component->isValidComponent())
  44297. {
  44298. updateMouseZone (e);
  44299. originalX = component->getX();
  44300. originalY = component->getY();
  44301. originalW = component->getWidth();
  44302. originalH = component->getHeight();
  44303. if (constrainer != 0)
  44304. constrainer->resizeStart();
  44305. }
  44306. else
  44307. {
  44308. jassertfalse
  44309. }
  44310. }
  44311. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  44312. {
  44313. if (! component->isValidComponent())
  44314. {
  44315. jassertfalse
  44316. return;
  44317. }
  44318. int x = originalX;
  44319. int y = originalY;
  44320. int w = originalW;
  44321. int h = originalH;
  44322. const int dx = e.getDistanceFromDragStartX();
  44323. const int dy = e.getDistanceFromDragStartY();
  44324. if ((mouseZone & zoneL) != 0)
  44325. {
  44326. x += dx;
  44327. w -= dx;
  44328. }
  44329. if ((mouseZone & zoneT) != 0)
  44330. {
  44331. y += dy;
  44332. h -= dy;
  44333. }
  44334. if ((mouseZone & zoneR) != 0)
  44335. w += dx;
  44336. if ((mouseZone & zoneB) != 0)
  44337. h += dy;
  44338. if (constrainer != 0)
  44339. constrainer->setBoundsForComponent (component,
  44340. x, y, w, h,
  44341. (mouseZone & zoneT) != 0,
  44342. (mouseZone & zoneL) != 0,
  44343. (mouseZone & zoneB) != 0,
  44344. (mouseZone & zoneR) != 0);
  44345. else
  44346. component->setBounds (x, y, w, h);
  44347. }
  44348. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  44349. {
  44350. if (constrainer != 0)
  44351. constrainer->resizeEnd();
  44352. }
  44353. bool ResizableBorderComponent::hitTest (int x, int y)
  44354. {
  44355. return x < borderSize.getLeft()
  44356. || x >= getWidth() - borderSize.getRight()
  44357. || y < borderSize.getTop()
  44358. || y >= getHeight() - borderSize.getBottom();
  44359. }
  44360. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  44361. {
  44362. if (borderSize != newBorderSize)
  44363. {
  44364. borderSize = newBorderSize;
  44365. repaint();
  44366. }
  44367. }
  44368. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  44369. {
  44370. return borderSize;
  44371. }
  44372. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  44373. {
  44374. int newZone = 0;
  44375. if (ResizableBorderComponent::hitTest (e.x, e.y))
  44376. {
  44377. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  44378. newZone |= zoneL;
  44379. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  44380. newZone |= zoneR;
  44381. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  44382. newZone |= zoneT;
  44383. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  44384. newZone |= zoneB;
  44385. }
  44386. if (mouseZone != newZone)
  44387. {
  44388. mouseZone = newZone;
  44389. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  44390. switch (newZone)
  44391. {
  44392. case (zoneL | zoneT):
  44393. mc = MouseCursor::TopLeftCornerResizeCursor;
  44394. break;
  44395. case zoneT:
  44396. mc = MouseCursor::TopEdgeResizeCursor;
  44397. break;
  44398. case (zoneR | zoneT):
  44399. mc = MouseCursor::TopRightCornerResizeCursor;
  44400. break;
  44401. case zoneL:
  44402. mc = MouseCursor::LeftEdgeResizeCursor;
  44403. break;
  44404. case zoneR:
  44405. mc = MouseCursor::RightEdgeResizeCursor;
  44406. break;
  44407. case (zoneL | zoneB):
  44408. mc = MouseCursor::BottomLeftCornerResizeCursor;
  44409. break;
  44410. case zoneB:
  44411. mc = MouseCursor::BottomEdgeResizeCursor;
  44412. break;
  44413. case (zoneR | zoneB):
  44414. mc = MouseCursor::BottomRightCornerResizeCursor;
  44415. break;
  44416. default:
  44417. break;
  44418. }
  44419. setMouseCursor (mc);
  44420. }
  44421. }
  44422. END_JUCE_NAMESPACE
  44423. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  44424. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  44425. BEGIN_JUCE_NAMESPACE
  44426. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  44427. ComponentBoundsConstrainer* const constrainer_)
  44428. : component (componentToResize),
  44429. constrainer (constrainer_)
  44430. {
  44431. setRepaintsOnMouseActivity (true);
  44432. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  44433. }
  44434. ResizableCornerComponent::~ResizableCornerComponent()
  44435. {
  44436. }
  44437. void ResizableCornerComponent::paint (Graphics& g)
  44438. {
  44439. getLookAndFeel()
  44440. .drawCornerResizer (g, getWidth(), getHeight(),
  44441. isMouseOverOrDragging(),
  44442. isMouseButtonDown());
  44443. }
  44444. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  44445. {
  44446. if (component->isValidComponent())
  44447. {
  44448. originalX = component->getX();
  44449. originalY = component->getY();
  44450. originalW = component->getWidth();
  44451. originalH = component->getHeight();
  44452. if (constrainer != 0)
  44453. constrainer->resizeStart();
  44454. }
  44455. else
  44456. {
  44457. jassertfalse
  44458. }
  44459. }
  44460. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  44461. {
  44462. if (! component->isValidComponent())
  44463. {
  44464. jassertfalse
  44465. return;
  44466. }
  44467. int x = originalX;
  44468. int y = originalY;
  44469. int w = originalW + e.getDistanceFromDragStartX();
  44470. int h = originalH + e.getDistanceFromDragStartY();
  44471. if (constrainer != 0)
  44472. constrainer->setBoundsForComponent (component, x, y, w, h,
  44473. false, false, true, true);
  44474. else
  44475. component->setBounds (x, y, w, h);
  44476. }
  44477. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  44478. {
  44479. if (constrainer != 0)
  44480. constrainer->resizeStart();
  44481. }
  44482. bool ResizableCornerComponent::hitTest (int x, int y)
  44483. {
  44484. if (getWidth() <= 0)
  44485. return false;
  44486. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  44487. return y >= yAtX - getHeight() / 4;
  44488. }
  44489. END_JUCE_NAMESPACE
  44490. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  44491. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  44492. BEGIN_JUCE_NAMESPACE
  44493. class ScrollbarButton : public Button
  44494. {
  44495. public:
  44496. int direction;
  44497. ScrollbarButton (const int direction_,
  44498. ScrollBar& owner_) throw()
  44499. : Button (String::empty),
  44500. direction (direction_),
  44501. owner (owner_)
  44502. {
  44503. setWantsKeyboardFocus (false);
  44504. }
  44505. ~ScrollbarButton()
  44506. {
  44507. }
  44508. void paintButton (Graphics& g,
  44509. bool isMouseOver,
  44510. bool isMouseDown)
  44511. {
  44512. getLookAndFeel()
  44513. .drawScrollbarButton (g, owner,
  44514. getWidth(), getHeight(),
  44515. direction,
  44516. owner.isVertical(),
  44517. isMouseOver, isMouseDown);
  44518. }
  44519. void clicked()
  44520. {
  44521. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  44522. }
  44523. juce_UseDebuggingNewOperator
  44524. private:
  44525. ScrollBar& owner;
  44526. ScrollbarButton (const ScrollbarButton&);
  44527. const ScrollbarButton& operator= (const ScrollbarButton&);
  44528. };
  44529. ScrollBar::ScrollBar (const bool vertical_,
  44530. const bool buttonsAreVisible)
  44531. : minimum (0.0),
  44532. maximum (1.0),
  44533. rangeStart (0.0),
  44534. rangeSize (0.1),
  44535. singleStepSize (0.1),
  44536. thumbAreaStart (0),
  44537. thumbAreaSize (0),
  44538. thumbStart (0),
  44539. thumbSize (0),
  44540. initialDelayInMillisecs (100),
  44541. repeatDelayInMillisecs (50),
  44542. minimumDelayInMillisecs (10),
  44543. vertical (vertical_),
  44544. isDraggingThumb (false),
  44545. alwaysVisible (false),
  44546. upButton (0),
  44547. downButton (0),
  44548. listeners (2)
  44549. {
  44550. setButtonVisibility (buttonsAreVisible);
  44551. setRepaintsOnMouseActivity (true);
  44552. setFocusContainer (true);
  44553. }
  44554. ScrollBar::~ScrollBar()
  44555. {
  44556. deleteAllChildren();
  44557. }
  44558. void ScrollBar::setRangeLimits (const double newMinimum,
  44559. const double newMaximum) throw()
  44560. {
  44561. minimum = newMinimum;
  44562. maximum = newMaximum;
  44563. jassert (maximum >= minimum); // these can't be the wrong way round!
  44564. setCurrentRangeStart (rangeStart);
  44565. updateThumbPosition();
  44566. }
  44567. void ScrollBar::setCurrentRange (double newStart,
  44568. double newSize) throw()
  44569. {
  44570. newSize = jlimit (0.0, maximum - minimum, newSize);
  44571. newStart = jlimit (minimum, maximum - newSize, newStart);
  44572. if (rangeStart != newStart
  44573. || rangeSize != newSize)
  44574. {
  44575. rangeStart = newStart;
  44576. rangeSize = newSize;
  44577. updateThumbPosition();
  44578. triggerAsyncUpdate();
  44579. }
  44580. }
  44581. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  44582. {
  44583. setCurrentRange (newStart, rangeSize);
  44584. }
  44585. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  44586. {
  44587. singleStepSize = newSingleStepSize;
  44588. }
  44589. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  44590. {
  44591. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  44592. }
  44593. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  44594. {
  44595. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  44596. }
  44597. void ScrollBar::scrollToTop() throw()
  44598. {
  44599. setCurrentRangeStart (minimum);
  44600. }
  44601. void ScrollBar::scrollToBottom() throw()
  44602. {
  44603. setCurrentRangeStart (maximum - rangeSize);
  44604. }
  44605. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  44606. const int repeatDelayInMillisecs_,
  44607. const int minimumDelayInMillisecs_) throw()
  44608. {
  44609. initialDelayInMillisecs = initialDelayInMillisecs_;
  44610. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  44611. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  44612. if (upButton != 0)
  44613. {
  44614. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44615. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44616. }
  44617. }
  44618. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  44619. {
  44620. jassert (listener != 0);
  44621. if (listener != 0)
  44622. listeners.add (listener);
  44623. }
  44624. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  44625. {
  44626. listeners.removeValue (listener);
  44627. }
  44628. void ScrollBar::handleAsyncUpdate()
  44629. {
  44630. const double value = getCurrentRangeStart();
  44631. for (int i = listeners.size(); --i >= 0;)
  44632. {
  44633. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  44634. i = jmin (i, listeners.size());
  44635. }
  44636. }
  44637. void ScrollBar::updateThumbPosition() throw()
  44638. {
  44639. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  44640. : thumbAreaSize);
  44641. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44642. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  44643. if (newThumbSize > thumbAreaSize)
  44644. newThumbSize = thumbAreaSize;
  44645. int newThumbStart = thumbAreaStart;
  44646. if (maximum - minimum > rangeSize)
  44647. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  44648. / ((maximum - minimum) - rangeSize));
  44649. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  44650. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  44651. {
  44652. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  44653. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  44654. if (vertical)
  44655. repaint (0, repaintStart, getWidth(), repaintSize);
  44656. else
  44657. repaint (repaintStart, 0, repaintSize, getHeight());
  44658. thumbStart = newThumbStart;
  44659. thumbSize = newThumbSize;
  44660. }
  44661. }
  44662. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  44663. {
  44664. if (vertical != shouldBeVertical)
  44665. {
  44666. vertical = shouldBeVertical;
  44667. if (upButton != 0)
  44668. {
  44669. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  44670. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  44671. }
  44672. updateThumbPosition();
  44673. }
  44674. }
  44675. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  44676. {
  44677. deleteAndZero (upButton);
  44678. deleteAndZero (downButton);
  44679. if (buttonsAreVisible)
  44680. {
  44681. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  44682. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  44683. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44684. }
  44685. updateThumbPosition();
  44686. }
  44687. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  44688. {
  44689. alwaysVisible = ! shouldHideWhenFullRange;
  44690. updateThumbPosition();
  44691. }
  44692. void ScrollBar::paint (Graphics& g)
  44693. {
  44694. if (thumbAreaSize > 0)
  44695. {
  44696. LookAndFeel& lf = getLookAndFeel();
  44697. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  44698. ? thumbSize : 0;
  44699. if (vertical)
  44700. {
  44701. lf.drawScrollbar (g, *this,
  44702. 0, thumbAreaStart,
  44703. getWidth(), thumbAreaSize,
  44704. vertical,
  44705. thumbStart, thumb,
  44706. isMouseOver(), isMouseButtonDown());
  44707. }
  44708. else
  44709. {
  44710. lf.drawScrollbar (g, *this,
  44711. thumbAreaStart, 0,
  44712. thumbAreaSize, getHeight(),
  44713. vertical,
  44714. thumbStart, thumb,
  44715. isMouseOver(), isMouseButtonDown());
  44716. }
  44717. }
  44718. }
  44719. void ScrollBar::lookAndFeelChanged()
  44720. {
  44721. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  44722. }
  44723. void ScrollBar::resized()
  44724. {
  44725. const int length = ((vertical) ? getHeight() : getWidth());
  44726. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  44727. : 0;
  44728. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44729. {
  44730. thumbAreaStart = length >> 1;
  44731. thumbAreaSize = 0;
  44732. }
  44733. else
  44734. {
  44735. thumbAreaStart = buttonSize;
  44736. thumbAreaSize = length - (buttonSize << 1);
  44737. }
  44738. if (upButton != 0)
  44739. {
  44740. if (vertical)
  44741. {
  44742. upButton->setBounds (0, 0, getWidth(), buttonSize);
  44743. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  44744. }
  44745. else
  44746. {
  44747. upButton->setBounds (0, 0, buttonSize, getHeight());
  44748. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  44749. }
  44750. }
  44751. updateThumbPosition();
  44752. }
  44753. void ScrollBar::mouseDown (const MouseEvent& e)
  44754. {
  44755. isDraggingThumb = false;
  44756. lastMousePos = vertical ? e.y : e.x;
  44757. dragStartMousePos = lastMousePos;
  44758. dragStartRange = rangeStart;
  44759. if (dragStartMousePos < thumbStart)
  44760. {
  44761. moveScrollbarInPages (-1);
  44762. startTimer (400);
  44763. }
  44764. else if (dragStartMousePos >= thumbStart + thumbSize)
  44765. {
  44766. moveScrollbarInPages (1);
  44767. startTimer (400);
  44768. }
  44769. else
  44770. {
  44771. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44772. && (thumbAreaSize > thumbSize);
  44773. }
  44774. }
  44775. void ScrollBar::mouseDrag (const MouseEvent& e)
  44776. {
  44777. if (isDraggingThumb)
  44778. {
  44779. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  44780. setCurrentRangeStart (dragStartRange
  44781. + deltaPixels * ((maximum - minimum) - rangeSize)
  44782. / (thumbAreaSize - thumbSize));
  44783. }
  44784. else
  44785. {
  44786. lastMousePos = (vertical) ? e.y : e.x;
  44787. }
  44788. }
  44789. void ScrollBar::mouseUp (const MouseEvent&)
  44790. {
  44791. isDraggingThumb = false;
  44792. stopTimer();
  44793. repaint();
  44794. }
  44795. void ScrollBar::mouseWheelMove (const MouseEvent&,
  44796. float wheelIncrementX,
  44797. float wheelIncrementY)
  44798. {
  44799. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  44800. if (increment < 0)
  44801. increment = jmin (increment * 10.0f, -1.0f);
  44802. else if (increment > 0)
  44803. increment = jmax (increment * 10.0f, 1.0f);
  44804. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  44805. }
  44806. void ScrollBar::timerCallback()
  44807. {
  44808. if (isMouseButtonDown())
  44809. {
  44810. startTimer (40);
  44811. if (lastMousePos < thumbStart)
  44812. setCurrentRangeStart (rangeStart - rangeSize);
  44813. else if (lastMousePos > thumbStart + thumbSize)
  44814. setCurrentRangeStart (rangeStart + rangeSize);
  44815. }
  44816. else
  44817. {
  44818. stopTimer();
  44819. }
  44820. }
  44821. bool ScrollBar::keyPressed (const KeyPress& key)
  44822. {
  44823. if (! isVisible())
  44824. return false;
  44825. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  44826. moveScrollbarInSteps (-1);
  44827. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  44828. moveScrollbarInSteps (1);
  44829. else if (key.isKeyCode (KeyPress::pageUpKey))
  44830. moveScrollbarInPages (-1);
  44831. else if (key.isKeyCode (KeyPress::pageDownKey))
  44832. moveScrollbarInPages (1);
  44833. else if (key.isKeyCode (KeyPress::homeKey))
  44834. scrollToTop();
  44835. else if (key.isKeyCode (KeyPress::endKey))
  44836. scrollToBottom();
  44837. else
  44838. return false;
  44839. return true;
  44840. }
  44841. END_JUCE_NAMESPACE
  44842. /********* End of inlined file: juce_ScrollBar.cpp *********/
  44843. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  44844. BEGIN_JUCE_NAMESPACE
  44845. StretchableLayoutManager::StretchableLayoutManager()
  44846. : totalSize (0)
  44847. {
  44848. }
  44849. StretchableLayoutManager::~StretchableLayoutManager()
  44850. {
  44851. }
  44852. void StretchableLayoutManager::clearAllItems()
  44853. {
  44854. items.clear();
  44855. totalSize = 0;
  44856. }
  44857. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  44858. const double minimumSize,
  44859. const double maximumSize,
  44860. const double preferredSize)
  44861. {
  44862. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  44863. if (layout == 0)
  44864. {
  44865. layout = new ItemLayoutProperties();
  44866. layout->itemIndex = itemIndex;
  44867. int i;
  44868. for (i = 0; i < items.size(); ++i)
  44869. if (items.getUnchecked (i)->itemIndex > itemIndex)
  44870. break;
  44871. items.insert (i, layout);
  44872. }
  44873. layout->minSize = minimumSize;
  44874. layout->maxSize = maximumSize;
  44875. layout->preferredSize = preferredSize;
  44876. layout->currentSize = 0;
  44877. }
  44878. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  44879. double& minimumSize,
  44880. double& maximumSize,
  44881. double& preferredSize) const
  44882. {
  44883. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44884. if (layout != 0)
  44885. {
  44886. minimumSize = layout->minSize;
  44887. maximumSize = layout->maxSize;
  44888. preferredSize = layout->preferredSize;
  44889. return true;
  44890. }
  44891. return false;
  44892. }
  44893. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  44894. {
  44895. totalSize = newTotalSize;
  44896. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  44897. }
  44898. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  44899. {
  44900. int pos = 0;
  44901. for (int i = 0; i < itemIndex; ++i)
  44902. {
  44903. const ItemLayoutProperties* const layout = getInfoFor (i);
  44904. if (layout != 0)
  44905. pos += layout->currentSize;
  44906. }
  44907. return pos;
  44908. }
  44909. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  44910. {
  44911. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44912. if (layout != 0)
  44913. return layout->currentSize;
  44914. return 0;
  44915. }
  44916. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  44917. {
  44918. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44919. if (layout != 0)
  44920. return -layout->currentSize / (double) totalSize;
  44921. return 0;
  44922. }
  44923. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  44924. int newPosition)
  44925. {
  44926. for (int i = items.size(); --i >= 0;)
  44927. {
  44928. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  44929. if (layout->itemIndex == itemIndex)
  44930. {
  44931. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  44932. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  44933. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  44934. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  44935. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  44936. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  44937. endPos += layout->currentSize;
  44938. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  44939. updatePrefSizesToMatchCurrentPositions();
  44940. break;
  44941. }
  44942. }
  44943. }
  44944. void StretchableLayoutManager::layOutComponents (Component** const components,
  44945. int numComponents,
  44946. int x, int y, int w, int h,
  44947. const bool vertically,
  44948. const bool resizeOtherDimension)
  44949. {
  44950. setTotalSize (vertically ? h : w);
  44951. int pos = vertically ? y : x;
  44952. for (int i = 0; i < numComponents; ++i)
  44953. {
  44954. const ItemLayoutProperties* const layout = getInfoFor (i);
  44955. if (layout != 0)
  44956. {
  44957. Component* const c = components[i];
  44958. if (c != 0)
  44959. {
  44960. if (i == numComponents - 1)
  44961. {
  44962. // if it's the last item, crop it to exactly fit the available space..
  44963. if (resizeOtherDimension)
  44964. {
  44965. if (vertically)
  44966. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  44967. else
  44968. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  44969. }
  44970. else
  44971. {
  44972. if (vertically)
  44973. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  44974. else
  44975. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  44976. }
  44977. }
  44978. else
  44979. {
  44980. if (resizeOtherDimension)
  44981. {
  44982. if (vertically)
  44983. c->setBounds (x, pos, w, layout->currentSize);
  44984. else
  44985. c->setBounds (pos, y, layout->currentSize, h);
  44986. }
  44987. else
  44988. {
  44989. if (vertically)
  44990. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  44991. else
  44992. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  44993. }
  44994. }
  44995. }
  44996. pos += layout->currentSize;
  44997. }
  44998. }
  44999. }
  45000. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  45001. {
  45002. for (int i = items.size(); --i >= 0;)
  45003. if (items.getUnchecked(i)->itemIndex == itemIndex)
  45004. return items.getUnchecked(i);
  45005. return 0;
  45006. }
  45007. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  45008. const int endIndex,
  45009. const int availableSpace,
  45010. int startPos)
  45011. {
  45012. // calculate the total sizes
  45013. int i;
  45014. double totalIdealSize = 0.0;
  45015. int totalMinimums = 0;
  45016. for (i = startIndex; i < endIndex; ++i)
  45017. {
  45018. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45019. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  45020. totalMinimums += layout->currentSize;
  45021. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  45022. }
  45023. if (totalIdealSize <= 0)
  45024. totalIdealSize = 1.0;
  45025. // now calc the best sizes..
  45026. int extraSpace = availableSpace - totalMinimums;
  45027. while (extraSpace > 0)
  45028. {
  45029. int numWantingMoreSpace = 0;
  45030. int numHavingTakenExtraSpace = 0;
  45031. // first figure out how many comps want a slice of the extra space..
  45032. for (i = startIndex; i < endIndex; ++i)
  45033. {
  45034. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45035. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45036. const int bestSize = jlimit (layout->currentSize,
  45037. jmax (layout->currentSize,
  45038. sizeToRealSize (layout->maxSize, totalSize)),
  45039. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45040. if (bestSize > layout->currentSize)
  45041. ++numWantingMoreSpace;
  45042. }
  45043. // ..share out the extra space..
  45044. for (i = startIndex; i < endIndex; ++i)
  45045. {
  45046. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45047. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45048. int bestSize = jlimit (layout->currentSize,
  45049. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  45050. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45051. const int extraWanted = bestSize - layout->currentSize;
  45052. if (extraWanted > 0)
  45053. {
  45054. const int extraAllowed = jmin (extraWanted,
  45055. extraSpace / jmax (1, numWantingMoreSpace));
  45056. if (extraAllowed > 0)
  45057. {
  45058. ++numHavingTakenExtraSpace;
  45059. --numWantingMoreSpace;
  45060. layout->currentSize += extraAllowed;
  45061. extraSpace -= extraAllowed;
  45062. }
  45063. }
  45064. }
  45065. if (numHavingTakenExtraSpace <= 0)
  45066. break;
  45067. }
  45068. // ..and calculate the end position
  45069. for (i = startIndex; i < endIndex; ++i)
  45070. {
  45071. ItemLayoutProperties* const layout = items.getUnchecked(i);
  45072. startPos += layout->currentSize;
  45073. }
  45074. return startPos;
  45075. }
  45076. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  45077. const int endIndex) const
  45078. {
  45079. int totalMinimums = 0;
  45080. for (int i = startIndex; i < endIndex; ++i)
  45081. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  45082. return totalMinimums;
  45083. }
  45084. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  45085. {
  45086. int totalMaximums = 0;
  45087. for (int i = startIndex; i < endIndex; ++i)
  45088. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  45089. return totalMaximums;
  45090. }
  45091. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  45092. {
  45093. for (int i = 0; i < items.size(); ++i)
  45094. {
  45095. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45096. layout->preferredSize
  45097. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  45098. : getItemCurrentAbsoluteSize (i);
  45099. }
  45100. }
  45101. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  45102. {
  45103. if (size < 0)
  45104. size *= -totalSpace;
  45105. return roundDoubleToInt (size);
  45106. }
  45107. END_JUCE_NAMESPACE
  45108. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  45109. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45110. BEGIN_JUCE_NAMESPACE
  45111. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  45112. const int itemIndex_,
  45113. const bool isVertical_)
  45114. : layout (layout_),
  45115. itemIndex (itemIndex_),
  45116. isVertical (isVertical_)
  45117. {
  45118. setRepaintsOnMouseActivity (true);
  45119. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  45120. : MouseCursor::UpDownResizeCursor));
  45121. }
  45122. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  45123. {
  45124. }
  45125. void StretchableLayoutResizerBar::paint (Graphics& g)
  45126. {
  45127. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  45128. getWidth(), getHeight(),
  45129. isVertical,
  45130. isMouseOver(),
  45131. isMouseButtonDown());
  45132. }
  45133. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  45134. {
  45135. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  45136. }
  45137. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  45138. {
  45139. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  45140. : e.getDistanceFromDragStartY());
  45141. layout->setItemPosition (itemIndex, desiredPos);
  45142. hasBeenMoved();
  45143. }
  45144. void StretchableLayoutResizerBar::hasBeenMoved()
  45145. {
  45146. if (getParentComponent() != 0)
  45147. getParentComponent()->resized();
  45148. }
  45149. END_JUCE_NAMESPACE
  45150. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45151. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  45152. BEGIN_JUCE_NAMESPACE
  45153. StretchableObjectResizer::StretchableObjectResizer()
  45154. {
  45155. }
  45156. StretchableObjectResizer::~StretchableObjectResizer()
  45157. {
  45158. }
  45159. void StretchableObjectResizer::addItem (const double size,
  45160. const double minSize, const double maxSize,
  45161. const int order)
  45162. {
  45163. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  45164. Item* const item = new Item();
  45165. item->size = size;
  45166. item->minSize = minSize;
  45167. item->maxSize = maxSize;
  45168. item->order = order;
  45169. items.add (item);
  45170. }
  45171. double StretchableObjectResizer::getItemSize (const int index) const throw()
  45172. {
  45173. const Item* const it = items [index];
  45174. return it != 0 ? it->size : 0;
  45175. }
  45176. void StretchableObjectResizer::resizeToFit (const double targetSize)
  45177. {
  45178. int order = 0;
  45179. for (;;)
  45180. {
  45181. double currentSize = 0;
  45182. double minSize = 0;
  45183. double maxSize = 0;
  45184. int nextHighestOrder = INT_MAX;
  45185. for (int i = 0; i < items.size(); ++i)
  45186. {
  45187. const Item* const it = items.getUnchecked(i);
  45188. currentSize += it->size;
  45189. if (it->order <= order)
  45190. {
  45191. minSize += it->minSize;
  45192. maxSize += it->maxSize;
  45193. }
  45194. else
  45195. {
  45196. minSize += it->size;
  45197. maxSize += it->size;
  45198. nextHighestOrder = jmin (nextHighestOrder, it->order);
  45199. }
  45200. }
  45201. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  45202. if (thisIterationTarget >= currentSize)
  45203. {
  45204. const double availableExtraSpace = maxSize - currentSize;
  45205. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  45206. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  45207. for (int i = 0; i < items.size(); ++i)
  45208. {
  45209. Item* const it = items.getUnchecked(i);
  45210. if (it->order <= order)
  45211. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  45212. }
  45213. }
  45214. else
  45215. {
  45216. const double amountOfSlack = currentSize - minSize;
  45217. const double targetAmountOfSlack = thisIterationTarget - minSize;
  45218. const double scale = targetAmountOfSlack / amountOfSlack;
  45219. for (int i = 0; i < items.size(); ++i)
  45220. {
  45221. Item* const it = items.getUnchecked(i);
  45222. if (it->order <= order)
  45223. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  45224. }
  45225. }
  45226. if (nextHighestOrder < INT_MAX)
  45227. order = nextHighestOrder;
  45228. else
  45229. break;
  45230. }
  45231. }
  45232. END_JUCE_NAMESPACE
  45233. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  45234. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  45235. BEGIN_JUCE_NAMESPACE
  45236. TabBarButton::TabBarButton (const String& name,
  45237. TabbedButtonBar* const owner_,
  45238. const int index)
  45239. : Button (name),
  45240. owner (owner_),
  45241. tabIndex (index),
  45242. overlapPixels (0)
  45243. {
  45244. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  45245. setComponentEffect (&shadow);
  45246. setWantsKeyboardFocus (false);
  45247. }
  45248. TabBarButton::~TabBarButton()
  45249. {
  45250. }
  45251. void TabBarButton::paintButton (Graphics& g,
  45252. bool isMouseOverButton,
  45253. bool isButtonDown)
  45254. {
  45255. int x, y, w, h;
  45256. getActiveArea (x, y, w, h);
  45257. g.setOrigin (x, y);
  45258. getLookAndFeel()
  45259. .drawTabButton (g, w, h,
  45260. owner->getTabBackgroundColour (tabIndex),
  45261. tabIndex, getButtonText(), *this,
  45262. owner->getOrientation(),
  45263. isMouseOverButton, isButtonDown,
  45264. getToggleState());
  45265. }
  45266. void TabBarButton::clicked (const ModifierKeys& mods)
  45267. {
  45268. if (mods.isPopupMenu())
  45269. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  45270. else
  45271. owner->setCurrentTabIndex (tabIndex);
  45272. }
  45273. bool TabBarButton::hitTest (int mx, int my)
  45274. {
  45275. int x, y, w, h;
  45276. getActiveArea (x, y, w, h);
  45277. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  45278. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  45279. {
  45280. if (((unsigned int) mx) < (unsigned int) getWidth()
  45281. && my >= y + overlapPixels
  45282. && my < y + h - overlapPixels)
  45283. return true;
  45284. }
  45285. else
  45286. {
  45287. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  45288. && ((unsigned int) my) < (unsigned int) getHeight())
  45289. return true;
  45290. }
  45291. Path p;
  45292. getLookAndFeel()
  45293. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  45294. owner->getOrientation(),
  45295. false, false, getToggleState());
  45296. return p.contains ((float) (mx - x),
  45297. (float) (my - y));
  45298. }
  45299. int TabBarButton::getBestTabLength (const int depth)
  45300. {
  45301. return jlimit (depth * 2,
  45302. depth * 7,
  45303. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  45304. }
  45305. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  45306. {
  45307. x = 0;
  45308. y = 0;
  45309. int r = getWidth();
  45310. int b = getHeight();
  45311. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  45312. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  45313. r -= spaceAroundImage;
  45314. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  45315. x += spaceAroundImage;
  45316. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  45317. y += spaceAroundImage;
  45318. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  45319. b -= spaceAroundImage;
  45320. w = r - x;
  45321. h = b - y;
  45322. }
  45323. class TabAreaBehindFrontButtonComponent : public Component
  45324. {
  45325. public:
  45326. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  45327. : owner (owner_)
  45328. {
  45329. setInterceptsMouseClicks (false, false);
  45330. }
  45331. ~TabAreaBehindFrontButtonComponent()
  45332. {
  45333. }
  45334. void paint (Graphics& g)
  45335. {
  45336. getLookAndFeel()
  45337. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  45338. *owner, owner->getOrientation());
  45339. }
  45340. void enablementChanged()
  45341. {
  45342. repaint();
  45343. }
  45344. private:
  45345. TabbedButtonBar* const owner;
  45346. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  45347. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  45348. };
  45349. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  45350. : orientation (orientation_),
  45351. currentTabIndex (-1),
  45352. extraTabsButton (0)
  45353. {
  45354. setInterceptsMouseClicks (false, true);
  45355. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  45356. setFocusContainer (true);
  45357. }
  45358. TabbedButtonBar::~TabbedButtonBar()
  45359. {
  45360. deleteAllChildren();
  45361. }
  45362. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  45363. {
  45364. orientation = newOrientation;
  45365. for (int i = getNumChildComponents(); --i >= 0;)
  45366. getChildComponent (i)->resized();
  45367. resized();
  45368. }
  45369. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  45370. {
  45371. return new TabBarButton (name, this, index);
  45372. }
  45373. void TabbedButtonBar::clearTabs()
  45374. {
  45375. tabs.clear();
  45376. tabColours.clear();
  45377. currentTabIndex = -1;
  45378. deleteAndZero (extraTabsButton);
  45379. removeChildComponent (behindFrontTab);
  45380. deleteAllChildren();
  45381. addChildComponent (behindFrontTab);
  45382. setCurrentTabIndex (-1);
  45383. }
  45384. void TabbedButtonBar::addTab (const String& tabName,
  45385. const Colour& tabBackgroundColour,
  45386. int insertIndex)
  45387. {
  45388. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  45389. if (tabName.isNotEmpty())
  45390. {
  45391. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  45392. insertIndex = tabs.size();
  45393. for (int i = tabs.size(); --i >= insertIndex;)
  45394. {
  45395. TabBarButton* const tb = getTabButton (i);
  45396. if (tb != 0)
  45397. tb->tabIndex++;
  45398. }
  45399. tabs.insert (insertIndex, tabName);
  45400. tabColours.insert (insertIndex, tabBackgroundColour);
  45401. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  45402. jassert (tb != 0); // your createTabButton() mustn't return zero!
  45403. addAndMakeVisible (tb, insertIndex);
  45404. resized();
  45405. if (currentTabIndex < 0)
  45406. setCurrentTabIndex (0);
  45407. }
  45408. }
  45409. void TabbedButtonBar::setTabName (const int tabIndex,
  45410. const String& newName)
  45411. {
  45412. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  45413. && tabs[tabIndex] != newName)
  45414. {
  45415. tabs.set (tabIndex, newName);
  45416. TabBarButton* const tb = getTabButton (tabIndex);
  45417. if (tb != 0)
  45418. tb->setButtonText (newName);
  45419. resized();
  45420. }
  45421. }
  45422. void TabbedButtonBar::removeTab (const int tabIndex)
  45423. {
  45424. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  45425. {
  45426. const int oldTabIndex = currentTabIndex;
  45427. if (currentTabIndex == tabIndex)
  45428. currentTabIndex = -1;
  45429. tabs.remove (tabIndex);
  45430. tabColours.remove (tabIndex);
  45431. TabBarButton* const tb = getTabButton (tabIndex);
  45432. if (tb != 0)
  45433. delete tb;
  45434. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  45435. {
  45436. TabBarButton* const tb = getTabButton (i);
  45437. if (tb != 0)
  45438. tb->tabIndex--;
  45439. }
  45440. resized();
  45441. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  45442. }
  45443. }
  45444. void TabbedButtonBar::moveTab (const int currentIndex,
  45445. const int newIndex)
  45446. {
  45447. tabs.move (currentIndex, newIndex);
  45448. tabColours.move (currentIndex, newIndex);
  45449. resized();
  45450. }
  45451. int TabbedButtonBar::getNumTabs() const
  45452. {
  45453. return tabs.size();
  45454. }
  45455. const StringArray TabbedButtonBar::getTabNames() const
  45456. {
  45457. return tabs;
  45458. }
  45459. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  45460. {
  45461. if (currentTabIndex != newIndex)
  45462. {
  45463. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  45464. newIndex = -1;
  45465. currentTabIndex = newIndex;
  45466. for (int i = 0; i < getNumChildComponents(); ++i)
  45467. {
  45468. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45469. if (tb != 0)
  45470. tb->setToggleState (tb->tabIndex == newIndex, false);
  45471. }
  45472. resized();
  45473. sendChangeMessage (this);
  45474. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  45475. }
  45476. }
  45477. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  45478. {
  45479. for (int i = getNumChildComponents(); --i >= 0;)
  45480. {
  45481. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45482. if (tb != 0 && tb->tabIndex == index)
  45483. return tb;
  45484. }
  45485. return 0;
  45486. }
  45487. void TabbedButtonBar::lookAndFeelChanged()
  45488. {
  45489. deleteAndZero (extraTabsButton);
  45490. resized();
  45491. }
  45492. void TabbedButtonBar::resized()
  45493. {
  45494. const double minimumScale = 0.7;
  45495. int depth = getWidth();
  45496. int length = getHeight();
  45497. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45498. swapVariables (depth, length);
  45499. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  45500. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  45501. int i, totalLength = overlap;
  45502. int numVisibleButtons = tabs.size();
  45503. for (i = 0; i < getNumChildComponents(); ++i)
  45504. {
  45505. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45506. if (tb != 0)
  45507. {
  45508. totalLength += tb->getBestTabLength (depth) - overlap;
  45509. tb->overlapPixels = overlap / 2;
  45510. }
  45511. }
  45512. double scale = 1.0;
  45513. if (totalLength > length)
  45514. scale = jmax (minimumScale, length / (double) totalLength);
  45515. const bool isTooBig = totalLength * scale > length;
  45516. int tabsButtonPos = 0;
  45517. if (isTooBig)
  45518. {
  45519. if (extraTabsButton == 0)
  45520. {
  45521. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  45522. extraTabsButton->addButtonListener (this);
  45523. extraTabsButton->setAlwaysOnTop (true);
  45524. extraTabsButton->setTriggeredOnMouseDown (true);
  45525. }
  45526. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  45527. extraTabsButton->setSize (buttonSize, buttonSize);
  45528. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45529. {
  45530. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  45531. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  45532. }
  45533. else
  45534. {
  45535. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  45536. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  45537. }
  45538. totalLength = 0;
  45539. for (i = 0; i < tabs.size(); ++i)
  45540. {
  45541. TabBarButton* const tb = getTabButton (i);
  45542. if (tb != 0)
  45543. {
  45544. const int newLength = totalLength + tb->getBestTabLength (depth);
  45545. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  45546. {
  45547. totalLength += overlap;
  45548. break;
  45549. }
  45550. numVisibleButtons = i + 1;
  45551. totalLength = newLength - overlap;
  45552. }
  45553. }
  45554. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  45555. }
  45556. else
  45557. {
  45558. deleteAndZero (extraTabsButton);
  45559. }
  45560. int pos = 0;
  45561. TabBarButton* frontTab = 0;
  45562. for (i = 0; i < tabs.size(); ++i)
  45563. {
  45564. TabBarButton* const tb = getTabButton (i);
  45565. if (tb != 0)
  45566. {
  45567. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  45568. if (i < numVisibleButtons)
  45569. {
  45570. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45571. tb->setBounds (pos, 0, bestLength, getHeight());
  45572. else
  45573. tb->setBounds (0, pos, getWidth(), bestLength);
  45574. tb->toBack();
  45575. if (tb->tabIndex == currentTabIndex)
  45576. frontTab = tb;
  45577. tb->setVisible (true);
  45578. }
  45579. else
  45580. {
  45581. tb->setVisible (false);
  45582. }
  45583. pos += bestLength - overlap;
  45584. }
  45585. }
  45586. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  45587. if (frontTab != 0)
  45588. {
  45589. frontTab->toFront (false);
  45590. behindFrontTab->toBehind (frontTab);
  45591. }
  45592. }
  45593. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  45594. {
  45595. return tabColours [tabIndex];
  45596. }
  45597. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45598. {
  45599. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  45600. && tabColours [tabIndex] != newColour)
  45601. {
  45602. tabColours.set (tabIndex, newColour);
  45603. repaint();
  45604. }
  45605. }
  45606. void TabbedButtonBar::buttonClicked (Button* button)
  45607. {
  45608. if (extraTabsButton == button)
  45609. {
  45610. PopupMenu m;
  45611. for (int i = 0; i < tabs.size(); ++i)
  45612. {
  45613. TabBarButton* const tb = getTabButton (i);
  45614. if (tb != 0 && ! tb->isVisible())
  45615. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  45616. }
  45617. const int res = m.showAt (extraTabsButton);
  45618. if (res != 0)
  45619. setCurrentTabIndex (res - 1);
  45620. }
  45621. }
  45622. void TabbedButtonBar::currentTabChanged (const int, const String&)
  45623. {
  45624. }
  45625. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  45626. {
  45627. }
  45628. END_JUCE_NAMESPACE
  45629. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  45630. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  45631. BEGIN_JUCE_NAMESPACE
  45632. class TabCompButtonBar : public TabbedButtonBar
  45633. {
  45634. public:
  45635. TabCompButtonBar (TabbedComponent* const owner_,
  45636. const TabbedButtonBar::Orientation orientation)
  45637. : TabbedButtonBar (orientation),
  45638. owner (owner_)
  45639. {
  45640. }
  45641. ~TabCompButtonBar()
  45642. {
  45643. }
  45644. void currentTabChanged (const int newCurrentTabIndex,
  45645. const String& newTabName)
  45646. {
  45647. owner->changeCallback (newCurrentTabIndex, newTabName);
  45648. }
  45649. void popupMenuClickOnTab (const int tabIndex,
  45650. const String& tabName)
  45651. {
  45652. owner->popupMenuClickOnTab (tabIndex, tabName);
  45653. }
  45654. const Colour getTabBackgroundColour (const int tabIndex)
  45655. {
  45656. return owner->tabs->getTabBackgroundColour (tabIndex);
  45657. }
  45658. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  45659. {
  45660. return owner->createTabButton (tabName, tabIndex);
  45661. }
  45662. juce_UseDebuggingNewOperator
  45663. private:
  45664. TabbedComponent* const owner;
  45665. TabCompButtonBar (const TabCompButtonBar&);
  45666. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  45667. };
  45668. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  45669. : panelComponent (0),
  45670. tabDepth (30),
  45671. outlineColour (Colours::grey),
  45672. outlineThickness (1),
  45673. edgeIndent (0)
  45674. {
  45675. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  45676. }
  45677. TabbedComponent::~TabbedComponent()
  45678. {
  45679. clearTabs();
  45680. delete tabs;
  45681. }
  45682. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  45683. {
  45684. tabs->setOrientation (orientation);
  45685. resized();
  45686. }
  45687. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  45688. {
  45689. return tabs->getOrientation();
  45690. }
  45691. void TabbedComponent::setTabBarDepth (const int newDepth)
  45692. {
  45693. if (tabDepth != newDepth)
  45694. {
  45695. tabDepth = newDepth;
  45696. resized();
  45697. }
  45698. }
  45699. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  45700. {
  45701. return new TabBarButton (tabName, tabs, tabIndex);
  45702. }
  45703. void TabbedComponent::clearTabs()
  45704. {
  45705. if (panelComponent != 0)
  45706. {
  45707. panelComponent->setVisible (false);
  45708. removeChildComponent (panelComponent);
  45709. panelComponent = 0;
  45710. }
  45711. tabs->clearTabs();
  45712. for (int i = contentComponents.size(); --i >= 0;)
  45713. {
  45714. Component* const c = contentComponents.getUnchecked(i);
  45715. // be careful not to delete these components until they've been removed from the tab component
  45716. jassert (c == 0 || c->isValidComponent());
  45717. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45718. delete c;
  45719. }
  45720. contentComponents.clear();
  45721. }
  45722. void TabbedComponent::addTab (const String& tabName,
  45723. const Colour& tabBackgroundColour,
  45724. Component* const contentComponent,
  45725. const bool deleteComponentWhenNotNeeded,
  45726. const int insertIndex)
  45727. {
  45728. contentComponents.insert (insertIndex, contentComponent);
  45729. if (contentComponent != 0)
  45730. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  45731. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  45732. }
  45733. void TabbedComponent::setTabName (const int tabIndex,
  45734. const String& newName)
  45735. {
  45736. tabs->setTabName (tabIndex, newName);
  45737. }
  45738. void TabbedComponent::removeTab (const int tabIndex)
  45739. {
  45740. Component* const c = contentComponents [tabIndex];
  45741. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45742. {
  45743. if (c == panelComponent)
  45744. panelComponent = 0;
  45745. delete c;
  45746. }
  45747. contentComponents.remove (tabIndex);
  45748. tabs->removeTab (tabIndex);
  45749. }
  45750. int TabbedComponent::getNumTabs() const
  45751. {
  45752. return tabs->getNumTabs();
  45753. }
  45754. const StringArray TabbedComponent::getTabNames() const
  45755. {
  45756. return tabs->getTabNames();
  45757. }
  45758. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  45759. {
  45760. return contentComponents [tabIndex];
  45761. }
  45762. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  45763. {
  45764. return tabs->getTabBackgroundColour (tabIndex);
  45765. }
  45766. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45767. {
  45768. tabs->setTabBackgroundColour (tabIndex, newColour);
  45769. if (getCurrentTabIndex() == tabIndex)
  45770. repaint();
  45771. }
  45772. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  45773. {
  45774. tabs->setCurrentTabIndex (newTabIndex);
  45775. }
  45776. int TabbedComponent::getCurrentTabIndex() const
  45777. {
  45778. return tabs->getCurrentTabIndex();
  45779. }
  45780. const String& TabbedComponent::getCurrentTabName() const
  45781. {
  45782. return tabs->getCurrentTabName();
  45783. }
  45784. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  45785. {
  45786. outlineColour = colour;
  45787. outlineThickness = thickness;
  45788. repaint();
  45789. }
  45790. void TabbedComponent::setIndent (const int indentThickness)
  45791. {
  45792. edgeIndent = indentThickness;
  45793. }
  45794. void TabbedComponent::paint (Graphics& g)
  45795. {
  45796. const TabbedButtonBar::Orientation o = getOrientation();
  45797. int x = 0;
  45798. int y = 0;
  45799. int r = getWidth();
  45800. int b = getHeight();
  45801. if (o == TabbedButtonBar::TabsAtTop)
  45802. y += tabDepth;
  45803. else if (o == TabbedButtonBar::TabsAtBottom)
  45804. b -= tabDepth;
  45805. else if (o == TabbedButtonBar::TabsAtLeft)
  45806. x += tabDepth;
  45807. else if (o == TabbedButtonBar::TabsAtRight)
  45808. r -= tabDepth;
  45809. g.reduceClipRegion (x, y, r - x, b - y);
  45810. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  45811. if (outlineThickness > 0)
  45812. {
  45813. if (o == TabbedButtonBar::TabsAtTop)
  45814. --y;
  45815. else if (o == TabbedButtonBar::TabsAtBottom)
  45816. ++b;
  45817. else if (o == TabbedButtonBar::TabsAtLeft)
  45818. --x;
  45819. else if (o == TabbedButtonBar::TabsAtRight)
  45820. ++r;
  45821. g.setColour (outlineColour);
  45822. g.drawRect (x, y, r - x, b - y, outlineThickness);
  45823. }
  45824. }
  45825. void TabbedComponent::resized()
  45826. {
  45827. const TabbedButtonBar::Orientation o = getOrientation();
  45828. const int indent = edgeIndent + outlineThickness;
  45829. BorderSize indents (indent);
  45830. if (o == TabbedButtonBar::TabsAtTop)
  45831. {
  45832. tabs->setBounds (0, 0, getWidth(), tabDepth);
  45833. indents.setTop (tabDepth + edgeIndent);
  45834. }
  45835. else if (o == TabbedButtonBar::TabsAtBottom)
  45836. {
  45837. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  45838. indents.setBottom (tabDepth + edgeIndent);
  45839. }
  45840. else if (o == TabbedButtonBar::TabsAtLeft)
  45841. {
  45842. tabs->setBounds (0, 0, tabDepth, getHeight());
  45843. indents.setLeft (tabDepth + edgeIndent);
  45844. }
  45845. else if (o == TabbedButtonBar::TabsAtRight)
  45846. {
  45847. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  45848. indents.setRight (tabDepth + edgeIndent);
  45849. }
  45850. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  45851. for (int i = contentComponents.size(); --i >= 0;)
  45852. if (contentComponents.getUnchecked (i) != 0)
  45853. contentComponents.getUnchecked (i)->setBounds (bounds);
  45854. }
  45855. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  45856. const String& newTabName)
  45857. {
  45858. if (panelComponent != 0)
  45859. {
  45860. panelComponent->setVisible (false);
  45861. removeChildComponent (panelComponent);
  45862. panelComponent = 0;
  45863. }
  45864. if (getCurrentTabIndex() >= 0)
  45865. {
  45866. panelComponent = contentComponents [getCurrentTabIndex()];
  45867. if (panelComponent != 0)
  45868. {
  45869. // do these ops as two stages instead of addAndMakeVisible() so that the
  45870. // component has always got a parent when it gets the visibilityChanged() callback
  45871. addChildComponent (panelComponent);
  45872. panelComponent->setVisible (true);
  45873. panelComponent->toFront (true);
  45874. }
  45875. repaint();
  45876. }
  45877. resized();
  45878. currentTabChanged (newCurrentTabIndex, newTabName);
  45879. }
  45880. void TabbedComponent::currentTabChanged (const int, const String&)
  45881. {
  45882. }
  45883. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  45884. {
  45885. }
  45886. END_JUCE_NAMESPACE
  45887. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  45888. /********* Start of inlined file: juce_Viewport.cpp *********/
  45889. BEGIN_JUCE_NAMESPACE
  45890. Viewport::Viewport (const String& componentName)
  45891. : Component (componentName),
  45892. contentComp (0),
  45893. lastVX (0),
  45894. lastVY (0),
  45895. lastVW (0),
  45896. lastVH (0),
  45897. scrollBarThickness (0),
  45898. singleStepX (16),
  45899. singleStepY (16),
  45900. showHScrollbar (true),
  45901. showVScrollbar (true)
  45902. {
  45903. // content holder is used to clip the contents so they don't overlap the scrollbars
  45904. addAndMakeVisible (contentHolder = new Component());
  45905. contentHolder->setInterceptsMouseClicks (false, true);
  45906. verticalScrollBar = new ScrollBar (true);
  45907. horizontalScrollBar = new ScrollBar (false);
  45908. addChildComponent (verticalScrollBar);
  45909. addChildComponent (horizontalScrollBar);
  45910. verticalScrollBar->addListener (this);
  45911. horizontalScrollBar->addListener (this);
  45912. setInterceptsMouseClicks (false, true);
  45913. setWantsKeyboardFocus (true);
  45914. }
  45915. Viewport::~Viewport()
  45916. {
  45917. contentHolder->deleteAllChildren();
  45918. deleteAllChildren();
  45919. }
  45920. void Viewport::visibleAreaChanged (int, int, int, int)
  45921. {
  45922. }
  45923. void Viewport::setViewedComponent (Component* const newViewedComponent)
  45924. {
  45925. if (contentComp != newViewedComponent)
  45926. {
  45927. if (contentComp->isValidComponent())
  45928. {
  45929. Component* const oldComp = contentComp;
  45930. contentComp = 0;
  45931. delete oldComp;
  45932. }
  45933. contentComp = newViewedComponent;
  45934. if (contentComp != 0)
  45935. {
  45936. contentComp->setTopLeftPosition (0, 0);
  45937. contentHolder->addAndMakeVisible (contentComp);
  45938. contentComp->addComponentListener (this);
  45939. }
  45940. updateVisibleRegion();
  45941. }
  45942. }
  45943. int Viewport::getMaximumVisibleWidth() const throw()
  45944. {
  45945. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  45946. }
  45947. int Viewport::getMaximumVisibleHeight() const throw()
  45948. {
  45949. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  45950. }
  45951. void Viewport::setViewPosition (const int xPixelsOffset,
  45952. const int yPixelsOffset)
  45953. {
  45954. if (contentComp != 0)
  45955. contentComp->setTopLeftPosition (-xPixelsOffset,
  45956. -yPixelsOffset);
  45957. }
  45958. void Viewport::setViewPositionProportionately (const double x,
  45959. const double y)
  45960. {
  45961. if (contentComp != 0)
  45962. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  45963. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  45964. }
  45965. void Viewport::componentMovedOrResized (Component&, bool, bool)
  45966. {
  45967. updateVisibleRegion();
  45968. }
  45969. void Viewport::resized()
  45970. {
  45971. updateVisibleRegion();
  45972. }
  45973. void Viewport::updateVisibleRegion()
  45974. {
  45975. if (contentComp != 0)
  45976. {
  45977. const int newVX = -contentComp->getX();
  45978. const int newVY = -contentComp->getY();
  45979. if (newVX == 0 && newVY == 0
  45980. && contentComp->getWidth() <= getWidth()
  45981. && contentComp->getHeight() <= getHeight())
  45982. {
  45983. horizontalScrollBar->setVisible (false);
  45984. verticalScrollBar->setVisible (false);
  45985. }
  45986. if ((contentComp->getWidth() > 0) && showHScrollbar
  45987. && getHeight() > getScrollBarThickness())
  45988. {
  45989. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  45990. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  45991. horizontalScrollBar->setSingleStepSize (singleStepX);
  45992. }
  45993. else
  45994. {
  45995. horizontalScrollBar->setVisible (false);
  45996. }
  45997. if ((contentComp->getHeight() > 0) && showVScrollbar
  45998. && getWidth() > getScrollBarThickness())
  45999. {
  46000. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  46001. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46002. verticalScrollBar->setSingleStepSize (singleStepY);
  46003. }
  46004. else
  46005. {
  46006. verticalScrollBar->setVisible (false);
  46007. }
  46008. if (verticalScrollBar->isVisible())
  46009. {
  46010. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46011. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46012. verticalScrollBar
  46013. ->setBounds (getMaximumVisibleWidth(), 0,
  46014. getScrollBarThickness(), getMaximumVisibleHeight());
  46015. }
  46016. if (horizontalScrollBar->isVisible())
  46017. {
  46018. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46019. horizontalScrollBar
  46020. ->setBounds (0, getMaximumVisibleHeight(),
  46021. getMaximumVisibleWidth(), getScrollBarThickness());
  46022. }
  46023. contentHolder->setSize (getMaximumVisibleWidth(),
  46024. getMaximumVisibleHeight());
  46025. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  46026. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  46027. if (newVX != lastVX
  46028. || newVY != lastVY
  46029. || newVW != lastVW
  46030. || newVH != lastVH)
  46031. {
  46032. lastVX = newVX;
  46033. lastVY = newVY;
  46034. lastVW = newVW;
  46035. lastVH = newVH;
  46036. visibleAreaChanged (newVX, newVY, newVW, newVH);
  46037. }
  46038. horizontalScrollBar->handleUpdateNowIfNeeded();
  46039. verticalScrollBar->handleUpdateNowIfNeeded();
  46040. }
  46041. else
  46042. {
  46043. horizontalScrollBar->setVisible (false);
  46044. verticalScrollBar->setVisible (false);
  46045. }
  46046. }
  46047. void Viewport::setSingleStepSizes (const int stepX,
  46048. const int stepY)
  46049. {
  46050. singleStepX = stepX;
  46051. singleStepY = stepY;
  46052. updateVisibleRegion();
  46053. }
  46054. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  46055. const bool showHorizontalScrollbarIfNeeded)
  46056. {
  46057. showVScrollbar = showVerticalScrollbarIfNeeded;
  46058. showHScrollbar = showHorizontalScrollbarIfNeeded;
  46059. updateVisibleRegion();
  46060. }
  46061. void Viewport::setScrollBarThickness (const int thickness)
  46062. {
  46063. scrollBarThickness = thickness;
  46064. updateVisibleRegion();
  46065. }
  46066. int Viewport::getScrollBarThickness() const throw()
  46067. {
  46068. return (scrollBarThickness > 0) ? scrollBarThickness
  46069. : getLookAndFeel().getDefaultScrollbarWidth();
  46070. }
  46071. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  46072. {
  46073. verticalScrollBar->setButtonVisibility (buttonsVisible);
  46074. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  46075. }
  46076. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  46077. {
  46078. if (scrollBarThatHasMoved == horizontalScrollBar)
  46079. {
  46080. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  46081. }
  46082. else if (scrollBarThatHasMoved == verticalScrollBar)
  46083. {
  46084. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  46085. }
  46086. }
  46087. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46088. {
  46089. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  46090. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  46091. }
  46092. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46093. {
  46094. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  46095. {
  46096. const bool hasVertBar = verticalScrollBar->isVisible();
  46097. const bool hasHorzBar = horizontalScrollBar->isVisible();
  46098. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  46099. {
  46100. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  46101. wheelIncrementX, wheelIncrementY);
  46102. return true;
  46103. }
  46104. else if (hasVertBar && wheelIncrementY != 0)
  46105. {
  46106. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  46107. wheelIncrementX, wheelIncrementY);
  46108. return true;
  46109. }
  46110. }
  46111. return false;
  46112. }
  46113. bool Viewport::keyPressed (const KeyPress& key)
  46114. {
  46115. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  46116. || key.isKeyCode (KeyPress::downKey)
  46117. || key.isKeyCode (KeyPress::pageUpKey)
  46118. || key.isKeyCode (KeyPress::pageDownKey)
  46119. || key.isKeyCode (KeyPress::homeKey)
  46120. || key.isKeyCode (KeyPress::endKey);
  46121. if (verticalScrollBar->isVisible() && isUpDownKey)
  46122. return verticalScrollBar->keyPressed (key);
  46123. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  46124. || key.isKeyCode (KeyPress::rightKey);
  46125. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  46126. return horizontalScrollBar->keyPressed (key);
  46127. return false;
  46128. }
  46129. END_JUCE_NAMESPACE
  46130. /********* End of inlined file: juce_Viewport.cpp *********/
  46131. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  46132. BEGIN_JUCE_NAMESPACE
  46133. static const Colour createBaseColour (const Colour& buttonColour,
  46134. const bool hasKeyboardFocus,
  46135. const bool isMouseOverButton,
  46136. const bool isButtonDown) throw()
  46137. {
  46138. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  46139. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  46140. if (isButtonDown)
  46141. return baseColour.contrasting (0.2f);
  46142. else if (isMouseOverButton)
  46143. return baseColour.contrasting (0.1f);
  46144. return baseColour;
  46145. }
  46146. LookAndFeel::LookAndFeel()
  46147. {
  46148. /* if this fails it means you're trying to create a LookAndFeel object before
  46149. the static Colours have been initialised. That ain't gonna work. It probably
  46150. means that you're using a static LookAndFeel object and that your compiler has
  46151. decided to intialise it before the Colours class.
  46152. */
  46153. jassert (Colours::white == Colour (0xffffffff));
  46154. // set up the standard set of colours..
  46155. #define textButtonColour 0xffbbbbff
  46156. #define textHighlightColour 0x401111ee
  46157. #define standardOutlineColour 0xb2808080
  46158. static const int standardColours[] =
  46159. {
  46160. TextButton::buttonColourId, textButtonColour,
  46161. TextButton::buttonOnColourId, 0xff4444ff,
  46162. TextButton::textColourId, 0xff000000,
  46163. ComboBox::buttonColourId, 0xffbbbbff,
  46164. ComboBox::outlineColourId, standardOutlineColour,
  46165. ToggleButton::textColourId, 0xff000000,
  46166. TextEditor::backgroundColourId, 0xffffffff,
  46167. TextEditor::textColourId, 0xff000000,
  46168. TextEditor::highlightColourId, textHighlightColour,
  46169. TextEditor::highlightedTextColourId, 0xff000000,
  46170. TextEditor::caretColourId, 0xff000000,
  46171. TextEditor::outlineColourId, 0x00000000,
  46172. TextEditor::focusedOutlineColourId, textButtonColour,
  46173. TextEditor::shadowColourId, 0x38000000,
  46174. Label::backgroundColourId, 0x00000000,
  46175. Label::textColourId, 0xff000000,
  46176. Label::outlineColourId, 0x00000000,
  46177. ScrollBar::backgroundColourId, 0x00000000,
  46178. ScrollBar::thumbColourId, 0xffffffff,
  46179. ScrollBar::trackColourId, 0xffffffff,
  46180. TreeView::linesColourId, 0x4c000000,
  46181. TreeView::backgroundColourId, 0x00000000,
  46182. PopupMenu::backgroundColourId, 0xffffffff,
  46183. PopupMenu::textColourId, 0xff000000,
  46184. PopupMenu::headerTextColourId, 0xff000000,
  46185. PopupMenu::highlightedTextColourId, 0xffffffff,
  46186. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  46187. ComboBox::textColourId, 0xff000000,
  46188. ComboBox::backgroundColourId, 0xffffffff,
  46189. ComboBox::arrowColourId, 0x99000000,
  46190. ListBox::backgroundColourId, 0xffffffff,
  46191. ListBox::outlineColourId, standardOutlineColour,
  46192. ListBox::textColourId, 0xff000000,
  46193. Slider::backgroundColourId, 0x00000000,
  46194. Slider::thumbColourId, textButtonColour,
  46195. Slider::trackColourId, 0x7fffffff,
  46196. Slider::rotarySliderFillColourId, 0x7f0000ff,
  46197. Slider::rotarySliderOutlineColourId, 0x66000000,
  46198. Slider::textBoxTextColourId, 0xff000000,
  46199. Slider::textBoxBackgroundColourId, 0xffffffff,
  46200. Slider::textBoxHighlightColourId, textHighlightColour,
  46201. Slider::textBoxOutlineColourId, standardOutlineColour,
  46202. AlertWindow::backgroundColourId, 0xffededed,
  46203. AlertWindow::textColourId, 0xff000000,
  46204. AlertWindow::outlineColourId, 0xff666666,
  46205. ProgressBar::backgroundColourId, 0xffeeeeee,
  46206. ProgressBar::foregroundColourId, 0xffaaaaee,
  46207. TooltipWindow::backgroundColourId, 0xffeeeebb,
  46208. TooltipWindow::textColourId, 0xff000000,
  46209. TooltipWindow::outlineColourId, 0x4c000000,
  46210. Toolbar::backgroundColourId, 0xfff6f8f9,
  46211. Toolbar::separatorColourId, 0x4c000000,
  46212. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  46213. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  46214. Toolbar::labelTextColourId, 0xff000000,
  46215. Toolbar::editingModeOutlineColourId, 0xffff0000,
  46216. HyperlinkButton::textColourId, 0xcc1111ee,
  46217. GroupComponent::outlineColourId, 0x66000000,
  46218. GroupComponent::textColourId, 0xff000000,
  46219. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  46220. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  46221. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  46222. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  46223. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  46224. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  46225. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  46226. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  46227. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  46228. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  46229. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  46230. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  46231. ColourSelector::backgroundColourId, 0xffe5e5e5,
  46232. ColourSelector::labelTextColourId, 0xff000000,
  46233. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  46234. };
  46235. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  46236. setColour (standardColours [i], Colour (standardColours [i + 1]));
  46237. }
  46238. LookAndFeel::~LookAndFeel()
  46239. {
  46240. }
  46241. const Colour LookAndFeel::findColour (const int colourId) const throw()
  46242. {
  46243. const int index = colourIds.indexOf (colourId);
  46244. if (index >= 0)
  46245. return colours [index];
  46246. jassertfalse
  46247. return Colours::black;
  46248. }
  46249. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  46250. {
  46251. const int index = colourIds.indexOf (colourId);
  46252. if (index >= 0)
  46253. colours.set (index, colour);
  46254. colourIds.add (colourId);
  46255. colours.add (colour);
  46256. }
  46257. static LookAndFeel* defaultLF = 0;
  46258. static LookAndFeel* currentDefaultLF = 0;
  46259. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  46260. {
  46261. // if this happens, your app hasn't initialised itself properly.. if you're
  46262. // trying to hack your own main() function, have a look at
  46263. // JUCEApplication::initialiseForGUI()
  46264. jassert (currentDefaultLF != 0);
  46265. return *currentDefaultLF;
  46266. }
  46267. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  46268. {
  46269. if (newDefaultLookAndFeel == 0)
  46270. {
  46271. if (defaultLF == 0)
  46272. defaultLF = new LookAndFeel();
  46273. newDefaultLookAndFeel = defaultLF;
  46274. }
  46275. currentDefaultLF = newDefaultLookAndFeel;
  46276. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  46277. {
  46278. Component* const c = Desktop::getInstance().getComponent (i);
  46279. if (c != 0)
  46280. c->sendLookAndFeelChange();
  46281. }
  46282. }
  46283. void LookAndFeel::clearDefaultLookAndFeel() throw()
  46284. {
  46285. if (currentDefaultLF == defaultLF)
  46286. currentDefaultLF = 0;
  46287. deleteAndZero (defaultLF);
  46288. }
  46289. void LookAndFeel::drawButtonBackground (Graphics& g,
  46290. Button& button,
  46291. const Colour& backgroundColour,
  46292. bool isMouseOverButton,
  46293. bool isButtonDown)
  46294. {
  46295. const int width = button.getWidth();
  46296. const int height = button.getHeight();
  46297. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  46298. const float halfThickness = outlineThickness * 0.5f;
  46299. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  46300. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  46301. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  46302. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  46303. const Colour baseColour (createBaseColour (backgroundColour,
  46304. button.hasKeyboardFocus (true),
  46305. isMouseOverButton, isButtonDown)
  46306. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46307. drawGlassLozenge (g,
  46308. indentL,
  46309. indentT,
  46310. width - indentL - indentR,
  46311. height - indentT - indentB,
  46312. baseColour, outlineThickness, -1.0f,
  46313. button.isConnectedOnLeft(),
  46314. button.isConnectedOnRight(),
  46315. button.isConnectedOnTop(),
  46316. button.isConnectedOnBottom());
  46317. }
  46318. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  46319. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  46320. {
  46321. g.setFont (button.getFont());
  46322. g.setColour (button.findColour (TextButton::textColourId)
  46323. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46324. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  46325. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  46326. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  46327. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  46328. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  46329. g.drawFittedText (button.getButtonText(),
  46330. leftIndent,
  46331. yIndent,
  46332. button.getWidth() - leftIndent - rightIndent,
  46333. button.getHeight() - yIndent * 2,
  46334. Justification::centred, 2);
  46335. }
  46336. void LookAndFeel::drawTickBox (Graphics& g,
  46337. Component& component,
  46338. int x, int y, int w, int h,
  46339. const bool ticked,
  46340. const bool isEnabled,
  46341. const bool isMouseOverButton,
  46342. const bool isButtonDown)
  46343. {
  46344. const float boxSize = w * 0.7f;
  46345. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  46346. createBaseColour (component.findColour (TextButton::buttonColourId)
  46347. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  46348. true,
  46349. isMouseOverButton,
  46350. isButtonDown),
  46351. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  46352. if (ticked)
  46353. {
  46354. Path tick;
  46355. tick.startNewSubPath (1.5f, 3.0f);
  46356. tick.lineTo (3.0f, 6.0f);
  46357. tick.lineTo (6.0f, 0.0f);
  46358. g.setColour (isEnabled ? Colours::black : Colours::grey);
  46359. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  46360. .translated ((float) x, (float) y));
  46361. g.strokePath (tick, PathStrokeType (2.5f), trans);
  46362. }
  46363. }
  46364. void LookAndFeel::drawToggleButton (Graphics& g,
  46365. ToggleButton& button,
  46366. bool isMouseOverButton,
  46367. bool isButtonDown)
  46368. {
  46369. if (button.hasKeyboardFocus (true))
  46370. {
  46371. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  46372. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  46373. }
  46374. const int tickWidth = jmin (20, button.getHeight() - 4);
  46375. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  46376. tickWidth, tickWidth,
  46377. button.getToggleState(),
  46378. button.isEnabled(),
  46379. isMouseOverButton,
  46380. isButtonDown);
  46381. g.setColour (button.findColour (ToggleButton::textColourId));
  46382. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  46383. if (! button.isEnabled())
  46384. g.setOpacity (0.5f);
  46385. const int textX = tickWidth + 5;
  46386. g.drawFittedText (button.getButtonText(),
  46387. textX, 4,
  46388. button.getWidth() - textX - 2, button.getHeight() - 8,
  46389. Justification::centredLeft, 10);
  46390. }
  46391. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  46392. {
  46393. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  46394. const int tickWidth = jmin (24, button.getHeight());
  46395. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  46396. button.getHeight());
  46397. }
  46398. void LookAndFeel::drawAlertBox (Graphics& g,
  46399. AlertWindow& alert,
  46400. const Rectangle& textArea,
  46401. TextLayout& textLayout)
  46402. {
  46403. const int iconWidth = 80;
  46404. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  46405. g.fillAll (background);
  46406. int iconSpaceUsed = 0;
  46407. Justification alignment (Justification::horizontallyCentred);
  46408. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  46409. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  46410. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  46411. const Rectangle iconRect (iconSize / -10,
  46412. iconSize / -10,
  46413. iconSize,
  46414. iconSize);
  46415. if (alert.getAlertType() == AlertWindow::QuestionIcon
  46416. || alert.getAlertType() == AlertWindow::InfoIcon)
  46417. {
  46418. if (alert.getAlertType() == AlertWindow::InfoIcon)
  46419. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  46420. else
  46421. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  46422. g.fillEllipse ((float) iconRect.getX(),
  46423. (float) iconRect.getY(),
  46424. (float) iconRect.getWidth(),
  46425. (float) iconRect.getHeight());
  46426. g.setColour (background);
  46427. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46428. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  46429. : "?",
  46430. iconRect.getX(),
  46431. iconRect.getY(),
  46432. iconRect.getWidth(),
  46433. iconRect.getHeight(),
  46434. Justification::centred, false);
  46435. iconSpaceUsed = iconWidth;
  46436. alignment = Justification::left;
  46437. }
  46438. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  46439. {
  46440. Path p;
  46441. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  46442. (float) iconRect.getY(),
  46443. (float) iconRect.getRight(),
  46444. (float) iconRect.getBottom(),
  46445. (float) iconRect.getX(),
  46446. (float) iconRect.getBottom());
  46447. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  46448. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  46449. g.setColour (background);
  46450. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46451. g.drawText (T("!"),
  46452. iconRect.getX(),
  46453. iconRect.getY(),
  46454. iconRect.getWidth(),
  46455. iconRect.getHeight() + iconRect.getHeight() / 8,
  46456. Justification::centred, false);
  46457. iconSpaceUsed = iconWidth;
  46458. alignment = Justification::left;
  46459. }
  46460. g.setColour (alert.findColour (AlertWindow::textColourId));
  46461. textLayout.drawWithin (g,
  46462. textArea.getX() + iconSpaceUsed,
  46463. textArea.getY(),
  46464. textArea.getWidth() - iconSpaceUsed,
  46465. textArea.getHeight(),
  46466. alignment.getFlags() | Justification::top);
  46467. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  46468. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  46469. }
  46470. int LookAndFeel::getAlertBoxWindowFlags()
  46471. {
  46472. return ComponentPeer::windowAppearsOnTaskbar
  46473. | ComponentPeer::windowHasDropShadow;
  46474. }
  46475. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46476. int width, int height,
  46477. double progress, const String& textToShow)
  46478. {
  46479. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  46480. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  46481. g.fillAll (background);
  46482. if (progress >= 0.0f && progress < 1.0f)
  46483. {
  46484. drawGlassLozenge (g, 1.0f, 1.0f,
  46485. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  46486. (float) (height - 2),
  46487. foreground,
  46488. 0.5f, 0.0f,
  46489. true, true, true, true);
  46490. }
  46491. else
  46492. {
  46493. // spinning bar..
  46494. g.setColour (foreground);
  46495. const int stripeWidth = height * 2;
  46496. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  46497. Path p;
  46498. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  46499. p.addQuadrilateral (x, 0.0f,
  46500. x + stripeWidth * 0.5f, 0.0f,
  46501. x, (float) height,
  46502. x - stripeWidth * 0.5f, (float) height);
  46503. Image im (Image::ARGB, width, height, true);
  46504. {
  46505. Graphics g (im);
  46506. drawGlassLozenge (g, 1.0f, 1.0f,
  46507. (float) (width - 2),
  46508. (float) (height - 2),
  46509. foreground,
  46510. 0.5f, 0.0f,
  46511. true, true, true, true);
  46512. }
  46513. ImageBrush ib (&im, 0, 0, 0.85f);
  46514. g.setBrush (&ib);
  46515. g.fillPath (p);
  46516. }
  46517. if (textToShow.isNotEmpty())
  46518. {
  46519. g.setColour (Colour::contrasting (background, foreground));
  46520. g.setFont (height * 0.6f);
  46521. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  46522. }
  46523. }
  46524. void LookAndFeel::drawScrollbarButton (Graphics& g,
  46525. ScrollBar& scrollbar,
  46526. int width, int height,
  46527. int buttonDirection,
  46528. bool /*isScrollbarVertical*/,
  46529. bool /*isMouseOverButton*/,
  46530. bool isButtonDown)
  46531. {
  46532. Path p;
  46533. if (buttonDirection == 0)
  46534. p.addTriangle (width * 0.5f, height * 0.2f,
  46535. width * 0.1f, height * 0.7f,
  46536. width * 0.9f, height * 0.7f);
  46537. else if (buttonDirection == 1)
  46538. p.addTriangle (width * 0.8f, height * 0.5f,
  46539. width * 0.3f, height * 0.1f,
  46540. width * 0.3f, height * 0.9f);
  46541. else if (buttonDirection == 2)
  46542. p.addTriangle (width * 0.5f, height * 0.8f,
  46543. width * 0.1f, height * 0.3f,
  46544. width * 0.9f, height * 0.3f);
  46545. else if (buttonDirection == 3)
  46546. p.addTriangle (width * 0.2f, height * 0.5f,
  46547. width * 0.7f, height * 0.1f,
  46548. width * 0.7f, height * 0.9f);
  46549. if (isButtonDown)
  46550. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  46551. else
  46552. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  46553. g.fillPath (p);
  46554. g.setColour (Colour (0x80000000));
  46555. g.strokePath (p, PathStrokeType (0.5f));
  46556. }
  46557. void LookAndFeel::drawScrollbar (Graphics& g,
  46558. ScrollBar& scrollbar,
  46559. int x, int y,
  46560. int width, int height,
  46561. bool isScrollbarVertical,
  46562. int thumbStartPosition,
  46563. int thumbSize,
  46564. bool /*isMouseOver*/,
  46565. bool /*isMouseDown*/)
  46566. {
  46567. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  46568. Path slotPath, thumbPath;
  46569. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  46570. const float slotIndentx2 = slotIndent * 2.0f;
  46571. const float thumbIndent = slotIndent + 1.0f;
  46572. const float thumbIndentx2 = thumbIndent * 2.0f;
  46573. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  46574. if (isScrollbarVertical)
  46575. {
  46576. slotPath.addRoundedRectangle (x + slotIndent,
  46577. y + slotIndent,
  46578. width - slotIndentx2,
  46579. height - slotIndentx2,
  46580. (width - slotIndentx2) * 0.5f);
  46581. if (thumbSize > 0)
  46582. thumbPath.addRoundedRectangle (x + thumbIndent,
  46583. thumbStartPosition + thumbIndent,
  46584. width - thumbIndentx2,
  46585. thumbSize - thumbIndentx2,
  46586. (width - thumbIndentx2) * 0.5f);
  46587. gx1 = (float) x;
  46588. gx2 = x + width * 0.7f;
  46589. }
  46590. else
  46591. {
  46592. slotPath.addRoundedRectangle (x + slotIndent,
  46593. y + slotIndent,
  46594. width - slotIndentx2,
  46595. height - slotIndentx2,
  46596. (height - slotIndentx2) * 0.5f);
  46597. if (thumbSize > 0)
  46598. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  46599. y + thumbIndent,
  46600. thumbSize - thumbIndentx2,
  46601. height - thumbIndentx2,
  46602. (height - thumbIndentx2) * 0.5f);
  46603. gy1 = (float) y;
  46604. gy2 = y + height * 0.7f;
  46605. }
  46606. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  46607. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  46608. gx1, gy1,
  46609. thumbColour.overlaidWith (Colour (0x19000000)),
  46610. gx2, gy2, false);
  46611. g.setBrush (&gb);
  46612. g.fillPath (slotPath);
  46613. if (isScrollbarVertical)
  46614. {
  46615. gx1 = x + width * 0.6f;
  46616. gx2 = (float) x + width;
  46617. }
  46618. else
  46619. {
  46620. gy1 = y + height * 0.6f;
  46621. gy2 = (float) y + height;
  46622. }
  46623. GradientBrush gb2 (Colours::transparentBlack,
  46624. gx1, gy1,
  46625. Colour (0x19000000),
  46626. gx2, gy2, false);
  46627. g.setBrush (&gb2);
  46628. g.fillPath (slotPath);
  46629. g.setColour (thumbColour);
  46630. g.fillPath (thumbPath);
  46631. GradientBrush gb3 (Colour (0x10000000),
  46632. gx1, gy1,
  46633. Colours::transparentBlack,
  46634. gx2, gy2, false);
  46635. g.saveState();
  46636. g.setBrush (&gb3);
  46637. if (isScrollbarVertical)
  46638. g.reduceClipRegion (x + width / 2, y, width, height);
  46639. else
  46640. g.reduceClipRegion (x, y + height / 2, width, height);
  46641. g.fillPath (thumbPath);
  46642. g.restoreState();
  46643. g.setColour (Colour (0x4c000000));
  46644. g.strokePath (thumbPath, PathStrokeType (0.4f));
  46645. }
  46646. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  46647. {
  46648. return 0;
  46649. }
  46650. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  46651. {
  46652. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  46653. }
  46654. int LookAndFeel::getDefaultScrollbarWidth()
  46655. {
  46656. return 18;
  46657. }
  46658. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  46659. {
  46660. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  46661. : scrollbar.getHeight());
  46662. }
  46663. const Path LookAndFeel::getTickShape (const float height)
  46664. {
  46665. static const unsigned char tickShapeData[] =
  46666. {
  46667. 109,0,224,168,68,0,0,119,67,108,0,224,172,68,0,128,146,67,113,0,192,148,68,0,0,219,67,0,96,110,68,0,224,56,68,113,0,64,51,68,0,32,130,68,0,64,20,68,0,224,
  46668. 162,68,108,0,128,3,68,0,128,168,68,113,0,128,221,67,0,192,175,68,0,0,207,67,0,32,179,68,113,0,0,201,67,0,224,173,68,0,0,181,67,0,224,161,68,108,0,128,168,67,
  46669. 0,128,154,68,113,0,128,141,67,0,192,138,68,0,128,108,67,0,64,131,68,113,0,0,62,67,0,128,119,68,0,0,5,67,0,128,114,68,113,0,0,102,67,0,192,88,68,0,128,155,
  46670. 67,0,192,88,68,113,0,0,190,67,0,192,88,68,0,128,232,67,0,224,131,68,108,0,128,246,67,0,192,139,68,113,0,64,33,68,0,128,87,68,0,0,93,68,0,224,26,68,113,0,
  46671. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  46672. };
  46673. Path p;
  46674. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  46675. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46676. return p;
  46677. }
  46678. const Path LookAndFeel::getCrossShape (const float height)
  46679. {
  46680. static const unsigned char crossShapeData[] =
  46681. {
  46682. 109,0,0,17,68,0,96,145,68,108,0,192,13,68,0,192,147,68,113,0,0,213,67,0,64,174,68,0,0,168,67,0,64,174,68,113,0,0,104,67,0,64,174,68,0,0,5,67,0,64,
  46683. 153,68,113,0,0,18,67,0,64,153,68,0,0,24,67,0,64,153,68,113,0,0,135,67,0,64,153,68,0,128,207,67,0,224,130,68,108,0,0,220,67,0,0,126,68,108,0,0,204,67,
  46684. 0,128,117,68,113,0,0,138,67,0,64,82,68,0,0,138,67,0,192,57,68,113,0,0,138,67,0,192,37,68,0,128,210,67,0,64,10,68,113,0,128,220,67,0,64,45,68,0,0,8,
  46685. 68,0,128,78,68,108,0,192,14,68,0,0,87,68,108,0,64,20,68,0,0,80,68,113,0,192,57,68,0,0,32,68,0,128,88,68,0,0,32,68,113,0,64,112,68,0,0,32,68,0,
  46686. 128,124,68,0,64,68,68,113,0,0,121,68,0,192,67,68,0,128,119,68,0,192,67,68,113,0,192,108,68,0,192,67,68,0,32,89,68,0,96,82,68,113,0,128,69,68,0,0,97,68,
  46687. 0,0,56,68,0,64,115,68,108,0,64,49,68,0,128,124,68,108,0,192,55,68,0,96,129,68,113,0,0,92,68,0,224,146,68,0,192,129,68,0,224,146,68,113,0,64,110,68,0,64,
  46688. 168,68,0,64,87,68,0,64,168,68,113,0,128,66,68,0,64,168,68,0,64,27,68,0,32,150,68,99,101
  46689. };
  46690. Path p;
  46691. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  46692. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46693. return p;
  46694. }
  46695. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  46696. {
  46697. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  46698. x += (w - boxSize) >> 1;
  46699. y += (h - boxSize) >> 1;
  46700. w = boxSize;
  46701. h = boxSize;
  46702. g.setColour (Colour (0xe5ffffff));
  46703. g.fillRect (x, y, w, h);
  46704. g.setColour (Colour (0x80000000));
  46705. g.drawRect (x, y, w, h);
  46706. const float size = boxSize / 2 + 1.0f;
  46707. const float centre = (float) (boxSize / 2);
  46708. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  46709. if (isPlus)
  46710. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  46711. }
  46712. void LookAndFeel::drawBubble (Graphics& g,
  46713. float tipX, float tipY,
  46714. float boxX, float boxY,
  46715. float boxW, float boxH)
  46716. {
  46717. int side = 0;
  46718. if (tipX < boxX)
  46719. side = 1;
  46720. else if (tipX > boxX + boxW)
  46721. side = 3;
  46722. else if (tipY > boxY + boxH)
  46723. side = 2;
  46724. const float indent = 2.0f;
  46725. Path p;
  46726. p.addBubble (boxX + indent,
  46727. boxY + indent,
  46728. boxW - indent * 2.0f,
  46729. boxH - indent * 2.0f,
  46730. 5.0f,
  46731. tipX, tipY,
  46732. side,
  46733. 0.5f,
  46734. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  46735. //xxx need to take comp as param for colour
  46736. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  46737. g.fillPath (p);
  46738. //xxx as above
  46739. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  46740. g.strokePath (p, PathStrokeType (1.33f));
  46741. }
  46742. const Font LookAndFeel::getPopupMenuFont()
  46743. {
  46744. return Font (17.0f);
  46745. }
  46746. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  46747. const bool isSeparator,
  46748. int standardMenuItemHeight,
  46749. int& idealWidth,
  46750. int& idealHeight)
  46751. {
  46752. if (isSeparator)
  46753. {
  46754. idealWidth = 50;
  46755. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  46756. }
  46757. else
  46758. {
  46759. Font font (getPopupMenuFont());
  46760. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  46761. font.setHeight (standardMenuItemHeight / 1.3f);
  46762. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  46763. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  46764. }
  46765. }
  46766. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  46767. {
  46768. const Colour background (findColour (PopupMenu::backgroundColourId));
  46769. g.fillAll (background);
  46770. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  46771. for (int i = 0; i < height; i += 3)
  46772. g.fillRect (0, i, width, 1);
  46773. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  46774. g.drawRect (0, 0, width, height);
  46775. }
  46776. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  46777. int width, int height,
  46778. bool isScrollUpArrow)
  46779. {
  46780. const Colour background (findColour (PopupMenu::backgroundColourId));
  46781. GradientBrush gb (background,
  46782. 0.0f, height * 0.5f,
  46783. background.withAlpha (0.0f),
  46784. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  46785. false);
  46786. g.setBrush (&gb);
  46787. g.fillRect (1, 1, width - 2, height - 2);
  46788. const float hw = width * 0.5f;
  46789. const float arrowW = height * 0.3f;
  46790. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  46791. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  46792. Path p;
  46793. p.addTriangle (hw - arrowW, y1,
  46794. hw + arrowW, y1,
  46795. hw, y2);
  46796. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  46797. g.fillPath (p);
  46798. }
  46799. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  46800. int width, int height,
  46801. const bool isSeparator,
  46802. const bool isActive,
  46803. const bool isHighlighted,
  46804. const bool isTicked,
  46805. const bool hasSubMenu,
  46806. const String& text,
  46807. const String& shortcutKeyText,
  46808. Image* image,
  46809. const Colour* const textColourToUse)
  46810. {
  46811. const float halfH = height * 0.5f;
  46812. if (isSeparator)
  46813. {
  46814. const float separatorIndent = 5.5f;
  46815. g.setColour (Colour (0x33000000));
  46816. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  46817. g.setColour (Colour (0x66ffffff));
  46818. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  46819. }
  46820. else
  46821. {
  46822. Colour textColour (findColour (PopupMenu::textColourId));
  46823. if (textColourToUse != 0)
  46824. textColour = *textColourToUse;
  46825. if (isHighlighted)
  46826. {
  46827. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  46828. g.fillRect (1, 1, width - 2, height - 2);
  46829. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  46830. }
  46831. else
  46832. {
  46833. g.setColour (textColour);
  46834. }
  46835. if (! isActive)
  46836. g.setOpacity (0.3f);
  46837. Font font (getPopupMenuFont());
  46838. if (font.getHeight() > height / 1.3f)
  46839. font.setHeight (height / 1.3f);
  46840. g.setFont (font);
  46841. const int leftBorder = (height * 5) / 4;
  46842. const int rightBorder = 4;
  46843. if (image != 0)
  46844. {
  46845. g.drawImageWithin (image,
  46846. 2, 1, leftBorder - 4, height - 2,
  46847. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  46848. }
  46849. else if (isTicked)
  46850. {
  46851. const Path tick (getTickShape (1.0f));
  46852. const float th = font.getAscent();
  46853. const float ty = halfH - th * 0.5f;
  46854. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  46855. th, true));
  46856. }
  46857. g.drawFittedText (text,
  46858. leftBorder, 0,
  46859. width - (leftBorder + rightBorder), height,
  46860. Justification::centredLeft, 1);
  46861. if (shortcutKeyText.isNotEmpty())
  46862. {
  46863. Font f2 (g.getCurrentFont());
  46864. f2.setHeight (f2.getHeight() * 0.75f);
  46865. f2.setHorizontalScale (0.95f);
  46866. g.setFont (f2);
  46867. g.drawText (shortcutKeyText,
  46868. leftBorder,
  46869. 0,
  46870. width - (leftBorder + rightBorder + 4),
  46871. height,
  46872. Justification::centredRight,
  46873. true);
  46874. }
  46875. if (hasSubMenu)
  46876. {
  46877. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  46878. const float x = width - height * 0.6f;
  46879. Path p;
  46880. p.addTriangle (x, halfH - arrowH * 0.5f,
  46881. x, halfH + arrowH * 0.5f,
  46882. x + arrowH * 0.6f, halfH);
  46883. g.fillPath (p);
  46884. }
  46885. }
  46886. }
  46887. int LookAndFeel::getMenuWindowFlags()
  46888. {
  46889. return ComponentPeer::windowHasDropShadow;
  46890. }
  46891. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  46892. bool, MenuBarComponent& menuBar)
  46893. {
  46894. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  46895. if (menuBar.isEnabled())
  46896. {
  46897. drawShinyButtonShape (g,
  46898. -4.0f, 0.0f,
  46899. width + 8.0f, (float) height,
  46900. 0.0f,
  46901. baseColour,
  46902. 0.4f,
  46903. true, true, true, true);
  46904. }
  46905. else
  46906. {
  46907. g.fillAll (baseColour);
  46908. }
  46909. }
  46910. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  46911. {
  46912. return Font (menuBar.getHeight() * 0.7f);
  46913. }
  46914. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  46915. {
  46916. return getMenuBarFont (menuBar, itemIndex, itemText)
  46917. .getStringWidth (itemText) + menuBar.getHeight();
  46918. }
  46919. void LookAndFeel::drawMenuBarItem (Graphics& g,
  46920. int width, int height,
  46921. int itemIndex,
  46922. const String& itemText,
  46923. bool isMouseOverItem,
  46924. bool isMenuOpen,
  46925. bool /*isMouseOverBar*/,
  46926. MenuBarComponent& menuBar)
  46927. {
  46928. if (! menuBar.isEnabled())
  46929. {
  46930. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  46931. .withMultipliedAlpha (0.5f));
  46932. }
  46933. else if (isMenuOpen || isMouseOverItem)
  46934. {
  46935. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  46936. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  46937. }
  46938. else
  46939. {
  46940. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  46941. }
  46942. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  46943. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  46944. }
  46945. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  46946. TextEditor& textEditor)
  46947. {
  46948. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  46949. }
  46950. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  46951. {
  46952. if (textEditor.isEnabled())
  46953. {
  46954. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  46955. {
  46956. const int border = 2;
  46957. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  46958. g.drawRect (0, 0, width, height, border);
  46959. g.setOpacity (1.0f);
  46960. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  46961. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  46962. }
  46963. else
  46964. {
  46965. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  46966. g.drawRect (0, 0, width, height);
  46967. g.setOpacity (1.0f);
  46968. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  46969. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  46970. }
  46971. }
  46972. }
  46973. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  46974. const bool isButtonDown,
  46975. int buttonX, int buttonY,
  46976. int buttonW, int buttonH,
  46977. ComboBox& box)
  46978. {
  46979. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  46980. if (box.isEnabled() && box.hasKeyboardFocus (false))
  46981. {
  46982. g.setColour (box.findColour (TextButton::buttonColourId));
  46983. g.drawRect (0, 0, width, height, 2);
  46984. }
  46985. else
  46986. {
  46987. g.setColour (box.findColour (ComboBox::outlineColourId));
  46988. g.drawRect (0, 0, width, height);
  46989. }
  46990. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  46991. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  46992. box.hasKeyboardFocus (true),
  46993. false, isButtonDown)
  46994. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  46995. drawGlassLozenge (g,
  46996. buttonX + outlineThickness, buttonY + outlineThickness,
  46997. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  46998. baseColour, outlineThickness, -1.0f,
  46999. true, true, true, true);
  47000. if (box.isEnabled())
  47001. {
  47002. const float arrowX = 0.3f;
  47003. const float arrowH = 0.2f;
  47004. Path p;
  47005. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  47006. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  47007. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  47008. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  47009. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  47010. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  47011. g.setColour (box.findColour (ComboBox::arrowColourId));
  47012. g.fillPath (p);
  47013. }
  47014. }
  47015. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  47016. {
  47017. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  47018. }
  47019. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  47020. {
  47021. return new Label (String::empty, String::empty);
  47022. }
  47023. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  47024. {
  47025. label.setBounds (1, 1,
  47026. box.getWidth() + 3 - box.getHeight(),
  47027. box.getHeight() - 2);
  47028. label.setFont (getComboBoxFont (box));
  47029. }
  47030. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  47031. int x, int y,
  47032. int width, int height,
  47033. float /*sliderPos*/,
  47034. float /*minSliderPos*/,
  47035. float /*maxSliderPos*/,
  47036. const Slider::SliderStyle /*style*/,
  47037. Slider& slider)
  47038. {
  47039. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47040. const Colour trackColour (slider.findColour (Slider::trackColourId));
  47041. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  47042. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  47043. Path indent;
  47044. if (slider.isHorizontal())
  47045. {
  47046. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  47047. const float ih = sliderRadius;
  47048. GradientBrush gb (gradCol1, 0.0f, iy,
  47049. gradCol2, 0.0f, iy + ih, false);
  47050. g.setBrush (&gb);
  47051. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  47052. width + sliderRadius, ih,
  47053. 5.0f);
  47054. g.fillPath (indent);
  47055. }
  47056. else
  47057. {
  47058. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  47059. const float iw = sliderRadius;
  47060. GradientBrush gb (gradCol1, ix, 0.0f,
  47061. gradCol2, ix + iw, 0.0f, false);
  47062. g.setBrush (&gb);
  47063. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  47064. iw, height + sliderRadius,
  47065. 5.0f);
  47066. g.fillPath (indent);
  47067. }
  47068. g.setColour (Colour (0x4c000000));
  47069. g.strokePath (indent, PathStrokeType (0.5f));
  47070. }
  47071. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  47072. int x, int y,
  47073. int width, int height,
  47074. float sliderPos,
  47075. float minSliderPos,
  47076. float maxSliderPos,
  47077. const Slider::SliderStyle style,
  47078. Slider& slider)
  47079. {
  47080. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47081. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  47082. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  47083. slider.isMouseOverOrDragging() && slider.isEnabled(),
  47084. slider.isMouseButtonDown() && slider.isEnabled()));
  47085. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  47086. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  47087. {
  47088. float kx, ky;
  47089. if (style == Slider::LinearVertical)
  47090. {
  47091. kx = x + width * 0.5f;
  47092. ky = sliderPos;
  47093. }
  47094. else
  47095. {
  47096. kx = sliderPos;
  47097. ky = y + height * 0.5f;
  47098. }
  47099. drawGlassSphere (g,
  47100. kx - sliderRadius,
  47101. ky - sliderRadius,
  47102. sliderRadius * 2.0f,
  47103. knobColour, outlineThickness);
  47104. }
  47105. else
  47106. {
  47107. if (style == Slider::ThreeValueVertical)
  47108. {
  47109. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  47110. sliderPos - sliderRadius,
  47111. sliderRadius * 2.0f,
  47112. knobColour, outlineThickness);
  47113. }
  47114. else if (style == Slider::ThreeValueHorizontal)
  47115. {
  47116. drawGlassSphere (g,sliderPos - sliderRadius,
  47117. y + height * 0.5f - sliderRadius,
  47118. sliderRadius * 2.0f,
  47119. knobColour, outlineThickness);
  47120. }
  47121. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  47122. {
  47123. const float sr = jmin (sliderRadius, width * 0.4f);
  47124. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  47125. minSliderPos - sliderRadius,
  47126. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  47127. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  47128. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  47129. }
  47130. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  47131. {
  47132. const float sr = jmin (sliderRadius, height * 0.4f);
  47133. drawGlassPointer (g, minSliderPos - sr,
  47134. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  47135. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  47136. drawGlassPointer (g, maxSliderPos - sliderRadius,
  47137. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  47138. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  47139. }
  47140. }
  47141. }
  47142. void LookAndFeel::drawLinearSlider (Graphics& g,
  47143. int x, int y,
  47144. int width, int height,
  47145. float sliderPos,
  47146. float minSliderPos,
  47147. float maxSliderPos,
  47148. const Slider::SliderStyle style,
  47149. Slider& slider)
  47150. {
  47151. g.fillAll (slider.findColour (Slider::backgroundColourId));
  47152. if (style == Slider::LinearBar)
  47153. {
  47154. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47155. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  47156. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  47157. false,
  47158. isMouseOver,
  47159. isMouseOver || slider.isMouseButtonDown()));
  47160. drawShinyButtonShape (g,
  47161. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  47162. baseColour,
  47163. slider.isEnabled() ? 0.9f : 0.3f,
  47164. true, true, true, true);
  47165. }
  47166. else
  47167. {
  47168. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47169. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47170. }
  47171. }
  47172. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  47173. {
  47174. return jmin (7,
  47175. slider.getHeight() / 2,
  47176. slider.getWidth() / 2) + 2;
  47177. }
  47178. void LookAndFeel::drawRotarySlider (Graphics& g,
  47179. int x, int y,
  47180. int width, int height,
  47181. float sliderPos,
  47182. const float rotaryStartAngle,
  47183. const float rotaryEndAngle,
  47184. Slider& slider)
  47185. {
  47186. const float radius = jmin (width / 2, height / 2) - 2.0f;
  47187. const float centreX = x + width * 0.5f;
  47188. const float centreY = y + height * 0.5f;
  47189. const float rx = centreX - radius;
  47190. const float ry = centreY - radius;
  47191. const float rw = radius * 2.0f;
  47192. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  47193. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47194. if (radius > 12.0f)
  47195. {
  47196. if (slider.isEnabled())
  47197. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47198. else
  47199. g.setColour (Colour (0x80808080));
  47200. const float thickness = 0.7f;
  47201. {
  47202. Path filledArc;
  47203. filledArc.addPieSegment (rx, ry, rw, rw,
  47204. rotaryStartAngle,
  47205. angle,
  47206. thickness);
  47207. g.fillPath (filledArc);
  47208. }
  47209. if (thickness > 0)
  47210. {
  47211. const float innerRadius = radius * 0.2f;
  47212. Path p;
  47213. p.addTriangle (-innerRadius, 0.0f,
  47214. 0.0f, -radius * thickness * 1.1f,
  47215. innerRadius, 0.0f);
  47216. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  47217. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47218. }
  47219. if (slider.isEnabled())
  47220. {
  47221. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  47222. Path outlineArc;
  47223. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  47224. outlineArc.closeSubPath();
  47225. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  47226. }
  47227. }
  47228. else
  47229. {
  47230. if (slider.isEnabled())
  47231. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47232. else
  47233. g.setColour (Colour (0x80808080));
  47234. Path p;
  47235. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  47236. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  47237. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  47238. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47239. }
  47240. }
  47241. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  47242. {
  47243. return new TextButton (isIncrement ? "+" : "-", String::empty);
  47244. }
  47245. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  47246. {
  47247. Label* const l = new Label (T("n"), String::empty);
  47248. l->setJustificationType (Justification::centred);
  47249. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47250. l->setColour (Label::backgroundColourId,
  47251. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  47252. : slider.findColour (Slider::textBoxBackgroundColourId));
  47253. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47254. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47255. l->setColour (TextEditor::backgroundColourId,
  47256. slider.findColour (Slider::textBoxBackgroundColourId)
  47257. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  47258. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47259. return l;
  47260. }
  47261. ImageEffectFilter* LookAndFeel::getSliderEffect()
  47262. {
  47263. return 0;
  47264. }
  47265. static const TextLayout layoutTooltipText (const String& text) throw()
  47266. {
  47267. const float tooltipFontSize = 15.0f;
  47268. const int maxToolTipWidth = 400;
  47269. const Font f (tooltipFontSize, Font::bold);
  47270. TextLayout tl (text, f);
  47271. tl.layout (maxToolTipWidth, Justification::left, true);
  47272. return tl;
  47273. }
  47274. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  47275. {
  47276. const TextLayout tl (layoutTooltipText (tipText));
  47277. width = tl.getWidth() + 14;
  47278. height = tl.getHeight() + 10;
  47279. }
  47280. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  47281. {
  47282. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  47283. const Colour textCol (findColour (TooltipWindow::textColourId));
  47284. g.setColour (findColour (TooltipWindow::outlineColourId));
  47285. g.drawRect (0, 0, width, height);
  47286. const TextLayout tl (layoutTooltipText (text));
  47287. g.setColour (findColour (TooltipWindow::textColourId));
  47288. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  47289. }
  47290. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  47291. {
  47292. return new TextButton (text, TRANS("click to browse for a different file"));
  47293. }
  47294. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  47295. ComboBox* filenameBox,
  47296. Button* browseButton)
  47297. {
  47298. browseButton->setSize (80, filenameComp.getHeight());
  47299. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  47300. if (tb != 0)
  47301. tb->changeWidthToFitText();
  47302. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  47303. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  47304. }
  47305. void LookAndFeel::drawCornerResizer (Graphics& g,
  47306. int w, int h,
  47307. bool /*isMouseOver*/,
  47308. bool /*isMouseDragging*/)
  47309. {
  47310. const float lineThickness = jmin (w, h) * 0.075f;
  47311. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  47312. {
  47313. g.setColour (Colours::lightgrey);
  47314. g.drawLine (w * i,
  47315. h + 1.0f,
  47316. w + 1.0f,
  47317. h * i,
  47318. lineThickness);
  47319. g.setColour (Colours::darkgrey);
  47320. g.drawLine (w * i + lineThickness,
  47321. h + 1.0f,
  47322. w + 1.0f,
  47323. h * i + lineThickness,
  47324. lineThickness);
  47325. }
  47326. }
  47327. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  47328. const BorderSize& /*borders*/)
  47329. {
  47330. }
  47331. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  47332. const BorderSize& border, ResizableWindow&)
  47333. {
  47334. g.setColour (Colour (0x80000000));
  47335. g.drawRect (0, 0, w, h);
  47336. g.setColour (Colour (0x19000000));
  47337. g.drawRect (border.getLeft() - 1,
  47338. border.getTop() - 1,
  47339. w + 2 - border.getLeftAndRight(),
  47340. h + 2 - border.getTopAndBottom());
  47341. }
  47342. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  47343. Graphics& g, int w, int h,
  47344. int titleSpaceX, int titleSpaceW,
  47345. const Image* icon,
  47346. bool drawTitleTextOnLeft)
  47347. {
  47348. const bool isActive = window.isActiveWindow();
  47349. GradientBrush gb (window.getBackgroundColour(),
  47350. 0.0f, 0.0f,
  47351. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  47352. 0.0f, (float) h, false);
  47353. g.setBrush (&gb);
  47354. g.fillAll();
  47355. g.setFont (h * 0.65f, Font::bold);
  47356. int textW = g.getCurrentFont().getStringWidth (window.getName());
  47357. int iconW = 0;
  47358. int iconH = 0;
  47359. if (icon != 0)
  47360. {
  47361. iconH = (int) g.getCurrentFont().getHeight();
  47362. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  47363. }
  47364. textW = jmin (titleSpaceW, textW + iconW);
  47365. int textX = drawTitleTextOnLeft ? titleSpaceX
  47366. : jmax (titleSpaceX, (w - textW) / 2);
  47367. if (textX + textW > titleSpaceX + titleSpaceW)
  47368. textX = titleSpaceX + titleSpaceW - textW;
  47369. if (icon != 0)
  47370. {
  47371. g.setOpacity (isActive ? 1.0f : 0.6f);
  47372. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  47373. RectanglePlacement::centred, false);
  47374. textX += iconW;
  47375. textW -= iconW;
  47376. }
  47377. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  47378. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  47379. }
  47380. class GlassWindowButton : public Button
  47381. {
  47382. public:
  47383. GlassWindowButton (const String& name, const Colour& col,
  47384. const Path& normalShape_,
  47385. const Path& toggledShape_) throw()
  47386. : Button (name),
  47387. colour (col),
  47388. normalShape (normalShape_),
  47389. toggledShape (toggledShape_)
  47390. {
  47391. }
  47392. ~GlassWindowButton()
  47393. {
  47394. }
  47395. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  47396. {
  47397. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  47398. if (! isEnabled())
  47399. alpha *= 0.5f;
  47400. float x = 0, y = 0, diam;
  47401. if (getWidth() < getHeight())
  47402. {
  47403. diam = (float) getWidth();
  47404. y = (getHeight() - getWidth()) * 0.5f;
  47405. }
  47406. else
  47407. {
  47408. diam = (float) getHeight();
  47409. y = (getWidth() - getHeight()) * 0.5f;
  47410. }
  47411. x += diam * 0.05f;
  47412. y += diam * 0.05f;
  47413. diam *= 0.9f;
  47414. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  47415. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  47416. g.setBrush (&gb1);
  47417. g.fillEllipse (x, y, diam, diam);
  47418. x += 2.0f;
  47419. y += 2.0f;
  47420. diam -= 4.0f;
  47421. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  47422. Path& p = getToggleState() ? toggledShape : normalShape;
  47423. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  47424. diam * 0.4f, diam * 0.4f, true));
  47425. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  47426. g.fillPath (p, t);
  47427. }
  47428. juce_UseDebuggingNewOperator
  47429. private:
  47430. Colour colour;
  47431. Path normalShape, toggledShape;
  47432. GlassWindowButton (const GlassWindowButton&);
  47433. const GlassWindowButton& operator= (const GlassWindowButton&);
  47434. };
  47435. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  47436. {
  47437. Path shape;
  47438. const float crossThickness = 0.25f;
  47439. if (buttonType == DocumentWindow::closeButton)
  47440. {
  47441. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  47442. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  47443. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  47444. }
  47445. else if (buttonType == DocumentWindow::minimiseButton)
  47446. {
  47447. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47448. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  47449. }
  47450. else if (buttonType == DocumentWindow::maximiseButton)
  47451. {
  47452. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  47453. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47454. Path fullscreenShape;
  47455. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  47456. fullscreenShape.lineTo (0.0f, 100.0f);
  47457. fullscreenShape.lineTo (0.0f, 0.0f);
  47458. fullscreenShape.lineTo (100.0f, 0.0f);
  47459. fullscreenShape.lineTo (100.0f, 45.0f);
  47460. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  47461. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  47462. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  47463. }
  47464. jassertfalse
  47465. return 0;
  47466. }
  47467. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  47468. int titleBarX,
  47469. int titleBarY,
  47470. int titleBarW,
  47471. int titleBarH,
  47472. Button* minimiseButton,
  47473. Button* maximiseButton,
  47474. Button* closeButton,
  47475. bool positionTitleBarButtonsOnLeft)
  47476. {
  47477. const int buttonW = titleBarH - titleBarH / 8;
  47478. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  47479. : titleBarX + titleBarW - buttonW - buttonW / 4;
  47480. if (closeButton != 0)
  47481. {
  47482. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47483. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  47484. }
  47485. if (positionTitleBarButtonsOnLeft)
  47486. swapVariables (minimiseButton, maximiseButton);
  47487. if (maximiseButton != 0)
  47488. {
  47489. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47490. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  47491. }
  47492. if (minimiseButton != 0)
  47493. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47494. }
  47495. int LookAndFeel::getDefaultMenuBarHeight()
  47496. {
  47497. return 24;
  47498. }
  47499. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  47500. {
  47501. return new DropShadower (0.4f, 1, 5, 10);
  47502. }
  47503. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  47504. int w, int h,
  47505. bool /*isVerticalBar*/,
  47506. bool isMouseOver,
  47507. bool isMouseDragging)
  47508. {
  47509. float alpha = 0.5f;
  47510. if (isMouseOver || isMouseDragging)
  47511. {
  47512. g.fillAll (Colour (0x190000ff));
  47513. alpha = 1.0f;
  47514. }
  47515. const float cx = w * 0.5f;
  47516. const float cy = h * 0.5f;
  47517. const float cr = jmin (w, h) * 0.4f;
  47518. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  47519. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  47520. true);
  47521. g.setBrush (&gb);
  47522. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  47523. }
  47524. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  47525. const String& text,
  47526. const Justification& position,
  47527. GroupComponent& group)
  47528. {
  47529. const float textH = 15.0f;
  47530. const float indent = 3.0f;
  47531. const float textEdgeGap = 4.0f;
  47532. float cs = 5.0f;
  47533. Font f (textH);
  47534. Path p;
  47535. float x = indent;
  47536. float y = f.getAscent() - 3.0f;
  47537. float w = jmax (0.0f, width - x * 2.0f);
  47538. float h = jmax (0.0f, height - y - indent);
  47539. cs = jmin (cs, w * 0.5f, h * 0.5f);
  47540. const float cs2 = 2.0f * cs;
  47541. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  47542. float textX = cs + textEdgeGap;
  47543. if (position.testFlags (Justification::horizontallyCentred))
  47544. textX = cs + (w - cs2 - textW) * 0.5f;
  47545. else if (position.testFlags (Justification::right))
  47546. textX = w - cs - textW - textEdgeGap;
  47547. p.startNewSubPath (x + textX + textW, y);
  47548. p.lineTo (x + w - cs, y);
  47549. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  47550. p.lineTo (x + w, y + h - cs);
  47551. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  47552. p.lineTo (x + cs, y + h);
  47553. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  47554. p.lineTo (x, y + cs);
  47555. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  47556. p.lineTo (x + textX, y);
  47557. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  47558. g.setColour (group.findColour (GroupComponent::outlineColourId)
  47559. .withMultipliedAlpha (alpha));
  47560. g.strokePath (p, PathStrokeType (2.0f));
  47561. g.setColour (group.findColour (GroupComponent::textColourId)
  47562. .withMultipliedAlpha (alpha));
  47563. g.setFont (f);
  47564. g.drawText (text,
  47565. roundFloatToInt (x + textX), 0,
  47566. roundFloatToInt (textW),
  47567. roundFloatToInt (textH),
  47568. Justification::centred, true);
  47569. }
  47570. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  47571. {
  47572. return 1 + tabDepth / 3;
  47573. }
  47574. int LookAndFeel::getTabButtonSpaceAroundImage()
  47575. {
  47576. return 4;
  47577. }
  47578. void LookAndFeel::createTabButtonShape (Path& p,
  47579. int width, int height,
  47580. int /*tabIndex*/,
  47581. const String& /*text*/,
  47582. Button& /*button*/,
  47583. TabbedButtonBar::Orientation orientation,
  47584. const bool /*isMouseOver*/,
  47585. const bool /*isMouseDown*/,
  47586. const bool /*isFrontTab*/)
  47587. {
  47588. const float w = (float) width;
  47589. const float h = (float) height;
  47590. float length = w;
  47591. float depth = h;
  47592. if (orientation == TabbedButtonBar::TabsAtLeft
  47593. || orientation == TabbedButtonBar::TabsAtRight)
  47594. {
  47595. swapVariables (length, depth);
  47596. }
  47597. const float indent = (float) getTabButtonOverlap ((int) depth);
  47598. const float overhang = 4.0f;
  47599. if (orientation == TabbedButtonBar::TabsAtLeft)
  47600. {
  47601. p.startNewSubPath (w, 0.0f);
  47602. p.lineTo (0.0f, indent);
  47603. p.lineTo (0.0f, h - indent);
  47604. p.lineTo (w, h);
  47605. p.lineTo (w + overhang, h + overhang);
  47606. p.lineTo (w + overhang, -overhang);
  47607. }
  47608. else if (orientation == TabbedButtonBar::TabsAtRight)
  47609. {
  47610. p.startNewSubPath (0.0f, 0.0f);
  47611. p.lineTo (w, indent);
  47612. p.lineTo (w, h - indent);
  47613. p.lineTo (0.0f, h);
  47614. p.lineTo (-overhang, h + overhang);
  47615. p.lineTo (-overhang, -overhang);
  47616. }
  47617. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47618. {
  47619. p.startNewSubPath (0.0f, 0.0f);
  47620. p.lineTo (indent, h);
  47621. p.lineTo (w - indent, h);
  47622. p.lineTo (w, 0.0f);
  47623. p.lineTo (w + overhang, -overhang);
  47624. p.lineTo (-overhang, -overhang);
  47625. }
  47626. else
  47627. {
  47628. p.startNewSubPath (0.0f, h);
  47629. p.lineTo (indent, 0.0f);
  47630. p.lineTo (w - indent, 0.0f);
  47631. p.lineTo (w, h);
  47632. p.lineTo (w + overhang, h + overhang);
  47633. p.lineTo (-overhang, h + overhang);
  47634. }
  47635. p.closeSubPath();
  47636. p = p.createPathWithRoundedCorners (3.0f);
  47637. }
  47638. void LookAndFeel::fillTabButtonShape (Graphics& g,
  47639. const Path& path,
  47640. const Colour& preferredColour,
  47641. int /*tabIndex*/,
  47642. const String& /*text*/,
  47643. Button& button,
  47644. TabbedButtonBar::Orientation /*orientation*/,
  47645. const bool /*isMouseOver*/,
  47646. const bool /*isMouseDown*/,
  47647. const bool isFrontTab)
  47648. {
  47649. g.setColour (isFrontTab ? preferredColour
  47650. : preferredColour.withMultipliedAlpha (0.9f));
  47651. g.fillPath (path);
  47652. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  47653. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  47654. }
  47655. void LookAndFeel::drawTabButtonText (Graphics& g,
  47656. int x, int y, int w, int h,
  47657. const Colour& preferredBackgroundColour,
  47658. int /*tabIndex*/,
  47659. const String& text,
  47660. Button& button,
  47661. TabbedButtonBar::Orientation orientation,
  47662. const bool isMouseOver,
  47663. const bool isMouseDown,
  47664. const bool /*isFrontTab*/)
  47665. {
  47666. int length = w;
  47667. int depth = h;
  47668. if (orientation == TabbedButtonBar::TabsAtLeft
  47669. || orientation == TabbedButtonBar::TabsAtRight)
  47670. {
  47671. swapVariables (length, depth);
  47672. }
  47673. Font font (depth * 0.6f);
  47674. font.setUnderline (button.hasKeyboardFocus (false));
  47675. GlyphArrangement textLayout;
  47676. textLayout.addFittedText (font, text.trim(),
  47677. 0.0f, 0.0f, (float) length, (float) depth,
  47678. Justification::centred,
  47679. jmax (1, depth / 12));
  47680. AffineTransform transform;
  47681. if (orientation == TabbedButtonBar::TabsAtLeft)
  47682. {
  47683. transform = transform.rotated (float_Pi * -0.5f)
  47684. .translated ((float) x, (float) (y + h));
  47685. }
  47686. else if (orientation == TabbedButtonBar::TabsAtRight)
  47687. {
  47688. transform = transform.rotated (float_Pi * 0.5f)
  47689. .translated ((float) (x + w), (float) y);
  47690. }
  47691. else
  47692. {
  47693. transform = transform.translated ((float) x, (float) y);
  47694. }
  47695. g.setColour (preferredBackgroundColour.contrasting());
  47696. if (! (isMouseOver || isMouseDown))
  47697. g.setOpacity (0.8f);
  47698. if (! button.isEnabled())
  47699. g.setOpacity (0.3f);
  47700. textLayout.draw (g, transform);
  47701. }
  47702. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  47703. const String& text,
  47704. int tabDepth,
  47705. Button&)
  47706. {
  47707. Font f (tabDepth * 0.6f);
  47708. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  47709. }
  47710. void LookAndFeel::drawTabButton (Graphics& g,
  47711. int w, int h,
  47712. const Colour& preferredColour,
  47713. int tabIndex,
  47714. const String& text,
  47715. Button& button,
  47716. TabbedButtonBar::Orientation orientation,
  47717. const bool isMouseOver,
  47718. const bool isMouseDown,
  47719. const bool isFrontTab)
  47720. {
  47721. int length = w;
  47722. int depth = h;
  47723. if (orientation == TabbedButtonBar::TabsAtLeft
  47724. || orientation == TabbedButtonBar::TabsAtRight)
  47725. {
  47726. swapVariables (length, depth);
  47727. }
  47728. Path tabShape;
  47729. createTabButtonShape (tabShape, w, h,
  47730. tabIndex, text, button, orientation,
  47731. isMouseOver, isMouseDown, isFrontTab);
  47732. fillTabButtonShape (g, tabShape, preferredColour,
  47733. tabIndex, text, button, orientation,
  47734. isMouseOver, isMouseDown, isFrontTab);
  47735. const int indent = getTabButtonOverlap (depth);
  47736. int x = 0, y = 0;
  47737. if (orientation == TabbedButtonBar::TabsAtLeft
  47738. || orientation == TabbedButtonBar::TabsAtRight)
  47739. {
  47740. y += indent;
  47741. h -= indent * 2;
  47742. }
  47743. else
  47744. {
  47745. x += indent;
  47746. w -= indent * 2;
  47747. }
  47748. drawTabButtonText (g, x, y, w, h, preferredColour,
  47749. tabIndex, text, button, orientation,
  47750. isMouseOver, isMouseDown, isFrontTab);
  47751. }
  47752. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  47753. int w, int h,
  47754. TabbedButtonBar& tabBar,
  47755. TabbedButtonBar::Orientation orientation)
  47756. {
  47757. const float shadowSize = 0.2f;
  47758. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  47759. Rectangle shadowRect;
  47760. if (orientation == TabbedButtonBar::TabsAtLeft)
  47761. {
  47762. x1 = (float) w;
  47763. x2 = w * (1.0f - shadowSize);
  47764. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  47765. }
  47766. else if (orientation == TabbedButtonBar::TabsAtRight)
  47767. {
  47768. x2 = w * shadowSize;
  47769. shadowRect.setBounds (0, 0, (int) x2, h);
  47770. }
  47771. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47772. {
  47773. y2 = h * shadowSize;
  47774. shadowRect.setBounds (0, 0, w, (int) y2);
  47775. }
  47776. else
  47777. {
  47778. y1 = (float) h;
  47779. y2 = h * (1.0f - shadowSize);
  47780. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  47781. }
  47782. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  47783. Colours::transparentBlack, x2, y2,
  47784. false);
  47785. g.setBrush (&gb);
  47786. shadowRect.expand (2, 2);
  47787. g.fillRect (shadowRect);
  47788. g.setColour (Colour (0x80000000));
  47789. if (orientation == TabbedButtonBar::TabsAtLeft)
  47790. {
  47791. g.fillRect (w - 1, 0, 1, h);
  47792. }
  47793. else if (orientation == TabbedButtonBar::TabsAtRight)
  47794. {
  47795. g.fillRect (0, 0, 1, h);
  47796. }
  47797. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47798. {
  47799. g.fillRect (0, 0, w, 1);
  47800. }
  47801. else
  47802. {
  47803. g.fillRect (0, h - 1, w, 1);
  47804. }
  47805. }
  47806. Button* LookAndFeel::createTabBarExtrasButton()
  47807. {
  47808. const float thickness = 7.0f;
  47809. const float indent = 22.0f;
  47810. Path p;
  47811. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  47812. DrawablePath ellipse;
  47813. ellipse.setPath (p);
  47814. ellipse.setSolidFill (Colour (0x99ffffff));
  47815. p.clear();
  47816. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  47817. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  47818. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  47819. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  47820. p.setUsingNonZeroWinding (false);
  47821. DrawablePath dp;
  47822. dp.setPath (p);
  47823. dp.setSolidFill (Colour (0x59000000));
  47824. DrawableComposite normalImage;
  47825. normalImage.insertDrawable (ellipse);
  47826. normalImage.insertDrawable (dp);
  47827. dp.setSolidFill (Colour (0xcc000000));
  47828. DrawableComposite overImage;
  47829. overImage.insertDrawable (ellipse);
  47830. overImage.insertDrawable (dp);
  47831. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  47832. db->setImages (&normalImage, &overImage, 0);
  47833. return db;
  47834. }
  47835. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  47836. {
  47837. g.fillAll (Colours::white);
  47838. const int w = header.getWidth();
  47839. const int h = header.getHeight();
  47840. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  47841. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  47842. false);
  47843. g.setBrush (&gb);
  47844. g.fillRect (0, h / 2, w, h);
  47845. g.setColour (Colour (0x33000000));
  47846. g.fillRect (0, h - 1, w, 1);
  47847. for (int i = header.getNumColumns (true); --i >= 0;)
  47848. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  47849. }
  47850. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  47851. int width, int height,
  47852. bool isMouseOver, bool isMouseDown,
  47853. int columnFlags)
  47854. {
  47855. if (isMouseDown)
  47856. g.fillAll (Colour (0x8899aadd));
  47857. else if (isMouseOver)
  47858. g.fillAll (Colour (0x5599aadd));
  47859. int rightOfText = width - 4;
  47860. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  47861. {
  47862. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  47863. const float bottom = height - top;
  47864. const float w = height * 0.5f;
  47865. const float x = rightOfText - (w * 1.25f);
  47866. rightOfText = (int) x;
  47867. Path sortArrow;
  47868. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  47869. g.setColour (Colour (0x99000000));
  47870. g.fillPath (sortArrow);
  47871. }
  47872. g.setColour (Colours::black);
  47873. g.setFont (height * 0.5f, Font::bold);
  47874. const int textX = 4;
  47875. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  47876. }
  47877. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  47878. {
  47879. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  47880. GradientBrush gb (background, 0.0f, 0.0f,
  47881. background.darker (0.1f),
  47882. toolbar.isVertical() ? w - 1.0f : 0.0f,
  47883. toolbar.isVertical() ? 0.0f : h - 1.0f,
  47884. false);
  47885. g.setBrush (&gb);
  47886. g.fillAll();
  47887. }
  47888. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  47889. {
  47890. return createTabBarExtrasButton();
  47891. }
  47892. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  47893. bool isMouseOver, bool isMouseDown,
  47894. ToolbarItemComponent& component)
  47895. {
  47896. if (isMouseDown)
  47897. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  47898. else if (isMouseOver)
  47899. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  47900. }
  47901. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  47902. const String& text, ToolbarItemComponent& component)
  47903. {
  47904. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  47905. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  47906. const float fontHeight = jmin (14.0f, height * 0.85f);
  47907. g.setFont (fontHeight);
  47908. g.drawFittedText (text,
  47909. x, y, width, height,
  47910. Justification::centred,
  47911. jmax (1, height / (int) fontHeight));
  47912. }
  47913. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  47914. bool isOpen, int width, int height)
  47915. {
  47916. const int buttonSize = (height * 3) / 4;
  47917. const int buttonIndent = (height - buttonSize) / 2;
  47918. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  47919. const int textX = buttonIndent * 2 + buttonSize + 2;
  47920. g.setColour (Colours::black);
  47921. g.setFont (height * 0.7f, Font::bold);
  47922. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  47923. }
  47924. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  47925. PropertyComponent&)
  47926. {
  47927. g.setColour (Colour (0x66ffffff));
  47928. g.fillRect (0, 0, width, height - 1);
  47929. }
  47930. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  47931. PropertyComponent& component)
  47932. {
  47933. g.setColour (Colours::black);
  47934. if (! component.isEnabled())
  47935. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  47936. g.setFont (jmin (height, 24) * 0.65f);
  47937. const Rectangle r (getPropertyComponentContentPosition (component));
  47938. g.drawFittedText (component.getName(),
  47939. 3, r.getY(), r.getX() - 5, r.getHeight(),
  47940. Justification::centredLeft, 2);
  47941. }
  47942. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  47943. {
  47944. return Rectangle (component.getWidth() / 3, 1,
  47945. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  47946. }
  47947. void LookAndFeel::createFileChooserHeaderText (const String& title,
  47948. const String& instructions,
  47949. GlyphArrangement& text,
  47950. int width)
  47951. {
  47952. text.clear();
  47953. text.addJustifiedText (Font (17.0f, Font::bold), title,
  47954. 8.0f, 22.0f, width - 16.0f,
  47955. Justification::centred);
  47956. text.addJustifiedText (Font (14.0f), instructions,
  47957. 8.0f, 24.0f + 16.0f, width - 16.0f,
  47958. Justification::centred);
  47959. }
  47960. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  47961. const String& filename, Image* icon,
  47962. const String& fileSizeDescription,
  47963. const String& fileTimeDescription,
  47964. const bool isDirectory,
  47965. const bool isItemSelected,
  47966. const int /*itemIndex*/)
  47967. {
  47968. if (isItemSelected)
  47969. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  47970. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  47971. g.setFont (height * 0.7f);
  47972. Image* im = icon;
  47973. Image* toRelease = 0;
  47974. if (im == 0)
  47975. {
  47976. toRelease = im = (isDirectory ? getDefaultFolderImage()
  47977. : getDefaultDocumentFileImage());
  47978. }
  47979. const int x = 32;
  47980. if (im != 0)
  47981. {
  47982. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  47983. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47984. false);
  47985. ImageCache::release (toRelease);
  47986. }
  47987. if (width > 450 && ! isDirectory)
  47988. {
  47989. const int sizeX = roundFloatToInt (width * 0.7f);
  47990. const int dateX = roundFloatToInt (width * 0.8f);
  47991. g.drawFittedText (filename,
  47992. x, 0, sizeX - x, height,
  47993. Justification::centredLeft, 1);
  47994. g.setFont (height * 0.5f);
  47995. g.setColour (Colours::darkgrey);
  47996. if (! isDirectory)
  47997. {
  47998. g.drawFittedText (fileSizeDescription,
  47999. sizeX, 0, dateX - sizeX - 8, height,
  48000. Justification::centredRight, 1);
  48001. g.drawFittedText (fileTimeDescription,
  48002. dateX, 0, width - 8 - dateX, height,
  48003. Justification::centredRight, 1);
  48004. }
  48005. }
  48006. else
  48007. {
  48008. g.drawFittedText (filename,
  48009. x, 0, width - x, height,
  48010. Justification::centredLeft, 1);
  48011. }
  48012. }
  48013. Button* LookAndFeel::createFileBrowserGoUpButton()
  48014. {
  48015. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  48016. Path arrowPath;
  48017. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  48018. DrawablePath arrowImage;
  48019. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  48020. arrowImage.setPath (arrowPath);
  48021. goUpButton->setImages (&arrowImage);
  48022. return goUpButton;
  48023. }
  48024. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  48025. DirectoryContentsDisplayComponent* fileListComponent,
  48026. FilePreviewComponent* previewComp,
  48027. ComboBox* currentPathBox,
  48028. TextEditor* filenameBox,
  48029. Button* goUpButton)
  48030. {
  48031. const int x = 8;
  48032. int w = browserComp.getWidth() - x - x;
  48033. if (previewComp != 0)
  48034. {
  48035. const int previewWidth = w / 3;
  48036. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  48037. w -= previewWidth + 4;
  48038. }
  48039. int y = 4;
  48040. const int controlsHeight = 22;
  48041. const int bottomSectionHeight = controlsHeight + 8;
  48042. const int upButtonWidth = 50;
  48043. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  48044. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  48045. y += controlsHeight + 4;
  48046. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  48047. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  48048. y = listAsComp->getBottom() + 4;
  48049. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  48050. }
  48051. Image* LookAndFeel::getDefaultFolderImage()
  48052. {
  48053. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  48054. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  48055. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  48056. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  48057. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  48058. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  48059. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  48060. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  48061. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  48062. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  48063. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  48064. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  48065. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  48066. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  48067. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  48068. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  48069. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  48070. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  48071. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  48072. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  48073. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  48074. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  48075. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  48076. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  48077. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  48078. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  48079. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  48080. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  48081. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  48082. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  48083. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  48084. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  48085. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  48086. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  48087. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  48088. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  48089. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  48090. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  48091. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  48092. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  48093. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  48094. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  48095. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  48096. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  48097. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  48098. }
  48099. Image* LookAndFeel::getDefaultDocumentFileImage()
  48100. {
  48101. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  48102. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  48103. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  48104. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  48105. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  48106. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  48107. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  48108. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  48109. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  48110. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  48111. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  48112. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  48113. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  48114. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  48115. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  48116. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  48117. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  48118. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  48119. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  48120. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  48121. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  48122. 174,66,96,130,0,0};
  48123. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  48124. }
  48125. void LookAndFeel::playAlertSound()
  48126. {
  48127. PlatformUtilities::beep();
  48128. }
  48129. static void createRoundedPath (Path& p,
  48130. const float x, const float y,
  48131. const float w, const float h,
  48132. const float cs,
  48133. const bool curveTopLeft, const bool curveTopRight,
  48134. const bool curveBottomLeft, const bool curveBottomRight) throw()
  48135. {
  48136. const float cs2 = 2.0f * cs;
  48137. if (curveTopLeft)
  48138. {
  48139. p.startNewSubPath (x, y + cs);
  48140. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48141. }
  48142. else
  48143. {
  48144. p.startNewSubPath (x, y);
  48145. }
  48146. if (curveTopRight)
  48147. {
  48148. p.lineTo (x + w - cs, y);
  48149. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  48150. }
  48151. else
  48152. {
  48153. p.lineTo (x + w, y);
  48154. }
  48155. if (curveBottomRight)
  48156. {
  48157. p.lineTo (x + w, y + h - cs);
  48158. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48159. }
  48160. else
  48161. {
  48162. p.lineTo (x + w, y + h);
  48163. }
  48164. if (curveBottomLeft)
  48165. {
  48166. p.lineTo (x + cs, y + h);
  48167. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48168. }
  48169. else
  48170. {
  48171. p.lineTo (x, y + h);
  48172. }
  48173. p.closeSubPath();
  48174. }
  48175. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  48176. float x, float y, float w, float h,
  48177. float maxCornerSize,
  48178. const Colour& baseColour,
  48179. const float strokeWidth,
  48180. const bool flatOnLeft,
  48181. const bool flatOnRight,
  48182. const bool flatOnTop,
  48183. const bool flatOnBottom) throw()
  48184. {
  48185. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  48186. return;
  48187. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  48188. Path outline;
  48189. createRoundedPath (outline, x, y, w, h, cs,
  48190. ! (flatOnLeft || flatOnTop),
  48191. ! (flatOnRight || flatOnTop),
  48192. ! (flatOnLeft || flatOnBottom),
  48193. ! (flatOnRight || flatOnBottom));
  48194. ColourGradient cg (baseColour, 0.0f, y,
  48195. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  48196. false);
  48197. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  48198. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  48199. GradientBrush gb (cg);
  48200. g.setBrush (&gb);
  48201. g.fillPath (outline);
  48202. g.setColour (Colour (0x80000000));
  48203. g.strokePath (outline, PathStrokeType (strokeWidth));
  48204. }
  48205. void LookAndFeel::drawGlassSphere (Graphics& g,
  48206. const float x, const float y,
  48207. const float diameter,
  48208. const Colour& colour,
  48209. const float outlineThickness) throw()
  48210. {
  48211. if (diameter <= outlineThickness)
  48212. return;
  48213. Path p;
  48214. p.addEllipse (x, y, diameter, diameter);
  48215. {
  48216. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48217. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48218. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48219. GradientBrush gb (cg);
  48220. g.setBrush (&gb);
  48221. g.fillPath (p);
  48222. }
  48223. {
  48224. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  48225. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  48226. g.setBrush (&gb);
  48227. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  48228. }
  48229. {
  48230. ColourGradient cg (Colours::transparentBlack,
  48231. x + diameter * 0.5f, y + diameter * 0.5f,
  48232. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48233. x, y + diameter * 0.5f, true);
  48234. cg.addColour (0.7, Colours::transparentBlack);
  48235. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  48236. GradientBrush gb (cg);
  48237. g.setBrush (&gb);
  48238. g.fillPath (p);
  48239. }
  48240. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48241. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  48242. }
  48243. void LookAndFeel::drawGlassPointer (Graphics& g,
  48244. const float x, const float y,
  48245. const float diameter,
  48246. const Colour& colour, const float outlineThickness,
  48247. const int direction) throw()
  48248. {
  48249. if (diameter <= outlineThickness)
  48250. return;
  48251. Path p;
  48252. p.startNewSubPath (x + diameter * 0.5f, y);
  48253. p.lineTo (x + diameter, y + diameter * 0.6f);
  48254. p.lineTo (x + diameter, y + diameter);
  48255. p.lineTo (x, y + diameter);
  48256. p.lineTo (x, y + diameter * 0.6f);
  48257. p.closeSubPath();
  48258. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  48259. {
  48260. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48261. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48262. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48263. GradientBrush gb (cg);
  48264. g.setBrush (&gb);
  48265. g.fillPath (p);
  48266. }
  48267. {
  48268. ColourGradient cg (Colours::transparentBlack,
  48269. x + diameter * 0.5f, y + diameter * 0.5f,
  48270. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48271. x - diameter * 0.2f, y + diameter * 0.5f, true);
  48272. cg.addColour (0.5, Colours::transparentBlack);
  48273. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  48274. GradientBrush gb (cg);
  48275. g.setBrush (&gb);
  48276. g.fillPath (p);
  48277. }
  48278. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48279. g.strokePath (p, PathStrokeType (outlineThickness));
  48280. }
  48281. void LookAndFeel::drawGlassLozenge (Graphics& g,
  48282. const float x, const float y,
  48283. const float width, const float height,
  48284. const Colour& colour,
  48285. const float outlineThickness,
  48286. const float cornerSize,
  48287. const bool flatOnLeft,
  48288. const bool flatOnRight,
  48289. const bool flatOnTop,
  48290. const bool flatOnBottom) throw()
  48291. {
  48292. if (width <= outlineThickness || height <= outlineThickness)
  48293. return;
  48294. const int intX = (int) x;
  48295. const int intY = (int) y;
  48296. const int intW = (int) width;
  48297. const int intH = (int) height;
  48298. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  48299. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  48300. const int intEdge = (int) edgeBlurRadius;
  48301. Path outline;
  48302. createRoundedPath (outline, x, y, width, height, cs,
  48303. ! (flatOnLeft || flatOnTop),
  48304. ! (flatOnRight || flatOnTop),
  48305. ! (flatOnLeft || flatOnBottom),
  48306. ! (flatOnRight || flatOnBottom));
  48307. {
  48308. ColourGradient cg (colour.darker (0.2f), 0, y,
  48309. colour.darker (0.2f), 0, y + height, false);
  48310. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  48311. cg.addColour (0.4, colour);
  48312. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  48313. GradientBrush gb (cg);
  48314. g.setBrush (&gb);
  48315. g.fillPath (outline);
  48316. }
  48317. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  48318. colour.darker (0.2f), x, y + height * 0.5f, true);
  48319. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  48320. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  48321. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  48322. {
  48323. GradientBrush gb (cg);
  48324. g.saveState();
  48325. g.setBrush (&gb);
  48326. g.reduceClipRegion (intX, intY, intEdge, intH);
  48327. g.fillPath (outline);
  48328. g.restoreState();
  48329. }
  48330. if (! (flatOnRight || flatOnTop || flatOnBottom))
  48331. {
  48332. cg.x1 = x + width - edgeBlurRadius;
  48333. cg.x2 = x + width;
  48334. GradientBrush gb (cg);
  48335. g.saveState();
  48336. g.setBrush (&gb);
  48337. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  48338. g.fillPath (outline);
  48339. g.restoreState();
  48340. }
  48341. {
  48342. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  48343. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  48344. Path highlight;
  48345. createRoundedPath (highlight,
  48346. x + leftIndent,
  48347. y + cs * 0.1f,
  48348. width - (leftIndent + rightIndent),
  48349. height * 0.4f, cs * 0.4f,
  48350. ! (flatOnLeft || flatOnTop),
  48351. ! (flatOnRight || flatOnTop),
  48352. ! (flatOnLeft || flatOnBottom),
  48353. ! (flatOnRight || flatOnBottom));
  48354. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  48355. Colours::transparentWhite, 0, y + height * 0.4f, false);
  48356. g.setBrush (&gb);
  48357. g.fillPath (highlight);
  48358. }
  48359. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  48360. g.strokePath (outline, PathStrokeType (outlineThickness));
  48361. }
  48362. END_JUCE_NAMESPACE
  48363. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  48364. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48365. BEGIN_JUCE_NAMESPACE
  48366. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  48367. {
  48368. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  48369. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  48370. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  48371. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  48372. setColour (Slider::thumbColourId, Colours::white);
  48373. setColour (Slider::trackColourId, Colour (0x7f000000));
  48374. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  48375. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  48376. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  48377. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  48378. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  48379. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  48380. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  48381. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  48382. }
  48383. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  48384. {
  48385. }
  48386. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  48387. Button& button,
  48388. const Colour& backgroundColour,
  48389. bool isMouseOverButton,
  48390. bool isButtonDown)
  48391. {
  48392. const int width = button.getWidth();
  48393. const int height = button.getHeight();
  48394. const float indent = 2.0f;
  48395. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  48396. roundFloatToInt (height * 0.4f));
  48397. Path p;
  48398. p.addRoundedRectangle (indent, indent,
  48399. width - indent * 2.0f,
  48400. height - indent * 2.0f,
  48401. (float) cornerSize);
  48402. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  48403. if (isMouseOverButton)
  48404. {
  48405. if (isButtonDown)
  48406. bc = bc.brighter();
  48407. else if (bc.getBrightness() > 0.5f)
  48408. bc = bc.darker (0.1f);
  48409. else
  48410. bc = bc.brighter (0.1f);
  48411. }
  48412. g.setColour (bc);
  48413. g.fillPath (p);
  48414. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  48415. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  48416. }
  48417. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  48418. Component& /*component*/,
  48419. int x, int y, int w, int h,
  48420. const bool ticked,
  48421. const bool isEnabled,
  48422. const bool /*isMouseOverButton*/,
  48423. const bool isButtonDown)
  48424. {
  48425. Path box;
  48426. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  48427. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  48428. : Colours::lightgrey.withAlpha (0.1f));
  48429. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48430. .translated ((float) x, (float) y));
  48431. g.fillPath (box, trans);
  48432. g.setColour (Colours::black.withAlpha (0.6f));
  48433. g.strokePath (box, PathStrokeType (0.9f), trans);
  48434. if (ticked)
  48435. {
  48436. Path tick;
  48437. tick.startNewSubPath (1.5f, 3.0f);
  48438. tick.lineTo (3.0f, 6.0f);
  48439. tick.lineTo (6.0f, 0.0f);
  48440. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48441. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48442. }
  48443. }
  48444. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  48445. ToggleButton& button,
  48446. bool isMouseOverButton,
  48447. bool isButtonDown)
  48448. {
  48449. if (button.hasKeyboardFocus (true))
  48450. {
  48451. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48452. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48453. }
  48454. const int tickWidth = jmin (20, button.getHeight() - 4);
  48455. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48456. tickWidth, tickWidth,
  48457. button.getToggleState(),
  48458. button.isEnabled(),
  48459. isMouseOverButton,
  48460. isButtonDown);
  48461. g.setColour (button.findColour (ToggleButton::textColourId));
  48462. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48463. if (! button.isEnabled())
  48464. g.setOpacity (0.5f);
  48465. const int textX = tickWidth + 5;
  48466. g.drawFittedText (button.getButtonText(),
  48467. textX, 4,
  48468. button.getWidth() - textX - 2, button.getHeight() - 8,
  48469. Justification::centredLeft, 10);
  48470. }
  48471. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48472. int width, int height,
  48473. double progress, const String& textToShow)
  48474. {
  48475. if (progress < 0 || progress >= 1.0)
  48476. {
  48477. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  48478. }
  48479. else
  48480. {
  48481. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48482. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48483. g.fillAll (background);
  48484. g.setColour (foreground);
  48485. g.fillRect (1, 1,
  48486. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  48487. height - 2);
  48488. if (textToShow.isNotEmpty())
  48489. {
  48490. g.setColour (Colour::contrasting (background, foreground));
  48491. g.setFont (height * 0.6f);
  48492. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48493. }
  48494. }
  48495. }
  48496. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  48497. ScrollBar& bar,
  48498. int width, int height,
  48499. int buttonDirection,
  48500. bool isScrollbarVertical,
  48501. bool isMouseOverButton,
  48502. bool isButtonDown)
  48503. {
  48504. if (isScrollbarVertical)
  48505. width -= 2;
  48506. else
  48507. height -= 2;
  48508. Path p;
  48509. if (buttonDirection == 0)
  48510. p.addTriangle (width * 0.5f, height * 0.2f,
  48511. width * 0.1f, height * 0.7f,
  48512. width * 0.9f, height * 0.7f);
  48513. else if (buttonDirection == 1)
  48514. p.addTriangle (width * 0.8f, height * 0.5f,
  48515. width * 0.3f, height * 0.1f,
  48516. width * 0.3f, height * 0.9f);
  48517. else if (buttonDirection == 2)
  48518. p.addTriangle (width * 0.5f, height * 0.8f,
  48519. width * 0.1f, height * 0.3f,
  48520. width * 0.9f, height * 0.3f);
  48521. else if (buttonDirection == 3)
  48522. p.addTriangle (width * 0.2f, height * 0.5f,
  48523. width * 0.7f, height * 0.1f,
  48524. width * 0.7f, height * 0.9f);
  48525. if (isButtonDown)
  48526. g.setColour (Colours::white);
  48527. else if (isMouseOverButton)
  48528. g.setColour (Colours::white.withAlpha (0.7f));
  48529. else
  48530. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  48531. g.fillPath (p);
  48532. g.setColour (Colours::black.withAlpha (0.5f));
  48533. g.strokePath (p, PathStrokeType (0.5f));
  48534. }
  48535. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  48536. ScrollBar& bar,
  48537. int x, int y,
  48538. int width, int height,
  48539. bool isScrollbarVertical,
  48540. int thumbStartPosition,
  48541. int thumbSize,
  48542. bool isMouseOver,
  48543. bool isMouseDown)
  48544. {
  48545. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  48546. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48547. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  48548. if (thumbSize > 0.0f)
  48549. {
  48550. Rectangle thumb;
  48551. if (isScrollbarVertical)
  48552. {
  48553. width -= 2;
  48554. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  48555. roundFloatToInt (width * 0.3f), height);
  48556. thumb.setBounds (x + 1, thumbStartPosition,
  48557. width - 2, thumbSize);
  48558. }
  48559. else
  48560. {
  48561. height -= 2;
  48562. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  48563. width, roundFloatToInt (height * 0.3f));
  48564. thumb.setBounds (thumbStartPosition, y + 1,
  48565. thumbSize, height - 2);
  48566. }
  48567. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48568. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  48569. g.fillRect (thumb);
  48570. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  48571. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  48572. if (thumbSize > 16)
  48573. {
  48574. for (int i = 3; --i >= 0;)
  48575. {
  48576. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  48577. g.setColour (Colours::black.withAlpha (0.15f));
  48578. if (isScrollbarVertical)
  48579. {
  48580. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  48581. g.setColour (Colours::white.withAlpha (0.15f));
  48582. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  48583. }
  48584. else
  48585. {
  48586. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  48587. g.setColour (Colours::white.withAlpha (0.15f));
  48588. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  48589. }
  48590. }
  48591. }
  48592. }
  48593. }
  48594. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  48595. {
  48596. return &scrollbarShadow;
  48597. }
  48598. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48599. {
  48600. g.fillAll (findColour (PopupMenu::backgroundColourId));
  48601. g.setColour (Colours::black.withAlpha (0.6f));
  48602. g.drawRect (0, 0, width, height);
  48603. }
  48604. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  48605. bool, MenuBarComponent& menuBar)
  48606. {
  48607. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  48608. }
  48609. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48610. {
  48611. if (textEditor.isEnabled())
  48612. {
  48613. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48614. g.drawRect (0, 0, width, height);
  48615. }
  48616. }
  48617. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48618. const bool isButtonDown,
  48619. int buttonX, int buttonY,
  48620. int buttonW, int buttonH,
  48621. ComboBox& box)
  48622. {
  48623. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48624. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  48625. : ComboBox::backgroundColourId));
  48626. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  48627. g.setColour (box.findColour (ComboBox::outlineColourId));
  48628. g.drawRect (0, 0, width, height);
  48629. const float arrowX = 0.2f;
  48630. const float arrowH = 0.3f;
  48631. if (box.isEnabled())
  48632. {
  48633. Path p;
  48634. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48635. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48636. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48637. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48638. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48639. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48640. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  48641. : ComboBox::buttonColourId));
  48642. g.fillPath (p);
  48643. }
  48644. }
  48645. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  48646. {
  48647. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  48648. f.setHorizontalScale (0.9f);
  48649. return f;
  48650. }
  48651. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  48652. {
  48653. Path p;
  48654. p.addTriangle (x1, y1, x2, y2, x3, y3);
  48655. g.setColour (fill);
  48656. g.fillPath (p);
  48657. g.setColour (outline);
  48658. g.strokePath (p, PathStrokeType (0.3f));
  48659. }
  48660. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  48661. int x, int y,
  48662. int w, int h,
  48663. float sliderPos,
  48664. float minSliderPos,
  48665. float maxSliderPos,
  48666. const Slider::SliderStyle style,
  48667. Slider& slider)
  48668. {
  48669. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48670. if (style == Slider::LinearBar)
  48671. {
  48672. g.setColour (slider.findColour (Slider::thumbColourId));
  48673. g.fillRect (x, y, (int) sliderPos - x, h);
  48674. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  48675. g.drawRect (x, y, (int) sliderPos - x, h);
  48676. }
  48677. else
  48678. {
  48679. g.setColour (slider.findColour (Slider::trackColourId)
  48680. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  48681. if (slider.isHorizontal())
  48682. {
  48683. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  48684. w, roundFloatToInt (h * 0.2f));
  48685. }
  48686. else
  48687. {
  48688. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  48689. jmin (4, roundFloatToInt (w * 0.2f)), h);
  48690. }
  48691. float alpha = 0.35f;
  48692. if (slider.isEnabled())
  48693. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  48694. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  48695. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  48696. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48697. {
  48698. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  48699. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  48700. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  48701. fill, outline);
  48702. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  48703. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  48704. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  48705. fill, outline);
  48706. }
  48707. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48708. {
  48709. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48710. minSliderPos - 7.0f, y + h * 0.9f ,
  48711. minSliderPos, y + h * 0.9f,
  48712. fill, outline);
  48713. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48714. maxSliderPos, y + h * 0.9f,
  48715. maxSliderPos + 7.0f, y + h * 0.9f,
  48716. fill, outline);
  48717. }
  48718. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  48719. {
  48720. drawTriangle (g, sliderPos, y + h * 0.9f,
  48721. sliderPos - 7.0f, y + h * 0.2f,
  48722. sliderPos + 7.0f, y + h * 0.2f,
  48723. fill, outline);
  48724. }
  48725. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  48726. {
  48727. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  48728. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  48729. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  48730. fill, outline);
  48731. }
  48732. }
  48733. }
  48734. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  48735. {
  48736. if (isIncrement)
  48737. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  48738. else
  48739. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  48740. }
  48741. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  48742. {
  48743. return &scrollbarShadow;
  48744. }
  48745. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  48746. {
  48747. return 8;
  48748. }
  48749. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  48750. int w, int h,
  48751. bool isMouseOver,
  48752. bool isMouseDragging)
  48753. {
  48754. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  48755. : Colours::darkgrey);
  48756. const float lineThickness = jmin (w, h) * 0.1f;
  48757. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  48758. {
  48759. g.drawLine (w * i,
  48760. h + 1.0f,
  48761. w + 1.0f,
  48762. h * i,
  48763. lineThickness);
  48764. }
  48765. }
  48766. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  48767. {
  48768. Path shape;
  48769. if (buttonType == DocumentWindow::closeButton)
  48770. {
  48771. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  48772. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  48773. ShapeButton* const b = new ShapeButton ("close",
  48774. Colour (0x7fff3333),
  48775. Colour (0xd7ff3333),
  48776. Colour (0xf7ff3333));
  48777. b->setShape (shape, true, true, true);
  48778. return b;
  48779. }
  48780. else if (buttonType == DocumentWindow::minimiseButton)
  48781. {
  48782. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  48783. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  48784. DrawablePath dp;
  48785. dp.setPath (shape);
  48786. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  48787. b->setImages (&dp);
  48788. return b;
  48789. }
  48790. else if (buttonType == DocumentWindow::maximiseButton)
  48791. {
  48792. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  48793. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  48794. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  48795. DrawablePath dp;
  48796. dp.setPath (shape);
  48797. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  48798. b->setImages (&dp);
  48799. return b;
  48800. }
  48801. jassertfalse
  48802. return 0;
  48803. }
  48804. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  48805. int titleBarX,
  48806. int titleBarY,
  48807. int titleBarW,
  48808. int titleBarH,
  48809. Button* minimiseButton,
  48810. Button* maximiseButton,
  48811. Button* closeButton,
  48812. bool positionTitleBarButtonsOnLeft)
  48813. {
  48814. titleBarY += titleBarH / 8;
  48815. titleBarH -= titleBarH / 4;
  48816. const int buttonW = titleBarH;
  48817. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  48818. : titleBarX + titleBarW - buttonW - 4;
  48819. if (closeButton != 0)
  48820. {
  48821. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  48822. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  48823. : -(buttonW + buttonW / 5);
  48824. }
  48825. if (positionTitleBarButtonsOnLeft)
  48826. swapVariables (minimiseButton, maximiseButton);
  48827. if (maximiseButton != 0)
  48828. {
  48829. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  48830. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  48831. }
  48832. if (minimiseButton != 0)
  48833. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  48834. }
  48835. END_JUCE_NAMESPACE
  48836. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48837. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  48838. BEGIN_JUCE_NAMESPACE
  48839. class DummyMenuComponent : public Component
  48840. {
  48841. DummyMenuComponent (const DummyMenuComponent&);
  48842. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  48843. public:
  48844. DummyMenuComponent() {}
  48845. ~DummyMenuComponent() {}
  48846. void inputAttemptWhenModal()
  48847. {
  48848. exitModalState (0);
  48849. }
  48850. };
  48851. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  48852. : model (0),
  48853. itemUnderMouse (-1),
  48854. currentPopupIndex (-1),
  48855. indexToShowAgain (-1),
  48856. lastMouseX (0),
  48857. lastMouseY (0),
  48858. inModalState (false),
  48859. currentPopup (0)
  48860. {
  48861. setRepaintsOnMouseActivity (true);
  48862. setWantsKeyboardFocus (false);
  48863. setMouseClickGrabsKeyboardFocus (false);
  48864. setModel (model_);
  48865. }
  48866. MenuBarComponent::~MenuBarComponent()
  48867. {
  48868. setModel (0);
  48869. Desktop::getInstance().removeGlobalMouseListener (this);
  48870. deleteAndZero (currentPopup);
  48871. }
  48872. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  48873. {
  48874. if (model != newModel)
  48875. {
  48876. if (model != 0)
  48877. model->removeListener (this);
  48878. model = newModel;
  48879. if (model != 0)
  48880. model->addListener (this);
  48881. repaint();
  48882. menuBarItemsChanged (0);
  48883. }
  48884. }
  48885. void MenuBarComponent::paint (Graphics& g)
  48886. {
  48887. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  48888. getLookAndFeel().drawMenuBarBackground (g,
  48889. getWidth(),
  48890. getHeight(),
  48891. isMouseOverBar,
  48892. *this);
  48893. if (model != 0)
  48894. {
  48895. for (int i = 0; i < menuNames.size(); ++i)
  48896. {
  48897. g.saveState();
  48898. g.setOrigin (xPositions [i], 0);
  48899. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  48900. getLookAndFeel().drawMenuBarItem (g,
  48901. xPositions[i + 1] - xPositions[i],
  48902. getHeight(),
  48903. i,
  48904. menuNames[i],
  48905. i == itemUnderMouse,
  48906. i == currentPopupIndex,
  48907. isMouseOverBar,
  48908. *this);
  48909. g.restoreState();
  48910. }
  48911. }
  48912. }
  48913. void MenuBarComponent::resized()
  48914. {
  48915. xPositions.clear();
  48916. int x = 2;
  48917. xPositions.add (x);
  48918. for (int i = 0; i < menuNames.size(); ++i)
  48919. {
  48920. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  48921. xPositions.add (x);
  48922. }
  48923. }
  48924. int MenuBarComponent::getItemAt (const int x, const int y)
  48925. {
  48926. for (int i = 0; i < xPositions.size(); ++i)
  48927. if (x >= xPositions[i] && x < xPositions[i + 1])
  48928. return reallyContains (x, y, true) ? i : -1;
  48929. return -1;
  48930. }
  48931. void MenuBarComponent::repaintMenuItem (int index)
  48932. {
  48933. if (((unsigned int) index) < (unsigned int) xPositions.size())
  48934. {
  48935. const int x1 = xPositions [index];
  48936. const int x2 = xPositions [index + 1];
  48937. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  48938. }
  48939. }
  48940. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  48941. {
  48942. const int newItem = getItemAt (x, y);
  48943. if (itemUnderMouse != newItem)
  48944. {
  48945. repaintMenuItem (itemUnderMouse);
  48946. itemUnderMouse = newItem;
  48947. repaintMenuItem (itemUnderMouse);
  48948. }
  48949. }
  48950. void MenuBarComponent::hideCurrentMenu()
  48951. {
  48952. deleteAndZero (currentPopup);
  48953. repaint();
  48954. }
  48955. void MenuBarComponent::showMenu (int index)
  48956. {
  48957. if (index != currentPopupIndex)
  48958. {
  48959. if (inModalState)
  48960. {
  48961. hideCurrentMenu();
  48962. indexToShowAgain = index;
  48963. return;
  48964. }
  48965. indexToShowAgain = -1;
  48966. currentPopupIndex = -1;
  48967. deleteAndZero (currentPopup);
  48968. menuBarItemsChanged (0);
  48969. Component* const prevFocused = getCurrentlyFocusedComponent();
  48970. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  48971. if (prevFocused != 0)
  48972. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  48973. ComponentDeletionWatcher deletionChecker (this);
  48974. enterModalState (false);
  48975. inModalState = true;
  48976. int result = 0;
  48977. ApplicationCommandManager* managerOfChosenCommand = 0;
  48978. Desktop::getInstance().addGlobalMouseListener (this);
  48979. for (;;)
  48980. {
  48981. const int x = getScreenX() + xPositions [itemUnderMouse];
  48982. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  48983. currentPopupIndex = itemUnderMouse;
  48984. indexToShowAgain = -1;
  48985. repaint();
  48986. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  48987. {
  48988. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  48989. menuNames [itemUnderMouse]));
  48990. currentPopup = m.createMenuComponent (x, getScreenY(),
  48991. w, getHeight(),
  48992. 0, w, 0, 0,
  48993. true, this,
  48994. &managerOfChosenCommand,
  48995. this);
  48996. }
  48997. if (currentPopup == 0)
  48998. {
  48999. currentPopup = new DummyMenuComponent();
  49000. addAndMakeVisible (currentPopup);
  49001. }
  49002. currentPopup->enterModalState (false);
  49003. currentPopup->toFront (false); // need to do this after making it modal, or it could
  49004. // be stuck behind other comps that are already modal..
  49005. result = currentPopup->runModalLoop();
  49006. if (deletionChecker.hasBeenDeleted())
  49007. {
  49008. delete prevCompDeletionChecker;
  49009. return;
  49010. }
  49011. const int lastPopupIndex = currentPopupIndex;
  49012. deleteAndZero (currentPopup);
  49013. currentPopupIndex = -1;
  49014. if (result != 0)
  49015. {
  49016. topLevelIndexClicked = lastPopupIndex;
  49017. break;
  49018. }
  49019. else if (indexToShowAgain >= 0)
  49020. {
  49021. menuBarItemsChanged (0);
  49022. repaint();
  49023. itemUnderMouse = indexToShowAgain;
  49024. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  49025. break;
  49026. }
  49027. else
  49028. {
  49029. break;
  49030. }
  49031. }
  49032. Desktop::getInstance().removeGlobalMouseListener (this);
  49033. inModalState = false;
  49034. exitModalState (0);
  49035. if (prevCompDeletionChecker != 0)
  49036. {
  49037. if (! prevCompDeletionChecker->hasBeenDeleted())
  49038. prevFocused->grabKeyboardFocus();
  49039. delete prevCompDeletionChecker;
  49040. }
  49041. int mx, my;
  49042. getMouseXYRelative (mx, my);
  49043. updateItemUnderMouse (mx, my);
  49044. repaint();
  49045. if (result != 0)
  49046. {
  49047. if (managerOfChosenCommand != 0)
  49048. {
  49049. ApplicationCommandTarget::InvocationInfo info (result);
  49050. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  49051. managerOfChosenCommand->invoke (info, true);
  49052. }
  49053. postCommandMessage (result);
  49054. }
  49055. }
  49056. }
  49057. void MenuBarComponent::handleCommandMessage (int commandId)
  49058. {
  49059. if (model != 0)
  49060. model->menuItemSelected (commandId, topLevelIndexClicked);
  49061. }
  49062. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  49063. {
  49064. if (e.eventComponent == this)
  49065. updateItemUnderMouse (e.x, e.y);
  49066. }
  49067. void MenuBarComponent::mouseExit (const MouseEvent& e)
  49068. {
  49069. if (e.eventComponent == this)
  49070. updateItemUnderMouse (e.x, e.y);
  49071. }
  49072. void MenuBarComponent::mouseDown (const MouseEvent& e)
  49073. {
  49074. const MouseEvent e2 (e.getEventRelativeTo (this));
  49075. if (currentPopupIndex < 0)
  49076. {
  49077. updateItemUnderMouse (e2.x, e2.y);
  49078. currentPopupIndex = -2;
  49079. showMenu (itemUnderMouse);
  49080. }
  49081. }
  49082. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  49083. {
  49084. const MouseEvent e2 (e.getEventRelativeTo (this));
  49085. const int item = getItemAt (e2.x, e2.y);
  49086. if (item >= 0)
  49087. showMenu (item);
  49088. }
  49089. void MenuBarComponent::mouseUp (const MouseEvent& e)
  49090. {
  49091. const MouseEvent e2 (e.getEventRelativeTo (this));
  49092. updateItemUnderMouse (e2.x, e2.y);
  49093. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  49094. hideCurrentMenu();
  49095. }
  49096. void MenuBarComponent::mouseMove (const MouseEvent& e)
  49097. {
  49098. const MouseEvent e2 (e.getEventRelativeTo (this));
  49099. if (lastMouseX != e2.x || lastMouseY != e2.y)
  49100. {
  49101. if (currentPopupIndex >= 0)
  49102. {
  49103. const int item = getItemAt (e2.x, e2.y);
  49104. if (item >= 0)
  49105. showMenu (item);
  49106. }
  49107. else
  49108. {
  49109. updateItemUnderMouse (e2.x, e2.y);
  49110. }
  49111. lastMouseX = e2.x;
  49112. lastMouseY = e2.y;
  49113. }
  49114. }
  49115. bool MenuBarComponent::keyPressed (const KeyPress& key)
  49116. {
  49117. bool used = false;
  49118. const int numMenus = menuNames.size();
  49119. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  49120. if (key.isKeyCode (KeyPress::leftKey))
  49121. {
  49122. showMenu ((currentIndex + numMenus - 1) % numMenus);
  49123. used = true;
  49124. }
  49125. else if (key.isKeyCode (KeyPress::rightKey))
  49126. {
  49127. showMenu ((currentIndex + 1) % numMenus);
  49128. used = true;
  49129. }
  49130. return used;
  49131. }
  49132. void MenuBarComponent::inputAttemptWhenModal()
  49133. {
  49134. hideCurrentMenu();
  49135. }
  49136. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  49137. {
  49138. StringArray newNames;
  49139. if (model != 0)
  49140. newNames = model->getMenuBarNames();
  49141. if (newNames != menuNames)
  49142. {
  49143. menuNames = newNames;
  49144. repaint();
  49145. resized();
  49146. }
  49147. }
  49148. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  49149. const ApplicationCommandTarget::InvocationInfo& info)
  49150. {
  49151. if (model == 0
  49152. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  49153. return;
  49154. for (int i = 0; i < menuNames.size(); ++i)
  49155. {
  49156. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  49157. if (menu.containsCommandItem (info.commandID))
  49158. {
  49159. itemUnderMouse = i;
  49160. repaintMenuItem (i);
  49161. startTimer (200);
  49162. break;
  49163. }
  49164. }
  49165. }
  49166. void MenuBarComponent::timerCallback()
  49167. {
  49168. stopTimer();
  49169. int mx, my;
  49170. getMouseXYRelative (mx, my);
  49171. updateItemUnderMouse (mx, my);
  49172. }
  49173. END_JUCE_NAMESPACE
  49174. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  49175. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  49176. BEGIN_JUCE_NAMESPACE
  49177. MenuBarModel::MenuBarModel() throw()
  49178. : manager (0)
  49179. {
  49180. }
  49181. MenuBarModel::~MenuBarModel()
  49182. {
  49183. setApplicationCommandManagerToWatch (0);
  49184. }
  49185. void MenuBarModel::menuItemsChanged()
  49186. {
  49187. triggerAsyncUpdate();
  49188. }
  49189. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  49190. {
  49191. if (manager != newManager)
  49192. {
  49193. if (manager != 0)
  49194. manager->removeListener (this);
  49195. manager = newManager;
  49196. if (manager != 0)
  49197. manager->addListener (this);
  49198. }
  49199. }
  49200. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  49201. {
  49202. jassert (newListener != 0);
  49203. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  49204. if (newListener != 0)
  49205. listeners.add (newListener);
  49206. }
  49207. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  49208. {
  49209. // Trying to remove a listener that isn't on the list!
  49210. // If this assertion happens because this object is a dangling pointer, make sure you've not
  49211. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  49212. jassert (listeners.contains (listenerToRemove));
  49213. listeners.removeValue (listenerToRemove);
  49214. }
  49215. void MenuBarModel::handleAsyncUpdate()
  49216. {
  49217. for (int i = listeners.size(); --i >= 0;)
  49218. {
  49219. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  49220. i = jmin (i, listeners.size());
  49221. }
  49222. }
  49223. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  49224. {
  49225. for (int i = listeners.size(); --i >= 0;)
  49226. {
  49227. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  49228. i = jmin (i, listeners.size());
  49229. }
  49230. }
  49231. void MenuBarModel::applicationCommandListChanged()
  49232. {
  49233. menuItemsChanged();
  49234. }
  49235. END_JUCE_NAMESPACE
  49236. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  49237. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  49238. BEGIN_JUCE_NAMESPACE
  49239. static VoidArray activeMenuWindows;
  49240. class MenuItemInfo
  49241. {
  49242. public:
  49243. const int itemId;
  49244. String text;
  49245. const Colour textColour;
  49246. const bool active, isSeparator, isTicked, usesColour;
  49247. Image* image;
  49248. PopupMenuCustomComponent* const customComp;
  49249. PopupMenu* subMenu;
  49250. ApplicationCommandManager* const commandManager;
  49251. MenuItemInfo() throw()
  49252. : itemId (0),
  49253. active (true),
  49254. isSeparator (true),
  49255. isTicked (false),
  49256. usesColour (false),
  49257. image (0),
  49258. customComp (0),
  49259. subMenu (0),
  49260. commandManager (0)
  49261. {
  49262. }
  49263. MenuItemInfo (const int itemId_,
  49264. const String& text_,
  49265. const bool active_,
  49266. const bool isTicked_,
  49267. const Image* im,
  49268. const Colour& textColour_,
  49269. const bool usesColour_,
  49270. PopupMenuCustomComponent* const customComp_,
  49271. const PopupMenu* const subMenu_,
  49272. ApplicationCommandManager* const commandManager_) throw()
  49273. : itemId (itemId_),
  49274. text (text_),
  49275. textColour (textColour_),
  49276. active (active_),
  49277. isSeparator (false),
  49278. isTicked (isTicked_),
  49279. usesColour (usesColour_),
  49280. image (0),
  49281. customComp (customComp_),
  49282. commandManager (commandManager_)
  49283. {
  49284. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  49285. if (customComp != 0)
  49286. customComp->refCount_++;
  49287. if (im != 0)
  49288. image = im->createCopy();
  49289. if (commandManager_ != 0 && itemId_ != 0)
  49290. {
  49291. String shortcutKey;
  49292. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  49293. ->getKeyPressesAssignedToCommand (itemId_));
  49294. for (int i = 0; i < keyPresses.size(); ++i)
  49295. {
  49296. const String key (keyPresses.getReference(i).getTextDescription());
  49297. if (shortcutKey.isNotEmpty())
  49298. shortcutKey << ", ";
  49299. if (key.length() == 1)
  49300. shortcutKey << "shortcut: '" << key << '\'';
  49301. else
  49302. shortcutKey << key;
  49303. }
  49304. shortcutKey = shortcutKey.trim();
  49305. if (shortcutKey.isNotEmpty())
  49306. text << "<end>" << shortcutKey;
  49307. }
  49308. }
  49309. MenuItemInfo (const MenuItemInfo& other) throw()
  49310. : itemId (other.itemId),
  49311. text (other.text),
  49312. textColour (other.textColour),
  49313. active (other.active),
  49314. isSeparator (other.isSeparator),
  49315. isTicked (other.isTicked),
  49316. usesColour (other.usesColour),
  49317. customComp (other.customComp),
  49318. commandManager (other.commandManager)
  49319. {
  49320. if (other.subMenu != 0)
  49321. subMenu = new PopupMenu (*(other.subMenu));
  49322. else
  49323. subMenu = 0;
  49324. if (other.image != 0)
  49325. image = other.image->createCopy();
  49326. else
  49327. image = 0;
  49328. if (customComp != 0)
  49329. customComp->refCount_++;
  49330. }
  49331. ~MenuItemInfo() throw()
  49332. {
  49333. delete subMenu;
  49334. delete image;
  49335. if (customComp != 0 && --(customComp->refCount_) == 0)
  49336. delete customComp;
  49337. }
  49338. bool canBeTriggered() const throw()
  49339. {
  49340. return active && ! (isSeparator || (subMenu != 0));
  49341. }
  49342. bool hasActiveSubMenu() const throw()
  49343. {
  49344. return active && (subMenu != 0);
  49345. }
  49346. juce_UseDebuggingNewOperator
  49347. private:
  49348. const MenuItemInfo& operator= (const MenuItemInfo&);
  49349. };
  49350. class MenuItemComponent : public Component
  49351. {
  49352. bool isHighlighted;
  49353. public:
  49354. MenuItemInfo itemInfo;
  49355. MenuItemComponent (const MenuItemInfo& itemInfo_)
  49356. : isHighlighted (false),
  49357. itemInfo (itemInfo_)
  49358. {
  49359. if (itemInfo.customComp != 0)
  49360. addAndMakeVisible (itemInfo.customComp);
  49361. }
  49362. ~MenuItemComponent()
  49363. {
  49364. if (itemInfo.customComp != 0)
  49365. removeChildComponent (itemInfo.customComp);
  49366. }
  49367. void getIdealSize (int& idealWidth,
  49368. int& idealHeight,
  49369. const int standardItemHeight)
  49370. {
  49371. if (itemInfo.customComp != 0)
  49372. {
  49373. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  49374. }
  49375. else
  49376. {
  49377. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  49378. itemInfo.isSeparator,
  49379. standardItemHeight,
  49380. idealWidth,
  49381. idealHeight);
  49382. }
  49383. }
  49384. void paint (Graphics& g)
  49385. {
  49386. if (itemInfo.customComp == 0)
  49387. {
  49388. String mainText (itemInfo.text);
  49389. String endText;
  49390. const int endIndex = mainText.indexOf (T("<end>"));
  49391. if (endIndex >= 0)
  49392. {
  49393. endText = mainText.substring (endIndex + 5).trim();
  49394. mainText = mainText.substring (0, endIndex);
  49395. }
  49396. getLookAndFeel()
  49397. .drawPopupMenuItem (g, getWidth(), getHeight(),
  49398. itemInfo.isSeparator,
  49399. itemInfo.active,
  49400. isHighlighted,
  49401. itemInfo.isTicked,
  49402. itemInfo.subMenu != 0,
  49403. mainText, endText,
  49404. itemInfo.image,
  49405. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  49406. }
  49407. }
  49408. void resized()
  49409. {
  49410. if (getNumChildComponents() > 0)
  49411. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  49412. }
  49413. void setHighlighted (bool shouldBeHighlighted)
  49414. {
  49415. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  49416. if (isHighlighted != shouldBeHighlighted)
  49417. {
  49418. isHighlighted = shouldBeHighlighted;
  49419. if (itemInfo.customComp != 0)
  49420. {
  49421. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  49422. itemInfo.customComp->repaint();
  49423. }
  49424. repaint();
  49425. }
  49426. }
  49427. private:
  49428. MenuItemComponent (const MenuItemComponent&);
  49429. const MenuItemComponent& operator= (const MenuItemComponent&);
  49430. };
  49431. static const int scrollZone = 24;
  49432. static const int borderSize = 2;
  49433. static const int timerInterval = 50;
  49434. static const int dismissCommandId = 0x6287345f;
  49435. static bool wasHiddenBecauseOfAppChange = false;
  49436. class PopupMenuWindow : public Component,
  49437. private Timer
  49438. {
  49439. public:
  49440. PopupMenuWindow() throw()
  49441. : Component (T("menu")),
  49442. owner (0),
  49443. currentChild (0),
  49444. activeSubMenu (0),
  49445. menuBarComponent (0),
  49446. managerOfChosenCommand (0),
  49447. componentAttachedTo (0),
  49448. attachedCompWatcher (0),
  49449. lastMouseX (0),
  49450. lastMouseY (0),
  49451. minimumWidth (0),
  49452. maximumNumColumns (7),
  49453. standardItemHeight (0),
  49454. isOver (false),
  49455. hasBeenOver (false),
  49456. isDown (false),
  49457. needsToScroll (false),
  49458. hideOnExit (false),
  49459. disableMouseMoves (false),
  49460. hasAnyJuceCompHadFocus (false),
  49461. numColumns (0),
  49462. contentHeight (0),
  49463. childYOffset (0),
  49464. timeEnteredCurrentChildComp (0),
  49465. scrollAcceleration (1.0)
  49466. {
  49467. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  49468. setWantsKeyboardFocus (true);
  49469. setOpaque (true);
  49470. setAlwaysOnTop (true);
  49471. Desktop::getInstance().addGlobalMouseListener (this);
  49472. activeMenuWindows.add (this);
  49473. }
  49474. ~PopupMenuWindow()
  49475. {
  49476. activeMenuWindows.removeValue (this);
  49477. Desktop::getInstance().removeGlobalMouseListener (this);
  49478. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49479. delete activeSubMenu;
  49480. deleteAllChildren();
  49481. delete attachedCompWatcher;
  49482. }
  49483. static PopupMenuWindow* create (const PopupMenu& menu,
  49484. const bool dismissOnMouseUp,
  49485. PopupMenuWindow* const owner_,
  49486. const int minX, const int maxX,
  49487. const int minY, const int maxY,
  49488. const int minimumWidth,
  49489. const int maximumNumColumns,
  49490. const int standardItemHeight,
  49491. const bool alignToRectangle,
  49492. const int itemIdThatMustBeVisible,
  49493. Component* const menuBarComponent,
  49494. ApplicationCommandManager** managerOfChosenCommand,
  49495. Component* const componentAttachedTo) throw()
  49496. {
  49497. if (menu.items.size() > 0)
  49498. {
  49499. int totalItems = 0;
  49500. PopupMenuWindow* const mw = new PopupMenuWindow();
  49501. mw->setLookAndFeel (menu.lookAndFeel);
  49502. mw->setWantsKeyboardFocus (false);
  49503. mw->minimumWidth = minimumWidth;
  49504. mw->maximumNumColumns = maximumNumColumns;
  49505. mw->standardItemHeight = standardItemHeight;
  49506. mw->dismissOnMouseUp = dismissOnMouseUp;
  49507. for (int i = 0; i < menu.items.size(); ++i)
  49508. {
  49509. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  49510. mw->addItem (*item);
  49511. ++totalItems;
  49512. }
  49513. if (totalItems == 0)
  49514. {
  49515. delete mw;
  49516. }
  49517. else
  49518. {
  49519. mw->owner = owner_;
  49520. mw->menuBarComponent = menuBarComponent;
  49521. mw->managerOfChosenCommand = managerOfChosenCommand;
  49522. mw->componentAttachedTo = componentAttachedTo;
  49523. delete mw->attachedCompWatcher;
  49524. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  49525. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  49526. mw->setTopLeftPosition (mw->windowPos.getX(),
  49527. mw->windowPos.getY());
  49528. mw->updateYPositions();
  49529. if (itemIdThatMustBeVisible != 0)
  49530. {
  49531. const int y = minY - mw->windowPos.getY();
  49532. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  49533. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  49534. }
  49535. mw->resizeToBestWindowPos();
  49536. mw->addToDesktop (ComponentPeer::windowIsTemporary
  49537. | mw->getLookAndFeel().getMenuWindowFlags());
  49538. return mw;
  49539. }
  49540. }
  49541. return 0;
  49542. }
  49543. void paint (Graphics& g)
  49544. {
  49545. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  49546. }
  49547. void paintOverChildren (Graphics& g)
  49548. {
  49549. if (isScrolling())
  49550. {
  49551. LookAndFeel& lf = getLookAndFeel();
  49552. if (isScrollZoneActive (false))
  49553. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  49554. if (isScrollZoneActive (true))
  49555. {
  49556. g.setOrigin (0, getHeight() - scrollZone);
  49557. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  49558. }
  49559. }
  49560. }
  49561. bool isScrollZoneActive (bool bottomOne) const
  49562. {
  49563. return isScrolling()
  49564. && (bottomOne
  49565. ? childYOffset < contentHeight - windowPos.getHeight()
  49566. : childYOffset > 0);
  49567. }
  49568. void addItem (const MenuItemInfo& item) throw()
  49569. {
  49570. MenuItemComponent* const mic = new MenuItemComponent (item);
  49571. addAndMakeVisible (mic);
  49572. int itemW = 80;
  49573. int itemH = 16;
  49574. mic->getIdealSize (itemW, itemH, standardItemHeight);
  49575. mic->setSize (itemW, jlimit (10, 600, itemH));
  49576. mic->addMouseListener (this, false);
  49577. }
  49578. // hide this and all sub-comps
  49579. void hide (const MenuItemInfo* const item) throw()
  49580. {
  49581. if (isVisible())
  49582. {
  49583. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49584. deleteAndZero (activeSubMenu);
  49585. currentChild = 0;
  49586. exitModalState (item != 0 ? item->itemId : 0);
  49587. setVisible (false);
  49588. if (item != 0
  49589. && item->commandManager != 0
  49590. && item->itemId != 0)
  49591. {
  49592. *managerOfChosenCommand = item->commandManager;
  49593. }
  49594. }
  49595. }
  49596. void dismissMenu (const MenuItemInfo* const item) throw()
  49597. {
  49598. if (owner != 0)
  49599. {
  49600. owner->dismissMenu (item);
  49601. }
  49602. else
  49603. {
  49604. if (item != 0)
  49605. {
  49606. // need a copy of this on the stack as the one passed in will get deleted during this call
  49607. const MenuItemInfo mi (*item);
  49608. hide (&mi);
  49609. }
  49610. else
  49611. {
  49612. hide (0);
  49613. }
  49614. }
  49615. }
  49616. void mouseMove (const MouseEvent&)
  49617. {
  49618. timerCallback();
  49619. }
  49620. void mouseDown (const MouseEvent&)
  49621. {
  49622. timerCallback();
  49623. }
  49624. void mouseDrag (const MouseEvent&)
  49625. {
  49626. timerCallback();
  49627. }
  49628. void mouseUp (const MouseEvent&)
  49629. {
  49630. timerCallback();
  49631. }
  49632. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  49633. {
  49634. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  49635. lastMouseX = -1;
  49636. }
  49637. bool keyPressed (const KeyPress& key)
  49638. {
  49639. if (key.isKeyCode (KeyPress::downKey))
  49640. {
  49641. selectNextItem (1);
  49642. }
  49643. else if (key.isKeyCode (KeyPress::upKey))
  49644. {
  49645. selectNextItem (-1);
  49646. }
  49647. else if (key.isKeyCode (KeyPress::leftKey))
  49648. {
  49649. PopupMenuWindow* parentWindow = owner;
  49650. if (parentWindow != 0)
  49651. {
  49652. MenuItemComponent* currentChildOfParent
  49653. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  49654. hide (0);
  49655. if (parentWindow->isValidComponent())
  49656. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  49657. disableTimerUntilMouseMoves();
  49658. }
  49659. else if (menuBarComponent != 0)
  49660. {
  49661. menuBarComponent->keyPressed (key);
  49662. }
  49663. }
  49664. else if (key.isKeyCode (KeyPress::rightKey))
  49665. {
  49666. disableTimerUntilMouseMoves();
  49667. if (showSubMenuFor (currentChild))
  49668. {
  49669. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49670. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  49671. activeSubMenu->selectNextItem (1);
  49672. }
  49673. else if (menuBarComponent != 0)
  49674. {
  49675. menuBarComponent->keyPressed (key);
  49676. }
  49677. }
  49678. else if (key.isKeyCode (KeyPress::returnKey))
  49679. {
  49680. triggerCurrentlyHighlightedItem();
  49681. }
  49682. else if (key.isKeyCode (KeyPress::escapeKey))
  49683. {
  49684. dismissMenu (0);
  49685. }
  49686. else
  49687. {
  49688. return false;
  49689. }
  49690. return true;
  49691. }
  49692. void inputAttemptWhenModal()
  49693. {
  49694. timerCallback();
  49695. if (! isOverAnyMenu())
  49696. {
  49697. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  49698. {
  49699. // we want to dismiss the menu, but if we do it synchronously, then
  49700. // the mouse-click will be allowed to pass through. That's good, except
  49701. // when the user clicks on the button that orginally popped the menu up,
  49702. // as they'll expect the menu to go away, and in fact it'll just
  49703. // come back. So only dismiss synchronously if they're not on the original
  49704. // comp that we're attached to.
  49705. int mx, my;
  49706. componentAttachedTo->getMouseXYRelative (mx, my);
  49707. if (componentAttachedTo->reallyContains (mx, my, true))
  49708. {
  49709. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  49710. return;
  49711. }
  49712. }
  49713. dismissMenu (0);
  49714. }
  49715. }
  49716. void handleCommandMessage (int commandId)
  49717. {
  49718. Component::handleCommandMessage (commandId);
  49719. if (commandId == dismissCommandId)
  49720. dismissMenu (0);
  49721. }
  49722. void timerCallback()
  49723. {
  49724. if (! isVisible())
  49725. return;
  49726. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  49727. {
  49728. dismissMenu (0);
  49729. return;
  49730. }
  49731. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  49732. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  49733. return;
  49734. startTimer (timerInterval); // do this in case it was called from a mouse
  49735. // move rather than a real timer callback
  49736. int mx, my;
  49737. Desktop::getMousePosition (mx, my);
  49738. int x = mx, y = my;
  49739. globalPositionToRelative (x, y);
  49740. const uint32 now = Time::getMillisecondCounter();
  49741. if (now > timeEnteredCurrentChildComp + 100
  49742. && reallyContains (x, y, true)
  49743. && currentChild->isValidComponent()
  49744. && (! disableMouseMoves)
  49745. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  49746. {
  49747. showSubMenuFor (currentChild);
  49748. }
  49749. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  49750. {
  49751. highlightItemUnderMouse (mx, my, x, y);
  49752. }
  49753. bool overScrollArea = false;
  49754. if (isScrolling()
  49755. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  49756. && ((isScrollZoneActive (false) && y < scrollZone)
  49757. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  49758. {
  49759. if (now > lastScroll + 20)
  49760. {
  49761. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  49762. int amount = 0;
  49763. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  49764. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  49765. alterChildYPos (y < scrollZone ? -amount : amount);
  49766. lastScroll = now;
  49767. }
  49768. overScrollArea = true;
  49769. lastMouseX = -1; // trigger a mouse-move
  49770. }
  49771. else
  49772. {
  49773. scrollAcceleration = 1.0;
  49774. }
  49775. const bool wasDown = isDown;
  49776. bool isOverAny = isOverAnyMenu();
  49777. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  49778. {
  49779. activeSubMenu->updateMouseOverStatus (mx, my);
  49780. isOverAny = isOverAnyMenu();
  49781. }
  49782. if (hideOnExit && hasBeenOver && ! isOverAny)
  49783. {
  49784. hide (0);
  49785. }
  49786. else
  49787. {
  49788. isDown = hasBeenOver
  49789. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  49790. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  49791. bool anyFocused = Process::isForegroundProcess();
  49792. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  49793. {
  49794. // because no component at all may have focus, our test here will
  49795. // only be triggered when something has focus and then loses it.
  49796. anyFocused = ! hasAnyJuceCompHadFocus;
  49797. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  49798. {
  49799. if (ComponentPeer::getPeer (i)->isFocused())
  49800. {
  49801. anyFocused = true;
  49802. hasAnyJuceCompHadFocus = true;
  49803. break;
  49804. }
  49805. }
  49806. }
  49807. if (! anyFocused)
  49808. {
  49809. if (now > lastFocused + 10)
  49810. {
  49811. wasHiddenBecauseOfAppChange = true;
  49812. dismissMenu (0);
  49813. return; // may have been deleted by the previous call..
  49814. }
  49815. }
  49816. else if (wasDown && now > menuCreationTime + 250
  49817. && ! (isDown || overScrollArea))
  49818. {
  49819. isOver = reallyContains (x, y, true);
  49820. if (isOver)
  49821. {
  49822. triggerCurrentlyHighlightedItem();
  49823. }
  49824. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  49825. {
  49826. dismissMenu (0);
  49827. }
  49828. return; // may have been deleted by the previous calls..
  49829. }
  49830. else
  49831. {
  49832. lastFocused = now;
  49833. }
  49834. }
  49835. }
  49836. juce_UseDebuggingNewOperator
  49837. private:
  49838. PopupMenuWindow* owner;
  49839. MenuItemComponent* currentChild;
  49840. PopupMenuWindow* activeSubMenu;
  49841. Component* menuBarComponent;
  49842. ApplicationCommandManager** managerOfChosenCommand;
  49843. Component* componentAttachedTo;
  49844. ComponentDeletionWatcher* attachedCompWatcher;
  49845. Rectangle windowPos;
  49846. int lastMouseX, lastMouseY;
  49847. int minimumWidth, maximumNumColumns, standardItemHeight;
  49848. bool isOver, hasBeenOver, isDown, needsToScroll;
  49849. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  49850. int numColumns, contentHeight, childYOffset;
  49851. Array <int> columnWidths;
  49852. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  49853. double scrollAcceleration;
  49854. bool overlaps (const Rectangle& r) const throw()
  49855. {
  49856. return r.intersects (getBounds())
  49857. || (owner != 0 && owner->overlaps (r));
  49858. }
  49859. bool isOverAnyMenu() const throw()
  49860. {
  49861. return (owner != 0) ? owner->isOverAnyMenu()
  49862. : isOverChildren();
  49863. }
  49864. bool isOverChildren() const throw()
  49865. {
  49866. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49867. return isVisible()
  49868. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  49869. }
  49870. void updateMouseOverStatus (const int mx, const int my) throw()
  49871. {
  49872. int rx = mx, ry = my;
  49873. globalPositionToRelative (rx, ry);
  49874. isOver = reallyContains (rx, ry, true);
  49875. if (activeSubMenu != 0)
  49876. activeSubMenu->updateMouseOverStatus (mx, my);
  49877. }
  49878. bool treeContains (const PopupMenuWindow* const window) const throw()
  49879. {
  49880. const PopupMenuWindow* mw = this;
  49881. while (mw->owner != 0)
  49882. mw = mw->owner;
  49883. while (mw != 0)
  49884. {
  49885. if (mw == window)
  49886. return true;
  49887. mw = mw->activeSubMenu;
  49888. }
  49889. return false;
  49890. }
  49891. void calculateWindowPos (const int minX, const int maxX,
  49892. const int minY, const int maxY,
  49893. const bool alignToRectangle)
  49894. {
  49895. const Rectangle mon (Desktop::getInstance()
  49896. .getMonitorAreaContaining ((minX + maxX) / 2,
  49897. (minY + maxY) / 2,
  49898. true));
  49899. int x, y, widthToUse, heightToUse;
  49900. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  49901. if (alignToRectangle)
  49902. {
  49903. x = minX;
  49904. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  49905. const int spaceOver = minY - mon.getY();
  49906. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  49907. y = maxY;
  49908. else
  49909. y = minY - heightToUse;
  49910. }
  49911. else
  49912. {
  49913. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  49914. if (owner != 0)
  49915. {
  49916. if (owner->owner != 0)
  49917. {
  49918. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  49919. > owner->owner->getX() + owner->owner->getWidth() / 2);
  49920. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  49921. tendTowardsRight = true;
  49922. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  49923. tendTowardsRight = false;
  49924. }
  49925. else if (maxX + widthToUse < mon.getRight() - 32)
  49926. {
  49927. tendTowardsRight = true;
  49928. }
  49929. }
  49930. const int biggestSpace = jmax (mon.getRight() - maxX,
  49931. minX - mon.getX()) - 32;
  49932. if (biggestSpace < widthToUse)
  49933. {
  49934. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  49935. if (numColumns > 1)
  49936. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  49937. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  49938. }
  49939. if (tendTowardsRight)
  49940. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  49941. else
  49942. x = jmax (mon.getX() + 4, minX - widthToUse);
  49943. y = minY;
  49944. if ((minY + maxY) / 2 > mon.getCentreY())
  49945. y = jmax (mon.getY(), maxY - heightToUse);
  49946. }
  49947. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  49948. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  49949. windowPos.setBounds (x, y, widthToUse, heightToUse);
  49950. // sets this flag if it's big enough to obscure any of its parent menus
  49951. hideOnExit = (owner != 0)
  49952. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  49953. }
  49954. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  49955. {
  49956. numColumns = 0;
  49957. contentHeight = 0;
  49958. const int maxMenuH = getParentHeight() - 24;
  49959. int totalW;
  49960. do
  49961. {
  49962. ++numColumns;
  49963. totalW = workOutBestSize (numColumns, maxMenuW);
  49964. if (totalW > maxMenuW)
  49965. {
  49966. numColumns = jmax (1, numColumns - 1);
  49967. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  49968. break;
  49969. }
  49970. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  49971. {
  49972. break;
  49973. }
  49974. } while (numColumns < maximumNumColumns);
  49975. const int actualH = jmin (contentHeight, maxMenuH);
  49976. needsToScroll = contentHeight > actualH;
  49977. width = updateYPositions();
  49978. height = actualH + borderSize * 2;
  49979. }
  49980. int workOutBestSize (const int numColumns, const int maxMenuW)
  49981. {
  49982. int totalW = 0;
  49983. contentHeight = 0;
  49984. int childNum = 0;
  49985. for (int col = 0; col < numColumns; ++col)
  49986. {
  49987. int i, colW = 50, colH = 0;
  49988. const int numChildren = jmin (getNumChildComponents() - childNum,
  49989. (getNumChildComponents() + numColumns - 1) / numColumns);
  49990. for (i = numChildren; --i >= 0;)
  49991. {
  49992. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  49993. colH += getChildComponent (childNum + i)->getHeight();
  49994. }
  49995. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  49996. columnWidths.set (col, colW);
  49997. totalW += colW;
  49998. contentHeight = jmax (contentHeight, colH);
  49999. childNum += numChildren;
  50000. }
  50001. if (totalW < minimumWidth)
  50002. {
  50003. totalW = minimumWidth;
  50004. for (int col = 0; col < numColumns; ++col)
  50005. columnWidths.set (0, totalW / numColumns);
  50006. }
  50007. return totalW;
  50008. }
  50009. void ensureItemIsVisible (const int itemId, int wantedY)
  50010. {
  50011. jassert (itemId != 0)
  50012. for (int i = getNumChildComponents(); --i >= 0;)
  50013. {
  50014. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  50015. if (m != 0
  50016. && m->itemInfo.itemId == itemId
  50017. && windowPos.getHeight() > scrollZone * 4)
  50018. {
  50019. const int currentY = m->getY();
  50020. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  50021. {
  50022. if (wantedY < 0)
  50023. wantedY = jlimit (scrollZone,
  50024. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  50025. currentY);
  50026. const Rectangle mon (Desktop::getInstance()
  50027. .getMonitorAreaContaining (windowPos.getX(),
  50028. windowPos.getY(),
  50029. true));
  50030. int deltaY = wantedY - currentY;
  50031. const int newY = jlimit (mon.getY(),
  50032. mon.getBottom() - windowPos.getHeight(),
  50033. windowPos.getY() + deltaY);
  50034. deltaY -= newY - windowPos.getY();
  50035. childYOffset -= deltaY;
  50036. windowPos.setPosition (windowPos.getX(), newY);
  50037. updateYPositions();
  50038. }
  50039. break;
  50040. }
  50041. }
  50042. }
  50043. void resizeToBestWindowPos()
  50044. {
  50045. Rectangle r (windowPos);
  50046. if (childYOffset < 0)
  50047. {
  50048. r.setBounds (r.getX(), r.getY() - childYOffset,
  50049. r.getWidth(), r.getHeight() + childYOffset);
  50050. }
  50051. else if (childYOffset > 0)
  50052. {
  50053. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  50054. if (spaceAtBottom > 0)
  50055. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  50056. }
  50057. setBounds (r);
  50058. updateYPositions();
  50059. }
  50060. void alterChildYPos (const int delta)
  50061. {
  50062. if (isScrolling())
  50063. {
  50064. childYOffset += delta;
  50065. if (delta < 0)
  50066. {
  50067. childYOffset = jmax (childYOffset, 0);
  50068. }
  50069. else if (delta > 0)
  50070. {
  50071. childYOffset = jmin (childYOffset,
  50072. contentHeight - windowPos.getHeight() + borderSize);
  50073. }
  50074. updateYPositions();
  50075. }
  50076. else
  50077. {
  50078. childYOffset = 0;
  50079. }
  50080. resizeToBestWindowPos();
  50081. repaint();
  50082. }
  50083. int updateYPositions()
  50084. {
  50085. int x = 0;
  50086. int childNum = 0;
  50087. for (int col = 0; col < numColumns; ++col)
  50088. {
  50089. const int numChildren = jmin (getNumChildComponents() - childNum,
  50090. (getNumChildComponents() + numColumns - 1) / numColumns);
  50091. const int colW = columnWidths [col];
  50092. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  50093. for (int i = 0; i < numChildren; ++i)
  50094. {
  50095. Component* const c = getChildComponent (childNum + i);
  50096. c->setBounds (x, y, colW, c->getHeight());
  50097. y += c->getHeight();
  50098. }
  50099. x += colW;
  50100. childNum += numChildren;
  50101. }
  50102. return x;
  50103. }
  50104. bool isScrolling() const throw()
  50105. {
  50106. return childYOffset != 0 || needsToScroll;
  50107. }
  50108. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  50109. {
  50110. if (currentChild->isValidComponent())
  50111. currentChild->setHighlighted (false);
  50112. currentChild = child;
  50113. if (currentChild != 0)
  50114. {
  50115. currentChild->setHighlighted (true);
  50116. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  50117. }
  50118. }
  50119. bool showSubMenuFor (MenuItemComponent* const childComp)
  50120. {
  50121. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50122. deleteAndZero (activeSubMenu);
  50123. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  50124. {
  50125. int left = 0, top = 0;
  50126. childComp->relativePositionToGlobal (left, top);
  50127. int right = childComp->getWidth(), bottom = childComp->getHeight();
  50128. childComp->relativePositionToGlobal (right, bottom);
  50129. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  50130. dismissOnMouseUp,
  50131. this,
  50132. left, right, top, bottom,
  50133. 0, maximumNumColumns,
  50134. standardItemHeight,
  50135. false, 0, menuBarComponent,
  50136. managerOfChosenCommand,
  50137. componentAttachedTo);
  50138. if (activeSubMenu != 0)
  50139. {
  50140. activeSubMenu->setVisible (true);
  50141. activeSubMenu->enterModalState (false);
  50142. activeSubMenu->toFront (false);
  50143. return true;
  50144. }
  50145. }
  50146. return false;
  50147. }
  50148. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  50149. {
  50150. isOver = reallyContains (x, y, true);
  50151. if (isOver)
  50152. hasBeenOver = true;
  50153. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  50154. {
  50155. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  50156. if (disableMouseMoves && isOver)
  50157. disableMouseMoves = false;
  50158. }
  50159. if (disableMouseMoves)
  50160. return;
  50161. bool isMovingTowardsMenu = false;
  50162. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  50163. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  50164. {
  50165. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  50166. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  50167. // extends from the last mouse pos to the submenu's rectangle..
  50168. float subX = (float) activeSubMenu->getScreenX();
  50169. if (activeSubMenu->getX() > getX())
  50170. {
  50171. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  50172. }
  50173. else
  50174. {
  50175. lastMouseX += 2;
  50176. subX += activeSubMenu->getWidth();
  50177. }
  50178. Path areaTowardsSubMenu;
  50179. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  50180. (float) lastMouseY,
  50181. subX,
  50182. (float) activeSubMenu->getScreenY(),
  50183. subX,
  50184. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  50185. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  50186. }
  50187. lastMouseX = mx;
  50188. lastMouseY = my;
  50189. if (! isMovingTowardsMenu)
  50190. {
  50191. Component* c = getComponentAt (x, y);
  50192. if (c == this)
  50193. c = 0;
  50194. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  50195. if (mic == 0 && c != 0)
  50196. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  50197. if (mic != currentChild
  50198. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  50199. {
  50200. if (isOver && (c != 0) && (activeSubMenu != 0))
  50201. {
  50202. activeSubMenu->hide (0);
  50203. }
  50204. if (! isOver)
  50205. mic = 0;
  50206. setCurrentlyHighlightedChild (mic);
  50207. }
  50208. }
  50209. }
  50210. void triggerCurrentlyHighlightedItem()
  50211. {
  50212. if (currentChild->isValidComponent()
  50213. && currentChild->itemInfo.canBeTriggered()
  50214. && (currentChild->itemInfo.customComp == 0
  50215. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  50216. {
  50217. dismissMenu (&currentChild->itemInfo);
  50218. }
  50219. }
  50220. void selectNextItem (const int delta)
  50221. {
  50222. disableTimerUntilMouseMoves();
  50223. MenuItemComponent* mic = 0;
  50224. bool wasLastOne = (currentChild == 0);
  50225. const int numItems = getNumChildComponents();
  50226. for (int i = 0; i < numItems + 1; ++i)
  50227. {
  50228. int index = (delta > 0) ? i : (numItems - 1 - i);
  50229. index = (index + numItems) % numItems;
  50230. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  50231. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  50232. && wasLastOne)
  50233. break;
  50234. if (mic == currentChild)
  50235. wasLastOne = true;
  50236. }
  50237. setCurrentlyHighlightedChild (mic);
  50238. }
  50239. void disableTimerUntilMouseMoves() throw()
  50240. {
  50241. disableMouseMoves = true;
  50242. if (owner != 0)
  50243. owner->disableTimerUntilMouseMoves();
  50244. }
  50245. PopupMenuWindow (const PopupMenuWindow&);
  50246. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  50247. };
  50248. PopupMenu::PopupMenu() throw()
  50249. : items (8),
  50250. lookAndFeel (0),
  50251. separatorPending (false)
  50252. {
  50253. }
  50254. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  50255. : items (8),
  50256. lookAndFeel (other.lookAndFeel),
  50257. separatorPending (false)
  50258. {
  50259. items.ensureStorageAllocated (other.items.size());
  50260. for (int i = 0; i < other.items.size(); ++i)
  50261. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50262. }
  50263. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  50264. {
  50265. if (this != &other)
  50266. {
  50267. lookAndFeel = other.lookAndFeel;
  50268. clear();
  50269. items.ensureStorageAllocated (other.items.size());
  50270. for (int i = 0; i < other.items.size(); ++i)
  50271. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50272. }
  50273. return *this;
  50274. }
  50275. PopupMenu::~PopupMenu() throw()
  50276. {
  50277. clear();
  50278. }
  50279. void PopupMenu::clear() throw()
  50280. {
  50281. for (int i = items.size(); --i >= 0;)
  50282. {
  50283. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  50284. delete mi;
  50285. }
  50286. items.clear();
  50287. separatorPending = false;
  50288. }
  50289. void PopupMenu::addSeparatorIfPending()
  50290. {
  50291. if (separatorPending)
  50292. {
  50293. separatorPending = false;
  50294. if (items.size() > 0)
  50295. items.add (new MenuItemInfo());
  50296. }
  50297. }
  50298. void PopupMenu::addItem (const int itemResultId,
  50299. const String& itemText,
  50300. const bool isActive,
  50301. const bool isTicked,
  50302. const Image* const iconToUse) throw()
  50303. {
  50304. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50305. // didn't pick anything, so you shouldn't use it as the id
  50306. // for an item..
  50307. addSeparatorIfPending();
  50308. items.add (new MenuItemInfo (itemResultId,
  50309. itemText,
  50310. isActive,
  50311. isTicked,
  50312. iconToUse,
  50313. Colours::black,
  50314. false,
  50315. 0, 0, 0));
  50316. }
  50317. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  50318. const int commandID,
  50319. const String& displayName) throw()
  50320. {
  50321. jassert (commandManager != 0 && commandID != 0);
  50322. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  50323. if (registeredInfo != 0)
  50324. {
  50325. ApplicationCommandInfo info (*registeredInfo);
  50326. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  50327. addSeparatorIfPending();
  50328. items.add (new MenuItemInfo (commandID,
  50329. displayName.isNotEmpty() ? displayName
  50330. : info.shortName,
  50331. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  50332. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  50333. 0,
  50334. Colours::black,
  50335. false,
  50336. 0, 0,
  50337. commandManager));
  50338. }
  50339. }
  50340. void PopupMenu::addColouredItem (const int itemResultId,
  50341. const String& itemText,
  50342. const Colour& itemTextColour,
  50343. const bool isActive,
  50344. const bool isTicked,
  50345. const Image* const iconToUse) throw()
  50346. {
  50347. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50348. // didn't pick anything, so you shouldn't use it as the id
  50349. // for an item..
  50350. addSeparatorIfPending();
  50351. items.add (new MenuItemInfo (itemResultId,
  50352. itemText,
  50353. isActive,
  50354. isTicked,
  50355. iconToUse,
  50356. itemTextColour,
  50357. true,
  50358. 0, 0, 0));
  50359. }
  50360. void PopupMenu::addCustomItem (const int itemResultId,
  50361. PopupMenuCustomComponent* const customComponent) throw()
  50362. {
  50363. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50364. // didn't pick anything, so you shouldn't use it as the id
  50365. // for an item..
  50366. addSeparatorIfPending();
  50367. items.add (new MenuItemInfo (itemResultId,
  50368. String::empty,
  50369. true,
  50370. false,
  50371. 0,
  50372. Colours::black,
  50373. false,
  50374. customComponent,
  50375. 0, 0));
  50376. }
  50377. class NormalComponentWrapper : public PopupMenuCustomComponent
  50378. {
  50379. public:
  50380. NormalComponentWrapper (Component* const comp,
  50381. const int w, const int h,
  50382. const bool triggerMenuItemAutomaticallyWhenClicked)
  50383. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  50384. width (w),
  50385. height (h)
  50386. {
  50387. addAndMakeVisible (comp);
  50388. }
  50389. ~NormalComponentWrapper() {}
  50390. void getIdealSize (int& idealWidth, int& idealHeight)
  50391. {
  50392. idealWidth = width;
  50393. idealHeight = height;
  50394. }
  50395. void resized()
  50396. {
  50397. if (getChildComponent(0) != 0)
  50398. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  50399. }
  50400. juce_UseDebuggingNewOperator
  50401. private:
  50402. const int width, height;
  50403. NormalComponentWrapper (const NormalComponentWrapper&);
  50404. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  50405. };
  50406. void PopupMenu::addCustomItem (const int itemResultId,
  50407. Component* customComponent,
  50408. int idealWidth, int idealHeight,
  50409. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  50410. {
  50411. addCustomItem (itemResultId,
  50412. new NormalComponentWrapper (customComponent,
  50413. idealWidth, idealHeight,
  50414. triggerMenuItemAutomaticallyWhenClicked));
  50415. }
  50416. void PopupMenu::addSubMenu (const String& subMenuName,
  50417. const PopupMenu& subMenu,
  50418. const bool isActive,
  50419. Image* const iconToUse) throw()
  50420. {
  50421. addSeparatorIfPending();
  50422. items.add (new MenuItemInfo (0,
  50423. subMenuName,
  50424. isActive && (subMenu.getNumItems() > 0),
  50425. false,
  50426. iconToUse,
  50427. Colours::black,
  50428. false,
  50429. 0,
  50430. &subMenu,
  50431. 0));
  50432. }
  50433. void PopupMenu::addSeparator() throw()
  50434. {
  50435. separatorPending = true;
  50436. }
  50437. class HeaderItemComponent : public PopupMenuCustomComponent
  50438. {
  50439. public:
  50440. HeaderItemComponent (const String& name)
  50441. : PopupMenuCustomComponent (false)
  50442. {
  50443. setName (name);
  50444. }
  50445. ~HeaderItemComponent()
  50446. {
  50447. }
  50448. void paint (Graphics& g)
  50449. {
  50450. Font f (getLookAndFeel().getPopupMenuFont());
  50451. f.setBold (true);
  50452. g.setFont (f);
  50453. g.setColour (findColour (PopupMenu::headerTextColourId));
  50454. g.drawFittedText (getName(),
  50455. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  50456. Justification::bottomLeft, 1);
  50457. }
  50458. void getIdealSize (int& idealWidth,
  50459. int& idealHeight)
  50460. {
  50461. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  50462. idealHeight += idealHeight / 2;
  50463. idealWidth += idealWidth / 4;
  50464. }
  50465. juce_UseDebuggingNewOperator
  50466. };
  50467. void PopupMenu::addSectionHeader (const String& title) throw()
  50468. {
  50469. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  50470. }
  50471. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  50472. const int itemIdThatMustBeVisible,
  50473. const int minimumWidth,
  50474. const int maximumNumColumns,
  50475. const int standardItemHeight,
  50476. const bool alignToRectangle,
  50477. Component* menuBarComponent,
  50478. ApplicationCommandManager** managerOfChosenCommand,
  50479. Component* const componentAttachedTo) throw()
  50480. {
  50481. PopupMenuWindow* const pw
  50482. = PopupMenuWindow::create (*this,
  50483. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  50484. 0,
  50485. x, x + w,
  50486. y, y + h,
  50487. minimumWidth,
  50488. maximumNumColumns,
  50489. standardItemHeight,
  50490. alignToRectangle,
  50491. itemIdThatMustBeVisible,
  50492. menuBarComponent,
  50493. managerOfChosenCommand,
  50494. componentAttachedTo);
  50495. if (pw != 0)
  50496. pw->setVisible (true);
  50497. return pw;
  50498. }
  50499. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  50500. const int itemIdThatMustBeVisible,
  50501. const int minimumWidth,
  50502. const int maximumNumColumns,
  50503. const int standardItemHeight,
  50504. const bool alignToRectangle,
  50505. Component* const componentAttachedTo) throw()
  50506. {
  50507. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  50508. ComponentDeletionWatcher* deletionChecker1 = 0;
  50509. if (prevFocused != 0)
  50510. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  50511. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  50512. ComponentDeletionWatcher* deletionChecker2 = 0;
  50513. if (prevTopLevel != 0)
  50514. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  50515. wasHiddenBecauseOfAppChange = false;
  50516. int result = 0;
  50517. ApplicationCommandManager* managerOfChosenCommand = 0;
  50518. Component* const popupComp = createMenuComponent (x, y, w, h,
  50519. itemIdThatMustBeVisible,
  50520. minimumWidth,
  50521. maximumNumColumns > 0 ? maximumNumColumns : 7,
  50522. standardItemHeight,
  50523. alignToRectangle, 0,
  50524. &managerOfChosenCommand,
  50525. componentAttachedTo);
  50526. if (popupComp != 0)
  50527. {
  50528. popupComp->enterModalState (false);
  50529. popupComp->toFront (false); // need to do this after making it modal, or it could
  50530. // be stuck behind other comps that are already modal..
  50531. result = popupComp->runModalLoop();
  50532. delete popupComp;
  50533. if (! wasHiddenBecauseOfAppChange)
  50534. {
  50535. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  50536. prevTopLevel->toFront (true);
  50537. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  50538. prevFocused->grabKeyboardFocus();
  50539. }
  50540. }
  50541. delete deletionChecker1;
  50542. delete deletionChecker2;
  50543. if (managerOfChosenCommand != 0 && result != 0)
  50544. {
  50545. ApplicationCommandTarget::InvocationInfo info (result);
  50546. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50547. managerOfChosenCommand->invoke (info, true);
  50548. }
  50549. return result;
  50550. }
  50551. int PopupMenu::show (const int itemIdThatMustBeVisible,
  50552. const int minimumWidth,
  50553. const int maximumNumColumns,
  50554. const int standardItemHeight)
  50555. {
  50556. int x, y;
  50557. Desktop::getMousePosition (x, y);
  50558. return showAt (x, y,
  50559. itemIdThatMustBeVisible,
  50560. minimumWidth,
  50561. maximumNumColumns,
  50562. standardItemHeight);
  50563. }
  50564. int PopupMenu::showAt (const int screenX,
  50565. const int screenY,
  50566. const int itemIdThatMustBeVisible,
  50567. const int minimumWidth,
  50568. const int maximumNumColumns,
  50569. const int standardItemHeight)
  50570. {
  50571. return showMenu (screenX, screenY, 1, 1,
  50572. itemIdThatMustBeVisible,
  50573. minimumWidth, maximumNumColumns,
  50574. standardItemHeight,
  50575. false, 0);
  50576. }
  50577. int PopupMenu::showAt (Component* componentToAttachTo,
  50578. const int itemIdThatMustBeVisible,
  50579. const int minimumWidth,
  50580. const int maximumNumColumns,
  50581. const int standardItemHeight)
  50582. {
  50583. if (componentToAttachTo != 0)
  50584. {
  50585. return showMenu (componentToAttachTo->getScreenX(),
  50586. componentToAttachTo->getScreenY(),
  50587. componentToAttachTo->getWidth(),
  50588. componentToAttachTo->getHeight(),
  50589. itemIdThatMustBeVisible,
  50590. minimumWidth,
  50591. maximumNumColumns,
  50592. standardItemHeight,
  50593. true, componentToAttachTo);
  50594. }
  50595. else
  50596. {
  50597. return show (itemIdThatMustBeVisible,
  50598. minimumWidth,
  50599. maximumNumColumns,
  50600. standardItemHeight);
  50601. }
  50602. }
  50603. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  50604. {
  50605. for (int i = activeMenuWindows.size(); --i >= 0;)
  50606. {
  50607. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  50608. if (pmw != 0)
  50609. pmw->dismissMenu (0);
  50610. }
  50611. }
  50612. int PopupMenu::getNumItems() const throw()
  50613. {
  50614. int num = 0;
  50615. for (int i = items.size(); --i >= 0;)
  50616. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  50617. ++num;
  50618. return num;
  50619. }
  50620. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  50621. {
  50622. for (int i = items.size(); --i >= 0;)
  50623. {
  50624. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  50625. if ((mi->itemId == commandID && mi->commandManager != 0)
  50626. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  50627. {
  50628. return true;
  50629. }
  50630. }
  50631. return false;
  50632. }
  50633. bool PopupMenu::containsAnyActiveItems() const throw()
  50634. {
  50635. for (int i = items.size(); --i >= 0;)
  50636. {
  50637. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  50638. if (mi->subMenu != 0)
  50639. {
  50640. if (mi->subMenu->containsAnyActiveItems())
  50641. return true;
  50642. }
  50643. else if (mi->active)
  50644. {
  50645. return true;
  50646. }
  50647. }
  50648. return false;
  50649. }
  50650. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  50651. {
  50652. lookAndFeel = newLookAndFeel;
  50653. }
  50654. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  50655. : refCount_ (0),
  50656. isHighlighted (false),
  50657. isTriggeredAutomatically (isTriggeredAutomatically_)
  50658. {
  50659. }
  50660. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  50661. {
  50662. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  50663. }
  50664. void PopupMenuCustomComponent::triggerMenuItem()
  50665. {
  50666. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  50667. if (mic != 0)
  50668. {
  50669. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  50670. if (pmw != 0)
  50671. {
  50672. pmw->dismissMenu (&mic->itemInfo);
  50673. }
  50674. else
  50675. {
  50676. // something must have gone wrong with the component hierarchy if this happens..
  50677. jassertfalse
  50678. }
  50679. }
  50680. else
  50681. {
  50682. // why isn't this component inside a menu? Not much point triggering the item if
  50683. // there's no menu.
  50684. jassertfalse
  50685. }
  50686. }
  50687. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  50688. : subMenu (0),
  50689. itemId (0),
  50690. isSeparator (false),
  50691. isTicked (false),
  50692. isEnabled (false),
  50693. isCustomComponent (false),
  50694. isSectionHeader (false),
  50695. customColour (0),
  50696. customImage (0),
  50697. menu (menu_),
  50698. index (0)
  50699. {
  50700. }
  50701. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  50702. {
  50703. }
  50704. bool PopupMenu::MenuItemIterator::next() throw()
  50705. {
  50706. if (index >= menu.items.size())
  50707. return false;
  50708. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  50709. ++index;
  50710. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  50711. subMenu = item->subMenu;
  50712. itemId = item->itemId;
  50713. isSeparator = item->isSeparator;
  50714. isTicked = item->isTicked;
  50715. isEnabled = item->active;
  50716. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  50717. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  50718. customColour = item->usesColour ? &(item->textColour) : 0;
  50719. customImage = item->image;
  50720. commandManager = item->commandManager;
  50721. return true;
  50722. }
  50723. END_JUCE_NAMESPACE
  50724. /********* End of inlined file: juce_PopupMenu.cpp *********/
  50725. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  50726. BEGIN_JUCE_NAMESPACE
  50727. ComponentDragger::ComponentDragger()
  50728. : constrainer (0),
  50729. originalX (0),
  50730. originalY (0)
  50731. {
  50732. }
  50733. ComponentDragger::~ComponentDragger()
  50734. {
  50735. }
  50736. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  50737. ComponentBoundsConstrainer* const constrainer_)
  50738. {
  50739. jassert (componentToDrag->isValidComponent());
  50740. if (componentToDrag->isValidComponent())
  50741. {
  50742. constrainer = constrainer_;
  50743. originalX = 0;
  50744. originalY = 0;
  50745. componentToDrag->relativePositionToGlobal (originalX, originalY);
  50746. }
  50747. }
  50748. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  50749. {
  50750. jassert (componentToDrag->isValidComponent());
  50751. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  50752. if (componentToDrag->isValidComponent())
  50753. {
  50754. int x = originalX + e.getDistanceFromDragStartX();
  50755. int y = originalY + e.getDistanceFromDragStartY();
  50756. int w = componentToDrag->getWidth();
  50757. int h = componentToDrag->getHeight();
  50758. const Component* const parentComp = componentToDrag->getParentComponent();
  50759. if (parentComp != 0)
  50760. parentComp->globalPositionToRelative (x, y);
  50761. if (constrainer != 0)
  50762. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  50763. false, false, false, false);
  50764. else
  50765. componentToDrag->setBounds (x, y, w, h);
  50766. }
  50767. }
  50768. END_JUCE_NAMESPACE
  50769. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  50770. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  50771. BEGIN_JUCE_NAMESPACE
  50772. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  50773. bool juce_performDragDropText (const String& text, bool& shouldStop);
  50774. class DragImageComponent : public Component,
  50775. public Timer
  50776. {
  50777. private:
  50778. Image* image;
  50779. Component* const source;
  50780. DragAndDropContainer* const owner;
  50781. ComponentDeletionWatcher* sourceWatcher;
  50782. Component* mouseDragSource;
  50783. ComponentDeletionWatcher* mouseDragSourceWatcher;
  50784. DragAndDropTarget* currentlyOver;
  50785. String dragDesc;
  50786. int xOff, yOff;
  50787. bool hasCheckedForExternalDrag, drawImage;
  50788. DragImageComponent (const DragImageComponent&);
  50789. const DragImageComponent& operator= (const DragImageComponent&);
  50790. public:
  50791. DragImageComponent (Image* const im,
  50792. const String& desc,
  50793. Component* const s,
  50794. DragAndDropContainer* const o)
  50795. : image (im),
  50796. source (s),
  50797. owner (o),
  50798. currentlyOver (0),
  50799. dragDesc (desc),
  50800. hasCheckedForExternalDrag (false),
  50801. drawImage (true)
  50802. {
  50803. setSize (im->getWidth(), im->getHeight());
  50804. sourceWatcher = new ComponentDeletionWatcher (source);
  50805. mouseDragSource = Component::getComponentUnderMouse();
  50806. if (mouseDragSource == 0)
  50807. mouseDragSource = source;
  50808. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  50809. mouseDragSource->addMouseListener (this, false);
  50810. int mx, my;
  50811. Desktop::getLastMouseDownPosition (mx, my);
  50812. source->globalPositionToRelative (mx, my);
  50813. xOff = jlimit (0, im->getWidth(), mx);
  50814. yOff = jlimit (0, im->getHeight(), my);
  50815. startTimer (200);
  50816. setInterceptsMouseClicks (false, false);
  50817. setAlwaysOnTop (true);
  50818. }
  50819. ~DragImageComponent()
  50820. {
  50821. if (owner->dragImageComponent == this)
  50822. owner->dragImageComponent = 0;
  50823. if (((Component*) currentlyOver)->isValidComponent())
  50824. {
  50825. Component* const over = dynamic_cast <Component*> (currentlyOver);
  50826. if (over != 0
  50827. && over->isValidComponent()
  50828. && source->isValidComponent()
  50829. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50830. {
  50831. currentlyOver->itemDragExit (dragDesc, source);
  50832. }
  50833. }
  50834. if (! mouseDragSourceWatcher->hasBeenDeleted())
  50835. mouseDragSource->removeMouseListener (this);
  50836. delete mouseDragSourceWatcher;
  50837. delete sourceWatcher;
  50838. delete image;
  50839. }
  50840. void paint (Graphics& g)
  50841. {
  50842. if (isOpaque())
  50843. g.fillAll (Colours::white);
  50844. if (drawImage)
  50845. {
  50846. g.setOpacity (1.0f);
  50847. g.drawImageAt (image, 0, 0);
  50848. }
  50849. }
  50850. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  50851. int& relX, int& relY) const throw()
  50852. {
  50853. Component* hit = getParentComponent();
  50854. if (hit == 0)
  50855. {
  50856. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  50857. }
  50858. else
  50859. {
  50860. int rx = screenX, ry = screenY;
  50861. hit->globalPositionToRelative (rx, ry);
  50862. hit = hit->getComponentAt (rx, ry);
  50863. }
  50864. while (hit != 0)
  50865. {
  50866. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  50867. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  50868. {
  50869. relX = screenX;
  50870. relY = screenY;
  50871. hit->globalPositionToRelative (relX, relY);
  50872. return ddt;
  50873. }
  50874. hit = hit->getParentComponent();
  50875. }
  50876. return 0;
  50877. }
  50878. void mouseUp (const MouseEvent& e)
  50879. {
  50880. if (e.originalComponent != this)
  50881. {
  50882. if (! mouseDragSourceWatcher->hasBeenDeleted())
  50883. mouseDragSource->removeMouseListener (this);
  50884. bool dropAccepted = false;
  50885. DragAndDropTarget* ddt = 0;
  50886. int relX = 0, relY = 0;
  50887. if (isVisible())
  50888. {
  50889. setVisible (false);
  50890. ddt = findTarget (e.getScreenX(),
  50891. e.getScreenY(),
  50892. relX, relY);
  50893. // fade this component and remove it - it'll be deleted later by the timer callback
  50894. dropAccepted = ddt != 0;
  50895. setVisible (true);
  50896. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  50897. {
  50898. fadeOutComponent (120);
  50899. }
  50900. else
  50901. {
  50902. int targetX = source->getWidth() / 2;
  50903. int targetY = source->getHeight() / 2;
  50904. source->relativePositionToGlobal (targetX, targetY);
  50905. int ourCentreX = getWidth() / 2;
  50906. int ourCentreY = getHeight() / 2;
  50907. relativePositionToGlobal (ourCentreX, ourCentreY);
  50908. fadeOutComponent (120,
  50909. targetX - ourCentreX,
  50910. targetY - ourCentreY);
  50911. }
  50912. }
  50913. if (getParentComponent() != 0)
  50914. getParentComponent()->removeChildComponent (this);
  50915. if (dropAccepted && ddt != 0)
  50916. ddt->itemDropped (dragDesc, source, relX, relY);
  50917. // careful - this object could now be deleted..
  50918. }
  50919. }
  50920. void updateLocation (const bool canDoExternalDrag, int x, int y)
  50921. {
  50922. int newX = x - xOff;
  50923. int newY = y - yOff;
  50924. if (getParentComponent() != 0)
  50925. getParentComponent()->globalPositionToRelative (newX, newY);
  50926. if (newX != getX() || newY != getY())
  50927. {
  50928. setTopLeftPosition (newX, newY);
  50929. int relX = 0, relY = 0;
  50930. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  50931. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  50932. if (ddt != currentlyOver)
  50933. {
  50934. Component* const over = dynamic_cast <Component*> (currentlyOver);
  50935. if (over != 0
  50936. && over->isValidComponent()
  50937. && ! (sourceWatcher->hasBeenDeleted())
  50938. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50939. {
  50940. currentlyOver->itemDragExit (dragDesc, source);
  50941. }
  50942. currentlyOver = ddt;
  50943. if (currentlyOver != 0
  50944. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50945. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  50946. }
  50947. if (currentlyOver != 0
  50948. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50949. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  50950. if (currentlyOver == 0
  50951. && canDoExternalDrag
  50952. && ! hasCheckedForExternalDrag)
  50953. {
  50954. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  50955. {
  50956. hasCheckedForExternalDrag = true;
  50957. StringArray files;
  50958. bool canMoveFiles = false;
  50959. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  50960. && files.size() > 0)
  50961. {
  50962. ComponentDeletionWatcher cdw (this);
  50963. setVisible (false);
  50964. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  50965. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  50966. if (! cdw.hasBeenDeleted())
  50967. delete this;
  50968. return;
  50969. }
  50970. }
  50971. }
  50972. }
  50973. }
  50974. void mouseDrag (const MouseEvent& e)
  50975. {
  50976. if (e.originalComponent != this)
  50977. updateLocation (true, e.getScreenX(), e.getScreenY());
  50978. }
  50979. void timerCallback()
  50980. {
  50981. if (sourceWatcher->hasBeenDeleted())
  50982. {
  50983. delete this;
  50984. }
  50985. else if (! isMouseButtonDownAnywhere())
  50986. {
  50987. if (! mouseDragSourceWatcher->hasBeenDeleted())
  50988. mouseDragSource->removeMouseListener (this);
  50989. delete this;
  50990. }
  50991. }
  50992. };
  50993. DragAndDropContainer::DragAndDropContainer()
  50994. : dragImageComponent (0)
  50995. {
  50996. }
  50997. DragAndDropContainer::~DragAndDropContainer()
  50998. {
  50999. if (dragImageComponent != 0)
  51000. delete dragImageComponent;
  51001. }
  51002. void DragAndDropContainer::startDragging (const String& sourceDescription,
  51003. Component* sourceComponent,
  51004. Image* im,
  51005. const bool allowDraggingToExternalWindows)
  51006. {
  51007. if (dragImageComponent != 0)
  51008. {
  51009. if (im != 0)
  51010. delete im;
  51011. }
  51012. else
  51013. {
  51014. Component* const thisComp = dynamic_cast <Component*> (this);
  51015. if (thisComp != 0)
  51016. {
  51017. int mx, my;
  51018. Desktop::getLastMouseDownPosition (mx, my);
  51019. if (im == 0)
  51020. {
  51021. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  51022. if (im->getFormat() != Image::ARGB)
  51023. {
  51024. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  51025. Graphics g2 (*newIm);
  51026. g2.drawImageAt (im, 0, 0);
  51027. delete im;
  51028. im = newIm;
  51029. }
  51030. im->multiplyAllAlphas (0.6f);
  51031. const int lo = 150;
  51032. const int hi = 400;
  51033. int rx = mx, ry = my;
  51034. sourceComponent->globalPositionToRelative (rx, ry);
  51035. const int cx = jlimit (0, im->getWidth(), rx);
  51036. const int cy = jlimit (0, im->getHeight(), ry);
  51037. for (int y = im->getHeight(); --y >= 0;)
  51038. {
  51039. const double dy = (y - cy) * (y - cy);
  51040. for (int x = im->getWidth(); --x >= 0;)
  51041. {
  51042. const int dx = x - cx;
  51043. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  51044. if (distance > lo)
  51045. {
  51046. const float alpha = (distance > hi) ? 0
  51047. : (hi - distance) / (float) (hi - lo)
  51048. + Random::getSystemRandom().nextFloat() * 0.008f;
  51049. im->multiplyAlphaAt (x, y, alpha);
  51050. }
  51051. }
  51052. }
  51053. }
  51054. DragImageComponent* const dic
  51055. = new DragImageComponent (im,
  51056. sourceDescription,
  51057. sourceComponent,
  51058. this);
  51059. dragImageComponent = dic;
  51060. currentDragDesc = sourceDescription;
  51061. if (allowDraggingToExternalWindows)
  51062. {
  51063. if (! Desktop::canUseSemiTransparentWindows())
  51064. dic->setOpaque (true);
  51065. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  51066. | ComponentPeer::windowIsTemporary);
  51067. }
  51068. else
  51069. thisComp->addChildComponent (dic);
  51070. dic->updateLocation (false, mx, my);
  51071. dic->setVisible (true);
  51072. }
  51073. else
  51074. {
  51075. // this class must only be implemented by an object that
  51076. // is also a Component.
  51077. jassertfalse
  51078. if (im != 0)
  51079. delete im;
  51080. }
  51081. }
  51082. }
  51083. bool DragAndDropContainer::isDragAndDropActive() const
  51084. {
  51085. return dragImageComponent != 0;
  51086. }
  51087. const String DragAndDropContainer::getCurrentDragDescription() const
  51088. {
  51089. return (dragImageComponent != 0) ? currentDragDesc
  51090. : String::empty;
  51091. }
  51092. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  51093. {
  51094. if (c == 0)
  51095. return 0;
  51096. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51097. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  51098. }
  51099. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  51100. {
  51101. return false;
  51102. }
  51103. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  51104. {
  51105. }
  51106. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  51107. {
  51108. }
  51109. void DragAndDropTarget::itemDragExit (const String&, Component*)
  51110. {
  51111. }
  51112. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  51113. {
  51114. return true;
  51115. }
  51116. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  51117. {
  51118. }
  51119. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  51120. {
  51121. }
  51122. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  51123. {
  51124. }
  51125. END_JUCE_NAMESPACE
  51126. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  51127. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  51128. BEGIN_JUCE_NAMESPACE
  51129. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  51130. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  51131. // isStandard set depending on which interface was used to create the cursor
  51132. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  51133. static CriticalSection mouseCursorLock;
  51134. static VoidArray standardCursors (2);
  51135. class RefCountedMouseCursor
  51136. {
  51137. public:
  51138. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  51139. : refCount (1),
  51140. standardType (t),
  51141. isStandard (true)
  51142. {
  51143. handle = juce_createStandardMouseCursor (standardType);
  51144. standardCursors.add (this);
  51145. }
  51146. RefCountedMouseCursor (Image& image,
  51147. const int hotSpotX,
  51148. const int hotSpotY) throw()
  51149. : refCount (1),
  51150. standardType (MouseCursor::NormalCursor),
  51151. isStandard (false)
  51152. {
  51153. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  51154. }
  51155. ~RefCountedMouseCursor() throw()
  51156. {
  51157. juce_deleteMouseCursor (handle, isStandard);
  51158. standardCursors.removeValue (this);
  51159. }
  51160. void decRef() throw()
  51161. {
  51162. if (--refCount == 0)
  51163. delete this;
  51164. }
  51165. void incRef() throw()
  51166. {
  51167. ++refCount;
  51168. }
  51169. void* getHandle() const throw()
  51170. {
  51171. return handle;
  51172. }
  51173. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  51174. {
  51175. const ScopedLock sl (mouseCursorLock);
  51176. for (int i = 0; i < standardCursors.size(); i++)
  51177. {
  51178. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  51179. if (r->standardType == type)
  51180. {
  51181. r->incRef();
  51182. return r;
  51183. }
  51184. }
  51185. return new RefCountedMouseCursor (type);
  51186. }
  51187. juce_UseDebuggingNewOperator
  51188. private:
  51189. void* handle;
  51190. int refCount;
  51191. const MouseCursor::StandardCursorType standardType;
  51192. const bool isStandard;
  51193. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  51194. };
  51195. MouseCursor::MouseCursor() throw()
  51196. {
  51197. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  51198. }
  51199. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  51200. {
  51201. cursorHandle = RefCountedMouseCursor::findInstance (type);
  51202. }
  51203. MouseCursor::MouseCursor (Image& image,
  51204. const int hotSpotX,
  51205. const int hotSpotY) throw()
  51206. {
  51207. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  51208. }
  51209. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  51210. : cursorHandle (other.cursorHandle)
  51211. {
  51212. const ScopedLock sl (mouseCursorLock);
  51213. cursorHandle->incRef();
  51214. }
  51215. MouseCursor::~MouseCursor() throw()
  51216. {
  51217. const ScopedLock sl (mouseCursorLock);
  51218. cursorHandle->decRef();
  51219. }
  51220. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  51221. {
  51222. if (this != &other)
  51223. {
  51224. const ScopedLock sl (mouseCursorLock);
  51225. cursorHandle->decRef();
  51226. cursorHandle = other.cursorHandle;
  51227. cursorHandle->incRef();
  51228. }
  51229. return *this;
  51230. }
  51231. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  51232. {
  51233. return cursorHandle == other.cursorHandle;
  51234. }
  51235. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  51236. {
  51237. return cursorHandle != other.cursorHandle;
  51238. }
  51239. void* MouseCursor::getHandle() const throw()
  51240. {
  51241. return cursorHandle->getHandle();
  51242. }
  51243. void MouseCursor::showWaitCursor() throw()
  51244. {
  51245. const MouseCursor mc (MouseCursor::WaitCursor);
  51246. mc.showInAllWindows();
  51247. }
  51248. void MouseCursor::hideWaitCursor() throw()
  51249. {
  51250. if (Component::getComponentUnderMouse()->isValidComponent())
  51251. {
  51252. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  51253. }
  51254. else
  51255. {
  51256. const MouseCursor mc (MouseCursor::NormalCursor);
  51257. mc.showInAllWindows();
  51258. }
  51259. }
  51260. END_JUCE_NAMESPACE
  51261. /********* End of inlined file: juce_MouseCursor.cpp *********/
  51262. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  51263. BEGIN_JUCE_NAMESPACE
  51264. MouseEvent::MouseEvent (const int x_,
  51265. const int y_,
  51266. const ModifierKeys& mods_,
  51267. Component* const originator,
  51268. const Time& eventTime_,
  51269. const int mouseDownX_,
  51270. const int mouseDownY_,
  51271. const Time& mouseDownTime_,
  51272. const int numberOfClicks_,
  51273. const bool mouseWasDragged) throw()
  51274. : x (x_),
  51275. y (y_),
  51276. mods (mods_),
  51277. eventComponent (originator),
  51278. originalComponent (originator),
  51279. eventTime (eventTime_),
  51280. mouseDownX (mouseDownX_),
  51281. mouseDownY (mouseDownY_),
  51282. mouseDownTime (mouseDownTime_),
  51283. numberOfClicks (numberOfClicks_),
  51284. wasMovedSinceMouseDown (mouseWasDragged)
  51285. {
  51286. }
  51287. MouseEvent::~MouseEvent() throw()
  51288. {
  51289. }
  51290. bool MouseEvent::mouseWasClicked() const throw()
  51291. {
  51292. return ! wasMovedSinceMouseDown;
  51293. }
  51294. int MouseEvent::getMouseDownX() const throw()
  51295. {
  51296. return mouseDownX;
  51297. }
  51298. int MouseEvent::getMouseDownY() const throw()
  51299. {
  51300. return mouseDownY;
  51301. }
  51302. int MouseEvent::getDistanceFromDragStartX() const throw()
  51303. {
  51304. return x - mouseDownX;
  51305. }
  51306. int MouseEvent::getDistanceFromDragStartY() const throw()
  51307. {
  51308. return y - mouseDownY;
  51309. }
  51310. int MouseEvent::getDistanceFromDragStart() const throw()
  51311. {
  51312. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  51313. getDistanceFromDragStartY()));
  51314. }
  51315. int MouseEvent::getLengthOfMousePress() const throw()
  51316. {
  51317. if (mouseDownTime.toMilliseconds() > 0)
  51318. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  51319. return 0;
  51320. }
  51321. int MouseEvent::getScreenX() const throw()
  51322. {
  51323. int sx = x, sy = y;
  51324. eventComponent->relativePositionToGlobal (sx, sy);
  51325. return sx;
  51326. }
  51327. int MouseEvent::getScreenY() const throw()
  51328. {
  51329. int sx = x, sy = y;
  51330. eventComponent->relativePositionToGlobal (sx, sy);
  51331. return sy;
  51332. }
  51333. int MouseEvent::getMouseDownScreenX() const throw()
  51334. {
  51335. int sx = mouseDownX, sy = mouseDownY;
  51336. eventComponent->relativePositionToGlobal (sx, sy);
  51337. return sx;
  51338. }
  51339. int MouseEvent::getMouseDownScreenY() const throw()
  51340. {
  51341. int sx = mouseDownX, sy = mouseDownY;
  51342. eventComponent->relativePositionToGlobal (sx, sy);
  51343. return sy;
  51344. }
  51345. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  51346. {
  51347. if (otherComponent == 0)
  51348. {
  51349. jassertfalse
  51350. return *this;
  51351. }
  51352. MouseEvent me (*this);
  51353. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  51354. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  51355. me.eventComponent = otherComponent;
  51356. return me;
  51357. }
  51358. static int doubleClickTimeOutMs = 400;
  51359. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  51360. {
  51361. doubleClickTimeOutMs = newTime;
  51362. }
  51363. int MouseEvent::getDoubleClickTimeout() throw()
  51364. {
  51365. return doubleClickTimeOutMs;
  51366. }
  51367. END_JUCE_NAMESPACE
  51368. /********* End of inlined file: juce_MouseEvent.cpp *********/
  51369. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  51370. BEGIN_JUCE_NAMESPACE
  51371. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  51372. : source (0),
  51373. hoverTimeMillisecs (hoverTimeMillisecs_),
  51374. hasJustHovered (false)
  51375. {
  51376. internalTimer.owner = this;
  51377. }
  51378. MouseHoverDetector::~MouseHoverDetector()
  51379. {
  51380. setHoverComponent (0);
  51381. }
  51382. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  51383. {
  51384. hoverTimeMillisecs = newTimeInMillisecs;
  51385. }
  51386. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  51387. {
  51388. if (source != newSourceComponent)
  51389. {
  51390. internalTimer.stopTimer();
  51391. hasJustHovered = false;
  51392. if (source != 0)
  51393. {
  51394. // ! you need to delete the hover detector before deleting its component
  51395. jassert (source->isValidComponent());
  51396. source->removeMouseListener (&internalTimer);
  51397. }
  51398. source = newSourceComponent;
  51399. if (newSourceComponent != 0)
  51400. newSourceComponent->addMouseListener (&internalTimer, false);
  51401. }
  51402. }
  51403. void MouseHoverDetector::hoverTimerCallback()
  51404. {
  51405. internalTimer.stopTimer();
  51406. if (source != 0)
  51407. {
  51408. int mx, my;
  51409. source->getMouseXYRelative (mx, my);
  51410. if (source->reallyContains (mx, my, false))
  51411. {
  51412. hasJustHovered = true;
  51413. mouseHovered (mx, my);
  51414. }
  51415. }
  51416. }
  51417. void MouseHoverDetector::checkJustHoveredCallback()
  51418. {
  51419. if (hasJustHovered)
  51420. {
  51421. hasJustHovered = false;
  51422. mouseMovedAfterHover();
  51423. }
  51424. }
  51425. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  51426. {
  51427. owner->hoverTimerCallback();
  51428. }
  51429. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  51430. {
  51431. stopTimer();
  51432. owner->checkJustHoveredCallback();
  51433. }
  51434. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  51435. {
  51436. stopTimer();
  51437. owner->checkJustHoveredCallback();
  51438. }
  51439. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  51440. {
  51441. stopTimer();
  51442. owner->checkJustHoveredCallback();
  51443. }
  51444. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  51445. {
  51446. stopTimer();
  51447. owner->checkJustHoveredCallback();
  51448. }
  51449. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  51450. {
  51451. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  51452. {
  51453. lastX = e.x;
  51454. lastY = e.y;
  51455. if (owner->source != 0)
  51456. startTimer (owner->hoverTimeMillisecs);
  51457. owner->checkJustHoveredCallback();
  51458. }
  51459. }
  51460. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  51461. {
  51462. stopTimer();
  51463. owner->checkJustHoveredCallback();
  51464. }
  51465. END_JUCE_NAMESPACE
  51466. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  51467. /********* Start of inlined file: juce_MouseListener.cpp *********/
  51468. BEGIN_JUCE_NAMESPACE
  51469. void MouseListener::mouseEnter (const MouseEvent&)
  51470. {
  51471. }
  51472. void MouseListener::mouseExit (const MouseEvent&)
  51473. {
  51474. }
  51475. void MouseListener::mouseDown (const MouseEvent&)
  51476. {
  51477. }
  51478. void MouseListener::mouseUp (const MouseEvent&)
  51479. {
  51480. }
  51481. void MouseListener::mouseDrag (const MouseEvent&)
  51482. {
  51483. }
  51484. void MouseListener::mouseMove (const MouseEvent&)
  51485. {
  51486. }
  51487. void MouseListener::mouseDoubleClick (const MouseEvent&)
  51488. {
  51489. }
  51490. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  51491. {
  51492. }
  51493. END_JUCE_NAMESPACE
  51494. /********* End of inlined file: juce_MouseListener.cpp *********/
  51495. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51496. BEGIN_JUCE_NAMESPACE
  51497. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  51498. const String& buttonTextWhenTrue,
  51499. const String& buttonTextWhenFalse)
  51500. : PropertyComponent (name),
  51501. onText (buttonTextWhenTrue),
  51502. offText (buttonTextWhenFalse)
  51503. {
  51504. addAndMakeVisible (button = new ToggleButton (String::empty));
  51505. button->setClickingTogglesState (false);
  51506. button->addButtonListener (this);
  51507. }
  51508. BooleanPropertyComponent::~BooleanPropertyComponent()
  51509. {
  51510. deleteAllChildren();
  51511. }
  51512. void BooleanPropertyComponent::paint (Graphics& g)
  51513. {
  51514. PropertyComponent::paint (g);
  51515. const Rectangle r (button->getBounds());
  51516. g.setColour (Colours::white);
  51517. g.fillRect (r);
  51518. g.setColour (findColour (ComboBox::outlineColourId));
  51519. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  51520. }
  51521. void BooleanPropertyComponent::refresh()
  51522. {
  51523. button->setToggleState (getState(), false);
  51524. button->setButtonText (button->getToggleState() ? onText : offText);
  51525. }
  51526. void BooleanPropertyComponent::buttonClicked (Button*)
  51527. {
  51528. setState (! getState());
  51529. }
  51530. END_JUCE_NAMESPACE
  51531. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51532. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51533. BEGIN_JUCE_NAMESPACE
  51534. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  51535. const bool triggerOnMouseDown)
  51536. : PropertyComponent (name)
  51537. {
  51538. addAndMakeVisible (button = new TextButton (String::empty));
  51539. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  51540. button->addButtonListener (this);
  51541. }
  51542. ButtonPropertyComponent::~ButtonPropertyComponent()
  51543. {
  51544. deleteAllChildren();
  51545. }
  51546. void ButtonPropertyComponent::refresh()
  51547. {
  51548. button->setButtonText (getButtonText());
  51549. }
  51550. void ButtonPropertyComponent::buttonClicked (Button*)
  51551. {
  51552. buttonClicked();
  51553. }
  51554. END_JUCE_NAMESPACE
  51555. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51556. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51557. BEGIN_JUCE_NAMESPACE
  51558. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  51559. : PropertyComponent (name),
  51560. comboBox (0)
  51561. {
  51562. }
  51563. ChoicePropertyComponent::~ChoicePropertyComponent()
  51564. {
  51565. deleteAllChildren();
  51566. }
  51567. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  51568. {
  51569. return choices;
  51570. }
  51571. void ChoicePropertyComponent::refresh()
  51572. {
  51573. if (comboBox == 0)
  51574. {
  51575. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  51576. for (int i = 0; i < choices.size(); ++i)
  51577. {
  51578. if (choices[i].isNotEmpty())
  51579. comboBox->addItem (choices[i], i + 1);
  51580. else
  51581. comboBox->addSeparator();
  51582. }
  51583. comboBox->setEditableText (false);
  51584. comboBox->addListener (this);
  51585. }
  51586. comboBox->setSelectedId (getIndex() + 1, true);
  51587. }
  51588. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  51589. {
  51590. const int newIndex = comboBox->getSelectedId() - 1;
  51591. if (newIndex != getIndex())
  51592. setIndex (newIndex);
  51593. }
  51594. END_JUCE_NAMESPACE
  51595. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51596. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  51597. BEGIN_JUCE_NAMESPACE
  51598. PropertyComponent::PropertyComponent (const String& name,
  51599. const int preferredHeight_)
  51600. : Component (name),
  51601. preferredHeight (preferredHeight_)
  51602. {
  51603. jassert (name.isNotEmpty());
  51604. }
  51605. PropertyComponent::~PropertyComponent()
  51606. {
  51607. }
  51608. void PropertyComponent::paint (Graphics& g)
  51609. {
  51610. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  51611. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  51612. }
  51613. void PropertyComponent::resized()
  51614. {
  51615. if (getNumChildComponents() > 0)
  51616. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  51617. }
  51618. void PropertyComponent::enablementChanged()
  51619. {
  51620. repaint();
  51621. }
  51622. END_JUCE_NAMESPACE
  51623. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  51624. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  51625. BEGIN_JUCE_NAMESPACE
  51626. class PropertyHolderComponent : public Component
  51627. {
  51628. public:
  51629. PropertyHolderComponent()
  51630. {
  51631. }
  51632. ~PropertyHolderComponent()
  51633. {
  51634. deleteAllChildren();
  51635. }
  51636. void paint (Graphics&)
  51637. {
  51638. }
  51639. void updateLayout (const int width);
  51640. void refreshAll() const;
  51641. };
  51642. class PropertySectionComponent : public Component
  51643. {
  51644. public:
  51645. PropertySectionComponent (const String& sectionTitle,
  51646. const Array <PropertyComponent*>& newProperties,
  51647. const bool open)
  51648. : Component (sectionTitle),
  51649. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  51650. isOpen_ (open)
  51651. {
  51652. for (int i = newProperties.size(); --i >= 0;)
  51653. {
  51654. addAndMakeVisible (newProperties.getUnchecked(i));
  51655. newProperties.getUnchecked(i)->refresh();
  51656. }
  51657. }
  51658. ~PropertySectionComponent()
  51659. {
  51660. deleteAllChildren();
  51661. }
  51662. void paint (Graphics& g)
  51663. {
  51664. if (titleHeight > 0)
  51665. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  51666. }
  51667. void resized()
  51668. {
  51669. int y = titleHeight;
  51670. for (int i = getNumChildComponents(); --i >= 0;)
  51671. {
  51672. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51673. if (pec != 0)
  51674. {
  51675. const int prefH = pec->getPreferredHeight();
  51676. pec->setBounds (1, y, getWidth() - 2, prefH);
  51677. y += prefH;
  51678. }
  51679. }
  51680. }
  51681. int getPreferredHeight() const
  51682. {
  51683. int y = titleHeight;
  51684. if (isOpen())
  51685. {
  51686. for (int i = 0; i < getNumChildComponents(); ++i)
  51687. {
  51688. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51689. if (pec != 0)
  51690. y += pec->getPreferredHeight();
  51691. }
  51692. }
  51693. return y;
  51694. }
  51695. void setOpen (const bool open)
  51696. {
  51697. if (isOpen_ != open)
  51698. {
  51699. isOpen_ = open;
  51700. for (int i = 0; i < getNumChildComponents(); ++i)
  51701. {
  51702. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51703. if (pec != 0)
  51704. pec->setVisible (open);
  51705. }
  51706. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51707. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  51708. if (pp != 0)
  51709. pp->resized();
  51710. }
  51711. }
  51712. bool isOpen() const throw()
  51713. {
  51714. return isOpen_;
  51715. }
  51716. void refreshAll() const
  51717. {
  51718. for (int i = 0; i < getNumChildComponents(); ++i)
  51719. {
  51720. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51721. if (pec != 0)
  51722. pec->refresh();
  51723. }
  51724. }
  51725. void mouseDown (const MouseEvent&)
  51726. {
  51727. }
  51728. void mouseUp (const MouseEvent& e)
  51729. {
  51730. if (e.getMouseDownX() < titleHeight
  51731. && e.x < titleHeight
  51732. && e.y < titleHeight
  51733. && e.getNumberOfClicks() != 2)
  51734. {
  51735. setOpen (! isOpen());
  51736. }
  51737. }
  51738. void mouseDoubleClick (const MouseEvent& e)
  51739. {
  51740. if (e.y < titleHeight)
  51741. setOpen (! isOpen());
  51742. }
  51743. private:
  51744. int titleHeight;
  51745. bool isOpen_;
  51746. };
  51747. void PropertyHolderComponent::updateLayout (const int width)
  51748. {
  51749. int y = 0;
  51750. for (int i = getNumChildComponents(); --i >= 0;)
  51751. {
  51752. PropertySectionComponent* const section
  51753. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51754. if (section != 0)
  51755. {
  51756. const int prefH = section->getPreferredHeight();
  51757. section->setBounds (0, y, width, prefH);
  51758. y += prefH;
  51759. }
  51760. }
  51761. setSize (width, y);
  51762. repaint();
  51763. }
  51764. void PropertyHolderComponent::refreshAll() const
  51765. {
  51766. for (int i = getNumChildComponents(); --i >= 0;)
  51767. {
  51768. PropertySectionComponent* const section
  51769. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51770. if (section != 0)
  51771. section->refreshAll();
  51772. }
  51773. }
  51774. PropertyPanel::PropertyPanel()
  51775. {
  51776. messageWhenEmpty = TRANS("(nothing selected)");
  51777. addAndMakeVisible (viewport = new Viewport());
  51778. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  51779. viewport->setFocusContainer (true);
  51780. }
  51781. PropertyPanel::~PropertyPanel()
  51782. {
  51783. clear();
  51784. deleteAllChildren();
  51785. }
  51786. void PropertyPanel::paint (Graphics& g)
  51787. {
  51788. if (propertyHolderComponent->getNumChildComponents() == 0)
  51789. {
  51790. g.setColour (Colours::black.withAlpha (0.5f));
  51791. g.setFont (14.0f);
  51792. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  51793. Justification::centred, true);
  51794. }
  51795. }
  51796. void PropertyPanel::resized()
  51797. {
  51798. viewport->setBounds (0, 0, getWidth(), getHeight());
  51799. updatePropHolderLayout();
  51800. }
  51801. void PropertyPanel::clear()
  51802. {
  51803. if (propertyHolderComponent->getNumChildComponents() > 0)
  51804. {
  51805. propertyHolderComponent->deleteAllChildren();
  51806. repaint();
  51807. }
  51808. }
  51809. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  51810. {
  51811. if (propertyHolderComponent->getNumChildComponents() == 0)
  51812. repaint();
  51813. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  51814. newProperties,
  51815. true), 0);
  51816. updatePropHolderLayout();
  51817. }
  51818. void PropertyPanel::addSection (const String& sectionTitle,
  51819. const Array <PropertyComponent*>& newProperties,
  51820. const bool shouldBeOpen)
  51821. {
  51822. jassert (sectionTitle.isNotEmpty());
  51823. if (propertyHolderComponent->getNumChildComponents() == 0)
  51824. repaint();
  51825. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  51826. newProperties,
  51827. shouldBeOpen), 0);
  51828. updatePropHolderLayout();
  51829. }
  51830. void PropertyPanel::updatePropHolderLayout() const
  51831. {
  51832. const int maxWidth = viewport->getMaximumVisibleWidth();
  51833. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  51834. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  51835. if (maxWidth != newMaxWidth)
  51836. {
  51837. // need to do this twice because of scrollbars changing the size, etc.
  51838. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  51839. }
  51840. }
  51841. void PropertyPanel::refreshAll() const
  51842. {
  51843. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  51844. }
  51845. const StringArray PropertyPanel::getSectionNames() const
  51846. {
  51847. StringArray s;
  51848. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51849. {
  51850. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51851. if (section != 0 && section->getName().isNotEmpty())
  51852. s.add (section->getName());
  51853. }
  51854. return s;
  51855. }
  51856. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  51857. {
  51858. int index = 0;
  51859. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51860. {
  51861. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51862. if (section != 0 && section->getName().isNotEmpty())
  51863. {
  51864. if (index == sectionIndex)
  51865. return section->isOpen();
  51866. ++index;
  51867. }
  51868. }
  51869. return false;
  51870. }
  51871. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  51872. {
  51873. int index = 0;
  51874. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51875. {
  51876. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51877. if (section != 0 && section->getName().isNotEmpty())
  51878. {
  51879. if (index == sectionIndex)
  51880. {
  51881. section->setOpen (shouldBeOpen);
  51882. break;
  51883. }
  51884. ++index;
  51885. }
  51886. }
  51887. }
  51888. XmlElement* PropertyPanel::getOpennessState() const
  51889. {
  51890. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  51891. const StringArray sections (getSectionNames());
  51892. for (int i = 0; i < sections.size(); ++i)
  51893. {
  51894. if (sections[i].isNotEmpty())
  51895. {
  51896. XmlElement* const e = new XmlElement (T("SECTION"));
  51897. e->setAttribute (T("name"), sections[i]);
  51898. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  51899. xml->addChildElement (e);
  51900. }
  51901. }
  51902. return xml;
  51903. }
  51904. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  51905. {
  51906. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  51907. {
  51908. const StringArray sections (getSectionNames());
  51909. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  51910. {
  51911. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  51912. e->getBoolAttribute (T("open")));
  51913. }
  51914. }
  51915. }
  51916. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  51917. {
  51918. if (messageWhenEmpty != newMessage)
  51919. {
  51920. messageWhenEmpty = newMessage;
  51921. repaint();
  51922. }
  51923. }
  51924. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  51925. {
  51926. return messageWhenEmpty;
  51927. }
  51928. END_JUCE_NAMESPACE
  51929. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  51930. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  51931. BEGIN_JUCE_NAMESPACE
  51932. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  51933. const double rangeMin,
  51934. const double rangeMax,
  51935. const double interval,
  51936. const double skewFactor)
  51937. : PropertyComponent (name)
  51938. {
  51939. addAndMakeVisible (slider = new Slider (name));
  51940. slider->setRange (rangeMin, rangeMax, interval);
  51941. slider->setSkewFactor (skewFactor);
  51942. slider->setSliderStyle (Slider::LinearBar);
  51943. slider->addListener (this);
  51944. }
  51945. SliderPropertyComponent::~SliderPropertyComponent()
  51946. {
  51947. deleteAllChildren();
  51948. }
  51949. void SliderPropertyComponent::refresh()
  51950. {
  51951. slider->setValue (getValue(), false);
  51952. }
  51953. void SliderPropertyComponent::sliderValueChanged (Slider*)
  51954. {
  51955. if (getValue() != slider->getValue())
  51956. setValue (slider->getValue());
  51957. }
  51958. END_JUCE_NAMESPACE
  51959. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  51960. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  51961. BEGIN_JUCE_NAMESPACE
  51962. class TextPropLabel : public Label
  51963. {
  51964. TextPropertyComponent& owner;
  51965. int maxChars;
  51966. bool isMultiline;
  51967. public:
  51968. TextPropLabel (TextPropertyComponent& owner_,
  51969. const int maxChars_, const bool isMultiline_)
  51970. : Label (String::empty, String::empty),
  51971. owner (owner_),
  51972. maxChars (maxChars_),
  51973. isMultiline (isMultiline_)
  51974. {
  51975. setEditable (true, true, false);
  51976. setColour (backgroundColourId, Colours::white);
  51977. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  51978. }
  51979. ~TextPropLabel()
  51980. {
  51981. }
  51982. TextEditor* createEditorComponent()
  51983. {
  51984. TextEditor* const textEditor = Label::createEditorComponent();
  51985. textEditor->setInputRestrictions (maxChars);
  51986. if (isMultiline)
  51987. {
  51988. textEditor->setMultiLine (true, true);
  51989. textEditor->setReturnKeyStartsNewLine (true);
  51990. }
  51991. return textEditor;
  51992. }
  51993. void textWasEdited()
  51994. {
  51995. owner.textWasEdited();
  51996. }
  51997. };
  51998. TextPropertyComponent::TextPropertyComponent (const String& name,
  51999. const int maxNumChars,
  52000. const bool isMultiLine)
  52001. : PropertyComponent (name)
  52002. {
  52003. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  52004. if (isMultiLine)
  52005. {
  52006. textEditor->setJustificationType (Justification::topLeft);
  52007. preferredHeight = 120;
  52008. }
  52009. }
  52010. TextPropertyComponent::~TextPropertyComponent()
  52011. {
  52012. deleteAllChildren();
  52013. }
  52014. void TextPropertyComponent::refresh()
  52015. {
  52016. textEditor->setText (getText(), false);
  52017. }
  52018. void TextPropertyComponent::textWasEdited()
  52019. {
  52020. const String newText (textEditor->getText());
  52021. if (getText() != newText)
  52022. setText (newText);
  52023. }
  52024. END_JUCE_NAMESPACE
  52025. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  52026. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52027. BEGIN_JUCE_NAMESPACE
  52028. class AudioDeviceSelectorComponentListBox : public ListBox,
  52029. public ListBoxModel
  52030. {
  52031. public:
  52032. enum BoxType
  52033. {
  52034. midiInputType,
  52035. audioInputType,
  52036. audioOutputType
  52037. };
  52038. AudioDeviceSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  52039. const BoxType type_,
  52040. const String& noItemsMessage_,
  52041. const int minNumber_,
  52042. const int maxNumber_)
  52043. : ListBox (String::empty, 0),
  52044. deviceManager (deviceManager_),
  52045. type (type_),
  52046. noItemsMessage (noItemsMessage_),
  52047. minNumber (minNumber_),
  52048. maxNumber (maxNumber_)
  52049. {
  52050. AudioIODevice* const currentDevice = deviceManager.getCurrentAudioDevice();
  52051. if (type_ == midiInputType)
  52052. {
  52053. items = MidiInput::getDevices();
  52054. }
  52055. else if (type_ == audioInputType)
  52056. {
  52057. items = currentDevice->getInputChannelNames();
  52058. }
  52059. else if (type_ == audioOutputType)
  52060. {
  52061. items = currentDevice->getOutputChannelNames();
  52062. }
  52063. else
  52064. {
  52065. jassertfalse
  52066. }
  52067. setModel (this);
  52068. setOutlineThickness (1);
  52069. }
  52070. ~AudioDeviceSelectorComponentListBox()
  52071. {
  52072. }
  52073. int getNumRows()
  52074. {
  52075. return items.size();
  52076. }
  52077. void paintListBoxItem (int row,
  52078. Graphics& g,
  52079. int width, int height,
  52080. bool rowIsSelected)
  52081. {
  52082. if (((unsigned int) row) < (unsigned int) items.size())
  52083. {
  52084. if (rowIsSelected)
  52085. g.fillAll (findColour (TextEditor::highlightColourId)
  52086. .withMultipliedAlpha (0.3f));
  52087. const String item (items [row]);
  52088. bool enabled = false;
  52089. if (type == midiInputType)
  52090. {
  52091. enabled = deviceManager.isMidiInputEnabled (item);
  52092. }
  52093. else if (type == audioInputType)
  52094. {
  52095. enabled = deviceManager.getInputChannels() [row];
  52096. }
  52097. else if (type == audioOutputType)
  52098. {
  52099. enabled = deviceManager.getOutputChannels() [row];
  52100. }
  52101. const int x = getTickX();
  52102. const int tickW = height - height / 4;
  52103. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52104. enabled, true, true, false);
  52105. g.setFont (height * 0.6f);
  52106. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52107. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52108. }
  52109. }
  52110. void listBoxItemClicked (int row, const MouseEvent& e)
  52111. {
  52112. selectRow (row);
  52113. if (e.x < getTickX())
  52114. flipEnablement (row);
  52115. }
  52116. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52117. {
  52118. flipEnablement (row);
  52119. }
  52120. void returnKeyPressed (int row)
  52121. {
  52122. flipEnablement (row);
  52123. }
  52124. void paint (Graphics& g)
  52125. {
  52126. ListBox::paint (g);
  52127. if (items.size() == 0)
  52128. {
  52129. g.setColour (Colours::grey);
  52130. g.setFont (13.0f);
  52131. g.drawText (noItemsMessage,
  52132. 0, 0, getWidth(), getHeight() / 2,
  52133. Justification::centred, true);
  52134. }
  52135. }
  52136. int getBestHeight (const int preferredHeight)
  52137. {
  52138. const int extra = getOutlineThickness() * 2;
  52139. return jmax (getRowHeight() * 2 + extra,
  52140. jmin (getRowHeight() * getNumRows() + extra,
  52141. preferredHeight));
  52142. }
  52143. juce_UseDebuggingNewOperator
  52144. private:
  52145. AudioDeviceManager& deviceManager;
  52146. const BoxType type;
  52147. const String noItemsMessage;
  52148. StringArray items;
  52149. int minNumber, maxNumber;
  52150. void flipEnablement (const int row)
  52151. {
  52152. if (((unsigned int) row) < (unsigned int) items.size())
  52153. {
  52154. AudioIODevice* const audioDevice = deviceManager.getCurrentAudioDevice();
  52155. const String item (items [row]);
  52156. if (type == midiInputType)
  52157. {
  52158. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  52159. }
  52160. else
  52161. {
  52162. jassert (type == audioInputType || type == audioOutputType);
  52163. if (audioDevice != 0)
  52164. {
  52165. BitArray chans (type == audioInputType ? deviceManager.getInputChannels()
  52166. : deviceManager.getOutputChannels());
  52167. const BitArray oldChans (chans);
  52168. const bool newVal = ! chans[row];
  52169. const int numActive = chans.countNumberOfSetBits();
  52170. if (! newVal)
  52171. {
  52172. if (numActive > minNumber)
  52173. chans.setBit (row, false);
  52174. }
  52175. else
  52176. {
  52177. if (numActive >= maxNumber)
  52178. {
  52179. const int firstActiveChan = chans.findNextSetBit();
  52180. chans.setBit (row > firstActiveChan
  52181. ? firstActiveChan : chans.getHighestBit(),
  52182. false);
  52183. }
  52184. chans.setBit (row, true);
  52185. }
  52186. if (type == audioInputType)
  52187. deviceManager.setInputChannels (chans, true);
  52188. else
  52189. deviceManager.setOutputChannels (chans, true);
  52190. }
  52191. }
  52192. }
  52193. }
  52194. int getTickX() const throw()
  52195. {
  52196. return getRowHeight() + 5;
  52197. }
  52198. AudioDeviceSelectorComponentListBox (const AudioDeviceSelectorComponentListBox&);
  52199. const AudioDeviceSelectorComponentListBox& operator= (const AudioDeviceSelectorComponentListBox&);
  52200. };
  52201. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  52202. const int minInputChannels_,
  52203. const int maxInputChannels_,
  52204. const int minOutputChannels_,
  52205. const int maxOutputChannels_,
  52206. const bool showMidiInputOptions,
  52207. const bool showMidiOutputSelector)
  52208. : deviceManager (deviceManager_),
  52209. minOutputChannels (minOutputChannels_),
  52210. maxOutputChannels (maxOutputChannels_),
  52211. minInputChannels (minInputChannels_),
  52212. maxInputChannels (maxInputChannels_),
  52213. sampleRateDropDown (0),
  52214. inputChansBox (0),
  52215. inputsLabel (0),
  52216. outputChansBox (0),
  52217. outputsLabel (0),
  52218. sampleRateLabel (0),
  52219. bufferSizeDropDown (0),
  52220. bufferSizeLabel (0),
  52221. launchUIButton (0)
  52222. {
  52223. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  52224. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  52225. audioDeviceDropDown = new ComboBox ("device");
  52226. deviceManager_.addDeviceNamesToComboBox (*audioDeviceDropDown);
  52227. audioDeviceDropDown->setSelectedId (-1, true);
  52228. if (deviceManager_.getCurrentAudioDeviceName().isNotEmpty())
  52229. audioDeviceDropDown->setText (deviceManager_.getCurrentAudioDeviceName(), true);
  52230. audioDeviceDropDown->addListener (this);
  52231. addAndMakeVisible (audioDeviceDropDown);
  52232. Label* label = new Label ("l1", TRANS ("audio device:"));
  52233. label->attachToComponent (audioDeviceDropDown, true);
  52234. if (showMidiInputOptions)
  52235. {
  52236. addAndMakeVisible (midiInputsList
  52237. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52238. AudioDeviceSelectorComponentListBox::midiInputType,
  52239. TRANS("(no midi inputs available)"),
  52240. 0, 0));
  52241. midiInputsLabel = new Label ("lm", TRANS ("active midi inputs:"));
  52242. midiInputsLabel->setJustificationType (Justification::topRight);
  52243. midiInputsLabel->attachToComponent (midiInputsList, true);
  52244. }
  52245. else
  52246. {
  52247. midiInputsList = 0;
  52248. midiInputsLabel = 0;
  52249. }
  52250. if (showMidiOutputSelector)
  52251. {
  52252. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  52253. midiOutputSelector->addListener (this);
  52254. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  52255. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  52256. }
  52257. else
  52258. {
  52259. midiOutputSelector = 0;
  52260. midiOutputLabel = 0;
  52261. }
  52262. deviceManager_.addChangeListener (this);
  52263. changeListenerCallback (0);
  52264. }
  52265. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  52266. {
  52267. deviceManager.removeChangeListener (this);
  52268. deleteAllChildren();
  52269. }
  52270. void AudioDeviceSelectorComponent::resized()
  52271. {
  52272. const int lx = proportionOfWidth (0.35f);
  52273. const int w = proportionOfWidth (0.55f);
  52274. const int h = 24;
  52275. const int space = 6;
  52276. const int dh = h + space;
  52277. int y = 15;
  52278. audioDeviceDropDown->setBounds (lx, y, w, h);
  52279. y += dh;
  52280. if (sampleRateDropDown != 0)
  52281. {
  52282. sampleRateDropDown->setBounds (lx, y, w, h);
  52283. y += dh;
  52284. }
  52285. if (bufferSizeDropDown != 0)
  52286. {
  52287. bufferSizeDropDown->setBounds (lx, y, w, h);
  52288. y += dh;
  52289. }
  52290. if (launchUIButton != 0)
  52291. {
  52292. launchUIButton->setBounds (lx, y, 150, h);
  52293. ((TextButton*) launchUIButton)->changeWidthToFitText();
  52294. y += dh;
  52295. }
  52296. VoidArray boxes;
  52297. if (outputChansBox != 0)
  52298. boxes.add (outputChansBox);
  52299. if (inputChansBox != 0)
  52300. boxes.add (inputChansBox);
  52301. if (midiInputsList != 0)
  52302. boxes.add (midiInputsList);
  52303. const int boxSpace = getHeight() - y;
  52304. for (int i = 0; i < boxes.size(); ++i)
  52305. {
  52306. AudioDeviceSelectorComponentListBox* const box = (AudioDeviceSelectorComponentListBox*) boxes.getUnchecked (i);
  52307. const int bh = box->getBestHeight (jmin (h * 8, boxSpace / boxes.size()) - space);
  52308. box->setBounds (lx, y, w, bh);
  52309. y += bh + space;
  52310. }
  52311. if (midiOutputSelector != 0)
  52312. midiOutputSelector->setBounds (lx, y, w, h);
  52313. }
  52314. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  52315. {
  52316. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  52317. if (device != 0 && device->hasControlPanel())
  52318. {
  52319. const String lastDevice (device->getName());
  52320. if (device->showControlPanel())
  52321. {
  52322. deviceManager.setAudioDevice (String::empty, 0, 0, 0, 0, false);
  52323. deviceManager.setAudioDevice (lastDevice, 0, 0, 0, 0, false);
  52324. }
  52325. getTopLevelComponent()->toFront (true);
  52326. }
  52327. }
  52328. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  52329. {
  52330. AudioIODevice* const audioDevice = deviceManager.getCurrentAudioDevice();
  52331. if (comboBoxThatHasChanged == audioDeviceDropDown)
  52332. {
  52333. if (audioDeviceDropDown->getSelectedId() < 0)
  52334. {
  52335. deviceManager.setAudioDevice (String::empty, 0, 0, 0, 0, true);
  52336. }
  52337. else
  52338. {
  52339. String error (deviceManager.setAudioDevice (audioDeviceDropDown->getText(),
  52340. 0, 0, 0, 0, true));
  52341. if (error.isNotEmpty())
  52342. {
  52343. #if JUCE_WIN32
  52344. if (deviceManager.getInputChannels().countNumberOfSetBits() > 0
  52345. && deviceManager.getOutputChannels().countNumberOfSetBits() > 0)
  52346. {
  52347. // in DSound, some machines lose their primary input device when a mic
  52348. // is removed, and this also buggers up our attempt at opening an output
  52349. // device, so this is a workaround that doesn't fail in that case.
  52350. BitArray noInputs;
  52351. error = deviceManager.setAudioDevice (audioDeviceDropDown->getText(),
  52352. 0, 0, &noInputs, 0, false);
  52353. }
  52354. #endif
  52355. if (error.isNotEmpty())
  52356. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  52357. T("Error while opening \"")
  52358. + audioDeviceDropDown->getText()
  52359. + T("\""),
  52360. error);
  52361. }
  52362. }
  52363. if (deviceManager.getCurrentAudioDeviceName().isNotEmpty())
  52364. audioDeviceDropDown->setText (deviceManager.getCurrentAudioDeviceName(), true);
  52365. else
  52366. audioDeviceDropDown->setSelectedId (-1, true);
  52367. }
  52368. else if (comboBoxThatHasChanged == midiOutputSelector)
  52369. {
  52370. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  52371. }
  52372. else if (audioDevice != 0)
  52373. {
  52374. if (bufferSizeDropDown != 0 && comboBoxThatHasChanged == bufferSizeDropDown)
  52375. {
  52376. if (bufferSizeDropDown->getSelectedId() > 0)
  52377. deviceManager.setAudioDevice (audioDevice->getName(),
  52378. bufferSizeDropDown->getSelectedId(),
  52379. audioDevice->getCurrentSampleRate(),
  52380. 0, 0, true);
  52381. }
  52382. else if (sampleRateDropDown != 0 && comboBoxThatHasChanged == sampleRateDropDown)
  52383. {
  52384. if (sampleRateDropDown->getSelectedId() > 0)
  52385. deviceManager.setAudioDevice (audioDevice->getName(),
  52386. audioDevice->getCurrentBufferSizeSamples(),
  52387. sampleRateDropDown->getSelectedId(),
  52388. 0, 0, true);
  52389. }
  52390. }
  52391. }
  52392. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  52393. {
  52394. deleteAndZero (sampleRateDropDown);
  52395. deleteAndZero (inputChansBox);
  52396. deleteAndZero (inputsLabel);
  52397. deleteAndZero (outputChansBox);
  52398. deleteAndZero (outputsLabel);
  52399. deleteAndZero (sampleRateLabel);
  52400. deleteAndZero (bufferSizeDropDown);
  52401. deleteAndZero (bufferSizeLabel);
  52402. deleteAndZero (launchUIButton);
  52403. AudioIODevice* const currentDevice = deviceManager.getCurrentAudioDevice();
  52404. if (currentDevice != 0)
  52405. {
  52406. audioDeviceDropDown->setText (currentDevice->getName(), true);
  52407. // sample rate
  52408. addAndMakeVisible (sampleRateDropDown = new ComboBox ("samplerate"));
  52409. sampleRateLabel = new Label ("l2", TRANS ("sample rate:"));
  52410. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  52411. const int numRates = currentDevice->getNumSampleRates();
  52412. int i;
  52413. for (i = 0; i < numRates; ++i)
  52414. {
  52415. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  52416. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  52417. }
  52418. const double currentRate = currentDevice->getCurrentSampleRate();
  52419. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentRate), true);
  52420. sampleRateDropDown->addListener (this);
  52421. // buffer size
  52422. addAndMakeVisible (bufferSizeDropDown = new ComboBox ("buffersize"));
  52423. bufferSizeLabel = new Label ("l2", TRANS ("audio buffer size:"));
  52424. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  52425. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  52426. for (i = 0; i < numBufferSizes; ++i)
  52427. {
  52428. const int bs = currentDevice->getBufferSizeSamples (i);
  52429. bufferSizeDropDown->addItem (String (bs)
  52430. + T(" samples (")
  52431. + String (bs * 1000.0 / currentRate, 1)
  52432. + T(" ms)"),
  52433. bs);
  52434. }
  52435. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  52436. bufferSizeDropDown->addListener (this);
  52437. if (currentDevice->hasControlPanel())
  52438. {
  52439. addAndMakeVisible (launchUIButton = new TextButton (TRANS ("show this device's control panel"),
  52440. TRANS ("opens the device's own control panel")));
  52441. launchUIButton->addButtonListener (this);
  52442. }
  52443. // output chans
  52444. if (maxOutputChannels > 0 && minOutputChannels < currentDevice->getOutputChannelNames().size())
  52445. {
  52446. addAndMakeVisible (outputChansBox
  52447. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52448. AudioDeviceSelectorComponentListBox::audioOutputType,
  52449. TRANS ("(no audio output channels found)"),
  52450. minOutputChannels, maxOutputChannels));
  52451. outputsLabel = new Label ("l3", TRANS ("active output channels:"));
  52452. outputsLabel->attachToComponent (outputChansBox, true);
  52453. }
  52454. // input chans
  52455. if (maxInputChannels > 0 && minInputChannels < currentDevice->getInputChannelNames().size())
  52456. {
  52457. addAndMakeVisible (inputChansBox
  52458. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52459. AudioDeviceSelectorComponentListBox::audioInputType,
  52460. TRANS ("(no audio input channels found)"),
  52461. minInputChannels, maxInputChannels));
  52462. inputsLabel = new Label ("l4", TRANS ("active input channels:"));
  52463. inputsLabel->attachToComponent (inputChansBox, true);
  52464. }
  52465. }
  52466. else
  52467. {
  52468. audioDeviceDropDown->setSelectedId (-1, true);
  52469. }
  52470. if (midiInputsList != 0)
  52471. {
  52472. midiInputsList->updateContent();
  52473. midiInputsList->repaint();
  52474. }
  52475. if (midiOutputSelector != 0)
  52476. {
  52477. midiOutputSelector->clear();
  52478. const StringArray midiOuts (MidiOutput::getDevices());
  52479. midiOutputSelector->addItem (TRANS("<< no audio device >>"), -1);
  52480. midiOutputSelector->addSeparator();
  52481. for (int i = 0; i < midiOuts.size(); ++i)
  52482. midiOutputSelector->addItem (midiOuts[i], i + 1);
  52483. int current = -1;
  52484. if (deviceManager.getDefaultMidiOutput() != 0)
  52485. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  52486. midiOutputSelector->setSelectedId (current, true);
  52487. }
  52488. resized();
  52489. }
  52490. END_JUCE_NAMESPACE
  52491. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52492. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  52493. BEGIN_JUCE_NAMESPACE
  52494. BubbleComponent::BubbleComponent()
  52495. : side (0),
  52496. allowablePlacements (above | below | left | right),
  52497. arrowTipX (0.0f),
  52498. arrowTipY (0.0f)
  52499. {
  52500. setInterceptsMouseClicks (false, false);
  52501. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  52502. setComponentEffect (&shadow);
  52503. }
  52504. BubbleComponent::~BubbleComponent()
  52505. {
  52506. }
  52507. void BubbleComponent::paint (Graphics& g)
  52508. {
  52509. int x = content.getX();
  52510. int y = content.getY();
  52511. int w = content.getWidth();
  52512. int h = content.getHeight();
  52513. int cw, ch;
  52514. getContentSize (cw, ch);
  52515. if (side == 3)
  52516. x += w - cw;
  52517. else if (side != 1)
  52518. x += (w - cw) / 2;
  52519. w = cw;
  52520. if (side == 2)
  52521. y += h - ch;
  52522. else if (side != 0)
  52523. y += (h - ch) / 2;
  52524. h = ch;
  52525. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  52526. (float) x, (float) y,
  52527. (float) w, (float) h);
  52528. const int cx = x + (w - cw) / 2;
  52529. const int cy = y + (h - ch) / 2;
  52530. const int indent = 3;
  52531. g.setOrigin (cx + indent, cy + indent);
  52532. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  52533. paintContent (g, cw - indent * 2, ch - indent * 2);
  52534. }
  52535. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  52536. {
  52537. allowablePlacements = newPlacement;
  52538. }
  52539. void BubbleComponent::setPosition (Component* componentToPointTo)
  52540. {
  52541. jassert (componentToPointTo->isValidComponent());
  52542. int tx = 0;
  52543. int ty = 0;
  52544. if (getParentComponent() != 0)
  52545. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  52546. else
  52547. componentToPointTo->relativePositionToGlobal (tx, ty);
  52548. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  52549. }
  52550. void BubbleComponent::setPosition (const int arrowTipX,
  52551. const int arrowTipY)
  52552. {
  52553. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  52554. }
  52555. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  52556. {
  52557. Rectangle availableSpace;
  52558. if (getParentComponent() != 0)
  52559. {
  52560. availableSpace.setSize (getParentComponent()->getWidth(),
  52561. getParentComponent()->getHeight());
  52562. }
  52563. else
  52564. {
  52565. availableSpace = getParentMonitorArea();
  52566. }
  52567. int x = 0;
  52568. int y = 0;
  52569. int w = 150;
  52570. int h = 30;
  52571. getContentSize (w, h);
  52572. w += 30;
  52573. h += 30;
  52574. const float edgeIndent = 2.0f;
  52575. const int arrowLength = jmin (10, h / 3, w / 3);
  52576. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  52577. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  52578. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  52579. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  52580. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  52581. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  52582. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  52583. {
  52584. spaceLeft = spaceRight = 0;
  52585. }
  52586. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  52587. && (spaceLeft > w + 20 || spaceRight > w + 20))
  52588. {
  52589. spaceAbove = spaceBelow = 0;
  52590. }
  52591. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  52592. {
  52593. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  52594. arrowTipX = w * 0.5f;
  52595. content.setSize (w, h - arrowLength);
  52596. if (spaceAbove >= spaceBelow)
  52597. {
  52598. // above
  52599. y = rectangleToPointTo.getY() - h;
  52600. content.setPosition (0, 0);
  52601. arrowTipY = h - edgeIndent;
  52602. side = 2;
  52603. }
  52604. else
  52605. {
  52606. // below
  52607. y = rectangleToPointTo.getBottom();
  52608. content.setPosition (0, arrowLength);
  52609. arrowTipY = edgeIndent;
  52610. side = 0;
  52611. }
  52612. }
  52613. else
  52614. {
  52615. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  52616. arrowTipY = h * 0.5f;
  52617. content.setSize (w - arrowLength, h);
  52618. if (spaceLeft > spaceRight)
  52619. {
  52620. // on the left
  52621. x = rectangleToPointTo.getX() - w;
  52622. content.setPosition (0, 0);
  52623. arrowTipX = w - edgeIndent;
  52624. side = 3;
  52625. }
  52626. else
  52627. {
  52628. // on the right
  52629. x = rectangleToPointTo.getRight();
  52630. content.setPosition (arrowLength, 0);
  52631. arrowTipX = edgeIndent;
  52632. side = 1;
  52633. }
  52634. }
  52635. setBounds (x, y, w, h);
  52636. }
  52637. END_JUCE_NAMESPACE
  52638. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  52639. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  52640. BEGIN_JUCE_NAMESPACE
  52641. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  52642. : fadeOutLength (fadeOutLengthMs),
  52643. deleteAfterUse (false)
  52644. {
  52645. }
  52646. BubbleMessageComponent::~BubbleMessageComponent()
  52647. {
  52648. fadeOutComponent (fadeOutLength);
  52649. }
  52650. void BubbleMessageComponent::showAt (int x, int y,
  52651. const String& text,
  52652. const int numMillisecondsBeforeRemoving,
  52653. const bool removeWhenMouseClicked,
  52654. const bool deleteSelfAfterUse)
  52655. {
  52656. textLayout.clear();
  52657. textLayout.setText (text, Font (14.0f));
  52658. textLayout.layout (256, Justification::centredLeft, true);
  52659. setPosition (x, y);
  52660. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  52661. }
  52662. void BubbleMessageComponent::showAt (Component* const component,
  52663. const String& text,
  52664. const int numMillisecondsBeforeRemoving,
  52665. const bool removeWhenMouseClicked,
  52666. const bool deleteSelfAfterUse)
  52667. {
  52668. textLayout.clear();
  52669. textLayout.setText (text, Font (14.0f));
  52670. textLayout.layout (256, Justification::centredLeft, true);
  52671. setPosition (component);
  52672. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  52673. }
  52674. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  52675. const bool removeWhenMouseClicked,
  52676. const bool deleteSelfAfterUse)
  52677. {
  52678. setVisible (true);
  52679. deleteAfterUse = deleteSelfAfterUse;
  52680. if (numMillisecondsBeforeRemoving > 0)
  52681. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  52682. else
  52683. expiryTime = 0;
  52684. startTimer (77);
  52685. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  52686. if (! (removeWhenMouseClicked && isShowing()))
  52687. mouseClickCounter += 0xfffff;
  52688. repaint();
  52689. }
  52690. void BubbleMessageComponent::getContentSize (int& w, int& h)
  52691. {
  52692. w = textLayout.getWidth() + 16;
  52693. h = textLayout.getHeight() + 16;
  52694. }
  52695. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  52696. {
  52697. g.setColour (findColour (TooltipWindow::textColourId));
  52698. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  52699. }
  52700. void BubbleMessageComponent::timerCallback()
  52701. {
  52702. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  52703. {
  52704. stopTimer();
  52705. setVisible (false);
  52706. if (deleteAfterUse)
  52707. delete this;
  52708. }
  52709. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  52710. {
  52711. stopTimer();
  52712. fadeOutComponent (fadeOutLength);
  52713. if (deleteAfterUse)
  52714. delete this;
  52715. }
  52716. }
  52717. END_JUCE_NAMESPACE
  52718. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  52719. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  52720. BEGIN_JUCE_NAMESPACE
  52721. static const int swatchesPerRow = 8;
  52722. static const int swatchHeight = 22;
  52723. class ColourComponentSlider : public Slider
  52724. {
  52725. public:
  52726. ColourComponentSlider (const String& name)
  52727. : Slider (name)
  52728. {
  52729. setRange (0.0, 255.0, 1.0);
  52730. }
  52731. ~ColourComponentSlider()
  52732. {
  52733. }
  52734. const String getTextFromValue (double currentValue)
  52735. {
  52736. return String::formatted (T("%02X"), (int)currentValue);
  52737. }
  52738. double getValueFromText (const String& text)
  52739. {
  52740. return (double) text.getHexValue32();
  52741. }
  52742. private:
  52743. ColourComponentSlider (const ColourComponentSlider&);
  52744. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  52745. };
  52746. class ColourSpaceMarker : public Component
  52747. {
  52748. public:
  52749. ColourSpaceMarker()
  52750. {
  52751. setInterceptsMouseClicks (false, false);
  52752. }
  52753. ~ColourSpaceMarker()
  52754. {
  52755. }
  52756. void paint (Graphics& g)
  52757. {
  52758. g.setColour (Colour::greyLevel (0.1f));
  52759. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  52760. g.setColour (Colour::greyLevel (0.9f));
  52761. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  52762. }
  52763. private:
  52764. ColourSpaceMarker (const ColourSpaceMarker&);
  52765. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  52766. };
  52767. class ColourSpaceView : public Component
  52768. {
  52769. ColourSelector* const owner;
  52770. float& h;
  52771. float& s;
  52772. float& v;
  52773. float lastHue;
  52774. ColourSpaceMarker* marker;
  52775. const int edge;
  52776. public:
  52777. ColourSpaceView (ColourSelector* owner_,
  52778. float& h_, float& s_, float& v_,
  52779. const int edgeSize)
  52780. : owner (owner_),
  52781. h (h_), s (s_), v (v_),
  52782. lastHue (0.0f),
  52783. edge (edgeSize)
  52784. {
  52785. addAndMakeVisible (marker = new ColourSpaceMarker());
  52786. setMouseCursor (MouseCursor::CrosshairCursor);
  52787. }
  52788. ~ColourSpaceView()
  52789. {
  52790. deleteAllChildren();
  52791. }
  52792. void paint (Graphics& g)
  52793. {
  52794. const float hue = h;
  52795. const float xScale = 1.0f / (getWidth() - edge * 2);
  52796. const float yScale = 1.0f / (getHeight() - edge * 2);
  52797. const Rectangle clip (g.getClipBounds());
  52798. const int x1 = jmax (clip.getX(), edge) & ~1;
  52799. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  52800. const int y1 = jmax (clip.getY(), edge) & ~1;
  52801. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  52802. for (int y = y1; y < y2; y += 2)
  52803. {
  52804. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  52805. for (int x = x1; x < x2; x += 2)
  52806. {
  52807. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  52808. g.setColour (Colour (hue, s, v, 1.0f));
  52809. g.fillRect (x, y, 2, 2);
  52810. }
  52811. }
  52812. }
  52813. void mouseDown (const MouseEvent& e)
  52814. {
  52815. mouseDrag (e);
  52816. }
  52817. void mouseDrag (const MouseEvent& e)
  52818. {
  52819. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  52820. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  52821. owner->setSV (s, v);
  52822. }
  52823. void updateIfNeeded()
  52824. {
  52825. if (lastHue != h)
  52826. {
  52827. lastHue = h;
  52828. repaint();
  52829. }
  52830. resized();
  52831. }
  52832. void resized()
  52833. {
  52834. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  52835. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  52836. edge * 2, edge * 2);
  52837. }
  52838. private:
  52839. ColourSpaceView (const ColourSpaceView&);
  52840. const ColourSpaceView& operator= (const ColourSpaceView&);
  52841. };
  52842. class HueSelectorMarker : public Component
  52843. {
  52844. public:
  52845. HueSelectorMarker()
  52846. {
  52847. setInterceptsMouseClicks (false, false);
  52848. }
  52849. ~HueSelectorMarker()
  52850. {
  52851. }
  52852. void paint (Graphics& g)
  52853. {
  52854. Path p;
  52855. p.addTriangle (1.0f, 1.0f,
  52856. getWidth() * 0.3f, getHeight() * 0.5f,
  52857. 1.0f, getHeight() - 1.0f);
  52858. p.addTriangle (getWidth() - 1.0f, 1.0f,
  52859. getWidth() * 0.7f, getHeight() * 0.5f,
  52860. getWidth() - 1.0f, getHeight() - 1.0f);
  52861. g.setColour (Colours::white.withAlpha (0.75f));
  52862. g.fillPath (p);
  52863. g.setColour (Colours::black.withAlpha (0.75f));
  52864. g.strokePath (p, PathStrokeType (1.2f));
  52865. }
  52866. private:
  52867. HueSelectorMarker (const HueSelectorMarker&);
  52868. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  52869. };
  52870. class HueSelectorComp : public Component
  52871. {
  52872. public:
  52873. HueSelectorComp (ColourSelector* owner_,
  52874. float& h_, float& s_, float& v_,
  52875. const int edgeSize)
  52876. : owner (owner_),
  52877. h (h_), s (s_), v (v_),
  52878. lastHue (0.0f),
  52879. edge (edgeSize)
  52880. {
  52881. addAndMakeVisible (marker = new HueSelectorMarker());
  52882. }
  52883. ~HueSelectorComp()
  52884. {
  52885. deleteAllChildren();
  52886. }
  52887. void paint (Graphics& g)
  52888. {
  52889. const float yScale = 1.0f / (getHeight() - edge * 2);
  52890. const Rectangle clip (g.getClipBounds());
  52891. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  52892. {
  52893. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  52894. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  52895. }
  52896. }
  52897. void resized()
  52898. {
  52899. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  52900. getWidth(), edge * 2);
  52901. }
  52902. void mouseDown (const MouseEvent& e)
  52903. {
  52904. mouseDrag (e);
  52905. }
  52906. void mouseDrag (const MouseEvent& e)
  52907. {
  52908. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  52909. owner->setHue (hue);
  52910. }
  52911. void updateIfNeeded()
  52912. {
  52913. resized();
  52914. }
  52915. private:
  52916. ColourSelector* const owner;
  52917. float& h;
  52918. float& s;
  52919. float& v;
  52920. float lastHue;
  52921. HueSelectorMarker* marker;
  52922. const int edge;
  52923. HueSelectorComp (const HueSelectorComp&);
  52924. const HueSelectorComp& operator= (const HueSelectorComp&);
  52925. };
  52926. class SwatchComponent : public Component
  52927. {
  52928. public:
  52929. SwatchComponent (ColourSelector* owner_, int index_)
  52930. : owner (owner_),
  52931. index (index_)
  52932. {
  52933. }
  52934. ~SwatchComponent()
  52935. {
  52936. }
  52937. void paint (Graphics& g)
  52938. {
  52939. const Colour colour (owner->getSwatchColour (index));
  52940. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  52941. 6, 6,
  52942. Colour (0xffdddddd).overlaidWith (colour),
  52943. Colour (0xffffffff).overlaidWith (colour));
  52944. }
  52945. void mouseDown (const MouseEvent&)
  52946. {
  52947. PopupMenu m;
  52948. m.addItem (1, TRANS("Use this swatch as the current colour"));
  52949. m.addSeparator();
  52950. m.addItem (2, TRANS("Set this swatch to the current colour"));
  52951. const int r = m.showAt (this);
  52952. if (r == 1)
  52953. {
  52954. owner->setCurrentColour (owner->getSwatchColour (index));
  52955. }
  52956. else if (r == 2)
  52957. {
  52958. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  52959. {
  52960. owner->setSwatchColour (index, owner->getCurrentColour());
  52961. repaint();
  52962. }
  52963. }
  52964. }
  52965. private:
  52966. ColourSelector* const owner;
  52967. const int index;
  52968. SwatchComponent (const SwatchComponent&);
  52969. const SwatchComponent& operator= (const SwatchComponent&);
  52970. };
  52971. ColourSelector::ColourSelector (const int flags_,
  52972. const int edgeGap_,
  52973. const int gapAroundColourSpaceComponent)
  52974. : colour (Colours::white),
  52975. flags (flags_),
  52976. topSpace (0),
  52977. edgeGap (edgeGap_)
  52978. {
  52979. // not much point having a selector with no components in it!
  52980. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  52981. updateHSV();
  52982. if ((flags & showSliders) != 0)
  52983. {
  52984. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  52985. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  52986. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  52987. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  52988. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  52989. for (int i = 4; --i >= 0;)
  52990. sliders[i]->addListener (this);
  52991. }
  52992. else
  52993. {
  52994. zeromem (sliders, sizeof (sliders));
  52995. }
  52996. if ((flags & showColourspace) != 0)
  52997. {
  52998. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  52999. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  53000. }
  53001. else
  53002. {
  53003. colourSpace = 0;
  53004. hueSelector = 0;
  53005. }
  53006. update();
  53007. }
  53008. ColourSelector::~ColourSelector()
  53009. {
  53010. dispatchPendingMessages();
  53011. deleteAllChildren();
  53012. }
  53013. const Colour ColourSelector::getCurrentColour() const
  53014. {
  53015. return ((flags & showAlphaChannel) != 0) ? colour
  53016. : colour.withAlpha ((uint8) 0xff);
  53017. }
  53018. void ColourSelector::setCurrentColour (const Colour& c)
  53019. {
  53020. if (c != colour)
  53021. {
  53022. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  53023. updateHSV();
  53024. update();
  53025. }
  53026. }
  53027. void ColourSelector::setHue (float newH)
  53028. {
  53029. newH = jlimit (0.0f, 1.0f, newH);
  53030. if (h != newH)
  53031. {
  53032. h = newH;
  53033. colour = Colour (h, s, v, colour.getFloatAlpha());
  53034. update();
  53035. }
  53036. }
  53037. void ColourSelector::setSV (float newS, float newV)
  53038. {
  53039. newS = jlimit (0.0f, 1.0f, newS);
  53040. newV = jlimit (0.0f, 1.0f, newV);
  53041. if (s != newS || v != newV)
  53042. {
  53043. s = newS;
  53044. v = newV;
  53045. colour = Colour (h, s, v, colour.getFloatAlpha());
  53046. update();
  53047. }
  53048. }
  53049. void ColourSelector::updateHSV()
  53050. {
  53051. colour.getHSB (h, s, v);
  53052. }
  53053. void ColourSelector::update()
  53054. {
  53055. if (sliders[0] != 0)
  53056. {
  53057. sliders[0]->setValue ((int) colour.getRed());
  53058. sliders[1]->setValue ((int) colour.getGreen());
  53059. sliders[2]->setValue ((int) colour.getBlue());
  53060. sliders[3]->setValue ((int) colour.getAlpha());
  53061. }
  53062. if (colourSpace != 0)
  53063. {
  53064. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  53065. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  53066. }
  53067. if ((flags & showColourAtTop) != 0)
  53068. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  53069. sendChangeMessage (this);
  53070. }
  53071. void ColourSelector::paint (Graphics& g)
  53072. {
  53073. g.fillAll (findColour (backgroundColourId));
  53074. if ((flags & showColourAtTop) != 0)
  53075. {
  53076. const Colour colour (getCurrentColour());
  53077. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  53078. 10, 10,
  53079. Colour (0xffdddddd).overlaidWith (colour),
  53080. Colour (0xffffffff).overlaidWith (colour));
  53081. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  53082. g.setFont (14.0f, true);
  53083. g.drawText (((flags & showAlphaChannel) != 0)
  53084. ? String::formatted (T("#%02X%02X%02X%02X"),
  53085. (int) colour.getAlpha(),
  53086. (int) colour.getRed(),
  53087. (int) colour.getGreen(),
  53088. (int) colour.getBlue())
  53089. : String::formatted (T("#%02X%02X%02X"),
  53090. (int) colour.getRed(),
  53091. (int) colour.getGreen(),
  53092. (int) colour.getBlue()),
  53093. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  53094. Justification::centred, false);
  53095. }
  53096. if ((flags & showSliders) != 0)
  53097. {
  53098. g.setColour (findColour (labelTextColourId));
  53099. g.setFont (11.0f);
  53100. for (int i = 4; --i >= 0;)
  53101. {
  53102. if (sliders[i]->isVisible())
  53103. g.drawText (sliders[i]->getName() + T(":"),
  53104. 0, sliders[i]->getY(),
  53105. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  53106. Justification::centredRight, false);
  53107. }
  53108. }
  53109. }
  53110. void ColourSelector::resized()
  53111. {
  53112. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  53113. const int numSwatches = getNumSwatches();
  53114. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  53115. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  53116. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  53117. int y = topSpace;
  53118. if ((flags & showColourspace) != 0)
  53119. {
  53120. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  53121. colourSpace->setBounds (edgeGap, y,
  53122. getWidth() - hueWidth - edgeGap - 4,
  53123. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  53124. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  53125. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  53126. colourSpace->getHeight());
  53127. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  53128. }
  53129. if ((flags & showSliders) != 0)
  53130. {
  53131. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  53132. for (int i = 0; i < numSliders; ++i)
  53133. {
  53134. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  53135. proportionOfWidth (0.72f), sliderHeight - 2);
  53136. y += sliderHeight;
  53137. }
  53138. }
  53139. if (numSwatches > 0)
  53140. {
  53141. const int startX = 8;
  53142. const int xGap = 4;
  53143. const int yGap = 4;
  53144. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  53145. y += edgeGap;
  53146. if (swatchComponents.size() != numSwatches)
  53147. {
  53148. int i;
  53149. for (i = swatchComponents.size(); --i >= 0;)
  53150. {
  53151. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53152. delete sc;
  53153. }
  53154. for (i = 0; i < numSwatches; ++i)
  53155. {
  53156. SwatchComponent* const sc = new SwatchComponent (this, i);
  53157. swatchComponents.add (sc);
  53158. addAndMakeVisible (sc);
  53159. }
  53160. }
  53161. int x = startX;
  53162. for (int i = 0; i < swatchComponents.size(); ++i)
  53163. {
  53164. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53165. sc->setBounds (x + xGap / 2,
  53166. y + yGap / 2,
  53167. swatchWidth - xGap,
  53168. swatchHeight - yGap);
  53169. if (((i + 1) % swatchesPerRow) == 0)
  53170. {
  53171. x = startX;
  53172. y += swatchHeight;
  53173. }
  53174. else
  53175. {
  53176. x += swatchWidth;
  53177. }
  53178. }
  53179. }
  53180. }
  53181. void ColourSelector::sliderValueChanged (Slider*)
  53182. {
  53183. if (sliders[0] != 0)
  53184. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  53185. (uint8) sliders[1]->getValue(),
  53186. (uint8) sliders[2]->getValue(),
  53187. (uint8) sliders[3]->getValue()));
  53188. }
  53189. int ColourSelector::getNumSwatches() const
  53190. {
  53191. return 0;
  53192. }
  53193. const Colour ColourSelector::getSwatchColour (const int) const
  53194. {
  53195. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53196. return Colours::black;
  53197. }
  53198. void ColourSelector::setSwatchColour (const int, const Colour&) const
  53199. {
  53200. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53201. }
  53202. END_JUCE_NAMESPACE
  53203. /********* End of inlined file: juce_ColourSelector.cpp *********/
  53204. /********* Start of inlined file: juce_DropShadower.cpp *********/
  53205. BEGIN_JUCE_NAMESPACE
  53206. class ShadowWindow : public Component
  53207. {
  53208. Component* owner;
  53209. Image** shadowImageSections;
  53210. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  53211. public:
  53212. ShadowWindow (Component* const owner_,
  53213. const int type_,
  53214. Image** const shadowImageSections_)
  53215. : owner (owner_),
  53216. shadowImageSections (shadowImageSections_),
  53217. type (type_)
  53218. {
  53219. setInterceptsMouseClicks (false, false);
  53220. if (owner_->isOnDesktop())
  53221. {
  53222. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  53223. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53224. | ComponentPeer::windowIsTemporary);
  53225. }
  53226. else if (owner_->getParentComponent() != 0)
  53227. {
  53228. owner_->getParentComponent()->addChildComponent (this);
  53229. }
  53230. }
  53231. ~ShadowWindow()
  53232. {
  53233. }
  53234. void paint (Graphics& g)
  53235. {
  53236. Image* const topLeft = shadowImageSections [type * 3];
  53237. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  53238. Image* const filler = shadowImageSections [type * 3 + 2];
  53239. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  53240. g.setOpacity (1.0f);
  53241. if (type < 2)
  53242. {
  53243. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  53244. g.drawImage (topLeft,
  53245. 0, 0, topLeft->getWidth(), imH,
  53246. 0, 0, topLeft->getWidth(), imH);
  53247. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  53248. g.drawImage (bottomRight,
  53249. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  53250. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  53251. g.setBrush (&fillBrush);
  53252. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  53253. }
  53254. else
  53255. {
  53256. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  53257. g.drawImage (topLeft,
  53258. 0, 0, imW, topLeft->getHeight(),
  53259. 0, 0, imW, topLeft->getHeight());
  53260. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  53261. g.drawImage (bottomRight,
  53262. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  53263. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  53264. g.setBrush (&fillBrush);
  53265. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  53266. }
  53267. }
  53268. void resized()
  53269. {
  53270. repaint(); // (needed for correct repainting)
  53271. }
  53272. private:
  53273. ShadowWindow (const ShadowWindow&);
  53274. const ShadowWindow& operator= (const ShadowWindow&);
  53275. };
  53276. DropShadower::DropShadower (const float alpha_,
  53277. const int xOffset_,
  53278. const int yOffset_,
  53279. const float blurRadius_)
  53280. : owner (0),
  53281. numShadows (0),
  53282. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  53283. xOffset (xOffset_),
  53284. yOffset (yOffset_),
  53285. alpha (alpha_),
  53286. blurRadius (blurRadius_),
  53287. inDestructor (false),
  53288. reentrant (false)
  53289. {
  53290. }
  53291. DropShadower::~DropShadower()
  53292. {
  53293. if (owner != 0)
  53294. owner->removeComponentListener (this);
  53295. inDestructor = true;
  53296. deleteShadowWindows();
  53297. }
  53298. void DropShadower::deleteShadowWindows()
  53299. {
  53300. if (numShadows > 0)
  53301. {
  53302. int i;
  53303. for (i = numShadows; --i >= 0;)
  53304. delete shadowWindows[i];
  53305. for (i = 12; --i >= 0;)
  53306. delete shadowImageSections[i];
  53307. numShadows = 0;
  53308. }
  53309. }
  53310. void DropShadower::setOwner (Component* componentToFollow)
  53311. {
  53312. if (componentToFollow != owner)
  53313. {
  53314. if (owner != 0)
  53315. owner->removeComponentListener (this);
  53316. // (the component can't be null)
  53317. jassert (componentToFollow != 0);
  53318. owner = componentToFollow;
  53319. jassert (owner != 0);
  53320. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  53321. owner->addComponentListener (this);
  53322. updateShadows();
  53323. }
  53324. }
  53325. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  53326. {
  53327. updateShadows();
  53328. }
  53329. void DropShadower::componentBroughtToFront (Component&)
  53330. {
  53331. bringShadowWindowsToFront();
  53332. }
  53333. void DropShadower::componentChildrenChanged (Component&)
  53334. {
  53335. }
  53336. void DropShadower::componentParentHierarchyChanged (Component&)
  53337. {
  53338. deleteShadowWindows();
  53339. updateShadows();
  53340. }
  53341. void DropShadower::componentVisibilityChanged (Component&)
  53342. {
  53343. updateShadows();
  53344. }
  53345. void DropShadower::updateShadows()
  53346. {
  53347. if (reentrant || inDestructor || (owner == 0))
  53348. return;
  53349. reentrant = true;
  53350. ComponentPeer* const nw = owner->getPeer();
  53351. const bool isOwnerVisible = owner->isVisible()
  53352. && (nw == 0 || ! nw->isMinimised());
  53353. const bool createShadowWindows = numShadows == 0
  53354. && owner->getWidth() > 0
  53355. && owner->getHeight() > 0
  53356. && isOwnerVisible
  53357. && (Desktop::canUseSemiTransparentWindows()
  53358. || owner->getParentComponent() != 0);
  53359. if (createShadowWindows)
  53360. {
  53361. // keep a cached version of the image to save doing the gaussian too often
  53362. String imageId;
  53363. imageId << shadowEdge << T(',')
  53364. << xOffset << T(',')
  53365. << yOffset << T(',')
  53366. << alpha;
  53367. const int hash = imageId.hashCode();
  53368. Image* bigIm = ImageCache::getFromHashCode (hash);
  53369. if (bigIm == 0)
  53370. {
  53371. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  53372. Graphics bigG (*bigIm);
  53373. bigG.setColour (Colours::black.withAlpha (alpha));
  53374. bigG.fillRect (shadowEdge + xOffset,
  53375. shadowEdge + yOffset,
  53376. bigIm->getWidth() - (shadowEdge * 2),
  53377. bigIm->getHeight() - (shadowEdge * 2));
  53378. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  53379. blurKernel.createGaussianBlur (blurRadius);
  53380. blurKernel.applyToImage (*bigIm, 0,
  53381. xOffset,
  53382. yOffset,
  53383. bigIm->getWidth(),
  53384. bigIm->getHeight());
  53385. ImageCache::addImageToCache (bigIm, hash);
  53386. }
  53387. const int iw = bigIm->getWidth();
  53388. const int ih = bigIm->getHeight();
  53389. const int shadowEdge2 = shadowEdge * 2;
  53390. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  53391. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  53392. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  53393. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  53394. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  53395. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  53396. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  53397. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  53398. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  53399. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  53400. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  53401. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  53402. ImageCache::release (bigIm);
  53403. for (int i = 0; i < 4; ++i)
  53404. {
  53405. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  53406. ++numShadows;
  53407. }
  53408. }
  53409. if (numShadows > 0)
  53410. {
  53411. for (int i = numShadows; --i >= 0;)
  53412. {
  53413. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  53414. shadowWindows[i]->setVisible (isOwnerVisible);
  53415. }
  53416. const int x = owner->getX();
  53417. const int y = owner->getY() - shadowEdge;
  53418. const int w = owner->getWidth();
  53419. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  53420. shadowWindows[0]->setBounds (x - shadowEdge,
  53421. y,
  53422. shadowEdge,
  53423. h);
  53424. shadowWindows[1]->setBounds (x + w,
  53425. y,
  53426. shadowEdge,
  53427. h);
  53428. shadowWindows[2]->setBounds (x,
  53429. y,
  53430. w,
  53431. shadowEdge);
  53432. shadowWindows[3]->setBounds (x,
  53433. owner->getBottom(),
  53434. w,
  53435. shadowEdge);
  53436. }
  53437. reentrant = false;
  53438. if (createShadowWindows)
  53439. bringShadowWindowsToFront();
  53440. }
  53441. void DropShadower::setShadowImage (Image* const src,
  53442. const int num,
  53443. const int w,
  53444. const int h,
  53445. const int sx,
  53446. const int sy) throw()
  53447. {
  53448. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  53449. Graphics g (*shadowImageSections[num]);
  53450. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  53451. }
  53452. void DropShadower::bringShadowWindowsToFront()
  53453. {
  53454. if (! (inDestructor || reentrant))
  53455. {
  53456. updateShadows();
  53457. reentrant = true;
  53458. for (int i = numShadows; --i >= 0;)
  53459. shadowWindows[i]->toBehind (owner);
  53460. reentrant = false;
  53461. }
  53462. }
  53463. END_JUCE_NAMESPACE
  53464. /********* End of inlined file: juce_DropShadower.cpp *********/
  53465. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  53466. BEGIN_JUCE_NAMESPACE
  53467. class MagnifyingPeer : public ComponentPeer
  53468. {
  53469. public:
  53470. MagnifyingPeer (Component* const component,
  53471. MagnifierComponent* const magnifierComp_)
  53472. : ComponentPeer (component, 0),
  53473. magnifierComp (magnifierComp_)
  53474. {
  53475. }
  53476. ~MagnifyingPeer()
  53477. {
  53478. }
  53479. void* getNativeHandle() const { return 0; }
  53480. void setVisible (bool) {}
  53481. void setTitle (const String&) {}
  53482. void setPosition (int, int) {}
  53483. void setSize (int, int) {}
  53484. void setBounds (int, int, int, int, const bool) {}
  53485. void setMinimised (bool) {}
  53486. bool isMinimised() const { return false; }
  53487. void setFullScreen (bool) {}
  53488. bool isFullScreen() const { return false; }
  53489. const BorderSize getFrameSize() const { return BorderSize (0); }
  53490. bool setAlwaysOnTop (bool) { return true; }
  53491. void toFront (bool) {}
  53492. void toBehind (ComponentPeer*) {}
  53493. void setIcon (const Image&) {}
  53494. bool isFocused() const
  53495. {
  53496. return magnifierComp->hasKeyboardFocus (true);
  53497. }
  53498. void grabFocus()
  53499. {
  53500. ComponentPeer* peer = magnifierComp->getPeer();
  53501. if (peer != 0)
  53502. peer->grabFocus();
  53503. }
  53504. void getBounds (int& x, int& y, int& w, int& h) const
  53505. {
  53506. x = magnifierComp->getScreenX();
  53507. y = magnifierComp->getScreenY();
  53508. w = component->getWidth();
  53509. h = component->getHeight();
  53510. }
  53511. int getScreenX() const { return magnifierComp->getScreenX(); }
  53512. int getScreenY() const { return magnifierComp->getScreenY(); }
  53513. void relativePositionToGlobal (int& x, int& y)
  53514. {
  53515. const double zoom = magnifierComp->getScaleFactor();
  53516. x = roundDoubleToInt (x * zoom);
  53517. y = roundDoubleToInt (y * zoom);
  53518. magnifierComp->relativePositionToGlobal (x, y);
  53519. }
  53520. void globalPositionToRelative (int& x, int& y)
  53521. {
  53522. magnifierComp->globalPositionToRelative (x, y);
  53523. const double zoom = magnifierComp->getScaleFactor();
  53524. x = roundDoubleToInt (x / zoom);
  53525. y = roundDoubleToInt (y / zoom);
  53526. }
  53527. bool contains (int x, int y, bool) const
  53528. {
  53529. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  53530. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  53531. }
  53532. void repaint (int x, int y, int w, int h)
  53533. {
  53534. const double zoom = magnifierComp->getScaleFactor();
  53535. magnifierComp->repaint ((int) (x * zoom),
  53536. (int) (y * zoom),
  53537. roundDoubleToInt (w * zoom) + 1,
  53538. roundDoubleToInt (h * zoom) + 1);
  53539. }
  53540. void performAnyPendingRepaintsNow()
  53541. {
  53542. }
  53543. juce_UseDebuggingNewOperator
  53544. private:
  53545. MagnifierComponent* const magnifierComp;
  53546. MagnifyingPeer (const MagnifyingPeer&);
  53547. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  53548. };
  53549. class PeerHolderComp : public Component
  53550. {
  53551. public:
  53552. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  53553. : magnifierComp (magnifierComp_)
  53554. {
  53555. setVisible (true);
  53556. }
  53557. ~PeerHolderComp()
  53558. {
  53559. }
  53560. ComponentPeer* createNewPeer (int, void*)
  53561. {
  53562. return new MagnifyingPeer (this, magnifierComp);
  53563. }
  53564. void childBoundsChanged (Component* c)
  53565. {
  53566. if (c != 0)
  53567. {
  53568. setSize (c->getWidth(), c->getHeight());
  53569. magnifierComp->childBoundsChanged (this);
  53570. }
  53571. }
  53572. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  53573. {
  53574. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  53575. Component* const p = magnifierComp->getParentComponent();
  53576. if (p != 0)
  53577. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  53578. }
  53579. private:
  53580. MagnifierComponent* const magnifierComp;
  53581. PeerHolderComp (const PeerHolderComp&);
  53582. const PeerHolderComp& operator= (const PeerHolderComp&);
  53583. };
  53584. MagnifierComponent::MagnifierComponent (Component* const content_,
  53585. const bool deleteContentCompWhenNoLongerNeeded)
  53586. : content (content_),
  53587. scaleFactor (0.0),
  53588. peer (0),
  53589. deleteContent (deleteContentCompWhenNoLongerNeeded)
  53590. {
  53591. holderComp = new PeerHolderComp (this);
  53592. setScaleFactor (1.0);
  53593. }
  53594. MagnifierComponent::~MagnifierComponent()
  53595. {
  53596. delete holderComp;
  53597. if (deleteContent)
  53598. delete content;
  53599. }
  53600. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  53601. {
  53602. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  53603. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  53604. if (scaleFactor != newScaleFactor)
  53605. {
  53606. scaleFactor = newScaleFactor;
  53607. if (scaleFactor == 1.0)
  53608. {
  53609. holderComp->removeFromDesktop();
  53610. peer = 0;
  53611. addChildComponent (content);
  53612. childBoundsChanged (content);
  53613. }
  53614. else
  53615. {
  53616. holderComp->addAndMakeVisible (content);
  53617. holderComp->childBoundsChanged (content);
  53618. childBoundsChanged (holderComp);
  53619. holderComp->addToDesktop (0);
  53620. peer = holderComp->getPeer();
  53621. }
  53622. repaint();
  53623. }
  53624. }
  53625. void MagnifierComponent::paint (Graphics& g)
  53626. {
  53627. const int w = holderComp->getWidth();
  53628. const int h = holderComp->getHeight();
  53629. if (w == 0 || h == 0)
  53630. return;
  53631. const Rectangle r (g.getClipBounds());
  53632. const int srcX = (int) (r.getX() / scaleFactor);
  53633. const int srcY = (int) (r.getY() / scaleFactor);
  53634. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  53635. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  53636. if (scaleFactor >= 1.0)
  53637. {
  53638. ++srcW;
  53639. ++srcH;
  53640. }
  53641. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  53642. temp.clear (srcX, srcY, srcW, srcH);
  53643. Graphics g2 (temp);
  53644. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  53645. holderComp->paintEntireComponent (g2);
  53646. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  53647. g.drawImage (&temp,
  53648. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  53649. 0, 0, w, h,
  53650. false);
  53651. }
  53652. void MagnifierComponent::childBoundsChanged (Component* c)
  53653. {
  53654. if (c != 0)
  53655. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  53656. roundDoubleToInt (c->getHeight() * scaleFactor));
  53657. }
  53658. void MagnifierComponent::mouseDown (const MouseEvent& e)
  53659. {
  53660. if (peer != 0)
  53661. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53662. }
  53663. void MagnifierComponent::mouseUp (const MouseEvent& e)
  53664. {
  53665. if (peer != 0)
  53666. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53667. }
  53668. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  53669. {
  53670. if (peer != 0)
  53671. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53672. }
  53673. void MagnifierComponent::mouseMove (const MouseEvent& e)
  53674. {
  53675. if (peer != 0)
  53676. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53677. }
  53678. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  53679. {
  53680. if (peer != 0)
  53681. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53682. }
  53683. void MagnifierComponent::mouseExit (const MouseEvent& e)
  53684. {
  53685. if (peer != 0)
  53686. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53687. }
  53688. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  53689. {
  53690. if (peer != 0)
  53691. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  53692. roundFloatToInt (iy * 256.0f),
  53693. e.eventTime.toMilliseconds());
  53694. else
  53695. Component::mouseWheelMove (e, ix, iy);
  53696. }
  53697. int MagnifierComponent::scaleInt (const int n) const throw()
  53698. {
  53699. return roundDoubleToInt (n / scaleFactor);
  53700. }
  53701. END_JUCE_NAMESPACE
  53702. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  53703. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  53704. BEGIN_JUCE_NAMESPACE
  53705. class MidiKeyboardUpDownButton : public Button
  53706. {
  53707. public:
  53708. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  53709. const int delta_)
  53710. : Button (String::empty),
  53711. owner (owner_),
  53712. delta (delta_)
  53713. {
  53714. setOpaque (true);
  53715. }
  53716. ~MidiKeyboardUpDownButton()
  53717. {
  53718. }
  53719. void clicked()
  53720. {
  53721. int note = owner->getLowestVisibleKey();
  53722. if (delta < 0)
  53723. note = (note - 1) / 12;
  53724. else
  53725. note = note / 12 + 1;
  53726. owner->setLowestVisibleKey (note * 12);
  53727. }
  53728. void paintButton (Graphics& g,
  53729. bool isMouseOverButton,
  53730. bool isButtonDown)
  53731. {
  53732. owner->drawUpDownButton (g, getWidth(), getHeight(),
  53733. isMouseOverButton, isButtonDown,
  53734. delta > 0);
  53735. }
  53736. private:
  53737. MidiKeyboardComponent* const owner;
  53738. const int delta;
  53739. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  53740. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  53741. };
  53742. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  53743. const Orientation orientation_)
  53744. : state (state_),
  53745. xOffset (0),
  53746. blackNoteLength (1),
  53747. keyWidth (16.0f),
  53748. orientation (orientation_),
  53749. midiChannel (1),
  53750. midiInChannelMask (0xffff),
  53751. velocity (1.0f),
  53752. noteUnderMouse (-1),
  53753. mouseDownNote (-1),
  53754. rangeStart (0),
  53755. rangeEnd (127),
  53756. firstKey (12 * 4),
  53757. canScroll (true),
  53758. mouseDragging (false),
  53759. keyPresses (4),
  53760. keyPressNotes (16),
  53761. keyMappingOctave (6),
  53762. octaveNumForMiddleC (3)
  53763. {
  53764. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  53765. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  53766. // initialise with a default set of querty key-mappings..
  53767. const char* const keymap = "awsedftgyhujkolp;";
  53768. for (int i = String (keymap).length(); --i >= 0;)
  53769. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  53770. setOpaque (true);
  53771. setWantsKeyboardFocus (true);
  53772. state.addListener (this);
  53773. }
  53774. MidiKeyboardComponent::~MidiKeyboardComponent()
  53775. {
  53776. state.removeListener (this);
  53777. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  53778. deleteAllChildren();
  53779. }
  53780. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  53781. {
  53782. keyWidth = widthInPixels;
  53783. resized();
  53784. }
  53785. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  53786. {
  53787. if (orientation != newOrientation)
  53788. {
  53789. orientation = newOrientation;
  53790. resized();
  53791. }
  53792. }
  53793. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  53794. const int highestNote)
  53795. {
  53796. jassert (lowestNote >= 0 && lowestNote <= 127);
  53797. jassert (highestNote >= 0 && highestNote <= 127);
  53798. jassert (lowestNote <= highestNote);
  53799. if (rangeStart != lowestNote || rangeEnd != highestNote)
  53800. {
  53801. rangeStart = jlimit (0, 127, lowestNote);
  53802. rangeEnd = jlimit (0, 127, highestNote);
  53803. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  53804. resized();
  53805. }
  53806. }
  53807. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  53808. {
  53809. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  53810. if (noteNumber != firstKey)
  53811. {
  53812. firstKey = noteNumber;
  53813. sendChangeMessage (this);
  53814. resized();
  53815. }
  53816. }
  53817. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  53818. {
  53819. if (canScroll != canScroll_)
  53820. {
  53821. canScroll = canScroll_;
  53822. resized();
  53823. }
  53824. }
  53825. void MidiKeyboardComponent::colourChanged()
  53826. {
  53827. repaint();
  53828. }
  53829. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  53830. {
  53831. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  53832. if (midiChannel != midiChannelNumber)
  53833. {
  53834. resetAnyKeysInUse();
  53835. midiChannel = jlimit (1, 16, midiChannelNumber);
  53836. }
  53837. }
  53838. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  53839. {
  53840. midiInChannelMask = midiChannelMask;
  53841. triggerAsyncUpdate();
  53842. }
  53843. void MidiKeyboardComponent::setVelocity (const float velocity_)
  53844. {
  53845. jassert (velocity > 0 && velocity <= 1.0f);
  53846. velocity = jlimit (0.0f, 1.0f, velocity_);
  53847. }
  53848. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  53849. {
  53850. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  53851. static const float blackNoteWidth = 0.7f;
  53852. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  53853. 1.0f, 2 - blackNoteWidth * 0.4f,
  53854. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  53855. 4.0f, 5 - blackNoteWidth * 0.5f,
  53856. 5.0f, 6 - blackNoteWidth * 0.3f,
  53857. 6.0f };
  53858. static const float widths[] = { 1.0f, blackNoteWidth,
  53859. 1.0f, blackNoteWidth,
  53860. 1.0f, 1.0f, blackNoteWidth,
  53861. 1.0f, blackNoteWidth,
  53862. 1.0f, blackNoteWidth,
  53863. 1.0f };
  53864. const int octave = midiNoteNumber / 12;
  53865. const int note = midiNoteNumber % 12;
  53866. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  53867. w = roundFloatToInt (widths [note] * keyWidth);
  53868. }
  53869. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  53870. {
  53871. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  53872. int rx, rw;
  53873. getKeyPosition (rangeStart, keyWidth, rx, rw);
  53874. x -= xOffset + rx;
  53875. }
  53876. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  53877. {
  53878. int x, y;
  53879. getKeyPos (midiNoteNumber, x, y);
  53880. return x;
  53881. }
  53882. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  53883. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  53884. int MidiKeyboardComponent::xyToNote (int x, int y)
  53885. {
  53886. if (! reallyContains (x, y, false))
  53887. return -1;
  53888. if (orientation != horizontalKeyboard)
  53889. {
  53890. swapVariables (x, y);
  53891. if (orientation == verticalKeyboardFacingLeft)
  53892. y = getWidth() - y;
  53893. else
  53894. x = getHeight() - x;
  53895. }
  53896. return remappedXYToNote (x + xOffset, y);
  53897. }
  53898. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  53899. {
  53900. if (y < blackNoteLength)
  53901. {
  53902. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  53903. {
  53904. for (int i = 0; i < 5; ++i)
  53905. {
  53906. const int note = octaveStart + blackNotes [i];
  53907. if (note >= rangeStart && note <= rangeEnd)
  53908. {
  53909. int kx, kw;
  53910. getKeyPos (note, kx, kw);
  53911. kx += xOffset;
  53912. if (x >= kx && x < kx + kw)
  53913. return note;
  53914. }
  53915. }
  53916. }
  53917. }
  53918. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  53919. {
  53920. for (int i = 0; i < 7; ++i)
  53921. {
  53922. const int note = octaveStart + whiteNotes [i];
  53923. if (note >= rangeStart && note <= rangeEnd)
  53924. {
  53925. int kx, kw;
  53926. getKeyPos (note, kx, kw);
  53927. kx += xOffset;
  53928. if (x >= kx && x < kx + kw)
  53929. return note;
  53930. }
  53931. }
  53932. }
  53933. return -1;
  53934. }
  53935. void MidiKeyboardComponent::repaintNote (const int noteNum)
  53936. {
  53937. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  53938. {
  53939. int x, w;
  53940. getKeyPos (noteNum, x, w);
  53941. if (orientation == horizontalKeyboard)
  53942. repaint (x, 0, w, getHeight());
  53943. else if (orientation == verticalKeyboardFacingLeft)
  53944. repaint (0, x, getWidth(), w);
  53945. else if (orientation == verticalKeyboardFacingRight)
  53946. repaint (0, getHeight() - x - w, getWidth(), w);
  53947. }
  53948. }
  53949. void MidiKeyboardComponent::paint (Graphics& g)
  53950. {
  53951. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  53952. const Colour lineColour (findColour (keySeparatorLineColourId));
  53953. const Colour textColour (findColour (textLabelColourId));
  53954. int x, w, octave;
  53955. for (octave = 0; octave < 128; octave += 12)
  53956. {
  53957. for (int white = 0; white < 7; ++white)
  53958. {
  53959. const int noteNum = octave + whiteNotes [white];
  53960. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  53961. {
  53962. getKeyPos (noteNum, x, w);
  53963. if (orientation == horizontalKeyboard)
  53964. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  53965. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53966. noteUnderMouse == noteNum,
  53967. lineColour, textColour);
  53968. else if (orientation == verticalKeyboardFacingLeft)
  53969. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  53970. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53971. noteUnderMouse == noteNum,
  53972. lineColour, textColour);
  53973. else if (orientation == verticalKeyboardFacingRight)
  53974. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  53975. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53976. noteUnderMouse == noteNum,
  53977. lineColour, textColour);
  53978. }
  53979. }
  53980. }
  53981. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53982. if (orientation == verticalKeyboardFacingLeft)
  53983. {
  53984. x1 = getWidth() - 1.0f;
  53985. x2 = getWidth() - 5.0f;
  53986. }
  53987. else if (orientation == verticalKeyboardFacingRight)
  53988. x2 = 5.0f;
  53989. else
  53990. y2 = 5.0f;
  53991. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  53992. Colours::transparentBlack, x2, y2, false);
  53993. g.setBrush (&gb);
  53994. getKeyPos (rangeEnd, x, w);
  53995. x += w;
  53996. if (orientation == verticalKeyboardFacingLeft)
  53997. g.fillRect (getWidth() - 5, 0, 5, x);
  53998. else if (orientation == verticalKeyboardFacingRight)
  53999. g.fillRect (0, 0, 5, x);
  54000. else
  54001. g.fillRect (0, 0, x, 5);
  54002. g.setColour (lineColour);
  54003. if (orientation == verticalKeyboardFacingLeft)
  54004. g.fillRect (0, 0, 1, x);
  54005. else if (orientation == verticalKeyboardFacingRight)
  54006. g.fillRect (getWidth() - 1, 0, 1, x);
  54007. else
  54008. g.fillRect (0, getHeight() - 1, x, 1);
  54009. const Colour blackNoteColour (findColour (blackNoteColourId));
  54010. for (octave = 0; octave < 128; octave += 12)
  54011. {
  54012. for (int black = 0; black < 5; ++black)
  54013. {
  54014. const int noteNum = octave + blackNotes [black];
  54015. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54016. {
  54017. getKeyPos (noteNum, x, w);
  54018. if (orientation == horizontalKeyboard)
  54019. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  54020. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54021. noteUnderMouse == noteNum,
  54022. blackNoteColour);
  54023. else if (orientation == verticalKeyboardFacingLeft)
  54024. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  54025. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54026. noteUnderMouse == noteNum,
  54027. blackNoteColour);
  54028. else if (orientation == verticalKeyboardFacingRight)
  54029. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  54030. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54031. noteUnderMouse == noteNum,
  54032. blackNoteColour);
  54033. }
  54034. }
  54035. }
  54036. }
  54037. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  54038. Graphics& g, int x, int y, int w, int h,
  54039. bool isDown, bool isOver,
  54040. const Colour& lineColour,
  54041. const Colour& textColour)
  54042. {
  54043. Colour c (Colours::transparentWhite);
  54044. if (isDown)
  54045. c = findColour (keyDownOverlayColourId);
  54046. if (isOver)
  54047. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54048. g.setColour (c);
  54049. g.fillRect (x, y, w, h);
  54050. const String text (getWhiteNoteText (midiNoteNumber));
  54051. if (! text.isEmpty())
  54052. {
  54053. g.setColour (textColour);
  54054. Font f (jmin (12.0f, keyWidth * 0.9f));
  54055. f.setHorizontalScale (0.8f);
  54056. g.setFont (f);
  54057. Justification justification (Justification::centredBottom);
  54058. if (orientation == verticalKeyboardFacingLeft)
  54059. justification = Justification::centredLeft;
  54060. else if (orientation == verticalKeyboardFacingRight)
  54061. justification = Justification::centredRight;
  54062. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  54063. }
  54064. g.setColour (lineColour);
  54065. if (orientation == horizontalKeyboard)
  54066. g.fillRect (x, y, 1, h);
  54067. else if (orientation == verticalKeyboardFacingLeft)
  54068. g.fillRect (x, y, w, 1);
  54069. else if (orientation == verticalKeyboardFacingRight)
  54070. g.fillRect (x, y + h - 1, w, 1);
  54071. if (midiNoteNumber == rangeEnd)
  54072. {
  54073. if (orientation == horizontalKeyboard)
  54074. g.fillRect (x + w, y, 1, h);
  54075. else if (orientation == verticalKeyboardFacingLeft)
  54076. g.fillRect (x, y + h, w, 1);
  54077. else if (orientation == verticalKeyboardFacingRight)
  54078. g.fillRect (x, y - 1, w, 1);
  54079. }
  54080. }
  54081. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  54082. Graphics& g, int x, int y, int w, int h,
  54083. bool isDown, bool isOver,
  54084. const Colour& noteFillColour)
  54085. {
  54086. Colour c (noteFillColour);
  54087. if (isDown)
  54088. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  54089. if (isOver)
  54090. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54091. g.setColour (c);
  54092. g.fillRect (x, y, w, h);
  54093. if (isDown)
  54094. {
  54095. g.setColour (noteFillColour);
  54096. g.drawRect (x, y, w, h);
  54097. }
  54098. else
  54099. {
  54100. const int xIndent = jmax (1, jmin (w, h) / 8);
  54101. g.setColour (c.brighter());
  54102. if (orientation == horizontalKeyboard)
  54103. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  54104. else if (orientation == verticalKeyboardFacingLeft)
  54105. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  54106. else if (orientation == verticalKeyboardFacingRight)
  54107. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  54108. }
  54109. }
  54110. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  54111. {
  54112. octaveNumForMiddleC = octaveNumForMiddleC_;
  54113. repaint();
  54114. }
  54115. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  54116. {
  54117. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  54118. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  54119. return String::empty;
  54120. }
  54121. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  54122. const bool isMouseOver,
  54123. const bool isButtonDown,
  54124. const bool movesOctavesUp)
  54125. {
  54126. g.fillAll (findColour (upDownButtonBackgroundColourId));
  54127. float angle;
  54128. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  54129. angle = movesOctavesUp ? 0.0f : 0.5f;
  54130. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  54131. angle = movesOctavesUp ? 0.25f : 0.75f;
  54132. else
  54133. angle = movesOctavesUp ? 0.75f : 0.25f;
  54134. Path path;
  54135. path.lineTo (0.0f, 1.0f);
  54136. path.lineTo (1.0f, 0.5f);
  54137. path.closeSubPath();
  54138. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  54139. g.setColour (findColour (upDownButtonArrowColourId)
  54140. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  54141. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  54142. w - 2.0f,
  54143. h - 2.0f,
  54144. true));
  54145. }
  54146. void MidiKeyboardComponent::resized()
  54147. {
  54148. int w = getWidth();
  54149. int h = getHeight();
  54150. if (w > 0 && h > 0)
  54151. {
  54152. if (orientation != horizontalKeyboard)
  54153. swapVariables (w, h);
  54154. blackNoteLength = roundFloatToInt (h * 0.7f);
  54155. int kx2, kw2;
  54156. getKeyPos (rangeEnd, kx2, kw2);
  54157. kx2 += kw2;
  54158. if (firstKey != rangeStart)
  54159. {
  54160. int kx1, kw1;
  54161. getKeyPos (rangeStart, kx1, kw1);
  54162. if (kx2 - kx1 <= w)
  54163. {
  54164. firstKey = rangeStart;
  54165. sendChangeMessage (this);
  54166. repaint();
  54167. }
  54168. }
  54169. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  54170. scrollDown->setVisible (showScrollButtons);
  54171. scrollUp->setVisible (showScrollButtons);
  54172. xOffset = 0;
  54173. if (showScrollButtons)
  54174. {
  54175. const int scrollButtonW = jmin (12, w / 2);
  54176. if (orientation == horizontalKeyboard)
  54177. {
  54178. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  54179. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  54180. }
  54181. else if (orientation == verticalKeyboardFacingLeft)
  54182. {
  54183. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  54184. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54185. }
  54186. else if (orientation == verticalKeyboardFacingRight)
  54187. {
  54188. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54189. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  54190. }
  54191. int endOfLastKey, kw;
  54192. getKeyPos (rangeEnd, endOfLastKey, kw);
  54193. endOfLastKey += kw;
  54194. const int spaceAvailable = w - scrollButtonW * 2;
  54195. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  54196. if (lastStartKey >= 0 && firstKey > lastStartKey)
  54197. {
  54198. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  54199. sendChangeMessage (this);
  54200. }
  54201. int newOffset = 0;
  54202. getKeyPos (firstKey, newOffset, kw);
  54203. xOffset = newOffset - scrollButtonW;
  54204. }
  54205. else
  54206. {
  54207. firstKey = rangeStart;
  54208. }
  54209. timerCallback();
  54210. repaint();
  54211. }
  54212. }
  54213. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  54214. {
  54215. triggerAsyncUpdate();
  54216. }
  54217. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  54218. {
  54219. triggerAsyncUpdate();
  54220. }
  54221. void MidiKeyboardComponent::handleAsyncUpdate()
  54222. {
  54223. for (int i = rangeStart; i <= rangeEnd; ++i)
  54224. {
  54225. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  54226. {
  54227. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  54228. repaintNote (i);
  54229. }
  54230. }
  54231. }
  54232. void MidiKeyboardComponent::resetAnyKeysInUse()
  54233. {
  54234. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  54235. {
  54236. state.allNotesOff (midiChannel);
  54237. keysPressed.clear();
  54238. mouseDownNote = -1;
  54239. }
  54240. }
  54241. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  54242. {
  54243. const int newNote = (mouseDragging || isMouseOver())
  54244. ? xyToNote (x, y) : -1;
  54245. if (noteUnderMouse != newNote)
  54246. {
  54247. if (mouseDownNote >= 0)
  54248. {
  54249. state.noteOff (midiChannel, mouseDownNote);
  54250. mouseDownNote = -1;
  54251. }
  54252. if (mouseDragging && newNote >= 0)
  54253. {
  54254. state.noteOn (midiChannel, newNote, velocity);
  54255. mouseDownNote = newNote;
  54256. }
  54257. repaintNote (noteUnderMouse);
  54258. noteUnderMouse = newNote;
  54259. repaintNote (noteUnderMouse);
  54260. }
  54261. else if (mouseDownNote >= 0 && ! mouseDragging)
  54262. {
  54263. state.noteOff (midiChannel, mouseDownNote);
  54264. mouseDownNote = -1;
  54265. }
  54266. }
  54267. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  54268. {
  54269. updateNoteUnderMouse (e.x, e.y);
  54270. stopTimer();
  54271. }
  54272. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  54273. {
  54274. const int newNote = xyToNote (e.x, e.y);
  54275. if (newNote >= 0)
  54276. mouseDraggedToKey (newNote, e);
  54277. updateNoteUnderMouse (e.x, e.y);
  54278. }
  54279. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  54280. {
  54281. return true;
  54282. }
  54283. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  54284. {
  54285. }
  54286. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  54287. {
  54288. const int newNote = xyToNote (e.x, e.y);
  54289. mouseDragging = false;
  54290. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  54291. {
  54292. repaintNote (noteUnderMouse);
  54293. noteUnderMouse = -1;
  54294. mouseDragging = true;
  54295. updateNoteUnderMouse (e.x, e.y);
  54296. startTimer (500);
  54297. }
  54298. }
  54299. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  54300. {
  54301. mouseDragging = false;
  54302. updateNoteUnderMouse (e.x, e.y);
  54303. stopTimer();
  54304. }
  54305. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  54306. {
  54307. updateNoteUnderMouse (e.x, e.y);
  54308. }
  54309. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  54310. {
  54311. updateNoteUnderMouse (e.x, e.y);
  54312. }
  54313. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  54314. {
  54315. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  54316. }
  54317. void MidiKeyboardComponent::timerCallback()
  54318. {
  54319. int mx, my;
  54320. getMouseXYRelative (mx, my);
  54321. updateNoteUnderMouse (mx, my);
  54322. }
  54323. void MidiKeyboardComponent::clearKeyMappings()
  54324. {
  54325. resetAnyKeysInUse();
  54326. keyPressNotes.clear();
  54327. keyPresses.clear();
  54328. }
  54329. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  54330. const int midiNoteOffsetFromC)
  54331. {
  54332. removeKeyPressForNote (midiNoteOffsetFromC);
  54333. keyPressNotes.add (midiNoteOffsetFromC);
  54334. keyPresses.add (key);
  54335. }
  54336. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  54337. {
  54338. for (int i = keyPressNotes.size(); --i >= 0;)
  54339. {
  54340. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  54341. {
  54342. keyPressNotes.remove (i);
  54343. keyPresses.remove (i);
  54344. }
  54345. }
  54346. }
  54347. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  54348. {
  54349. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  54350. keyMappingOctave = newOctaveNumber;
  54351. }
  54352. bool MidiKeyboardComponent::keyStateChanged()
  54353. {
  54354. bool keyPressUsed = false;
  54355. for (int i = keyPresses.size(); --i >= 0;)
  54356. {
  54357. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  54358. if (keyPresses.getReference(i).isCurrentlyDown())
  54359. {
  54360. if (! keysPressed [note])
  54361. {
  54362. keysPressed.setBit (note);
  54363. state.noteOn (midiChannel, note, velocity);
  54364. keyPressUsed = true;
  54365. }
  54366. }
  54367. else
  54368. {
  54369. if (keysPressed [note])
  54370. {
  54371. keysPressed.clearBit (note);
  54372. state.noteOff (midiChannel, note);
  54373. keyPressUsed = true;
  54374. }
  54375. }
  54376. }
  54377. return keyPressUsed;
  54378. }
  54379. void MidiKeyboardComponent::focusLost (FocusChangeType)
  54380. {
  54381. resetAnyKeysInUse();
  54382. }
  54383. END_JUCE_NAMESPACE
  54384. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  54385. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  54386. #if JUCE_OPENGL
  54387. BEGIN_JUCE_NAMESPACE
  54388. extern void juce_glViewport (const int w, const int h);
  54389. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  54390. const int alphaBits_,
  54391. const int depthBufferBits_,
  54392. const int stencilBufferBits_) throw()
  54393. : redBits (bitsPerRGBComponent),
  54394. greenBits (bitsPerRGBComponent),
  54395. blueBits (bitsPerRGBComponent),
  54396. alphaBits (alphaBits_),
  54397. depthBufferBits (depthBufferBits_),
  54398. stencilBufferBits (stencilBufferBits_),
  54399. accumulationBufferRedBits (0),
  54400. accumulationBufferGreenBits (0),
  54401. accumulationBufferBlueBits (0),
  54402. accumulationBufferAlphaBits (0),
  54403. fullSceneAntiAliasingNumSamples (0)
  54404. {
  54405. }
  54406. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  54407. {
  54408. return memcmp (this, &other, sizeof (other)) == 0;
  54409. }
  54410. static VoidArray knownContexts;
  54411. OpenGLContext::OpenGLContext() throw()
  54412. {
  54413. knownContexts.add (this);
  54414. }
  54415. OpenGLContext::~OpenGLContext()
  54416. {
  54417. knownContexts.removeValue (this);
  54418. }
  54419. OpenGLContext* OpenGLContext::getCurrentContext()
  54420. {
  54421. for (int i = knownContexts.size(); --i >= 0;)
  54422. {
  54423. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  54424. if (oglc->isActive())
  54425. return oglc;
  54426. }
  54427. return 0;
  54428. }
  54429. class OpenGLComponentWatcher : public ComponentMovementWatcher
  54430. {
  54431. public:
  54432. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  54433. : ComponentMovementWatcher (owner_),
  54434. owner (owner_),
  54435. wasShowing (false)
  54436. {
  54437. }
  54438. ~OpenGLComponentWatcher() {}
  54439. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  54440. {
  54441. owner->updateContextPosition();
  54442. }
  54443. void componentPeerChanged()
  54444. {
  54445. const ScopedLock sl (owner->getContextLock());
  54446. owner->deleteContext();
  54447. }
  54448. void componentVisibilityChanged (Component&)
  54449. {
  54450. const bool isShowingNow = owner->isShowing();
  54451. if (wasShowing != isShowingNow)
  54452. {
  54453. wasShowing = isShowingNow;
  54454. owner->updateContextPosition();
  54455. }
  54456. }
  54457. juce_UseDebuggingNewOperator
  54458. private:
  54459. OpenGLComponent* const owner;
  54460. bool wasShowing;
  54461. };
  54462. OpenGLComponent::OpenGLComponent()
  54463. : context (0),
  54464. contextToShareListsWith (0),
  54465. needToUpdateViewport (true)
  54466. {
  54467. setOpaque (true);
  54468. componentWatcher = new OpenGLComponentWatcher (this);
  54469. }
  54470. OpenGLComponent::~OpenGLComponent()
  54471. {
  54472. deleteContext();
  54473. delete componentWatcher;
  54474. }
  54475. void OpenGLComponent::deleteContext()
  54476. {
  54477. const ScopedLock sl (contextLock);
  54478. deleteAndZero (context);
  54479. }
  54480. void OpenGLComponent::updateContextPosition()
  54481. {
  54482. needToUpdateViewport = true;
  54483. if (getWidth() > 0 && getHeight() > 0)
  54484. {
  54485. Component* const topComp = getTopLevelComponent();
  54486. if (topComp->getPeer() != 0)
  54487. {
  54488. const ScopedLock sl (contextLock);
  54489. if (context != 0)
  54490. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  54491. getScreenY() - topComp->getScreenY(),
  54492. getWidth(),
  54493. getHeight(),
  54494. topComp->getHeight());
  54495. }
  54496. }
  54497. }
  54498. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  54499. {
  54500. OpenGLPixelFormat pf;
  54501. const ScopedLock sl (contextLock);
  54502. if (context != 0)
  54503. pf = context->getPixelFormat();
  54504. return pf;
  54505. }
  54506. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  54507. {
  54508. if (! (preferredPixelFormat == formatToUse))
  54509. {
  54510. const ScopedLock sl (contextLock);
  54511. deleteContext();
  54512. preferredPixelFormat = formatToUse;
  54513. }
  54514. }
  54515. void OpenGLComponent::shareWith (OpenGLContext* context)
  54516. {
  54517. if (contextToShareListsWith != context)
  54518. {
  54519. const ScopedLock sl (contextLock);
  54520. deleteContext();
  54521. contextToShareListsWith = context;
  54522. }
  54523. }
  54524. bool OpenGLComponent::makeCurrentContextActive()
  54525. {
  54526. if (context == 0)
  54527. {
  54528. const ScopedLock sl (contextLock);
  54529. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  54530. {
  54531. context = OpenGLContext::createContextForWindow (this,
  54532. preferredPixelFormat,
  54533. contextToShareListsWith);
  54534. if (context != 0)
  54535. {
  54536. updateContextPosition();
  54537. if (context->makeActive())
  54538. newOpenGLContextCreated();
  54539. }
  54540. }
  54541. }
  54542. return context != 0 && context->makeActive();
  54543. }
  54544. void OpenGLComponent::makeCurrentContextInactive()
  54545. {
  54546. if (context != 0)
  54547. context->makeInactive();
  54548. }
  54549. bool OpenGLComponent::isActiveContext() const throw()
  54550. {
  54551. return context != 0 && context->isActive();
  54552. }
  54553. void OpenGLComponent::swapBuffers()
  54554. {
  54555. if (context != 0)
  54556. context->swapBuffers();
  54557. }
  54558. void OpenGLComponent::paint (Graphics&)
  54559. {
  54560. if (renderAndSwapBuffers())
  54561. {
  54562. ComponentPeer* const peer = getPeer();
  54563. if (peer != 0)
  54564. {
  54565. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  54566. getScreenY() - peer->getScreenY(),
  54567. getWidth(), getHeight());
  54568. }
  54569. }
  54570. }
  54571. bool OpenGLComponent::renderAndSwapBuffers()
  54572. {
  54573. const ScopedLock sl (contextLock);
  54574. if (! makeCurrentContextActive())
  54575. return false;
  54576. if (needToUpdateViewport)
  54577. {
  54578. needToUpdateViewport = false;
  54579. juce_glViewport (getWidth(), getHeight());
  54580. }
  54581. renderOpenGL();
  54582. swapBuffers();
  54583. return true;
  54584. }
  54585. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  54586. {
  54587. Component::internalRepaint (x, y, w, h);
  54588. if (context != 0)
  54589. context->repaint();
  54590. }
  54591. END_JUCE_NAMESPACE
  54592. #endif
  54593. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  54594. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  54595. BEGIN_JUCE_NAMESPACE
  54596. PreferencesPanel::PreferencesPanel()
  54597. : currentPage (0),
  54598. buttonSize (70)
  54599. {
  54600. }
  54601. PreferencesPanel::~PreferencesPanel()
  54602. {
  54603. deleteAllChildren();
  54604. }
  54605. void PreferencesPanel::addSettingsPage (const String& title,
  54606. const Drawable* icon,
  54607. const Drawable* overIcon,
  54608. const Drawable* downIcon)
  54609. {
  54610. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  54611. button->setImages (icon, overIcon, downIcon);
  54612. button->setRadioGroupId (1);
  54613. button->addButtonListener (this);
  54614. button->setClickingTogglesState (true);
  54615. button->setWantsKeyboardFocus (false);
  54616. addAndMakeVisible (button);
  54617. resized();
  54618. }
  54619. void PreferencesPanel::addSettingsPage (const String& title,
  54620. const char* imageData,
  54621. const int imageDataSize)
  54622. {
  54623. DrawableImage icon, iconOver, iconDown;
  54624. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54625. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54626. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  54627. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54628. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  54629. addSettingsPage (title, &icon, &iconOver, &iconDown);
  54630. if (currentPage == 0)
  54631. setCurrentPage (title);
  54632. }
  54633. class PrefsDialogWindow : public DialogWindow
  54634. {
  54635. public:
  54636. PrefsDialogWindow (const String& dialogtitle,
  54637. const Colour& backgroundColour)
  54638. : DialogWindow (dialogtitle, backgroundColour, true)
  54639. {
  54640. }
  54641. ~PrefsDialogWindow()
  54642. {
  54643. }
  54644. void closeButtonPressed()
  54645. {
  54646. exitModalState (0);
  54647. }
  54648. private:
  54649. PrefsDialogWindow (const PrefsDialogWindow&);
  54650. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  54651. };
  54652. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  54653. int dialogWidth,
  54654. int dialogHeight,
  54655. const Colour& backgroundColour)
  54656. {
  54657. setSize (dialogWidth, dialogHeight);
  54658. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  54659. dw.setContentComponent (this, true, true);
  54660. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  54661. dw.runModalLoop();
  54662. }
  54663. void PreferencesPanel::resized()
  54664. {
  54665. int x = 0;
  54666. for (int i = 0; i < getNumChildComponents(); ++i)
  54667. {
  54668. Component* c = getChildComponent (i);
  54669. if (dynamic_cast <DrawableButton*> (c) == 0)
  54670. {
  54671. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  54672. }
  54673. else
  54674. {
  54675. c->setBounds (x, 0, buttonSize, buttonSize);
  54676. x += buttonSize;
  54677. }
  54678. }
  54679. }
  54680. void PreferencesPanel::paint (Graphics& g)
  54681. {
  54682. g.setColour (Colours::grey);
  54683. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  54684. }
  54685. void PreferencesPanel::setCurrentPage (const String& pageName)
  54686. {
  54687. if (currentPageName != pageName)
  54688. {
  54689. currentPageName = pageName;
  54690. deleteAndZero (currentPage);
  54691. currentPage = createComponentForPage (pageName);
  54692. if (currentPage != 0)
  54693. {
  54694. addAndMakeVisible (currentPage);
  54695. currentPage->toBack();
  54696. resized();
  54697. }
  54698. for (int i = 0; i < getNumChildComponents(); ++i)
  54699. {
  54700. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  54701. if (db != 0 && db->getName() == pageName)
  54702. {
  54703. db->setToggleState (true, false);
  54704. break;
  54705. }
  54706. }
  54707. }
  54708. }
  54709. void PreferencesPanel::buttonClicked (Button*)
  54710. {
  54711. for (int i = 0; i < getNumChildComponents(); ++i)
  54712. {
  54713. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  54714. if (db != 0 && db->getToggleState())
  54715. {
  54716. setCurrentPage (db->getName());
  54717. break;
  54718. }
  54719. }
  54720. }
  54721. END_JUCE_NAMESPACE
  54722. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  54723. /********* Start of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  54724. #if JUCE_QUICKTIME
  54725. #ifdef _MSC_VER
  54726. #pragma warning (disable: 4514)
  54727. #endif
  54728. #ifdef _WIN32
  54729. #include <windows.h>
  54730. #ifdef _MSC_VER
  54731. #pragma warning (push)
  54732. #pragma warning (disable : 4100)
  54733. #endif
  54734. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  54735. add its header directory to your include path.
  54736. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  54737. flag in juce_Config.h
  54738. */
  54739. #include <Movies.h>
  54740. #include <QTML.h>
  54741. #include <QuickTimeComponents.h>
  54742. #include <MediaHandlers.h>
  54743. #include <ImageCodec.h>
  54744. #ifdef _MSC_VER
  54745. #pragma warning (pop)
  54746. #endif
  54747. // If you've got QuickTime 7 installed, then these COM objects should be found in
  54748. // the "\Program Files\Quicktime" directory. You'll need to add this directory to
  54749. // your include search path to make these import statements work.
  54750. #import <QTOLibrary.dll>
  54751. #import <QTOControl.dll>
  54752. using namespace QTOLibrary;
  54753. using namespace QTOControlLib;
  54754. #else
  54755. #include <Carbon/Carbon.h>
  54756. #include <QuickTime/Movies.h>
  54757. #include <QuickTime/QuickTimeComponents.h>
  54758. #include <QuickTime/MediaHandlers.h>
  54759. #endif
  54760. BEGIN_JUCE_NAMESPACE
  54761. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  54762. static bool hasLoadedQT = false;
  54763. static bool isQTAvailable = false;
  54764. struct QTMovieCompInternal
  54765. {
  54766. QTMovieCompInternal()
  54767. : dataHandle (0)
  54768. {
  54769. #if JUCE_MAC
  54770. movie = 0;
  54771. controller = 0;
  54772. #endif
  54773. }
  54774. ~QTMovieCompInternal()
  54775. {
  54776. clearHandle();
  54777. }
  54778. #if JUCE_MAC
  54779. Movie movie;
  54780. MovieController controller;
  54781. #else
  54782. IQTControlPtr qtControlInternal;
  54783. IQTMoviePtr qtMovieInternal;
  54784. #endif
  54785. Handle dataHandle;
  54786. void clearHandle()
  54787. {
  54788. if (dataHandle != 0)
  54789. {
  54790. DisposeHandle (dataHandle);
  54791. dataHandle = 0;
  54792. }
  54793. }
  54794. };
  54795. #if JUCE_WIN32
  54796. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  54797. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  54798. QuickTimeMovieComponent::QuickTimeMovieComponent()
  54799. : movieLoaded (false),
  54800. controllerVisible (true)
  54801. {
  54802. internal = new QTMovieCompInternal();
  54803. setMouseEventsAllowed (false);
  54804. }
  54805. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  54806. {
  54807. closeMovie();
  54808. qtControl = 0;
  54809. deleteControl();
  54810. delete internal;
  54811. internal = 0;
  54812. }
  54813. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  54814. {
  54815. if (! hasLoadedQT)
  54816. {
  54817. hasLoadedQT = true;
  54818. isQTAvailable = (InitializeQTML (0) == noErr)
  54819. && (EnterMovies() == noErr);
  54820. }
  54821. return isQTAvailable;
  54822. }
  54823. void QuickTimeMovieComponent::createControlIfNeeded()
  54824. {
  54825. if (isShowing() && ! isControlCreated())
  54826. {
  54827. const IID qtIID = __uuidof (QTControl);
  54828. if (createControl (&qtIID))
  54829. {
  54830. const IID qtInterfaceIID = __uuidof (IQTControl);
  54831. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  54832. if (qtControl != 0)
  54833. {
  54834. qtControl->Release(); // it has one ref too many at this point
  54835. qtControl->QuickTimeInitialize();
  54836. qtControl->PutSizing (qtMovieFitsControl);
  54837. if (movieFile != File::nonexistent)
  54838. loadMovie (movieFile, controllerVisible);
  54839. }
  54840. }
  54841. }
  54842. }
  54843. bool QuickTimeMovieComponent::isControlCreated() const
  54844. {
  54845. return isControlOpen();
  54846. }
  54847. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  54848. const bool isControllerVisible)
  54849. {
  54850. movieFile = File::nonexistent;
  54851. movieLoaded = false;
  54852. qtMovie = 0;
  54853. controllerVisible = isControllerVisible;
  54854. createControlIfNeeded();
  54855. if (isControlCreated())
  54856. {
  54857. if (qtControl != 0)
  54858. {
  54859. qtControl->Put_MovieHandle (0);
  54860. ((QTMovieCompInternal*) internal)->clearHandle();
  54861. Movie movie;
  54862. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  54863. {
  54864. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  54865. qtMovie = qtControl->GetMovie();
  54866. if (qtMovie != 0)
  54867. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  54868. : qtMovieControllerTypeNone);
  54869. }
  54870. if (movie == 0)
  54871. ((QTMovieCompInternal*) internal)->clearHandle();
  54872. }
  54873. movieLoaded = (qtMovie != 0);
  54874. }
  54875. else
  54876. {
  54877. // You're trying to open a movie when the control hasn't yet been created, probably because
  54878. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  54879. jassertfalse
  54880. }
  54881. delete movieStream;
  54882. return movieLoaded;
  54883. }
  54884. void QuickTimeMovieComponent::closeMovie()
  54885. {
  54886. stop();
  54887. movieFile = File::nonexistent;
  54888. movieLoaded = false;
  54889. qtMovie = 0;
  54890. if (qtControl != 0)
  54891. qtControl->Put_MovieHandle (0);
  54892. ((QTMovieCompInternal*) internal)->clearHandle();
  54893. }
  54894. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  54895. {
  54896. return movieFile;
  54897. }
  54898. bool QuickTimeMovieComponent::isMovieOpen() const
  54899. {
  54900. return movieLoaded;
  54901. }
  54902. double QuickTimeMovieComponent::getMovieDuration() const
  54903. {
  54904. if (qtMovie != 0)
  54905. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  54906. return 0.0;
  54907. }
  54908. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  54909. {
  54910. if (qtMovie != 0)
  54911. {
  54912. struct QTRECT r = qtMovie->GetNaturalRect();
  54913. width = r.right - r.left;
  54914. height = r.bottom - r.top;
  54915. }
  54916. else
  54917. {
  54918. width = height = 0;
  54919. }
  54920. }
  54921. void QuickTimeMovieComponent::play()
  54922. {
  54923. if (qtMovie != 0)
  54924. qtMovie->Play();
  54925. }
  54926. void QuickTimeMovieComponent::stop()
  54927. {
  54928. if (qtMovie != 0)
  54929. qtMovie->Stop();
  54930. }
  54931. bool QuickTimeMovieComponent::isPlaying() const
  54932. {
  54933. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  54934. }
  54935. void QuickTimeMovieComponent::setPosition (const double seconds)
  54936. {
  54937. if (qtMovie != 0)
  54938. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  54939. }
  54940. double QuickTimeMovieComponent::getPosition() const
  54941. {
  54942. if (qtMovie != 0)
  54943. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  54944. return 0.0;
  54945. }
  54946. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  54947. {
  54948. if (qtMovie != 0)
  54949. qtMovie->PutRate (newSpeed);
  54950. }
  54951. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  54952. {
  54953. if (qtMovie != 0)
  54954. qtMovie->PutAudioVolume (newVolume);
  54955. }
  54956. float QuickTimeMovieComponent::getMovieVolume() const
  54957. {
  54958. if (qtMovie != 0)
  54959. return qtMovie->GetAudioVolume();
  54960. return 0.0f;
  54961. }
  54962. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  54963. {
  54964. if (qtMovie != 0)
  54965. qtMovie->PutLoop (shouldLoop);
  54966. }
  54967. bool QuickTimeMovieComponent::isLooping() const
  54968. {
  54969. return qtMovie != 0 && qtMovie->GetLoop();
  54970. }
  54971. bool QuickTimeMovieComponent::isControllerVisible() const
  54972. {
  54973. return controllerVisible;
  54974. }
  54975. void QuickTimeMovieComponent::parentHierarchyChanged()
  54976. {
  54977. createControlIfNeeded();
  54978. QTWinBaseClass::parentHierarchyChanged();
  54979. }
  54980. void QuickTimeMovieComponent::visibilityChanged()
  54981. {
  54982. createControlIfNeeded();
  54983. QTWinBaseClass::visibilityChanged();
  54984. }
  54985. void QuickTimeMovieComponent::paint (Graphics& g)
  54986. {
  54987. if (! isControlCreated())
  54988. g.fillAll (Colours::black);
  54989. }
  54990. #endif
  54991. #if JUCE_MAC
  54992. static VoidArray activeQTWindows (2);
  54993. struct MacClickEventData
  54994. {
  54995. ::Point where;
  54996. long when;
  54997. long modifiers;
  54998. };
  54999. void OfferMouseClickToQuickTime (WindowRef window,
  55000. ::Point where, long when, long modifiers,
  55001. Component* topLevelComp)
  55002. {
  55003. if (hasLoadedQT)
  55004. {
  55005. for (int i = activeQTWindows.size(); --i >= 0;)
  55006. {
  55007. QuickTimeMovieComponent* const qtw = (QuickTimeMovieComponent*) activeQTWindows[i];
  55008. if (qtw->isVisible() && topLevelComp->isParentOf (qtw))
  55009. {
  55010. MacClickEventData data;
  55011. data.where = where;
  55012. data.when = when;
  55013. data.modifiers = modifiers;
  55014. qtw->handleMCEvent (&data);
  55015. }
  55016. }
  55017. }
  55018. }
  55019. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55020. : internal (new QTMovieCompInternal()),
  55021. associatedWindow (0),
  55022. controllerVisible (false),
  55023. controllerAssignedToWindow (false),
  55024. reentrant (false)
  55025. {
  55026. if (! hasLoadedQT)
  55027. {
  55028. hasLoadedQT = true;
  55029. isQTAvailable = EnterMovies() == noErr;
  55030. }
  55031. setOpaque (true);
  55032. setVisible (true);
  55033. activeQTWindows.add (this);
  55034. }
  55035. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55036. {
  55037. closeMovie();
  55038. activeQTWindows.removeValue ((void*) this);
  55039. QTMovieCompInternal* const i = (QTMovieCompInternal*) internal;
  55040. delete i;
  55041. if (activeQTWindows.size() == 0 && isQTAvailable)
  55042. {
  55043. isQTAvailable = false;
  55044. hasLoadedQT = false;
  55045. ExitMovies();
  55046. }
  55047. }
  55048. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55049. {
  55050. if (! hasLoadedQT)
  55051. {
  55052. hasLoadedQT = true;
  55053. isQTAvailable = EnterMovies() == noErr;
  55054. }
  55055. return isQTAvailable;
  55056. }
  55057. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55058. const bool controllerVisible_)
  55059. {
  55060. if (! isQTAvailable)
  55061. return false;
  55062. closeMovie();
  55063. movieFile = File::nonexistent;
  55064. if (getPeer() == 0)
  55065. {
  55066. // To open a movie, this component must be visible inside a functioning window, so that
  55067. // the QT control can be assigned to the window.
  55068. jassertfalse
  55069. return false;
  55070. }
  55071. controllerVisible = controllerVisible_;
  55072. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55073. GrafPtr savedPort;
  55074. GetPort (&savedPort);
  55075. bool result = false;
  55076. if (juce_OpenQuickTimeMovieFromStream (movieStream, qmci->movie, qmci->dataHandle))
  55077. {
  55078. qmci->controller = 0;
  55079. void* window = getWindowHandle();
  55080. if (window != associatedWindow && window != 0)
  55081. associatedWindow = window;
  55082. assignMovieToWindow();
  55083. SetMovieActive (qmci->movie, true);
  55084. SetMovieProgressProc (qmci->movie, (MovieProgressUPP) -1, 0);
  55085. startTimer (1000 / 50); // this needs to be quite a high frequency for smooth playback
  55086. result = true;
  55087. repaint();
  55088. }
  55089. MacSetPort (savedPort);
  55090. return result;
  55091. }
  55092. void QuickTimeMovieComponent::closeMovie()
  55093. {
  55094. stop();
  55095. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55096. if (qmci->controller != 0)
  55097. {
  55098. DisposeMovieController (qmci->controller);
  55099. qmci->controller = 0;
  55100. }
  55101. if (qmci->movie != 0)
  55102. {
  55103. DisposeMovie (qmci->movie);
  55104. qmci->movie = 0;
  55105. }
  55106. qmci->clearHandle();
  55107. stopTimer();
  55108. movieFile = File::nonexistent;
  55109. }
  55110. bool QuickTimeMovieComponent::isMovieOpen() const
  55111. {
  55112. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55113. return qmci->movie != 0 && qmci->controller != 0;
  55114. }
  55115. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55116. {
  55117. return movieFile;
  55118. }
  55119. static GrafPtr getPortForWindow (void* window)
  55120. {
  55121. if (window == 0)
  55122. return 0;
  55123. return (GrafPtr) GetWindowPort ((WindowRef) window);
  55124. }
  55125. void QuickTimeMovieComponent::assignMovieToWindow()
  55126. {
  55127. if (reentrant)
  55128. return;
  55129. reentrant = true;
  55130. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55131. if (qmci->controller != 0)
  55132. {
  55133. DisposeMovieController (qmci->controller);
  55134. qmci->controller = 0;
  55135. }
  55136. controllerAssignedToWindow = false;
  55137. void* window = getWindowHandle();
  55138. GrafPtr port = getPortForWindow (window);
  55139. if (port != 0)
  55140. {
  55141. GrafPtr savedPort;
  55142. GetPort (&savedPort);
  55143. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55144. MacSetPort (port);
  55145. Rect r;
  55146. r.top = 0;
  55147. r.left = 0;
  55148. r.right = (short) jmax (1, getWidth());
  55149. r.bottom = (short) jmax (1, getHeight());
  55150. SetMovieBox (qmci->movie, &r);
  55151. // create the movie controller
  55152. qmci->controller = NewMovieController (qmci->movie, &r,
  55153. controllerVisible ? mcTopLeftMovie
  55154. : mcNotVisible);
  55155. if (qmci->controller != 0)
  55156. {
  55157. MCEnableEditing (qmci->controller, true);
  55158. MCDoAction (qmci->controller, mcActionSetUseBadge, (void*) false);
  55159. MCDoAction (qmci->controller, mcActionSetLoopIsPalindrome, (void*) false);
  55160. setLooping (looping);
  55161. MCDoAction (qmci->controller, mcActionSetFlags,
  55162. (void*) (pointer_sized_int) (mcFlagSuppressMovieFrame | (controllerVisible ? 0 : (mcFlagSuppressStepButtons | mcFlagSuppressSpeakerButton))));
  55163. MCSetControllerBoundsRect (qmci->controller, &r);
  55164. controllerAssignedToWindow = true;
  55165. resized();
  55166. }
  55167. MacSetPort (savedPort);
  55168. }
  55169. else
  55170. {
  55171. SetMovieGWorld (qmci->movie, 0, 0);
  55172. }
  55173. reentrant = false;
  55174. }
  55175. void QuickTimeMovieComponent::play()
  55176. {
  55177. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55178. if (qmci->movie != 0)
  55179. StartMovie (qmci->movie);
  55180. }
  55181. void QuickTimeMovieComponent::stop()
  55182. {
  55183. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55184. if (qmci->movie != 0)
  55185. StopMovie (qmci->movie);
  55186. }
  55187. bool QuickTimeMovieComponent::isPlaying() const
  55188. {
  55189. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55190. return qmci->movie != 0 && GetMovieRate (qmci->movie) != 0;
  55191. }
  55192. void QuickTimeMovieComponent::setPosition (const double seconds)
  55193. {
  55194. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55195. if (qmci->controller != 0)
  55196. {
  55197. TimeRecord time;
  55198. time.base = GetMovieTimeBase (qmci->movie);
  55199. time.scale = 100000;
  55200. const uint64 t = (uint64) (100000.0 * seconds);
  55201. time.value.lo = (UInt32) (t & 0xffffffff);
  55202. time.value.hi = (UInt32) (t >> 32);
  55203. SetMovieTime (qmci->movie, &time);
  55204. timerCallback(); // to call MCIdle
  55205. }
  55206. else
  55207. {
  55208. jassertfalse // no movie is open, so can't set the position.
  55209. }
  55210. }
  55211. double QuickTimeMovieComponent::getPosition() const
  55212. {
  55213. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55214. if (qmci->movie != 0)
  55215. {
  55216. TimeRecord time;
  55217. GetMovieTime (qmci->movie, &time);
  55218. return ((int64) (((uint64) time.value.hi << 32) | (uint64) time.value.lo))
  55219. / (double) time.scale;
  55220. }
  55221. return 0.0;
  55222. }
  55223. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55224. {
  55225. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55226. if (qmci->movie != 0)
  55227. SetMovieRate (qmci->movie, (Fixed) (newSpeed * (Fixed) 0x00010000L));
  55228. }
  55229. double QuickTimeMovieComponent::getMovieDuration() const
  55230. {
  55231. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55232. if (qmci->movie != 0)
  55233. return GetMovieDuration (qmci->movie) / (double) GetMovieTimeScale (qmci->movie);
  55234. return 0.0;
  55235. }
  55236. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55237. {
  55238. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55239. looping = shouldLoop;
  55240. if (qmci->controller != 0)
  55241. MCDoAction (qmci->controller, mcActionSetLooping, (void*) shouldLoop);
  55242. }
  55243. bool QuickTimeMovieComponent::isLooping() const
  55244. {
  55245. return looping;
  55246. }
  55247. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55248. {
  55249. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55250. if (qmci->movie != 0)
  55251. SetMovieVolume (qmci->movie, jlimit ((short) 0, (short) 0x100, (short) (newVolume * 0x0100)));
  55252. }
  55253. float QuickTimeMovieComponent::getMovieVolume() const
  55254. {
  55255. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55256. if (qmci->movie != 0)
  55257. return jmax (0.0f, GetMovieVolume (qmci->movie) / (float) 0x0100);
  55258. return 0.0f;
  55259. }
  55260. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55261. {
  55262. width = 0;
  55263. height = 0;
  55264. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55265. if (qmci->movie != 0)
  55266. {
  55267. Rect r;
  55268. GetMovieNaturalBoundsRect (qmci->movie, &r);
  55269. width = r.right - r.left;
  55270. height = r.bottom - r.top;
  55271. }
  55272. }
  55273. void QuickTimeMovieComponent::paint (Graphics& g)
  55274. {
  55275. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55276. if (qmci->movie == 0 || qmci->controller == 0)
  55277. {
  55278. g.fillAll (Colours::black);
  55279. return;
  55280. }
  55281. GrafPtr savedPort;
  55282. GetPort (&savedPort);
  55283. MacSetPort (getPortForWindow (getWindowHandle()));
  55284. MCDraw (qmci->controller, (WindowRef) getWindowHandle());
  55285. MacSetPort (savedPort);
  55286. ComponentPeer* const peer = getPeer();
  55287. if (peer != 0)
  55288. {
  55289. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55290. getScreenY() - peer->getScreenY(),
  55291. getWidth(), getHeight());
  55292. }
  55293. timerCallback();
  55294. }
  55295. static const Rectangle getMoviePos (Component* const c)
  55296. {
  55297. return Rectangle (c->getScreenX() - c->getTopLevelComponent()->getScreenX(),
  55298. c->getScreenY() - c->getTopLevelComponent()->getScreenY(),
  55299. jmax (1, c->getWidth()),
  55300. jmax (1, c->getHeight()));
  55301. }
  55302. void QuickTimeMovieComponent::moved()
  55303. {
  55304. resized();
  55305. }
  55306. void QuickTimeMovieComponent::resized()
  55307. {
  55308. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55309. if (qmci->controller != 0 && isShowing())
  55310. {
  55311. checkWindowAssociation();
  55312. GrafPtr port = getPortForWindow (getWindowHandle());
  55313. if (port != 0)
  55314. {
  55315. GrafPtr savedPort;
  55316. GetPort (&savedPort);
  55317. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55318. MacSetPort (port);
  55319. lastPositionApplied = getMoviePos (this);
  55320. Rect r;
  55321. r.left = (short) lastPositionApplied.getX();
  55322. r.top = (short) lastPositionApplied.getY();
  55323. r.right = (short) lastPositionApplied.getRight();
  55324. r.bottom = (short) lastPositionApplied.getBottom();
  55325. if (MCGetVisible (qmci->controller))
  55326. MCSetControllerBoundsRect (qmci->controller, &r);
  55327. else
  55328. SetMovieBox (qmci->movie, &r);
  55329. if (! isPlaying())
  55330. timerCallback();
  55331. MacSetPort (savedPort);
  55332. repaint();
  55333. }
  55334. }
  55335. }
  55336. void QuickTimeMovieComponent::visibilityChanged()
  55337. {
  55338. checkWindowAssociation();
  55339. QTWinBaseClass::visibilityChanged();
  55340. }
  55341. void QuickTimeMovieComponent::timerCallback()
  55342. {
  55343. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55344. if (qmci->controller != 0)
  55345. {
  55346. if (isTimerRunning())
  55347. startTimer (getTimerInterval());
  55348. MCIdle (qmci->controller);
  55349. if (lastPositionApplied != getMoviePos (this))
  55350. resized();
  55351. }
  55352. }
  55353. void QuickTimeMovieComponent::checkWindowAssociation()
  55354. {
  55355. void* const window = getWindowHandle();
  55356. if (window != associatedWindow
  55357. || (window != 0 && ! controllerAssignedToWindow))
  55358. {
  55359. associatedWindow = window;
  55360. assignMovieToWindow();
  55361. }
  55362. }
  55363. void QuickTimeMovieComponent::parentHierarchyChanged()
  55364. {
  55365. checkWindowAssociation();
  55366. }
  55367. void QuickTimeMovieComponent::handleMCEvent (void* ev)
  55368. {
  55369. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55370. if (qmci->controller != 0 && isShowing())
  55371. {
  55372. MacClickEventData* data = (MacClickEventData*) ev;
  55373. data->where.h -= getTopLevelComponent()->getScreenX();
  55374. data->where.v -= getTopLevelComponent()->getScreenY();
  55375. Boolean b = false;
  55376. MCPtInController (qmci->controller, data->where, &b);
  55377. if (b)
  55378. {
  55379. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  55380. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  55381. MCClick (qmci->controller,
  55382. (WindowRef) getWindowHandle(),
  55383. data->where,
  55384. data->when,
  55385. data->modifiers);
  55386. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  55387. }
  55388. }
  55389. }
  55390. #endif
  55391. // (methods common to both platforms..)
  55392. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  55393. {
  55394. Handle dataRef = 0;
  55395. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  55396. if (err == noErr)
  55397. {
  55398. Str255 suffix;
  55399. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  55400. StringPtr name = suffix;
  55401. err = PtrAndHand (name, dataRef, name[0] + 1);
  55402. if (err == noErr)
  55403. {
  55404. long atoms[3];
  55405. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  55406. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  55407. atoms[2] = EndianU32_NtoB (MovieFileType);
  55408. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  55409. if (err == noErr)
  55410. return dataRef;
  55411. }
  55412. DisposeHandle (dataRef);
  55413. }
  55414. return 0;
  55415. }
  55416. static CFStringRef juceStringToCFString (const String& s)
  55417. {
  55418. const int len = s.length();
  55419. const juce_wchar* const t = (const juce_wchar*) s;
  55420. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  55421. for (int i = 0; i <= len; ++i)
  55422. temp[i] = t[i];
  55423. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  55424. juce_free (temp);
  55425. return result;
  55426. }
  55427. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  55428. {
  55429. Boolean trueBool = true;
  55430. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  55431. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  55432. props[prop].propValueSize = sizeof (trueBool);
  55433. props[prop].propValueAddress = &trueBool;
  55434. ++prop;
  55435. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  55436. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  55437. props[prop].propValueSize = sizeof (trueBool);
  55438. props[prop].propValueAddress = &trueBool;
  55439. ++prop;
  55440. Boolean isActive = true;
  55441. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  55442. props[prop].propID = kQTNewMoviePropertyID_Active;
  55443. props[prop].propValueSize = sizeof (isActive);
  55444. props[prop].propValueAddress = &isActive;
  55445. ++prop;
  55446. #if JUCE_MAC
  55447. SetPort (0);
  55448. #else
  55449. MacSetPort (0);
  55450. #endif
  55451. jassert (prop <= 5);
  55452. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  55453. return err == noErr;
  55454. }
  55455. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  55456. {
  55457. if (input == 0)
  55458. return false;
  55459. dataHandle = 0;
  55460. bool ok = false;
  55461. QTNewMoviePropertyElement props[5];
  55462. zeromem (props, sizeof (props));
  55463. int prop = 0;
  55464. DataReferenceRecord dr;
  55465. props[prop].propClass = kQTPropertyClass_DataLocation;
  55466. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  55467. props[prop].propValueSize = sizeof (dr);
  55468. props[prop].propValueAddress = (void*) &dr;
  55469. ++prop;
  55470. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  55471. if (fin != 0)
  55472. {
  55473. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  55474. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  55475. &dr.dataRef, &dr.dataRefType);
  55476. ok = openMovie (props, prop, movie);
  55477. DisposeHandle (dr.dataRef);
  55478. CFRelease (filePath);
  55479. }
  55480. else
  55481. {
  55482. // sanity-check because this currently needs to load the whole stream into memory..
  55483. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  55484. dataHandle = NewHandle ((Size) input->getTotalLength());
  55485. HLock (dataHandle);
  55486. // read the entire stream into memory - this is a pain, but can't get it to work
  55487. // properly using a custom callback to supply the data.
  55488. input->read (*dataHandle, (int) input->getTotalLength());
  55489. HUnlock (dataHandle);
  55490. // different types to get QT to try. (We should really be a bit smarter here by
  55491. // working out in advance which one the stream contains, rather than just trying
  55492. // each one)
  55493. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  55494. "\04.avi", "\04.m4a" };
  55495. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  55496. {
  55497. /* // this fails for some bizarre reason - it can be bodged to work with
  55498. // movies, but can't seem to do it for other file types..
  55499. QTNewMovieUserProcRecord procInfo;
  55500. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  55501. procInfo.getMovieUserProcRefcon = this;
  55502. procInfo.defaultDataRef.dataRef = dataRef;
  55503. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  55504. props[prop].propClass = kQTPropertyClass_DataLocation;
  55505. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  55506. props[prop].propValueSize = sizeof (procInfo);
  55507. props[prop].propValueAddress = (void*) &procInfo;
  55508. ++prop; */
  55509. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  55510. dr.dataRefType = HandleDataHandlerSubType;
  55511. ok = openMovie (props, prop, movie);
  55512. DisposeHandle (dr.dataRef);
  55513. }
  55514. }
  55515. return ok;
  55516. }
  55517. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  55518. const bool isControllerVisible)
  55519. {
  55520. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  55521. movieFile = movieFile_;
  55522. return ok;
  55523. }
  55524. void QuickTimeMovieComponent::goToStart()
  55525. {
  55526. setPosition (0.0);
  55527. }
  55528. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  55529. const RectanglePlacement& placement)
  55530. {
  55531. int normalWidth, normalHeight;
  55532. getMovieNormalSize (normalWidth, normalHeight);
  55533. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  55534. {
  55535. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  55536. placement.applyTo (x, y, w, h,
  55537. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  55538. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  55539. if (w > 0 && h > 0)
  55540. {
  55541. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  55542. roundDoubleToInt (w), roundDoubleToInt (h));
  55543. }
  55544. }
  55545. else
  55546. {
  55547. setBounds (spaceToFitWithin);
  55548. }
  55549. }
  55550. END_JUCE_NAMESPACE
  55551. #endif
  55552. /********* End of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  55553. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  55554. #if JUCE_WIN32 || JUCE_LINUX
  55555. BEGIN_JUCE_NAMESPACE
  55556. SystemTrayIconComponent::SystemTrayIconComponent()
  55557. {
  55558. addToDesktop (0);
  55559. }
  55560. SystemTrayIconComponent::~SystemTrayIconComponent()
  55561. {
  55562. }
  55563. END_JUCE_NAMESPACE
  55564. #endif
  55565. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  55566. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  55567. BEGIN_JUCE_NAMESPACE
  55568. static const int titleH = 24;
  55569. static const int iconWidth = 80;
  55570. class AlertWindowTextEditor : public TextEditor
  55571. {
  55572. public:
  55573. #if JUCE_LINUX
  55574. #define PASSWORD_CHAR 0x2022
  55575. #else
  55576. #define PASSWORD_CHAR 0x25cf
  55577. #endif
  55578. AlertWindowTextEditor (const String& name,
  55579. const bool isPasswordBox)
  55580. : TextEditor (name,
  55581. isPasswordBox ? (const tchar) PASSWORD_CHAR
  55582. : (const tchar) 0)
  55583. {
  55584. setSelectAllWhenFocused (true);
  55585. }
  55586. ~AlertWindowTextEditor()
  55587. {
  55588. }
  55589. void returnPressed()
  55590. {
  55591. // pass these up the component hierarchy to be trigger the buttons
  55592. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  55593. }
  55594. void escapePressed()
  55595. {
  55596. // pass these up the component hierarchy to be trigger the buttons
  55597. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  55598. }
  55599. private:
  55600. AlertWindowTextEditor (const AlertWindowTextEditor&);
  55601. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  55602. };
  55603. AlertWindow::AlertWindow (const String& title,
  55604. const String& message,
  55605. AlertIconType iconType)
  55606. : TopLevelWindow (title, true),
  55607. alertIconType (iconType)
  55608. {
  55609. if (message.isEmpty())
  55610. text = T(" "); // to force an update if the message is empty
  55611. setMessage (message);
  55612. #if JUCE_MAC
  55613. setAlwaysOnTop (true);
  55614. #else
  55615. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  55616. {
  55617. Component* const c = Desktop::getInstance().getComponent (i);
  55618. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  55619. {
  55620. setAlwaysOnTop (true);
  55621. break;
  55622. }
  55623. }
  55624. #endif
  55625. lookAndFeelChanged();
  55626. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  55627. }
  55628. AlertWindow::~AlertWindow()
  55629. {
  55630. for (int i = customComps.size(); --i >= 0;)
  55631. removeChildComponent ((Component*) customComps[i]);
  55632. deleteAllChildren();
  55633. }
  55634. void AlertWindow::setMessage (const String& message)
  55635. {
  55636. const String newMessage (message.substring (0, 2048));
  55637. if (text != newMessage)
  55638. {
  55639. text = newMessage;
  55640. font.setHeight (15.0f);
  55641. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  55642. textLayout.setText (getName() + T("\n\n"), titleFont);
  55643. textLayout.appendText (text, font);
  55644. updateLayout (true);
  55645. repaint();
  55646. }
  55647. }
  55648. void AlertWindow::buttonClicked (Button* button)
  55649. {
  55650. for (int i = 0; i < buttons.size(); i++)
  55651. {
  55652. TextButton* const c = (TextButton*) buttons[i];
  55653. if (button->getName() == c->getName())
  55654. {
  55655. if (c->getParentComponent() != 0)
  55656. c->getParentComponent()->exitModalState (c->getCommandID());
  55657. break;
  55658. }
  55659. }
  55660. }
  55661. void AlertWindow::addButton (const String& name,
  55662. const int returnValue,
  55663. const KeyPress& shortcutKey1,
  55664. const KeyPress& shortcutKey2)
  55665. {
  55666. TextButton* const b = new TextButton (name, String::empty);
  55667. b->setWantsKeyboardFocus (true);
  55668. b->setMouseClickGrabsKeyboardFocus (false);
  55669. b->setCommandToTrigger (0, returnValue, false);
  55670. b->addShortcut (shortcutKey1);
  55671. b->addShortcut (shortcutKey2);
  55672. b->addButtonListener (this);
  55673. b->changeWidthToFitText (28);
  55674. addAndMakeVisible (b, 0);
  55675. buttons.add (b);
  55676. updateLayout (false);
  55677. }
  55678. int AlertWindow::getNumButtons() const
  55679. {
  55680. return buttons.size();
  55681. }
  55682. void AlertWindow::addTextEditor (const String& name,
  55683. const String& initialContents,
  55684. const String& onScreenLabel,
  55685. const bool isPasswordBox)
  55686. {
  55687. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  55688. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  55689. tc->setFont (font);
  55690. tc->setText (initialContents);
  55691. tc->setCaretPosition (initialContents.length());
  55692. addAndMakeVisible (tc);
  55693. textBoxes.add (tc);
  55694. allComps.add (tc);
  55695. textboxNames.add (onScreenLabel);
  55696. updateLayout (false);
  55697. }
  55698. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  55699. {
  55700. for (int i = textBoxes.size(); --i >= 0;)
  55701. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  55702. return ((TextEditor*)textBoxes[i])->getText();
  55703. return String::empty;
  55704. }
  55705. void AlertWindow::addComboBox (const String& name,
  55706. const StringArray& items,
  55707. const String& onScreenLabel)
  55708. {
  55709. ComboBox* const cb = new ComboBox (name);
  55710. for (int i = 0; i < items.size(); ++i)
  55711. cb->addItem (items[i], i + 1);
  55712. addAndMakeVisible (cb);
  55713. cb->setSelectedItemIndex (0);
  55714. comboBoxes.add (cb);
  55715. allComps.add (cb);
  55716. comboBoxNames.add (onScreenLabel);
  55717. updateLayout (false);
  55718. }
  55719. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  55720. {
  55721. for (int i = comboBoxes.size(); --i >= 0;)
  55722. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  55723. return (ComboBox*) comboBoxes[i];
  55724. return 0;
  55725. }
  55726. class AlertTextComp : public TextEditor
  55727. {
  55728. AlertTextComp (const AlertTextComp&);
  55729. const AlertTextComp& operator= (const AlertTextComp&);
  55730. int bestWidth;
  55731. public:
  55732. AlertTextComp (const String& message,
  55733. const Font& font)
  55734. {
  55735. setReadOnly (true);
  55736. setMultiLine (true, true);
  55737. setCaretVisible (false);
  55738. setScrollbarsShown (true);
  55739. lookAndFeelChanged();
  55740. setWantsKeyboardFocus (false);
  55741. setFont (font);
  55742. setText (message, false);
  55743. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  55744. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  55745. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  55746. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  55747. }
  55748. ~AlertTextComp()
  55749. {
  55750. }
  55751. int getPreferredWidth() const throw() { return bestWidth; }
  55752. void updateLayout (const int width)
  55753. {
  55754. TextLayout text;
  55755. text.appendText (getText(), getFont());
  55756. text.layout (width - 8, Justification::topLeft, true);
  55757. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  55758. }
  55759. };
  55760. void AlertWindow::addTextBlock (const String& text)
  55761. {
  55762. AlertTextComp* const c = new AlertTextComp (text, font);
  55763. textBlocks.add (c);
  55764. allComps.add (c);
  55765. addAndMakeVisible (c);
  55766. updateLayout (false);
  55767. }
  55768. void AlertWindow::addProgressBarComponent (double& progressValue)
  55769. {
  55770. ProgressBar* const pb = new ProgressBar (progressValue);
  55771. progressBars.add (pb);
  55772. allComps.add (pb);
  55773. addAndMakeVisible (pb);
  55774. updateLayout (false);
  55775. }
  55776. void AlertWindow::addCustomComponent (Component* const component)
  55777. {
  55778. customComps.add (component);
  55779. allComps.add (component);
  55780. addAndMakeVisible (component);
  55781. updateLayout (false);
  55782. }
  55783. int AlertWindow::getNumCustomComponents() const
  55784. {
  55785. return customComps.size();
  55786. }
  55787. Component* AlertWindow::getCustomComponent (const int index) const
  55788. {
  55789. return (Component*) customComps [index];
  55790. }
  55791. Component* AlertWindow::removeCustomComponent (const int index)
  55792. {
  55793. Component* const c = getCustomComponent (index);
  55794. if (c != 0)
  55795. {
  55796. customComps.removeValue (c);
  55797. allComps.removeValue (c);
  55798. removeChildComponent (c);
  55799. updateLayout (false);
  55800. }
  55801. return c;
  55802. }
  55803. void AlertWindow::paint (Graphics& g)
  55804. {
  55805. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  55806. g.setColour (Colours::black);
  55807. g.setFont (12.0f);
  55808. int i;
  55809. for (i = textBoxes.size(); --i >= 0;)
  55810. {
  55811. if (textboxNames[i].isNotEmpty())
  55812. {
  55813. const TextEditor* const te = (TextEditor*) textBoxes[i];
  55814. g.drawFittedText (textboxNames[i],
  55815. te->getX(), te->getY() - 14,
  55816. te->getWidth(), 14,
  55817. Justification::centredLeft, 1);
  55818. }
  55819. }
  55820. for (i = comboBoxNames.size(); --i >= 0;)
  55821. {
  55822. if (comboBoxNames[i].isNotEmpty())
  55823. {
  55824. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  55825. g.drawFittedText (comboBoxNames[i],
  55826. cb->getX(), cb->getY() - 14,
  55827. cb->getWidth(), 14,
  55828. Justification::centredLeft, 1);
  55829. }
  55830. }
  55831. }
  55832. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  55833. {
  55834. const int wid = jmax (font.getStringWidth (text),
  55835. font.getStringWidth (getName()));
  55836. const int sw = (int) sqrt (font.getHeight() * wid);
  55837. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  55838. const int edgeGap = 10;
  55839. int iconSpace;
  55840. if (alertIconType == NoIcon)
  55841. {
  55842. textLayout.layout (w, Justification::horizontallyCentred, true);
  55843. iconSpace = 0;
  55844. }
  55845. else
  55846. {
  55847. textLayout.layout (w, Justification::left, true);
  55848. iconSpace = iconWidth;
  55849. }
  55850. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  55851. w = jmin (w, (int) (getParentWidth() * 0.7f));
  55852. const int textLayoutH = textLayout.getHeight();
  55853. const int textBottom = 16 + titleH + textLayoutH;
  55854. int h = textBottom;
  55855. int buttonW = 40;
  55856. int i;
  55857. for (i = 0; i < buttons.size(); ++i)
  55858. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  55859. w = jmax (buttonW, w);
  55860. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  55861. if (buttons.size() > 0)
  55862. h += 20 + ((TextButton*) buttons[0])->getHeight();
  55863. for (i = customComps.size(); --i >= 0;)
  55864. {
  55865. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  55866. h += 10 + ((Component*) customComps[i])->getHeight();
  55867. }
  55868. for (i = textBlocks.size(); --i >= 0;)
  55869. {
  55870. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  55871. w = jmax (w, ac->getPreferredWidth());
  55872. }
  55873. w = jmin (w, (int) (getParentWidth() * 0.7f));
  55874. for (i = textBlocks.size(); --i >= 0;)
  55875. {
  55876. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  55877. ac->updateLayout ((int) (w * 0.8f));
  55878. h += ac->getHeight() + 10;
  55879. }
  55880. h = jmin (getParentHeight() - 50, h);
  55881. if (onlyIncreaseSize)
  55882. {
  55883. w = jmax (w, getWidth());
  55884. h = jmax (h, getHeight());
  55885. }
  55886. if (! isVisible())
  55887. {
  55888. centreAroundComponent (0, w, h);
  55889. }
  55890. else
  55891. {
  55892. const int cx = getX() + getWidth() / 2;
  55893. const int cy = getY() + getHeight() / 2;
  55894. setBounds (cx - w / 2,
  55895. cy - h / 2,
  55896. w, h);
  55897. }
  55898. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  55899. const int spacer = 16;
  55900. int totalWidth = -spacer;
  55901. for (i = buttons.size(); --i >= 0;)
  55902. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  55903. int x = (w - totalWidth) / 2;
  55904. int y = (int) (getHeight() * 0.95f);
  55905. for (i = 0; i < buttons.size(); ++i)
  55906. {
  55907. TextButton* const c = (TextButton*) buttons[i];
  55908. int ny = proportionOfHeight (0.95f) - c->getHeight();
  55909. c->setTopLeftPosition (x, ny);
  55910. if (ny < y)
  55911. y = ny;
  55912. x += c->getWidth() + spacer;
  55913. c->toFront (false);
  55914. }
  55915. y = textBottom;
  55916. for (i = 0; i < allComps.size(); ++i)
  55917. {
  55918. Component* const c = (Component*) allComps[i];
  55919. const int h = 22;
  55920. const int comboIndex = comboBoxes.indexOf (c);
  55921. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  55922. y += 18;
  55923. const int tbIndex = textBoxes.indexOf (c);
  55924. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  55925. y += 18;
  55926. if (customComps.contains (c) || textBlocks.contains (c))
  55927. {
  55928. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  55929. y += c->getHeight() + 10;
  55930. }
  55931. else
  55932. {
  55933. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  55934. y += h + 10;
  55935. }
  55936. }
  55937. setWantsKeyboardFocus (getNumChildComponents() == 0);
  55938. }
  55939. bool AlertWindow::containsAnyExtraComponents() const
  55940. {
  55941. return textBoxes.size()
  55942. + comboBoxes.size()
  55943. + progressBars.size()
  55944. + customComps.size() > 0;
  55945. }
  55946. void AlertWindow::mouseDown (const MouseEvent&)
  55947. {
  55948. dragger.startDraggingComponent (this, &constrainer);
  55949. }
  55950. void AlertWindow::mouseDrag (const MouseEvent& e)
  55951. {
  55952. dragger.dragComponent (this, e);
  55953. }
  55954. bool AlertWindow::keyPressed (const KeyPress& key)
  55955. {
  55956. for (int i = buttons.size(); --i >= 0;)
  55957. {
  55958. TextButton* const b = (TextButton*) buttons[i];
  55959. if (b->isRegisteredForShortcut (key))
  55960. {
  55961. b->triggerClick();
  55962. return true;
  55963. }
  55964. }
  55965. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  55966. {
  55967. exitModalState (0);
  55968. return true;
  55969. }
  55970. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  55971. {
  55972. ((TextButton*) buttons.getFirst())->triggerClick();
  55973. return true;
  55974. }
  55975. return false;
  55976. }
  55977. void AlertWindow::lookAndFeelChanged()
  55978. {
  55979. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  55980. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  55981. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  55982. }
  55983. struct AlertWindowInfo
  55984. {
  55985. String title, message, button1, button2, button3;
  55986. AlertWindow::AlertIconType iconType;
  55987. int numButtons;
  55988. int run() const
  55989. {
  55990. return (int) (pointer_sized_int)
  55991. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  55992. }
  55993. private:
  55994. int show() const
  55995. {
  55996. AlertWindow aw (title, message, iconType);
  55997. if (numButtons == 1)
  55998. {
  55999. aw.addButton (button1, 0,
  56000. KeyPress (KeyPress::escapeKey, 0, 0),
  56001. KeyPress (KeyPress::returnKey, 0, 0));
  56002. }
  56003. else
  56004. {
  56005. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56006. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56007. if (button1ShortCut == button2ShortCut)
  56008. button2ShortCut = KeyPress();
  56009. if (numButtons == 2)
  56010. {
  56011. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56012. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56013. }
  56014. else
  56015. {
  56016. jassert (numButtons == 3);
  56017. aw.addButton (button1, 1, button1ShortCut);
  56018. aw.addButton (button2, 2, button2ShortCut);
  56019. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56020. }
  56021. }
  56022. return aw.runModalLoop();
  56023. }
  56024. static void* showCallback (void* userData)
  56025. {
  56026. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56027. }
  56028. };
  56029. void AlertWindow::showMessageBox (AlertIconType iconType,
  56030. const String& title,
  56031. const String& message,
  56032. const String& buttonText)
  56033. {
  56034. AlertWindowInfo info;
  56035. info.title = title;
  56036. info.message = message;
  56037. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  56038. info.iconType = iconType;
  56039. info.numButtons = 1;
  56040. info.run();
  56041. }
  56042. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  56043. const String& title,
  56044. const String& message,
  56045. const String& button1Text,
  56046. const String& button2Text)
  56047. {
  56048. AlertWindowInfo info;
  56049. info.title = title;
  56050. info.message = message;
  56051. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  56052. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  56053. info.iconType = iconType;
  56054. info.numButtons = 2;
  56055. return info.run() != 0;
  56056. }
  56057. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  56058. const String& title,
  56059. const String& message,
  56060. const String& button1Text,
  56061. const String& button2Text,
  56062. const String& button3Text)
  56063. {
  56064. AlertWindowInfo info;
  56065. info.title = title;
  56066. info.message = message;
  56067. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  56068. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  56069. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  56070. info.iconType = iconType;
  56071. info.numButtons = 3;
  56072. return info.run();
  56073. }
  56074. END_JUCE_NAMESPACE
  56075. /********* End of inlined file: juce_AlertWindow.cpp *********/
  56076. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  56077. BEGIN_JUCE_NAMESPACE
  56078. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  56079. // these are over in juce_component.cpp
  56080. extern int64 juce_recentMouseDownTimes[4];
  56081. extern int juce_recentMouseDownX [4];
  56082. extern int juce_recentMouseDownY [4];
  56083. extern Component* juce_recentMouseDownComponent [4];
  56084. extern int juce_LastMousePosX;
  56085. extern int juce_LastMousePosY;
  56086. extern int juce_MouseClickCounter;
  56087. extern bool juce_MouseHasMovedSignificantlySincePressed;
  56088. static const int fakeMouseMoveMessage = 0x7fff00ff;
  56089. static VoidArray heavyweightPeers (4);
  56090. ComponentPeer::ComponentPeer (Component* const component_,
  56091. const int styleFlags_) throw()
  56092. : component (component_),
  56093. styleFlags (styleFlags_),
  56094. lastPaintTime (0),
  56095. constrainer (0),
  56096. lastFocusedComponent (0),
  56097. dragAndDropTargetComponent (0),
  56098. lastDragAndDropCompUnderMouse (0),
  56099. fakeMouseMessageSent (false),
  56100. isWindowMinimised (false)
  56101. {
  56102. heavyweightPeers.add (this);
  56103. }
  56104. ComponentPeer::~ComponentPeer()
  56105. {
  56106. heavyweightPeers.removeValue (this);
  56107. delete dragAndDropTargetComponent;
  56108. }
  56109. int ComponentPeer::getNumPeers() throw()
  56110. {
  56111. return heavyweightPeers.size();
  56112. }
  56113. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  56114. {
  56115. return (ComponentPeer*) heavyweightPeers [index];
  56116. }
  56117. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  56118. {
  56119. for (int i = heavyweightPeers.size(); --i >= 0;)
  56120. {
  56121. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  56122. if (peer->getComponent() == component)
  56123. return peer;
  56124. }
  56125. return 0;
  56126. }
  56127. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  56128. {
  56129. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  56130. }
  56131. void ComponentPeer::updateCurrentModifiers() throw()
  56132. {
  56133. ModifierKeys::updateCurrentModifiers();
  56134. }
  56135. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  56136. {
  56137. jassert (component->isValidComponent());
  56138. updateCurrentModifiers();
  56139. Component* c = component->getComponentAt (x, y);
  56140. const ComponentDeletionWatcher deletionChecker (component);
  56141. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  56142. {
  56143. jassert (Component::componentUnderMouse->isValidComponent());
  56144. const int oldX = x;
  56145. const int oldY = y;
  56146. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56147. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56148. Component::componentUnderMouse = 0;
  56149. if (deletionChecker.hasBeenDeleted())
  56150. return;
  56151. c = component->getComponentAt (oldX, oldY);
  56152. }
  56153. Component::componentUnderMouse = c;
  56154. if (Component::componentUnderMouse != 0)
  56155. {
  56156. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56157. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56158. }
  56159. }
  56160. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  56161. {
  56162. jassert (component->isValidComponent());
  56163. updateCurrentModifiers();
  56164. fakeMouseMessageSent = false;
  56165. const ComponentDeletionWatcher deletionChecker (component);
  56166. Component* c = component->getComponentAt (x, y);
  56167. if (c != Component::componentUnderMouse)
  56168. {
  56169. const int oldX = x;
  56170. const int oldY = y;
  56171. if (Component::componentUnderMouse != 0)
  56172. {
  56173. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56174. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56175. x = oldX;
  56176. y = oldY;
  56177. Component::componentUnderMouse = 0;
  56178. if (deletionChecker.hasBeenDeleted())
  56179. return; // if this window has just been deleted..
  56180. c = component->getComponentAt (x, y);
  56181. }
  56182. Component::componentUnderMouse = c;
  56183. if (c != 0)
  56184. {
  56185. component->relativePositionToOtherComponent (c, x, y);
  56186. c->internalMouseEnter (x, y, time);
  56187. x = oldX;
  56188. y = oldY;
  56189. if (deletionChecker.hasBeenDeleted())
  56190. return; // if this window has just been deleted..
  56191. }
  56192. }
  56193. if (Component::componentUnderMouse != 0)
  56194. {
  56195. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56196. Component::componentUnderMouse->internalMouseMove (x, y, time);
  56197. }
  56198. }
  56199. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  56200. {
  56201. ++juce_MouseClickCounter;
  56202. updateCurrentModifiers();
  56203. int numMouseButtonsDown = 0;
  56204. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  56205. ++numMouseButtonsDown;
  56206. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  56207. ++numMouseButtonsDown;
  56208. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  56209. ++numMouseButtonsDown;
  56210. if (numMouseButtonsDown == 1)
  56211. {
  56212. Component::componentUnderMouse = component->getComponentAt (x, y);
  56213. if (Component::componentUnderMouse != 0)
  56214. {
  56215. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  56216. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  56217. {
  56218. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  56219. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  56220. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  56221. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  56222. }
  56223. juce_recentMouseDownTimes[0] = time;
  56224. juce_recentMouseDownX[0] = x;
  56225. juce_recentMouseDownY[0] = y;
  56226. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  56227. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  56228. juce_MouseHasMovedSignificantlySincePressed = false;
  56229. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56230. Component::componentUnderMouse->internalMouseDown (x, y);
  56231. }
  56232. }
  56233. }
  56234. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  56235. {
  56236. updateCurrentModifiers();
  56237. if (Component::componentUnderMouse != 0)
  56238. {
  56239. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56240. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  56241. }
  56242. }
  56243. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  56244. {
  56245. updateCurrentModifiers();
  56246. int numMouseButtonsDown = 0;
  56247. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  56248. ++numMouseButtonsDown;
  56249. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  56250. ++numMouseButtonsDown;
  56251. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  56252. ++numMouseButtonsDown;
  56253. if (numMouseButtonsDown == 1)
  56254. {
  56255. const ComponentDeletionWatcher deletionChecker (component);
  56256. Component* c = component->getComponentAt (x, y);
  56257. if (c != Component::componentUnderMouse)
  56258. {
  56259. const int oldX = x;
  56260. const int oldY = y;
  56261. if (Component::componentUnderMouse != 0)
  56262. {
  56263. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56264. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56265. x = oldX;
  56266. y = oldY;
  56267. if (Component::componentUnderMouse != 0)
  56268. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56269. if (deletionChecker.hasBeenDeleted())
  56270. return;
  56271. c = component->getComponentAt (oldX, oldY);
  56272. }
  56273. Component::componentUnderMouse = c;
  56274. if (Component::componentUnderMouse != 0)
  56275. {
  56276. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56277. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56278. }
  56279. }
  56280. else
  56281. {
  56282. if (Component::componentUnderMouse != 0)
  56283. {
  56284. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56285. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56286. }
  56287. }
  56288. }
  56289. }
  56290. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  56291. {
  56292. jassert (component->isValidComponent());
  56293. updateCurrentModifiers();
  56294. if (Component::componentUnderMouse != 0)
  56295. {
  56296. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56297. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56298. Component::componentUnderMouse = 0;
  56299. }
  56300. }
  56301. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  56302. {
  56303. updateCurrentModifiers();
  56304. if (Component::componentUnderMouse != 0)
  56305. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  56306. }
  56307. void ComponentPeer::sendFakeMouseMove() throw()
  56308. {
  56309. if ((! fakeMouseMessageSent)
  56310. && component->flags.hasHeavyweightPeerFlag
  56311. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  56312. {
  56313. if (! isMinimised())
  56314. {
  56315. int realX, realY, realW, realH;
  56316. getBounds (realX, realY, realW, realH);
  56317. component->bounds_.setBounds (realX, realY, realW, realH);
  56318. }
  56319. int x, y;
  56320. component->getMouseXYRelative (x, y);
  56321. if (((unsigned int) x) < (unsigned int) component->getWidth()
  56322. && ((unsigned int) y) < (unsigned int) component->getHeight()
  56323. && contains (x, y, false))
  56324. {
  56325. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  56326. }
  56327. fakeMouseMessageSent = true;
  56328. }
  56329. }
  56330. void ComponentPeer::handleMessage (const Message& message)
  56331. {
  56332. if (message.intParameter1 == fakeMouseMoveMessage)
  56333. {
  56334. handleMouseMove (message.intParameter2,
  56335. message.intParameter3,
  56336. Time::currentTimeMillis());
  56337. }
  56338. }
  56339. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  56340. {
  56341. Graphics g (&contextToPaintTo);
  56342. #if JUCE_ENABLE_REPAINT_DEBUGGING
  56343. g.saveState();
  56344. #endif
  56345. JUCE_TRY
  56346. {
  56347. component->paintEntireComponent (g);
  56348. }
  56349. JUCE_CATCH_EXCEPTION
  56350. #if JUCE_ENABLE_REPAINT_DEBUGGING
  56351. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  56352. // clearly when things are being repainted.
  56353. {
  56354. g.restoreState();
  56355. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  56356. (uint8) Random::getSystemRandom().nextInt (255),
  56357. (uint8) Random::getSystemRandom().nextInt (255),
  56358. (uint8) 0x50));
  56359. }
  56360. #endif
  56361. }
  56362. bool ComponentPeer::handleKeyPress (const int keyCode,
  56363. const juce_wchar textCharacter)
  56364. {
  56365. updateCurrentModifiers();
  56366. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  56367. ? Component::currentlyFocusedComponent
  56368. : component;
  56369. if (target->isCurrentlyBlockedByAnotherModalComponent())
  56370. {
  56371. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56372. if (currentModalComp != 0)
  56373. target = currentModalComp;
  56374. }
  56375. const KeyPress keyInfo (keyCode,
  56376. ModifierKeys::getCurrentModifiers().getRawFlags()
  56377. & ModifierKeys::allKeyboardModifiers,
  56378. textCharacter);
  56379. bool keyWasUsed = false;
  56380. while (target != 0)
  56381. {
  56382. const ComponentDeletionWatcher deletionChecker (target);
  56383. if (target->keyListeners_ != 0)
  56384. {
  56385. for (int i = target->keyListeners_->size(); --i >= 0;)
  56386. {
  56387. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  56388. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56389. return keyWasUsed;
  56390. i = jmin (i, target->keyListeners_->size());
  56391. }
  56392. }
  56393. keyWasUsed = target->keyPressed (keyInfo);
  56394. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56395. break;
  56396. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  56397. {
  56398. Component::getCurrentlyFocusedComponent()
  56399. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  56400. keyWasUsed = true;
  56401. break;
  56402. }
  56403. target = target->parentComponent_;
  56404. }
  56405. return keyWasUsed;
  56406. }
  56407. bool ComponentPeer::handleKeyUpOrDown()
  56408. {
  56409. updateCurrentModifiers();
  56410. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  56411. ? Component::currentlyFocusedComponent
  56412. : component;
  56413. if (target->isCurrentlyBlockedByAnotherModalComponent())
  56414. {
  56415. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56416. if (currentModalComp != 0)
  56417. target = currentModalComp;
  56418. }
  56419. bool keyWasUsed = false;
  56420. while (target != 0)
  56421. {
  56422. const ComponentDeletionWatcher deletionChecker (target);
  56423. keyWasUsed = target->keyStateChanged();
  56424. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56425. break;
  56426. if (target->keyListeners_ != 0)
  56427. {
  56428. for (int i = target->keyListeners_->size(); --i >= 0;)
  56429. {
  56430. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  56431. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56432. return keyWasUsed;
  56433. i = jmin (i, target->keyListeners_->size());
  56434. }
  56435. }
  56436. target = target->parentComponent_;
  56437. }
  56438. return keyWasUsed;
  56439. }
  56440. void ComponentPeer::handleModifierKeysChange()
  56441. {
  56442. updateCurrentModifiers();
  56443. Component* target = Component::getComponentUnderMouse();
  56444. if (target == 0)
  56445. target = Component::getCurrentlyFocusedComponent();
  56446. if (target == 0)
  56447. target = component;
  56448. if (target->isValidComponent())
  56449. target->internalModifierKeysChanged();
  56450. }
  56451. void ComponentPeer::handleBroughtToFront()
  56452. {
  56453. updateCurrentModifiers();
  56454. if (component != 0)
  56455. component->internalBroughtToFront();
  56456. }
  56457. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  56458. {
  56459. constrainer = newConstrainer;
  56460. }
  56461. void ComponentPeer::handleMovedOrResized()
  56462. {
  56463. jassert (component->isValidComponent());
  56464. updateCurrentModifiers();
  56465. const bool nowMinimised = isMinimised();
  56466. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  56467. {
  56468. const ComponentDeletionWatcher deletionChecker (component);
  56469. int realX, realY, realW, realH;
  56470. getBounds (realX, realY, realW, realH);
  56471. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  56472. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  56473. if (wasMoved || wasResized)
  56474. {
  56475. component->bounds_.setBounds (realX, realY, realW, realH);
  56476. if (wasResized)
  56477. component->repaint();
  56478. component->sendMovedResizedMessages (wasMoved, wasResized);
  56479. if (deletionChecker.hasBeenDeleted())
  56480. return;
  56481. }
  56482. }
  56483. if (isWindowMinimised != nowMinimised)
  56484. {
  56485. isWindowMinimised = nowMinimised;
  56486. component->minimisationStateChanged (nowMinimised);
  56487. component->sendVisibilityChangeMessage();
  56488. }
  56489. if (! isFullScreen())
  56490. lastNonFullscreenBounds = component->getBounds();
  56491. }
  56492. void ComponentPeer::handleFocusGain()
  56493. {
  56494. updateCurrentModifiers();
  56495. if (component->isParentOf (lastFocusedComponent))
  56496. {
  56497. Component::currentlyFocusedComponent = lastFocusedComponent;
  56498. Desktop::getInstance().triggerFocusCallback();
  56499. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  56500. }
  56501. else
  56502. {
  56503. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  56504. {
  56505. component->grabKeyboardFocus();
  56506. }
  56507. else
  56508. {
  56509. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56510. if (currentModalComp != 0)
  56511. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  56512. }
  56513. }
  56514. }
  56515. void ComponentPeer::handleFocusLoss()
  56516. {
  56517. updateCurrentModifiers();
  56518. if (component->hasKeyboardFocus (true))
  56519. {
  56520. lastFocusedComponent = Component::currentlyFocusedComponent;
  56521. if (lastFocusedComponent != 0)
  56522. {
  56523. Component::currentlyFocusedComponent = 0;
  56524. Desktop::getInstance().triggerFocusCallback();
  56525. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  56526. }
  56527. }
  56528. }
  56529. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  56530. {
  56531. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  56532. ? lastFocusedComponent
  56533. : component;
  56534. }
  56535. void ComponentPeer::handleScreenSizeChange()
  56536. {
  56537. updateCurrentModifiers();
  56538. component->parentSizeChanged();
  56539. handleMovedOrResized();
  56540. }
  56541. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  56542. {
  56543. lastNonFullscreenBounds = newBounds;
  56544. }
  56545. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  56546. {
  56547. return lastNonFullscreenBounds;
  56548. }
  56549. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  56550. const StringArray& files,
  56551. FileDragAndDropTarget* const lastOne)
  56552. {
  56553. while (c != 0)
  56554. {
  56555. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  56556. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  56557. return t;
  56558. c = c->getParentComponent();
  56559. }
  56560. return 0;
  56561. }
  56562. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  56563. {
  56564. updateCurrentModifiers();
  56565. FileDragAndDropTarget* lastTarget = 0;
  56566. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  56567. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  56568. FileDragAndDropTarget* newTarget = 0;
  56569. Component* const compUnderMouse = component->getComponentAt (x, y);
  56570. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  56571. {
  56572. lastDragAndDropCompUnderMouse = compUnderMouse;
  56573. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  56574. if (newTarget != lastTarget)
  56575. {
  56576. if (lastTarget != 0)
  56577. lastTarget->fileDragExit (files);
  56578. deleteAndZero (dragAndDropTargetComponent);
  56579. if (newTarget != 0)
  56580. {
  56581. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  56582. int mx = x, my = y;
  56583. component->relativePositionToOtherComponent (targetComp, mx, my);
  56584. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  56585. newTarget->fileDragEnter (files, mx, my);
  56586. }
  56587. }
  56588. }
  56589. else
  56590. {
  56591. newTarget = lastTarget;
  56592. }
  56593. if (newTarget != 0)
  56594. {
  56595. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  56596. component->relativePositionToOtherComponent (targetComp, x, y);
  56597. newTarget->fileDragMove (files, x, y);
  56598. }
  56599. }
  56600. void ComponentPeer::handleFileDragExit (const StringArray& files)
  56601. {
  56602. handleFileDragMove (files, -1, -1);
  56603. jassert (dragAndDropTargetComponent == 0);
  56604. lastDragAndDropCompUnderMouse = 0;
  56605. }
  56606. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  56607. {
  56608. handleFileDragMove (files, x, y);
  56609. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  56610. {
  56611. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  56612. deleteAndZero (dragAndDropTargetComponent);
  56613. lastDragAndDropCompUnderMouse = 0;
  56614. if (target != 0)
  56615. {
  56616. Component* const targetComp = dynamic_cast <Component*> (target);
  56617. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  56618. {
  56619. targetComp->internalModalInputAttempt();
  56620. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  56621. return;
  56622. }
  56623. component->relativePositionToOtherComponent (targetComp, x, y);
  56624. target->filesDropped (files, x, y);
  56625. }
  56626. }
  56627. }
  56628. void ComponentPeer::handleUserClosingWindow()
  56629. {
  56630. updateCurrentModifiers();
  56631. component->userTriedToCloseWindow();
  56632. }
  56633. void ComponentPeer::clearMaskedRegion() throw()
  56634. {
  56635. maskedRegion.clear();
  56636. }
  56637. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  56638. {
  56639. maskedRegion.add (x, y, w, h);
  56640. }
  56641. END_JUCE_NAMESPACE
  56642. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  56643. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  56644. BEGIN_JUCE_NAMESPACE
  56645. DialogWindow::DialogWindow (const String& name,
  56646. const Colour& backgroundColour_,
  56647. const bool escapeKeyTriggersCloseButton_,
  56648. const bool addToDesktop_)
  56649. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  56650. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  56651. {
  56652. }
  56653. DialogWindow::~DialogWindow()
  56654. {
  56655. }
  56656. void DialogWindow::resized()
  56657. {
  56658. DocumentWindow::resized();
  56659. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  56660. if (escapeKeyTriggersCloseButton
  56661. && getCloseButton() != 0
  56662. && ! getCloseButton()->isRegisteredForShortcut (esc))
  56663. {
  56664. getCloseButton()->addShortcut (esc);
  56665. }
  56666. }
  56667. class TempDialogWindow : public DialogWindow
  56668. {
  56669. public:
  56670. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  56671. : DialogWindow (title, colour, escapeCloses, true)
  56672. {
  56673. }
  56674. ~TempDialogWindow()
  56675. {
  56676. }
  56677. void closeButtonPressed()
  56678. {
  56679. setVisible (false);
  56680. }
  56681. private:
  56682. TempDialogWindow (const TempDialogWindow&);
  56683. const TempDialogWindow& operator= (const TempDialogWindow&);
  56684. };
  56685. int DialogWindow::showModalDialog (const String& dialogTitle,
  56686. Component* contentComponent,
  56687. Component* componentToCentreAround,
  56688. const Colour& colour,
  56689. const bool escapeKeyTriggersCloseButton,
  56690. const bool shouldBeResizable,
  56691. const bool useBottomRightCornerResizer)
  56692. {
  56693. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  56694. dw.setContentComponent (contentComponent, true, true);
  56695. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  56696. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  56697. const int result = dw.runModalLoop();
  56698. dw.setContentComponent (0, false);
  56699. return result;
  56700. }
  56701. END_JUCE_NAMESPACE
  56702. /********* End of inlined file: juce_DialogWindow.cpp *********/
  56703. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  56704. BEGIN_JUCE_NAMESPACE
  56705. DocumentWindow::DocumentWindow (const String& title,
  56706. const Colour& backgroundColour,
  56707. const int requiredButtons_,
  56708. const bool addToDesktop_)
  56709. : ResizableWindow (title, backgroundColour, addToDesktop_),
  56710. titleBarHeight (26),
  56711. menuBarHeight (24),
  56712. requiredButtons (requiredButtons_),
  56713. #if JUCE_MAC
  56714. positionTitleBarButtonsOnLeft (true),
  56715. #else
  56716. positionTitleBarButtonsOnLeft (false),
  56717. #endif
  56718. drawTitleTextCentred (true),
  56719. titleBarIcon (0),
  56720. menuBar (0),
  56721. menuBarModel (0)
  56722. {
  56723. zeromem (titleBarButtons, sizeof (titleBarButtons));
  56724. setResizeLimits (128, 128, 32768, 32768);
  56725. lookAndFeelChanged();
  56726. }
  56727. DocumentWindow::~DocumentWindow()
  56728. {
  56729. for (int i = 0; i < 3; ++i)
  56730. delete titleBarButtons[i];
  56731. delete titleBarIcon;
  56732. delete menuBar;
  56733. }
  56734. void DocumentWindow::repaintTitleBar()
  56735. {
  56736. const int border = getBorderSize();
  56737. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  56738. }
  56739. void DocumentWindow::setName (const String& newName)
  56740. {
  56741. if (newName != getName())
  56742. {
  56743. Component::setName (newName);
  56744. repaintTitleBar();
  56745. }
  56746. }
  56747. void DocumentWindow::setIcon (const Image* imageToUse)
  56748. {
  56749. deleteAndZero (titleBarIcon);
  56750. if (imageToUse != 0)
  56751. titleBarIcon = imageToUse->createCopy();
  56752. repaintTitleBar();
  56753. }
  56754. void DocumentWindow::setTitleBarHeight (const int newHeight)
  56755. {
  56756. titleBarHeight = newHeight;
  56757. resized();
  56758. repaintTitleBar();
  56759. }
  56760. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  56761. const bool positionTitleBarButtonsOnLeft_)
  56762. {
  56763. requiredButtons = requiredButtons_;
  56764. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  56765. lookAndFeelChanged();
  56766. }
  56767. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  56768. {
  56769. drawTitleTextCentred = textShouldBeCentred;
  56770. repaintTitleBar();
  56771. }
  56772. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  56773. const int menuBarHeight_)
  56774. {
  56775. if (menuBarModel != menuBarModel_)
  56776. {
  56777. delete menuBar;
  56778. menuBar = 0;
  56779. menuBarModel = menuBarModel_;
  56780. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  56781. : getLookAndFeel().getDefaultMenuBarHeight();
  56782. if (menuBarModel != 0)
  56783. {
  56784. // (call the Component method directly to avoid the assertion in ResizableWindow)
  56785. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  56786. menuBar->setEnabled (isActiveWindow());
  56787. }
  56788. resized();
  56789. }
  56790. }
  56791. void DocumentWindow::closeButtonPressed()
  56792. {
  56793. /* If you've got a close button, you have to override this method to get
  56794. rid of your window!
  56795. If the window is just a pop-up, you should override this method and make
  56796. it delete the window in whatever way is appropriate for your app. E.g. you
  56797. might just want to call "delete this".
  56798. If your app is centred around this window such that the whole app should quit when
  56799. the window is closed, then you will probably want to use this method as an opportunity
  56800. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  56801. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  56802. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  56803. or closing it via the taskbar icon on Windows).
  56804. */
  56805. jassertfalse
  56806. }
  56807. void DocumentWindow::minimiseButtonPressed()
  56808. {
  56809. setMinimised (true);
  56810. }
  56811. void DocumentWindow::maximiseButtonPressed()
  56812. {
  56813. setFullScreen (! isFullScreen());
  56814. }
  56815. void DocumentWindow::paint (Graphics& g)
  56816. {
  56817. ResizableWindow::paint (g);
  56818. if (resizableBorder == 0 && getBorderSize() == 1)
  56819. {
  56820. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  56821. g.drawRect (0, 0, getWidth(), getHeight());
  56822. }
  56823. const int border = getBorderSize();
  56824. g.setOrigin (border, border);
  56825. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  56826. int titleSpaceX1 = 6;
  56827. int titleSpaceX2 = getWidth() - 6;
  56828. for (int i = 0; i < 3; ++i)
  56829. {
  56830. if (titleBarButtons[i] != 0)
  56831. {
  56832. if (positionTitleBarButtonsOnLeft)
  56833. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  56834. else
  56835. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  56836. }
  56837. }
  56838. getLookAndFeel()
  56839. .drawDocumentWindowTitleBar (*this, g,
  56840. getWidth() - border * 2,
  56841. getTitleBarHeight(),
  56842. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  56843. titleBarIcon, ! drawTitleTextCentred);
  56844. }
  56845. void DocumentWindow::resized()
  56846. {
  56847. ResizableWindow::resized();
  56848. if (titleBarButtons[1] != 0)
  56849. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  56850. const int border = getBorderSize();
  56851. getLookAndFeel()
  56852. .positionDocumentWindowButtons (*this,
  56853. border, border,
  56854. getWidth() - border * 2, getTitleBarHeight(),
  56855. titleBarButtons[0],
  56856. titleBarButtons[1],
  56857. titleBarButtons[2],
  56858. positionTitleBarButtonsOnLeft);
  56859. if (menuBar != 0)
  56860. menuBar->setBounds (border, border + getTitleBarHeight(),
  56861. getWidth() - border * 2, menuBarHeight);
  56862. }
  56863. Button* DocumentWindow::getCloseButton() const throw()
  56864. {
  56865. return titleBarButtons[2];
  56866. }
  56867. Button* DocumentWindow::getMinimiseButton() const throw()
  56868. {
  56869. return titleBarButtons[0];
  56870. }
  56871. Button* DocumentWindow::getMaximiseButton() const throw()
  56872. {
  56873. return titleBarButtons[1];
  56874. }
  56875. int DocumentWindow::getDesktopWindowStyleFlags() const
  56876. {
  56877. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  56878. if ((requiredButtons & minimiseButton) != 0)
  56879. flags |= ComponentPeer::windowHasMinimiseButton;
  56880. if ((requiredButtons & maximiseButton) != 0)
  56881. flags |= ComponentPeer::windowHasMaximiseButton;
  56882. if ((requiredButtons & closeButton) != 0)
  56883. flags |= ComponentPeer::windowHasCloseButton;
  56884. return flags;
  56885. }
  56886. void DocumentWindow::lookAndFeelChanged()
  56887. {
  56888. int i;
  56889. for (i = 0; i < 3; ++i)
  56890. deleteAndZero (titleBarButtons[i]);
  56891. if (! isUsingNativeTitleBar())
  56892. {
  56893. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  56894. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  56895. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  56896. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  56897. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  56898. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  56899. for (i = 0; i < 3; ++i)
  56900. {
  56901. if (titleBarButtons[i] != 0)
  56902. {
  56903. buttonListener.owner = this;
  56904. titleBarButtons[i]->addButtonListener (&buttonListener);
  56905. titleBarButtons[i]->setWantsKeyboardFocus (false);
  56906. // (call the Component method directly to avoid the assertion in ResizableWindow)
  56907. Component::addAndMakeVisible (titleBarButtons[i]);
  56908. }
  56909. }
  56910. if (getCloseButton() != 0)
  56911. {
  56912. #if JUCE_MAC
  56913. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  56914. #else
  56915. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  56916. #endif
  56917. }
  56918. }
  56919. activeWindowStatusChanged();
  56920. ResizableWindow::lookAndFeelChanged();
  56921. }
  56922. void DocumentWindow::parentHierarchyChanged()
  56923. {
  56924. lookAndFeelChanged();
  56925. }
  56926. void DocumentWindow::activeWindowStatusChanged()
  56927. {
  56928. ResizableWindow::activeWindowStatusChanged();
  56929. for (int i = 0; i < 3; ++i)
  56930. if (titleBarButtons[i] != 0)
  56931. titleBarButtons[i]->setEnabled (isActiveWindow());
  56932. if (menuBar != 0)
  56933. menuBar->setEnabled (isActiveWindow());
  56934. }
  56935. const BorderSize DocumentWindow::getBorderThickness()
  56936. {
  56937. return BorderSize (getBorderSize());
  56938. }
  56939. const BorderSize DocumentWindow::getContentComponentBorder()
  56940. {
  56941. const int size = getBorderSize();
  56942. return BorderSize (size
  56943. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  56944. + (menuBar != 0 ? menuBarHeight : 0),
  56945. size, size, size);
  56946. }
  56947. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  56948. {
  56949. const int border = getBorderSize();
  56950. if (e.x >= border
  56951. && e.y >= border
  56952. && e.x < getWidth() - border
  56953. && e.y < border + getTitleBarHeight()
  56954. && getMaximiseButton() != 0)
  56955. {
  56956. getMaximiseButton()->triggerClick();
  56957. }
  56958. }
  56959. void DocumentWindow::userTriedToCloseWindow()
  56960. {
  56961. closeButtonPressed();
  56962. }
  56963. int DocumentWindow::getTitleBarHeight() const
  56964. {
  56965. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  56966. }
  56967. int DocumentWindow::getBorderSize() const
  56968. {
  56969. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  56970. }
  56971. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  56972. {
  56973. }
  56974. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  56975. {
  56976. if (button == owner->getMinimiseButton())
  56977. {
  56978. owner->minimiseButtonPressed();
  56979. }
  56980. else if (button == owner->getMaximiseButton())
  56981. {
  56982. owner->maximiseButtonPressed();
  56983. }
  56984. else if (button == owner->getCloseButton())
  56985. {
  56986. owner->closeButtonPressed();
  56987. }
  56988. }
  56989. END_JUCE_NAMESPACE
  56990. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  56991. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  56992. BEGIN_JUCE_NAMESPACE
  56993. ResizableWindow::ResizableWindow (const String& name,
  56994. const Colour& backgroundColour_,
  56995. const bool addToDesktop_)
  56996. : TopLevelWindow (name, addToDesktop_),
  56997. resizableCorner (0),
  56998. resizableBorder (0),
  56999. contentComponent (0),
  57000. resizeToFitContent (false),
  57001. fullscreen (false),
  57002. constrainer (0)
  57003. #ifdef JUCE_DEBUG
  57004. , hasBeenResized (false)
  57005. #endif
  57006. {
  57007. setBackgroundColour (backgroundColour_);
  57008. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57009. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57010. if (addToDesktop_)
  57011. Component::addToDesktop (getDesktopWindowStyleFlags());
  57012. }
  57013. ResizableWindow::~ResizableWindow()
  57014. {
  57015. deleteAndZero (resizableCorner);
  57016. deleteAndZero (resizableBorder);
  57017. deleteAndZero (contentComponent);
  57018. // have you been adding your own components directly to this window..? tut tut tut.
  57019. // Read the instructions for using a ResizableWindow!
  57020. jassert (getNumChildComponents() == 0);
  57021. }
  57022. int ResizableWindow::getDesktopWindowStyleFlags() const
  57023. {
  57024. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57025. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57026. flags |= ComponentPeer::windowIsResizable;
  57027. return flags;
  57028. }
  57029. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57030. const bool deleteOldOne,
  57031. const bool resizeToFit)
  57032. {
  57033. resizeToFitContent = resizeToFit;
  57034. if (contentComponent != newContentComponent)
  57035. {
  57036. if (deleteOldOne)
  57037. delete contentComponent;
  57038. else
  57039. removeChildComponent (contentComponent);
  57040. contentComponent = newContentComponent;
  57041. Component::addAndMakeVisible (contentComponent);
  57042. }
  57043. if (resizeToFit)
  57044. childBoundsChanged (contentComponent);
  57045. resized(); // must always be called to position the new content comp
  57046. }
  57047. void ResizableWindow::setContentComponentSize (int width, int height)
  57048. {
  57049. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  57050. const BorderSize border (getContentComponentBorder());
  57051. setSize (width + border.getLeftAndRight(),
  57052. height + border.getTopAndBottom());
  57053. }
  57054. const BorderSize ResizableWindow::getBorderThickness()
  57055. {
  57056. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  57057. }
  57058. const BorderSize ResizableWindow::getContentComponentBorder()
  57059. {
  57060. return getBorderThickness();
  57061. }
  57062. void ResizableWindow::moved()
  57063. {
  57064. updateLastPos();
  57065. }
  57066. void ResizableWindow::visibilityChanged()
  57067. {
  57068. TopLevelWindow::visibilityChanged();
  57069. updateLastPos();
  57070. }
  57071. void ResizableWindow::resized()
  57072. {
  57073. if (resizableBorder != 0)
  57074. {
  57075. resizableBorder->setVisible (! isFullScreen());
  57076. resizableBorder->setBorderThickness (getBorderThickness());
  57077. resizableBorder->setSize (getWidth(), getHeight());
  57078. resizableBorder->toBack();
  57079. }
  57080. if (resizableCorner != 0)
  57081. {
  57082. resizableCorner->setVisible (! isFullScreen());
  57083. const int resizerSize = 18;
  57084. resizableCorner->setBounds (getWidth() - resizerSize,
  57085. getHeight() - resizerSize,
  57086. resizerSize, resizerSize);
  57087. }
  57088. if (contentComponent != 0)
  57089. contentComponent->setBoundsInset (getContentComponentBorder());
  57090. updateLastPos();
  57091. #ifdef JUCE_DEBUG
  57092. hasBeenResized = true;
  57093. #endif
  57094. }
  57095. void ResizableWindow::childBoundsChanged (Component* child)
  57096. {
  57097. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  57098. {
  57099. // not going to look very good if this component has a zero size..
  57100. jassert (child->getWidth() > 0);
  57101. jassert (child->getHeight() > 0);
  57102. const BorderSize borders (getContentComponentBorder());
  57103. setSize (child->getWidth() + borders.getLeftAndRight(),
  57104. child->getHeight() + borders.getTopAndBottom());
  57105. }
  57106. }
  57107. void ResizableWindow::activeWindowStatusChanged()
  57108. {
  57109. const BorderSize borders (getContentComponentBorder());
  57110. repaint (0, 0, getWidth(), borders.getTop());
  57111. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  57112. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  57113. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  57114. }
  57115. void ResizableWindow::setResizable (const bool shouldBeResizable,
  57116. const bool useBottomRightCornerResizer)
  57117. {
  57118. if (shouldBeResizable)
  57119. {
  57120. if (useBottomRightCornerResizer)
  57121. {
  57122. deleteAndZero (resizableBorder);
  57123. if (resizableCorner == 0)
  57124. {
  57125. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  57126. resizableCorner->setAlwaysOnTop (true);
  57127. }
  57128. }
  57129. else
  57130. {
  57131. deleteAndZero (resizableCorner);
  57132. if (resizableBorder == 0)
  57133. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  57134. }
  57135. }
  57136. else
  57137. {
  57138. deleteAndZero (resizableCorner);
  57139. deleteAndZero (resizableBorder);
  57140. }
  57141. if (isUsingNativeTitleBar())
  57142. recreateDesktopWindow();
  57143. childBoundsChanged (contentComponent);
  57144. resized();
  57145. }
  57146. bool ResizableWindow::isResizable() const throw()
  57147. {
  57148. return resizableCorner != 0
  57149. || resizableBorder != 0;
  57150. }
  57151. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  57152. const int newMinimumHeight,
  57153. const int newMaximumWidth,
  57154. const int newMaximumHeight) throw()
  57155. {
  57156. // if you've set up a custom constrainer then these settings won't have any effect..
  57157. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  57158. if (constrainer == 0)
  57159. setConstrainer (&defaultConstrainer);
  57160. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  57161. newMaximumWidth, newMaximumHeight);
  57162. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  57163. }
  57164. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  57165. {
  57166. if (constrainer != newConstrainer)
  57167. {
  57168. constrainer = newConstrainer;
  57169. const bool useBottomRightCornerResizer = resizableCorner != 0;
  57170. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  57171. deleteAndZero (resizableCorner);
  57172. deleteAndZero (resizableBorder);
  57173. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57174. ComponentPeer* const peer = getPeer();
  57175. if (peer != 0)
  57176. peer->setConstrainer (newConstrainer);
  57177. }
  57178. }
  57179. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  57180. {
  57181. if (constrainer != 0)
  57182. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  57183. else
  57184. setBounds (x, y, w, h);
  57185. }
  57186. void ResizableWindow::paint (Graphics& g)
  57187. {
  57188. g.fillAll (backgroundColour);
  57189. if (! isFullScreen())
  57190. {
  57191. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  57192. getBorderThickness(), *this);
  57193. }
  57194. #ifdef JUCE_DEBUG
  57195. /* If this fails, then you've probably written a subclass with a resized()
  57196. callback but forgotten to make it call its parent class's resized() method.
  57197. It's important when you override methods like resized(), moved(),
  57198. etc., that you make sure the base class methods also get called.
  57199. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  57200. because your content should all be inside the content component - and it's the
  57201. content component's resized() method that you should be using to do your
  57202. layout.
  57203. */
  57204. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  57205. #endif
  57206. }
  57207. void ResizableWindow::lookAndFeelChanged()
  57208. {
  57209. resized();
  57210. if (isOnDesktop())
  57211. {
  57212. Component::addToDesktop (getDesktopWindowStyleFlags());
  57213. ComponentPeer* const peer = getPeer();
  57214. if (peer != 0)
  57215. peer->setConstrainer (constrainer);
  57216. }
  57217. }
  57218. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  57219. {
  57220. if (Desktop::canUseSemiTransparentWindows())
  57221. backgroundColour = newColour;
  57222. else
  57223. backgroundColour = newColour.withAlpha (1.0f);
  57224. setOpaque (backgroundColour.isOpaque());
  57225. repaint();
  57226. }
  57227. bool ResizableWindow::isFullScreen() const
  57228. {
  57229. if (isOnDesktop())
  57230. {
  57231. ComponentPeer* const peer = getPeer();
  57232. return peer != 0 && peer->isFullScreen();
  57233. }
  57234. return fullscreen;
  57235. }
  57236. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  57237. {
  57238. if (shouldBeFullScreen != isFullScreen())
  57239. {
  57240. updateLastPos();
  57241. fullscreen = shouldBeFullScreen;
  57242. if (isOnDesktop())
  57243. {
  57244. ComponentPeer* const peer = getPeer();
  57245. if (peer != 0)
  57246. {
  57247. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  57248. const Rectangle lastPos (lastNonFullScreenPos);
  57249. peer->setFullScreen (shouldBeFullScreen);
  57250. if (! shouldBeFullScreen)
  57251. setBounds (lastPos);
  57252. }
  57253. else
  57254. {
  57255. jassertfalse
  57256. }
  57257. }
  57258. else
  57259. {
  57260. if (shouldBeFullScreen)
  57261. setBounds (0, 0, getParentWidth(), getParentHeight());
  57262. else
  57263. setBounds (lastNonFullScreenPos);
  57264. }
  57265. resized();
  57266. }
  57267. }
  57268. bool ResizableWindow::isMinimised() const
  57269. {
  57270. ComponentPeer* const peer = getPeer();
  57271. return (peer != 0) && peer->isMinimised();
  57272. }
  57273. void ResizableWindow::setMinimised (const bool shouldMinimise)
  57274. {
  57275. if (shouldMinimise != isMinimised())
  57276. {
  57277. ComponentPeer* const peer = getPeer();
  57278. if (peer != 0)
  57279. {
  57280. updateLastPos();
  57281. peer->setMinimised (shouldMinimise);
  57282. }
  57283. else
  57284. {
  57285. jassertfalse
  57286. }
  57287. }
  57288. }
  57289. void ResizableWindow::updateLastPos()
  57290. {
  57291. if (isShowing() && ! (isFullScreen() || isMinimised()))
  57292. {
  57293. lastNonFullScreenPos = getBounds();
  57294. }
  57295. }
  57296. void ResizableWindow::parentSizeChanged()
  57297. {
  57298. if (isFullScreen() && getParentComponent() != 0)
  57299. {
  57300. setBounds (0, 0, getParentWidth(), getParentHeight());
  57301. }
  57302. }
  57303. const String ResizableWindow::getWindowStateAsString()
  57304. {
  57305. updateLastPos();
  57306. String s;
  57307. if (isFullScreen())
  57308. s << "fs ";
  57309. s << lastNonFullScreenPos.getX() << T(' ')
  57310. << lastNonFullScreenPos.getY() << T(' ')
  57311. << lastNonFullScreenPos.getWidth() << T(' ')
  57312. << lastNonFullScreenPos.getHeight();
  57313. return s;
  57314. }
  57315. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  57316. {
  57317. StringArray tokens;
  57318. tokens.addTokens (s, false);
  57319. tokens.removeEmptyStrings();
  57320. tokens.trim();
  57321. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  57322. const int n = fs ? 1 : 0;
  57323. if (tokens.size() != 4 + n)
  57324. return false;
  57325. Rectangle r (tokens[n].getIntValue(),
  57326. tokens[n + 1].getIntValue(),
  57327. tokens[n + 2].getIntValue(),
  57328. tokens[n + 3].getIntValue());
  57329. if (r.isEmpty())
  57330. return false;
  57331. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  57332. r = r.getIntersection (screen);
  57333. lastNonFullScreenPos = r;
  57334. if (isOnDesktop())
  57335. {
  57336. ComponentPeer* const peer = getPeer();
  57337. if (peer != 0)
  57338. peer->setNonFullScreenBounds (r);
  57339. }
  57340. setFullScreen (fs);
  57341. if (! fs)
  57342. setBoundsConstrained (r.getX(),
  57343. r.getY(),
  57344. r.getWidth(),
  57345. r.getHeight());
  57346. return true;
  57347. }
  57348. void ResizableWindow::mouseDown (const MouseEvent&)
  57349. {
  57350. if (! isFullScreen())
  57351. dragger.startDraggingComponent (this, constrainer);
  57352. }
  57353. void ResizableWindow::mouseDrag (const MouseEvent& e)
  57354. {
  57355. if (! isFullScreen())
  57356. dragger.dragComponent (this, e);
  57357. }
  57358. #ifdef JUCE_DEBUG
  57359. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  57360. {
  57361. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  57362. manages its child components automatically, and if you add your own it'll cause
  57363. trouble. Instead, use setContentComponent() to give it a component which
  57364. will be automatically resized and kept in the right place - then you can add
  57365. subcomponents to the content comp. See the notes for the ResizableWindow class
  57366. for more info.
  57367. If you really know what you're doing and want to avoid this assertion, just call
  57368. Component::addChildComponent directly.
  57369. */
  57370. jassertfalse
  57371. Component::addChildComponent (child, zOrder);
  57372. }
  57373. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  57374. {
  57375. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  57376. manages its child components automatically, and if you add your own it'll cause
  57377. trouble. Instead, use setContentComponent() to give it a component which
  57378. will be automatically resized and kept in the right place - then you can add
  57379. subcomponents to the content comp. See the notes for the ResizableWindow class
  57380. for more info.
  57381. If you really know what you're doing and want to avoid this assertion, just call
  57382. Component::addAndMakeVisible directly.
  57383. */
  57384. jassertfalse
  57385. Component::addAndMakeVisible (child, zOrder);
  57386. }
  57387. #endif
  57388. END_JUCE_NAMESPACE
  57389. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  57390. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  57391. BEGIN_JUCE_NAMESPACE
  57392. SplashScreen::SplashScreen()
  57393. : backgroundImage (0),
  57394. isImageInCache (false)
  57395. {
  57396. setOpaque (true);
  57397. }
  57398. SplashScreen::~SplashScreen()
  57399. {
  57400. if (isImageInCache)
  57401. ImageCache::release (backgroundImage);
  57402. else
  57403. delete backgroundImage;
  57404. }
  57405. void SplashScreen::show (const String& title,
  57406. Image* const backgroundImage_,
  57407. const int minimumTimeToDisplayFor,
  57408. const bool useDropShadow,
  57409. const bool removeOnMouseClick)
  57410. {
  57411. backgroundImage = backgroundImage_;
  57412. jassert (backgroundImage_ != 0);
  57413. if (backgroundImage_ != 0)
  57414. {
  57415. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  57416. setOpaque (! backgroundImage_->hasAlphaChannel());
  57417. show (title,
  57418. backgroundImage_->getWidth(),
  57419. backgroundImage_->getHeight(),
  57420. minimumTimeToDisplayFor,
  57421. useDropShadow,
  57422. removeOnMouseClick);
  57423. }
  57424. }
  57425. void SplashScreen::show (const String& title,
  57426. const int width,
  57427. const int height,
  57428. const int minimumTimeToDisplayFor,
  57429. const bool useDropShadow,
  57430. const bool removeOnMouseClick)
  57431. {
  57432. setName (title);
  57433. setAlwaysOnTop (true);
  57434. setVisible (true);
  57435. centreWithSize (width, height);
  57436. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  57437. toFront (false);
  57438. MessageManager::getInstance()->dispatchPendingMessages();
  57439. repaint();
  57440. originalClickCounter = removeOnMouseClick
  57441. ? Desktop::getMouseButtonClickCounter()
  57442. : INT_MAX;
  57443. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  57444. startTimer (50);
  57445. }
  57446. void SplashScreen::paint (Graphics& g)
  57447. {
  57448. if (backgroundImage != 0)
  57449. {
  57450. g.setOpacity (1.0f);
  57451. g.drawImage (backgroundImage,
  57452. 0, 0, getWidth(), getHeight(),
  57453. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  57454. }
  57455. }
  57456. void SplashScreen::timerCallback()
  57457. {
  57458. if (Time::getCurrentTime() > earliestTimeToDelete
  57459. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  57460. {
  57461. delete this;
  57462. }
  57463. }
  57464. END_JUCE_NAMESPACE
  57465. /********* End of inlined file: juce_SplashScreen.cpp *********/
  57466. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  57467. BEGIN_JUCE_NAMESPACE
  57468. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  57469. const bool hasProgressBar,
  57470. const bool hasCancelButton,
  57471. const int timeOutMsWhenCancelling_,
  57472. const String& cancelButtonText)
  57473. : Thread ("Juce Progress Window"),
  57474. progress (0.0),
  57475. alertWindow (title, String::empty, AlertWindow::NoIcon),
  57476. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  57477. {
  57478. if (hasProgressBar)
  57479. alertWindow.addProgressBarComponent (progress);
  57480. if (hasCancelButton)
  57481. alertWindow.addButton (cancelButtonText, 1);
  57482. }
  57483. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  57484. {
  57485. stopThread (timeOutMsWhenCancelling);
  57486. }
  57487. bool ThreadWithProgressWindow::runThread (const int priority)
  57488. {
  57489. startThread (priority);
  57490. startTimer (100);
  57491. {
  57492. const ScopedLock sl (messageLock);
  57493. alertWindow.setMessage (message);
  57494. }
  57495. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  57496. stopThread (timeOutMsWhenCancelling);
  57497. alertWindow.setVisible (false);
  57498. return ! wasCancelled;
  57499. }
  57500. void ThreadWithProgressWindow::setProgress (const double newProgress)
  57501. {
  57502. progress = newProgress;
  57503. }
  57504. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  57505. {
  57506. const ScopedLock sl (messageLock);
  57507. message = newStatusMessage;
  57508. }
  57509. void ThreadWithProgressWindow::timerCallback()
  57510. {
  57511. if (! isThreadRunning())
  57512. {
  57513. // thread has finished normally..
  57514. alertWindow.exitModalState (0);
  57515. alertWindow.setVisible (false);
  57516. }
  57517. else
  57518. {
  57519. const ScopedLock sl (messageLock);
  57520. alertWindow.setMessage (message);
  57521. }
  57522. }
  57523. END_JUCE_NAMESPACE
  57524. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  57525. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  57526. BEGIN_JUCE_NAMESPACE
  57527. TooltipWindow::TooltipWindow (Component* const parentComponent,
  57528. const int millisecondsBeforeTipAppears_)
  57529. : Component ("tooltip"),
  57530. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  57531. mouseX (0),
  57532. mouseY (0),
  57533. lastMouseMoveTime (0),
  57534. lastHideTime (0),
  57535. lastComponentUnderMouse (0),
  57536. changedCompsSinceShown (true)
  57537. {
  57538. startTimer (123);
  57539. setAlwaysOnTop (true);
  57540. setOpaque (true);
  57541. if (parentComponent != 0)
  57542. {
  57543. parentComponent->addChildComponent (this);
  57544. }
  57545. else
  57546. {
  57547. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  57548. addToDesktop (ComponentPeer::windowHasDropShadow
  57549. | ComponentPeer::windowIsTemporary);
  57550. }
  57551. }
  57552. TooltipWindow::~TooltipWindow()
  57553. {
  57554. }
  57555. void TooltipWindow::paint (Graphics& g)
  57556. {
  57557. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  57558. }
  57559. void TooltipWindow::mouseEnter (const MouseEvent&)
  57560. {
  57561. setVisible (false);
  57562. }
  57563. void TooltipWindow::showFor (Component* const c)
  57564. {
  57565. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  57566. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  57567. tip = ttc->getTooltip();
  57568. else
  57569. tip = String::empty;
  57570. if (tip.isEmpty())
  57571. {
  57572. setVisible (false);
  57573. }
  57574. else
  57575. {
  57576. int mx, my;
  57577. Desktop::getMousePosition (mx, my);
  57578. if (getParentComponent() != 0)
  57579. getParentComponent()->globalPositionToRelative (mx, my);
  57580. int x, y, w, h;
  57581. getLookAndFeel().getTooltipSize (tip, w, h);
  57582. if (mx > getParentWidth() / 2)
  57583. x = mx - (w + 12);
  57584. else
  57585. x = mx + 24;
  57586. if (my > getParentHeight() / 2)
  57587. y = my - (h + 6);
  57588. else
  57589. y = my + 6;
  57590. setBounds (x, y, w, h);
  57591. setVisible (true);
  57592. toFront (false);
  57593. }
  57594. }
  57595. void TooltipWindow::timerCallback()
  57596. {
  57597. int mx, my;
  57598. Desktop::getMousePosition (mx, my);
  57599. const unsigned int now = Time::getApproximateMillisecondCounter();
  57600. Component* const underMouse = Component::getComponentUnderMouse();
  57601. const bool changedComp = (underMouse != lastComponentUnderMouse);
  57602. lastComponentUnderMouse = underMouse;
  57603. if (changedComp
  57604. || abs (mx - mouseX) > 4
  57605. || abs (my - mouseY) > 4
  57606. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  57607. {
  57608. lastMouseMoveTime = now;
  57609. if (isVisible())
  57610. {
  57611. lastHideTime = now;
  57612. setVisible (false);
  57613. }
  57614. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  57615. tip = String::empty;
  57616. mouseX = mx;
  57617. mouseY = my;
  57618. }
  57619. if (changedCompsSinceShown)
  57620. {
  57621. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  57622. || now < lastHideTime + 500)
  57623. && ! isVisible())
  57624. {
  57625. if (underMouse->isValidComponent())
  57626. showFor (underMouse);
  57627. changedCompsSinceShown = false;
  57628. }
  57629. }
  57630. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  57631. }
  57632. END_JUCE_NAMESPACE
  57633. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  57634. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  57635. BEGIN_JUCE_NAMESPACE
  57636. /** Keeps track of the active top level window.
  57637. */
  57638. class TopLevelWindowManager : public Timer,
  57639. public DeletedAtShutdown
  57640. {
  57641. public:
  57642. TopLevelWindowManager()
  57643. : windows (8),
  57644. currentActive (0)
  57645. {
  57646. }
  57647. ~TopLevelWindowManager()
  57648. {
  57649. clearSingletonInstance();
  57650. }
  57651. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  57652. void timerCallback()
  57653. {
  57654. startTimer (1731);
  57655. TopLevelWindow* active = 0;
  57656. if (Process::isForegroundProcess())
  57657. {
  57658. active = currentActive;
  57659. Component* const c = Component::getCurrentlyFocusedComponent();
  57660. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  57661. if (tlw == 0 && c != 0)
  57662. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  57663. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  57664. if (tlw != 0)
  57665. active = tlw;
  57666. }
  57667. if (active != currentActive)
  57668. {
  57669. currentActive = active;
  57670. for (int i = windows.size(); --i >= 0;)
  57671. {
  57672. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  57673. tlw->setWindowActive (isWindowActive (tlw));
  57674. i = jmin (i, windows.size() - 1);
  57675. }
  57676. Desktop::getInstance().triggerFocusCallback();
  57677. }
  57678. }
  57679. bool addWindow (TopLevelWindow* const w) throw()
  57680. {
  57681. windows.add (w);
  57682. startTimer (10);
  57683. return isWindowActive (w);
  57684. }
  57685. void removeWindow (TopLevelWindow* const w) throw()
  57686. {
  57687. startTimer (10);
  57688. if (currentActive == w)
  57689. currentActive = 0;
  57690. windows.removeValue (w);
  57691. if (windows.size() == 0)
  57692. deleteInstance();
  57693. }
  57694. VoidArray windows;
  57695. private:
  57696. TopLevelWindow* currentActive;
  57697. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  57698. {
  57699. return (tlw == currentActive
  57700. || tlw->isParentOf (currentActive)
  57701. || tlw->hasKeyboardFocus (true))
  57702. && tlw->isShowing();
  57703. }
  57704. TopLevelWindowManager (const TopLevelWindowManager&);
  57705. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  57706. };
  57707. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  57708. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  57709. {
  57710. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  57711. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  57712. }
  57713. TopLevelWindow::TopLevelWindow (const String& name,
  57714. const bool addToDesktop_)
  57715. : Component (name),
  57716. useDropShadow (true),
  57717. useNativeTitleBar (false),
  57718. windowIsActive_ (false),
  57719. shadower (0)
  57720. {
  57721. setOpaque (true);
  57722. if (addToDesktop_)
  57723. Component::addToDesktop (getDesktopWindowStyleFlags());
  57724. else
  57725. setDropShadowEnabled (true);
  57726. setWantsKeyboardFocus (true);
  57727. setBroughtToFrontOnMouseClick (true);
  57728. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  57729. }
  57730. TopLevelWindow::~TopLevelWindow()
  57731. {
  57732. deleteAndZero (shadower);
  57733. TopLevelWindowManager::getInstance()->removeWindow (this);
  57734. }
  57735. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  57736. {
  57737. if (hasKeyboardFocus (true))
  57738. TopLevelWindowManager::getInstance()->timerCallback();
  57739. else
  57740. TopLevelWindowManager::getInstance()->startTimer (10);
  57741. }
  57742. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  57743. {
  57744. if (windowIsActive_ != isNowActive)
  57745. {
  57746. windowIsActive_ = isNowActive;
  57747. activeWindowStatusChanged();
  57748. }
  57749. }
  57750. void TopLevelWindow::activeWindowStatusChanged()
  57751. {
  57752. }
  57753. void TopLevelWindow::parentHierarchyChanged()
  57754. {
  57755. setDropShadowEnabled (useDropShadow);
  57756. }
  57757. void TopLevelWindow::visibilityChanged()
  57758. {
  57759. if (isShowing())
  57760. toFront (true);
  57761. }
  57762. int TopLevelWindow::getDesktopWindowStyleFlags() const
  57763. {
  57764. int flags = ComponentPeer::windowAppearsOnTaskbar;
  57765. if (useDropShadow)
  57766. flags |= ComponentPeer::windowHasDropShadow;
  57767. if (useNativeTitleBar)
  57768. flags |= ComponentPeer::windowHasTitleBar;
  57769. return flags;
  57770. }
  57771. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  57772. {
  57773. useDropShadow = useShadow;
  57774. if (isOnDesktop())
  57775. {
  57776. deleteAndZero (shadower);
  57777. Component::addToDesktop (getDesktopWindowStyleFlags());
  57778. }
  57779. else
  57780. {
  57781. if (useShadow && isOpaque())
  57782. {
  57783. if (shadower == 0)
  57784. {
  57785. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  57786. if (shadower != 0)
  57787. shadower->setOwner (this);
  57788. }
  57789. }
  57790. else
  57791. {
  57792. deleteAndZero (shadower);
  57793. }
  57794. }
  57795. }
  57796. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  57797. {
  57798. if (useNativeTitleBar != useNativeTitleBar_)
  57799. {
  57800. useNativeTitleBar = useNativeTitleBar_;
  57801. recreateDesktopWindow();
  57802. sendLookAndFeelChange();
  57803. }
  57804. }
  57805. void TopLevelWindow::recreateDesktopWindow()
  57806. {
  57807. if (isOnDesktop())
  57808. {
  57809. Component::addToDesktop (getDesktopWindowStyleFlags());
  57810. toFront (true);
  57811. }
  57812. }
  57813. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  57814. {
  57815. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  57816. because this class needs to make sure its layout corresponds with settings like whether
  57817. it's got a native title bar or not.
  57818. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  57819. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  57820. method, then add or remove whatever flags are necessary from this value before returning it.
  57821. */
  57822. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  57823. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  57824. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  57825. if (windowStyleFlags != getDesktopWindowStyleFlags())
  57826. sendLookAndFeelChange();
  57827. }
  57828. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  57829. {
  57830. if (c == 0)
  57831. c = TopLevelWindow::getActiveTopLevelWindow();
  57832. if (c == 0)
  57833. {
  57834. centreWithSize (width, height);
  57835. }
  57836. else
  57837. {
  57838. int x = (c->getWidth() - width) / 2;
  57839. int y = (c->getHeight() - height) / 2;
  57840. c->relativePositionToGlobal (x, y);
  57841. Rectangle parentArea (c->getParentMonitorArea());
  57842. if (getParentComponent() != 0)
  57843. {
  57844. getParentComponent()->globalPositionToRelative (x, y);
  57845. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  57846. }
  57847. parentArea.reduce (12, 12);
  57848. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  57849. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  57850. width, height);
  57851. }
  57852. }
  57853. int TopLevelWindow::getNumTopLevelWindows() throw()
  57854. {
  57855. return TopLevelWindowManager::getInstance()->windows.size();
  57856. }
  57857. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  57858. {
  57859. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  57860. }
  57861. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  57862. {
  57863. TopLevelWindow* best = 0;
  57864. int bestNumTWLParents = -1;
  57865. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  57866. {
  57867. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  57868. if (tlw->isActiveWindow())
  57869. {
  57870. int numTWLParents = 0;
  57871. const Component* c = tlw->getParentComponent();
  57872. while (c != 0)
  57873. {
  57874. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  57875. ++numTWLParents;
  57876. c = c->getParentComponent();
  57877. }
  57878. if (bestNumTWLParents < numTWLParents)
  57879. {
  57880. best = tlw;
  57881. bestNumTWLParents = numTWLParents;
  57882. }
  57883. }
  57884. }
  57885. return best;
  57886. }
  57887. END_JUCE_NAMESPACE
  57888. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  57889. /********* Start of inlined file: juce_Brush.cpp *********/
  57890. BEGIN_JUCE_NAMESPACE
  57891. Brush::Brush() throw()
  57892. {
  57893. }
  57894. Brush::~Brush() throw()
  57895. {
  57896. }
  57897. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  57898. int x, float y1, float y2) throw()
  57899. {
  57900. Path p;
  57901. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  57902. paintPath (context, p, AffineTransform::identity);
  57903. }
  57904. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  57905. int y, float x1, float x2) throw()
  57906. {
  57907. Path p;
  57908. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  57909. paintPath (context, p, AffineTransform::identity);
  57910. }
  57911. void Brush::paintLine (LowLevelGraphicsContext& context,
  57912. float x1, float y1, float x2, float y2) throw()
  57913. {
  57914. Path p;
  57915. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  57916. paintPath (context, p, AffineTransform::identity);
  57917. }
  57918. END_JUCE_NAMESPACE
  57919. /********* End of inlined file: juce_Brush.cpp *********/
  57920. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  57921. BEGIN_JUCE_NAMESPACE
  57922. GradientBrush::GradientBrush (const Colour& colour1,
  57923. const float x1,
  57924. const float y1,
  57925. const Colour& colour2,
  57926. const float x2,
  57927. const float y2,
  57928. const bool isRadial) throw()
  57929. : gradient (colour1, x1, y1,
  57930. colour2, x2, y2,
  57931. isRadial)
  57932. {
  57933. }
  57934. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  57935. : gradient (gradient_)
  57936. {
  57937. }
  57938. GradientBrush::~GradientBrush() throw()
  57939. {
  57940. }
  57941. Brush* GradientBrush::createCopy() const throw()
  57942. {
  57943. return new GradientBrush (gradient);
  57944. }
  57945. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  57946. {
  57947. gradient.transform = gradient.transform.followedBy (transform);
  57948. }
  57949. void GradientBrush::multiplyOpacity (const float multiple) throw()
  57950. {
  57951. gradient.multiplyOpacity (multiple);
  57952. }
  57953. bool GradientBrush::isInvisible() const throw()
  57954. {
  57955. return gradient.isInvisible();
  57956. }
  57957. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  57958. const Path& path, const AffineTransform& transform) throw()
  57959. {
  57960. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  57961. }
  57962. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  57963. int x, int y, int w, int h) throw()
  57964. {
  57965. context.fillRectWithGradient (x, y, w, h, gradient);
  57966. }
  57967. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  57968. const Image& alphaChannelImage, int imageX, int imageY,
  57969. int x, int y, int w, int h) throw()
  57970. {
  57971. context.saveState();
  57972. if (context.reduceClipRegion (x, y, w, h))
  57973. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  57974. context.restoreState();
  57975. }
  57976. END_JUCE_NAMESPACE
  57977. /********* End of inlined file: juce_GradientBrush.cpp *********/
  57978. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  57979. BEGIN_JUCE_NAMESPACE
  57980. ImageBrush::ImageBrush (Image* const image_,
  57981. const int anchorX_,
  57982. const int anchorY_,
  57983. const float opacity_) throw()
  57984. : image (image_),
  57985. anchorX (anchorX_),
  57986. anchorY (anchorY_),
  57987. opacity (opacity_)
  57988. {
  57989. jassert (image != 0); // not much point creating a brush without an image, is there?
  57990. if (image != 0)
  57991. {
  57992. if (image->getWidth() == 0 || image->getHeight() == 0)
  57993. {
  57994. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  57995. image = 0;
  57996. }
  57997. }
  57998. }
  57999. ImageBrush::~ImageBrush() throw()
  58000. {
  58001. }
  58002. Brush* ImageBrush::createCopy() const throw()
  58003. {
  58004. return new ImageBrush (image, anchorX, anchorY, opacity);
  58005. }
  58006. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58007. {
  58008. opacity *= multiple;
  58009. }
  58010. bool ImageBrush::isInvisible() const throw()
  58011. {
  58012. return opacity == 0.0f;
  58013. }
  58014. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58015. {
  58016. //xxx should probably be smarter and warp the image
  58017. }
  58018. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58019. {
  58020. x -= anchorX;
  58021. y -= anchorY;
  58022. const int iw = image->getWidth();
  58023. const int ih = image->getHeight();
  58024. if (x < 0)
  58025. x = ((x / iw) - 1) * iw;
  58026. else
  58027. x = (x / iw) * iw;
  58028. if (y < 0)
  58029. y = ((y / ih) - 1) * ih;
  58030. else
  58031. y = (y / ih) * ih;
  58032. x += anchorX;
  58033. y += anchorY;
  58034. }
  58035. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  58036. int x, int y, int w, int h) throw()
  58037. {
  58038. context.saveState();
  58039. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58040. {
  58041. const int right = x + w;
  58042. const int bottom = y + h;
  58043. const int iw = image->getWidth();
  58044. const int ih = image->getHeight();
  58045. int startX = x;
  58046. getStartXY (startX, y);
  58047. while (y < bottom)
  58048. {
  58049. x = startX;
  58050. while (x < right)
  58051. {
  58052. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  58053. x += iw;
  58054. }
  58055. y += ih;
  58056. }
  58057. }
  58058. context.restoreState();
  58059. }
  58060. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  58061. const Path& path, const AffineTransform& transform) throw()
  58062. {
  58063. if (image != 0)
  58064. {
  58065. Rectangle clip (context.getClipBounds());
  58066. {
  58067. float x, y, w, h;
  58068. path.getBoundsTransformed (transform, x, y, w, h);
  58069. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  58070. (int) floorf (y),
  58071. 2 + (int) floorf (w),
  58072. 2 + (int) floorf (h)));
  58073. }
  58074. int x = clip.getX();
  58075. int y = clip.getY();
  58076. const int right = clip.getRight();
  58077. const int bottom = clip.getBottom();
  58078. const int iw = image->getWidth();
  58079. const int ih = image->getHeight();
  58080. int startX = x;
  58081. getStartXY (startX, y);
  58082. while (y < bottom)
  58083. {
  58084. x = startX;
  58085. while (x < right)
  58086. {
  58087. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  58088. x += iw;
  58089. }
  58090. y += ih;
  58091. }
  58092. }
  58093. }
  58094. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58095. const Image& alphaChannelImage, int imageX, int imageY,
  58096. int x, int y, int w, int h) throw()
  58097. {
  58098. context.saveState();
  58099. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58100. {
  58101. const Rectangle clip (context.getClipBounds());
  58102. x = clip.getX();
  58103. y = clip.getY();
  58104. const int right = clip.getRight();
  58105. const int bottom = clip.getBottom();
  58106. const int iw = image->getWidth();
  58107. const int ih = image->getHeight();
  58108. int startX = x;
  58109. getStartXY (startX, y);
  58110. while (y < bottom)
  58111. {
  58112. x = startX;
  58113. while (x < right)
  58114. {
  58115. context.fillAlphaChannelWithImage (alphaChannelImage,
  58116. imageX, imageY, *image,
  58117. x, y, opacity);
  58118. x += iw;
  58119. }
  58120. y += ih;
  58121. }
  58122. }
  58123. context.restoreState();
  58124. }
  58125. END_JUCE_NAMESPACE
  58126. /********* End of inlined file: juce_ImageBrush.cpp *********/
  58127. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  58128. BEGIN_JUCE_NAMESPACE
  58129. SolidColourBrush::SolidColourBrush() throw()
  58130. : colour (0xff000000)
  58131. {
  58132. }
  58133. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  58134. : colour (colour_)
  58135. {
  58136. }
  58137. SolidColourBrush::~SolidColourBrush() throw()
  58138. {
  58139. }
  58140. Brush* SolidColourBrush::createCopy() const throw()
  58141. {
  58142. return new SolidColourBrush (colour);
  58143. }
  58144. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58145. {
  58146. }
  58147. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  58148. {
  58149. colour = colour.withMultipliedAlpha (multiple);
  58150. }
  58151. bool SolidColourBrush::isInvisible() const throw()
  58152. {
  58153. return colour.isTransparent();
  58154. }
  58155. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  58156. const Path& path, const AffineTransform& transform) throw()
  58157. {
  58158. if (! colour.isTransparent())
  58159. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  58160. }
  58161. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  58162. int x, int y, int w, int h) throw()
  58163. {
  58164. if (! colour.isTransparent())
  58165. context.fillRectWithColour (x, y, w, h, colour, false);
  58166. }
  58167. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58168. const Image& alphaChannelImage, int imageX, int imageY,
  58169. int x, int y, int w, int h) throw()
  58170. {
  58171. if (! colour.isTransparent())
  58172. {
  58173. context.saveState();
  58174. if (context.reduceClipRegion (x, y, w, h))
  58175. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  58176. context.restoreState();
  58177. }
  58178. }
  58179. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  58180. int x, float y1, float y2) throw()
  58181. {
  58182. context.drawVerticalLine (x, y1, y2, colour);
  58183. }
  58184. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58185. int y, float x1, float x2) throw()
  58186. {
  58187. context.drawHorizontalLine (y, x1, x2, colour);
  58188. }
  58189. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  58190. float x1, float y1, float x2, float y2) throw()
  58191. {
  58192. context.drawLine (x1, y1, x2, y2, colour);
  58193. }
  58194. END_JUCE_NAMESPACE
  58195. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  58196. /********* Start of inlined file: juce_Colour.cpp *********/
  58197. BEGIN_JUCE_NAMESPACE
  58198. static forcedinline uint8 floatAlphaToInt (const float alpha)
  58199. {
  58200. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  58201. }
  58202. static const float oneOver255 = 1.0f / 255.0f;
  58203. Colour::Colour() throw()
  58204. : argb (0)
  58205. {
  58206. }
  58207. Colour::Colour (const Colour& other) throw()
  58208. : argb (other.argb)
  58209. {
  58210. }
  58211. const Colour& Colour::operator= (const Colour& other) throw()
  58212. {
  58213. argb = other.argb;
  58214. return *this;
  58215. }
  58216. bool Colour::operator== (const Colour& other) const throw()
  58217. {
  58218. return argb.getARGB() == other.argb.getARGB();
  58219. }
  58220. bool Colour::operator!= (const Colour& other) const throw()
  58221. {
  58222. return argb.getARGB() != other.argb.getARGB();
  58223. }
  58224. Colour::Colour (const uint32 argb_) throw()
  58225. : argb (argb_)
  58226. {
  58227. }
  58228. Colour::Colour (const uint8 red,
  58229. const uint8 green,
  58230. const uint8 blue) throw()
  58231. {
  58232. argb.setARGB (0xff, red, green, blue);
  58233. }
  58234. Colour::Colour (const uint8 red,
  58235. const uint8 green,
  58236. const uint8 blue,
  58237. const uint8 alpha) throw()
  58238. {
  58239. argb.setARGB (alpha, red, green, blue);
  58240. }
  58241. Colour::Colour (const uint8 red,
  58242. const uint8 green,
  58243. const uint8 blue,
  58244. const float alpha) throw()
  58245. {
  58246. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  58247. }
  58248. static void convertHSBtoRGB (float h, const float s, float v,
  58249. uint8& r, uint8& g, uint8& b) throw()
  58250. {
  58251. v *= 255.0f;
  58252. const uint8 intV = (uint8) roundFloatToInt (v);
  58253. if (s == 0)
  58254. {
  58255. r = intV;
  58256. g = intV;
  58257. b = intV;
  58258. }
  58259. else
  58260. {
  58261. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  58262. const float f = h - floorf (h);
  58263. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  58264. const float y = v * (1.0f - s * f);
  58265. const float z = v * (1.0f - (s * (1.0f - f)));
  58266. if (h < 1.0f)
  58267. {
  58268. r = intV;
  58269. g = (uint8) roundFloatToInt (z);
  58270. b = x;
  58271. }
  58272. else if (h < 2.0f)
  58273. {
  58274. r = (uint8) roundFloatToInt (y);
  58275. g = intV;
  58276. b = x;
  58277. }
  58278. else if (h < 3.0f)
  58279. {
  58280. r = x;
  58281. g = intV;
  58282. b = (uint8) roundFloatToInt (z);
  58283. }
  58284. else if (h < 4.0f)
  58285. {
  58286. r = x;
  58287. g = (uint8) roundFloatToInt (y);
  58288. b = intV;
  58289. }
  58290. else if (h < 5.0f)
  58291. {
  58292. r = (uint8) roundFloatToInt (z);
  58293. g = x;
  58294. b = intV;
  58295. }
  58296. else if (h < 6.0f)
  58297. {
  58298. r = intV;
  58299. g = x;
  58300. b = (uint8) roundFloatToInt (y);
  58301. }
  58302. else
  58303. {
  58304. r = 0;
  58305. g = 0;
  58306. b = 0;
  58307. }
  58308. }
  58309. }
  58310. Colour::Colour (const float hue,
  58311. const float saturation,
  58312. const float brightness,
  58313. const float alpha) throw()
  58314. {
  58315. uint8 r = getRed(), g = getGreen(), b = getBlue();
  58316. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  58317. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  58318. }
  58319. Colour::Colour (const float hue,
  58320. const float saturation,
  58321. const float brightness,
  58322. const uint8 alpha) throw()
  58323. {
  58324. uint8 r = getRed(), g = getGreen(), b = getBlue();
  58325. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  58326. argb.setARGB (alpha, r, g, b);
  58327. }
  58328. Colour::~Colour() throw()
  58329. {
  58330. }
  58331. const PixelARGB Colour::getPixelARGB() const throw()
  58332. {
  58333. PixelARGB p (argb);
  58334. p.premultiply();
  58335. return p;
  58336. }
  58337. uint32 Colour::getARGB() const throw()
  58338. {
  58339. return argb.getARGB();
  58340. }
  58341. bool Colour::isTransparent() const throw()
  58342. {
  58343. return getAlpha() == 0;
  58344. }
  58345. bool Colour::isOpaque() const throw()
  58346. {
  58347. return getAlpha() == 0xff;
  58348. }
  58349. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  58350. {
  58351. PixelARGB newCol (argb);
  58352. newCol.setAlpha (newAlpha);
  58353. return Colour (newCol.getARGB());
  58354. }
  58355. const Colour Colour::withAlpha (const float newAlpha) const throw()
  58356. {
  58357. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  58358. PixelARGB newCol (argb);
  58359. newCol.setAlpha (floatAlphaToInt (newAlpha));
  58360. return Colour (newCol.getARGB());
  58361. }
  58362. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  58363. {
  58364. jassert (alphaMultiplier >= 0);
  58365. PixelARGB newCol (argb);
  58366. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  58367. return Colour (newCol.getARGB());
  58368. }
  58369. const Colour Colour::overlaidWith (const Colour& src) const throw()
  58370. {
  58371. const int destAlpha = getAlpha();
  58372. if (destAlpha > 0)
  58373. {
  58374. const int invA = 0xff - (int) src.getAlpha();
  58375. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  58376. if (resA > 0)
  58377. {
  58378. const int da = (invA * destAlpha) / resA;
  58379. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  58380. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  58381. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  58382. (uint8) resA);
  58383. }
  58384. return *this;
  58385. }
  58386. else
  58387. {
  58388. return src;
  58389. }
  58390. }
  58391. float Colour::getFloatRed() const throw()
  58392. {
  58393. return getRed() * oneOver255;
  58394. }
  58395. float Colour::getFloatGreen() const throw()
  58396. {
  58397. return getGreen() * oneOver255;
  58398. }
  58399. float Colour::getFloatBlue() const throw()
  58400. {
  58401. return getBlue() * oneOver255;
  58402. }
  58403. float Colour::getFloatAlpha() const throw()
  58404. {
  58405. return getAlpha() * oneOver255;
  58406. }
  58407. void Colour::getHSB (float& h, float& s, float& v) const throw()
  58408. {
  58409. const int r = getRed();
  58410. const int g = getGreen();
  58411. const int b = getBlue();
  58412. const int hi = jmax (r, g, b);
  58413. const int lo = jmin (r, g, b);
  58414. if (hi != 0)
  58415. {
  58416. s = (hi - lo) / (float) hi;
  58417. if (s != 0)
  58418. {
  58419. const float invDiff = 1.0f / (hi - lo);
  58420. const float red = (hi - r) * invDiff;
  58421. const float green = (hi - g) * invDiff;
  58422. const float blue = (hi - b) * invDiff;
  58423. if (r == hi)
  58424. h = blue - green;
  58425. else if (g == hi)
  58426. h = 2.0f + red - blue;
  58427. else
  58428. h = 4.0f + green - red;
  58429. h *= 1.0f / 6.0f;
  58430. if (h < 0)
  58431. ++h;
  58432. }
  58433. else
  58434. {
  58435. h = 0;
  58436. }
  58437. }
  58438. else
  58439. {
  58440. s = 0;
  58441. h = 0;
  58442. }
  58443. v = hi * oneOver255;
  58444. }
  58445. float Colour::getHue() const throw()
  58446. {
  58447. float h, s, b;
  58448. getHSB (h, s, b);
  58449. return h;
  58450. }
  58451. const Colour Colour::withHue (const float hue) const throw()
  58452. {
  58453. float h, s, b;
  58454. getHSB (h, s, b);
  58455. return Colour (hue, s, b, getAlpha());
  58456. }
  58457. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  58458. {
  58459. float h, s, b;
  58460. getHSB (h, s, b);
  58461. h += amountToRotate;
  58462. h -= floorf (h);
  58463. return Colour (h, s, b, getAlpha());
  58464. }
  58465. float Colour::getSaturation() const throw()
  58466. {
  58467. float h, s, b;
  58468. getHSB (h, s, b);
  58469. return s;
  58470. }
  58471. const Colour Colour::withSaturation (const float saturation) const throw()
  58472. {
  58473. float h, s, b;
  58474. getHSB (h, s, b);
  58475. return Colour (h, saturation, b, getAlpha());
  58476. }
  58477. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  58478. {
  58479. float h, s, b;
  58480. getHSB (h, s, b);
  58481. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  58482. }
  58483. float Colour::getBrightness() const throw()
  58484. {
  58485. float h, s, b;
  58486. getHSB (h, s, b);
  58487. return b;
  58488. }
  58489. const Colour Colour::withBrightness (const float brightness) const throw()
  58490. {
  58491. float h, s, b;
  58492. getHSB (h, s, b);
  58493. return Colour (h, s, brightness, getAlpha());
  58494. }
  58495. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  58496. {
  58497. float h, s, b;
  58498. getHSB (h, s, b);
  58499. b *= amount;
  58500. if (b > 1.0f)
  58501. b = 1.0f;
  58502. return Colour (h, s, b, getAlpha());
  58503. }
  58504. const Colour Colour::brighter (float amount) const throw()
  58505. {
  58506. amount = 1.0f / (1.0f + amount);
  58507. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  58508. (uint8) (255 - (amount * (255 - getGreen()))),
  58509. (uint8) (255 - (amount * (255 - getBlue()))),
  58510. getAlpha());
  58511. }
  58512. const Colour Colour::darker (float amount) const throw()
  58513. {
  58514. amount = 1.0f / (1.0f + amount);
  58515. return Colour ((uint8) (amount * getRed()),
  58516. (uint8) (amount * getGreen()),
  58517. (uint8) (amount * getBlue()),
  58518. getAlpha());
  58519. }
  58520. const Colour Colour::greyLevel (const float brightness) throw()
  58521. {
  58522. const uint8 level
  58523. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  58524. return Colour (level, level, level);
  58525. }
  58526. const Colour Colour::contrasting (const float amount) const throw()
  58527. {
  58528. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  58529. ? Colours::black
  58530. : Colours::white).withAlpha (amount));
  58531. }
  58532. const Colour Colour::contrasting (const Colour& colour1,
  58533. const Colour& colour2) throw()
  58534. {
  58535. const float b1 = colour1.getBrightness();
  58536. const float b2 = colour2.getBrightness();
  58537. float best = 0.0f;
  58538. float bestDist = 0.0f;
  58539. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  58540. {
  58541. const float d1 = fabsf (i - b1);
  58542. const float d2 = fabsf (i - b2);
  58543. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  58544. if (dist > bestDist)
  58545. {
  58546. best = i;
  58547. bestDist = dist;
  58548. }
  58549. }
  58550. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  58551. .withBrightness (best);
  58552. }
  58553. const String Colour::toString() const throw()
  58554. {
  58555. return String::toHexString ((int) argb.getARGB());
  58556. }
  58557. const Colour Colour::fromString (const String& encodedColourString)
  58558. {
  58559. return Colour ((uint32) encodedColourString.getHexValue32());
  58560. }
  58561. END_JUCE_NAMESPACE
  58562. /********* End of inlined file: juce_Colour.cpp *********/
  58563. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  58564. BEGIN_JUCE_NAMESPACE
  58565. ColourGradient::ColourGradient() throw()
  58566. : colours (4)
  58567. {
  58568. #ifdef JUCE_DEBUG
  58569. x1 = 987654.0f;
  58570. #endif
  58571. }
  58572. ColourGradient::ColourGradient (const Colour& colour1,
  58573. const float x1_,
  58574. const float y1_,
  58575. const Colour& colour2,
  58576. const float x2_,
  58577. const float y2_,
  58578. const bool isRadial_) throw()
  58579. : x1 (x1_),
  58580. y1 (y1_),
  58581. x2 (x2_),
  58582. y2 (y2_),
  58583. isRadial (isRadial_),
  58584. colours (4)
  58585. {
  58586. colours.add (0);
  58587. colours.add (colour1.getPixelARGB().getARGB());
  58588. colours.add (1 << 16);
  58589. colours.add (colour2.getPixelARGB().getARGB());
  58590. }
  58591. ColourGradient::~ColourGradient() throw()
  58592. {
  58593. }
  58594. void ColourGradient::clearColours() throw()
  58595. {
  58596. colours.clear();
  58597. }
  58598. void ColourGradient::addColour (const double proportionAlongGradient,
  58599. const Colour& colour) throw()
  58600. {
  58601. // must be within the two end-points
  58602. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  58603. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  58604. int i;
  58605. for (i = 0; i < colours.size(); i += 2)
  58606. if (colours.getUnchecked(i) > pos)
  58607. break;
  58608. colours.insert (i, pos);
  58609. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  58610. }
  58611. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  58612. {
  58613. for (int i = 1; i < colours.size(); i += 2)
  58614. {
  58615. PixelARGB pix (colours.getUnchecked(i));
  58616. pix.multiplyAlpha (multiplier);
  58617. colours.set (i, pix.getARGB());
  58618. }
  58619. }
  58620. int ColourGradient::getNumColours() const throw()
  58621. {
  58622. return colours.size() >> 1;
  58623. }
  58624. double ColourGradient::getColourPosition (const int index) const throw()
  58625. {
  58626. return colours [index << 1];
  58627. }
  58628. const Colour ColourGradient::getColour (const int index) const throw()
  58629. {
  58630. PixelARGB pix (colours [(index << 1) + 1]);
  58631. pix.unpremultiply();
  58632. return Colour (pix.getARGB());
  58633. }
  58634. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  58635. {
  58636. #ifdef JUCE_DEBUG
  58637. // trying to use the object without setting its co-ordinates? Have a careful read of
  58638. // the comments for the constructors.
  58639. jassert (x1 != 987654.0f);
  58640. #endif
  58641. const int numColours = colours.size() >> 1;
  58642. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  58643. transform.transformPoint (tx1, ty1);
  58644. transform.transformPoint (tx2, ty2);
  58645. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  58646. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  58647. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  58648. if (numColours >= 2)
  58649. {
  58650. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  58651. PixelARGB pix1 (colours.getUnchecked (1));
  58652. int index = 0;
  58653. for (int j = 2; j < colours.size(); j += 2)
  58654. {
  58655. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  58656. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  58657. for (int i = 0; i < numToDo; ++i)
  58658. {
  58659. jassert (index >= 0 && index < numEntries);
  58660. lookupTable[index] = pix1;
  58661. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  58662. ++index;
  58663. }
  58664. pix1 = pix2;
  58665. }
  58666. while (index < numEntries)
  58667. lookupTable [index++] = pix1;
  58668. }
  58669. else
  58670. {
  58671. jassertfalse // no colours specified!
  58672. }
  58673. return lookupTable;
  58674. }
  58675. bool ColourGradient::isOpaque() const throw()
  58676. {
  58677. for (int i = 1; i < colours.size(); i += 2)
  58678. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  58679. return false;
  58680. return true;
  58681. }
  58682. bool ColourGradient::isInvisible() const throw()
  58683. {
  58684. for (int i = 1; i < colours.size(); i += 2)
  58685. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  58686. return false;
  58687. return true;
  58688. }
  58689. END_JUCE_NAMESPACE
  58690. /********* End of inlined file: juce_ColourGradient.cpp *********/
  58691. /********* Start of inlined file: juce_Colours.cpp *********/
  58692. BEGIN_JUCE_NAMESPACE
  58693. const Colour Colours::transparentBlack (0);
  58694. const Colour Colours::transparentWhite (0x00ffffff);
  58695. const Colour Colours::aliceblue (0xfff0f8ff);
  58696. const Colour Colours::antiquewhite (0xfffaebd7);
  58697. const Colour Colours::aqua (0xff00ffff);
  58698. const Colour Colours::aquamarine (0xff7fffd4);
  58699. const Colour Colours::azure (0xfff0ffff);
  58700. const Colour Colours::beige (0xfff5f5dc);
  58701. const Colour Colours::bisque (0xffffe4c4);
  58702. const Colour Colours::black (0xff000000);
  58703. const Colour Colours::blanchedalmond (0xffffebcd);
  58704. const Colour Colours::blue (0xff0000ff);
  58705. const Colour Colours::blueviolet (0xff8a2be2);
  58706. const Colour Colours::brown (0xffa52a2a);
  58707. const Colour Colours::burlywood (0xffdeb887);
  58708. const Colour Colours::cadetblue (0xff5f9ea0);
  58709. const Colour Colours::chartreuse (0xff7fff00);
  58710. const Colour Colours::chocolate (0xffd2691e);
  58711. const Colour Colours::coral (0xffff7f50);
  58712. const Colour Colours::cornflowerblue (0xff6495ed);
  58713. const Colour Colours::cornsilk (0xfffff8dc);
  58714. const Colour Colours::crimson (0xffdc143c);
  58715. const Colour Colours::cyan (0xff00ffff);
  58716. const Colour Colours::darkblue (0xff00008b);
  58717. const Colour Colours::darkcyan (0xff008b8b);
  58718. const Colour Colours::darkgoldenrod (0xffb8860b);
  58719. const Colour Colours::darkgrey (0xff555555);
  58720. const Colour Colours::darkgreen (0xff006400);
  58721. const Colour Colours::darkkhaki (0xffbdb76b);
  58722. const Colour Colours::darkmagenta (0xff8b008b);
  58723. const Colour Colours::darkolivegreen (0xff556b2f);
  58724. const Colour Colours::darkorange (0xffff8c00);
  58725. const Colour Colours::darkorchid (0xff9932cc);
  58726. const Colour Colours::darkred (0xff8b0000);
  58727. const Colour Colours::darksalmon (0xffe9967a);
  58728. const Colour Colours::darkseagreen (0xff8fbc8f);
  58729. const Colour Colours::darkslateblue (0xff483d8b);
  58730. const Colour Colours::darkslategrey (0xff2f4f4f);
  58731. const Colour Colours::darkturquoise (0xff00ced1);
  58732. const Colour Colours::darkviolet (0xff9400d3);
  58733. const Colour Colours::deeppink (0xffff1493);
  58734. const Colour Colours::deepskyblue (0xff00bfff);
  58735. const Colour Colours::dimgrey (0xff696969);
  58736. const Colour Colours::dodgerblue (0xff1e90ff);
  58737. const Colour Colours::firebrick (0xffb22222);
  58738. const Colour Colours::floralwhite (0xfffffaf0);
  58739. const Colour Colours::forestgreen (0xff228b22);
  58740. const Colour Colours::fuchsia (0xffff00ff);
  58741. const Colour Colours::gainsboro (0xffdcdcdc);
  58742. const Colour Colours::gold (0xffffd700);
  58743. const Colour Colours::goldenrod (0xffdaa520);
  58744. const Colour Colours::grey (0xff808080);
  58745. const Colour Colours::green (0xff008000);
  58746. const Colour Colours::greenyellow (0xffadff2f);
  58747. const Colour Colours::honeydew (0xfff0fff0);
  58748. const Colour Colours::hotpink (0xffff69b4);
  58749. const Colour Colours::indianred (0xffcd5c5c);
  58750. const Colour Colours::indigo (0xff4b0082);
  58751. const Colour Colours::ivory (0xfffffff0);
  58752. const Colour Colours::khaki (0xfff0e68c);
  58753. const Colour Colours::lavender (0xffe6e6fa);
  58754. const Colour Colours::lavenderblush (0xfffff0f5);
  58755. const Colour Colours::lemonchiffon (0xfffffacd);
  58756. const Colour Colours::lightblue (0xffadd8e6);
  58757. const Colour Colours::lightcoral (0xfff08080);
  58758. const Colour Colours::lightcyan (0xffe0ffff);
  58759. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  58760. const Colour Colours::lightgreen (0xff90ee90);
  58761. const Colour Colours::lightgrey (0xffd3d3d3);
  58762. const Colour Colours::lightpink (0xffffb6c1);
  58763. const Colour Colours::lightsalmon (0xffffa07a);
  58764. const Colour Colours::lightseagreen (0xff20b2aa);
  58765. const Colour Colours::lightskyblue (0xff87cefa);
  58766. const Colour Colours::lightslategrey (0xff778899);
  58767. const Colour Colours::lightsteelblue (0xffb0c4de);
  58768. const Colour Colours::lightyellow (0xffffffe0);
  58769. const Colour Colours::lime (0xff00ff00);
  58770. const Colour Colours::limegreen (0xff32cd32);
  58771. const Colour Colours::linen (0xfffaf0e6);
  58772. const Colour Colours::magenta (0xffff00ff);
  58773. const Colour Colours::maroon (0xff800000);
  58774. const Colour Colours::mediumaquamarine (0xff66cdaa);
  58775. const Colour Colours::mediumblue (0xff0000cd);
  58776. const Colour Colours::mediumorchid (0xffba55d3);
  58777. const Colour Colours::mediumpurple (0xff9370db);
  58778. const Colour Colours::mediumseagreen (0xff3cb371);
  58779. const Colour Colours::mediumslateblue (0xff7b68ee);
  58780. const Colour Colours::mediumspringgreen (0xff00fa9a);
  58781. const Colour Colours::mediumturquoise (0xff48d1cc);
  58782. const Colour Colours::mediumvioletred (0xffc71585);
  58783. const Colour Colours::midnightblue (0xff191970);
  58784. const Colour Colours::mintcream (0xfff5fffa);
  58785. const Colour Colours::mistyrose (0xffffe4e1);
  58786. const Colour Colours::navajowhite (0xffffdead);
  58787. const Colour Colours::navy (0xff000080);
  58788. const Colour Colours::oldlace (0xfffdf5e6);
  58789. const Colour Colours::olive (0xff808000);
  58790. const Colour Colours::olivedrab (0xff6b8e23);
  58791. const Colour Colours::orange (0xffffa500);
  58792. const Colour Colours::orangered (0xffff4500);
  58793. const Colour Colours::orchid (0xffda70d6);
  58794. const Colour Colours::palegoldenrod (0xffeee8aa);
  58795. const Colour Colours::palegreen (0xff98fb98);
  58796. const Colour Colours::paleturquoise (0xffafeeee);
  58797. const Colour Colours::palevioletred (0xffdb7093);
  58798. const Colour Colours::papayawhip (0xffffefd5);
  58799. const Colour Colours::peachpuff (0xffffdab9);
  58800. const Colour Colours::peru (0xffcd853f);
  58801. const Colour Colours::pink (0xffffc0cb);
  58802. const Colour Colours::plum (0xffdda0dd);
  58803. const Colour Colours::powderblue (0xffb0e0e6);
  58804. const Colour Colours::purple (0xff800080);
  58805. const Colour Colours::red (0xffff0000);
  58806. const Colour Colours::rosybrown (0xffbc8f8f);
  58807. const Colour Colours::royalblue (0xff4169e1);
  58808. const Colour Colours::saddlebrown (0xff8b4513);
  58809. const Colour Colours::salmon (0xfffa8072);
  58810. const Colour Colours::sandybrown (0xfff4a460);
  58811. const Colour Colours::seagreen (0xff2e8b57);
  58812. const Colour Colours::seashell (0xfffff5ee);
  58813. const Colour Colours::sienna (0xffa0522d);
  58814. const Colour Colours::silver (0xffc0c0c0);
  58815. const Colour Colours::skyblue (0xff87ceeb);
  58816. const Colour Colours::slateblue (0xff6a5acd);
  58817. const Colour Colours::slategrey (0xff708090);
  58818. const Colour Colours::snow (0xfffffafa);
  58819. const Colour Colours::springgreen (0xff00ff7f);
  58820. const Colour Colours::steelblue (0xff4682b4);
  58821. const Colour Colours::tan (0xffd2b48c);
  58822. const Colour Colours::teal (0xff008080);
  58823. const Colour Colours::thistle (0xffd8bfd8);
  58824. const Colour Colours::tomato (0xffff6347);
  58825. const Colour Colours::turquoise (0xff40e0d0);
  58826. const Colour Colours::violet (0xffee82ee);
  58827. const Colour Colours::wheat (0xfff5deb3);
  58828. const Colour Colours::white (0xffffffff);
  58829. const Colour Colours::whitesmoke (0xfff5f5f5);
  58830. const Colour Colours::yellow (0xffffff00);
  58831. const Colour Colours::yellowgreen (0xff9acd32);
  58832. const Colour Colours::findColourForName (const String& colourName,
  58833. const Colour& defaultColour)
  58834. {
  58835. static const int presets[] =
  58836. {
  58837. // (first value is the string's hashcode, second is ARGB)
  58838. 0x05978fff, 0xff000000, /* black */
  58839. 0x06bdcc29, 0xffffffff, /* white */
  58840. 0x002e305a, 0xff0000ff, /* blue */
  58841. 0x00308adf, 0xff808080, /* grey */
  58842. 0x05e0cf03, 0xff008000, /* green */
  58843. 0x0001b891, 0xffff0000, /* red */
  58844. 0xd43c6474, 0xffffff00, /* yellow */
  58845. 0x620886da, 0xfff0f8ff, /* aliceblue */
  58846. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  58847. 0x002dcebc, 0xff00ffff, /* aqua */
  58848. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  58849. 0x0590228f, 0xfff0ffff, /* azure */
  58850. 0x05947fe4, 0xfff5f5dc, /* beige */
  58851. 0xad388e35, 0xffffe4c4, /* bisque */
  58852. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  58853. 0x39129959, 0xff8a2be2, /* blueviolet */
  58854. 0x059a8136, 0xffa52a2a, /* brown */
  58855. 0x89cea8f9, 0xffdeb887, /* burlywood */
  58856. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  58857. 0x6b748956, 0xff7fff00, /* chartreuse */
  58858. 0x2903623c, 0xffd2691e, /* chocolate */
  58859. 0x05a74431, 0xffff7f50, /* coral */
  58860. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  58861. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  58862. 0x3d8c4edf, 0xffdc143c, /* crimson */
  58863. 0x002ed323, 0xff00ffff, /* cyan */
  58864. 0x67cc74d0, 0xff00008b, /* darkblue */
  58865. 0x67cd1799, 0xff008b8b, /* darkcyan */
  58866. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  58867. 0x67cecf55, 0xff555555, /* darkgrey */
  58868. 0x920b194d, 0xff006400, /* darkgreen */
  58869. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  58870. 0x5c293873, 0xff8b008b, /* darkmagenta */
  58871. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  58872. 0xbcfd2524, 0xffff8c00, /* darkorange */
  58873. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  58874. 0x55ee0d5b, 0xff8b0000, /* darkred */
  58875. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  58876. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  58877. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  58878. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  58879. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  58880. 0xc8769375, 0xff9400d3, /* darkviolet */
  58881. 0x25832862, 0xffff1493, /* deeppink */
  58882. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  58883. 0x634c8b67, 0xff696969, /* dimgrey */
  58884. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  58885. 0xef19e3cb, 0xffb22222, /* firebrick */
  58886. 0xb852b195, 0xfffffaf0, /* floralwhite */
  58887. 0xd086fd06, 0xff228b22, /* forestgreen */
  58888. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  58889. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  58890. 0x00308060, 0xffffd700, /* gold */
  58891. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  58892. 0xbab8a537, 0xffadff2f, /* greenyellow */
  58893. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  58894. 0x41892743, 0xffff69b4, /* hotpink */
  58895. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  58896. 0xb969fed2, 0xff4b0082, /* indigo */
  58897. 0x05fef6a9, 0xfffffff0, /* ivory */
  58898. 0x06149302, 0xfff0e68c, /* khaki */
  58899. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  58900. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  58901. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  58902. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  58903. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  58904. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  58905. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  58906. 0xf40157ad, 0xff90ee90, /* lightgreen */
  58907. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  58908. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  58909. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  58910. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  58911. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  58912. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  58913. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  58914. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  58915. 0x0032afd5, 0xff00ff00, /* lime */
  58916. 0x607bbc4e, 0xff32cd32, /* limegreen */
  58917. 0x06234efa, 0xfffaf0e6, /* linen */
  58918. 0x316858a9, 0xffff00ff, /* magenta */
  58919. 0xbf8ca470, 0xff800000, /* maroon */
  58920. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  58921. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  58922. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  58923. 0x07556b71, 0xff9370db, /* mediumpurple */
  58924. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  58925. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  58926. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  58927. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  58928. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  58929. 0x168eb32a, 0xff191970, /* midnightblue */
  58930. 0x4306b960, 0xfff5fffa, /* mintcream */
  58931. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  58932. 0xe97218a6, 0xffffdead, /* navajowhite */
  58933. 0x00337bb6, 0xff000080, /* navy */
  58934. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  58935. 0x064ee1db, 0xff808000, /* olive */
  58936. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  58937. 0xc3de262e, 0xffffa500, /* orange */
  58938. 0x58bebba3, 0xffff4500, /* orangered */
  58939. 0xc3def8a3, 0xffda70d6, /* orchid */
  58940. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  58941. 0x3d9dd619, 0xff98fb98, /* palegreen */
  58942. 0x74022737, 0xffafeeee, /* paleturquoise */
  58943. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  58944. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  58945. 0x93e1b776, 0xffffdab9, /* peachpuff */
  58946. 0x003472f8, 0xffcd853f, /* peru */
  58947. 0x00348176, 0xffffc0cb, /* pink */
  58948. 0x00348d94, 0xffdda0dd, /* plum */
  58949. 0xd036be93, 0xffb0e0e6, /* powderblue */
  58950. 0xc5c507bc, 0xff800080, /* purple */
  58951. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  58952. 0xbd9413e1, 0xff4169e1, /* royalblue */
  58953. 0xf456044f, 0xff8b4513, /* saddlebrown */
  58954. 0xc9c6f66e, 0xfffa8072, /* salmon */
  58955. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  58956. 0x34636c14, 0xff2e8b57, /* seagreen */
  58957. 0x3507fb41, 0xfffff5ee, /* seashell */
  58958. 0xca348772, 0xffa0522d, /* sienna */
  58959. 0xca37d30d, 0xffc0c0c0, /* silver */
  58960. 0x80da74fb, 0xff87ceeb, /* skyblue */
  58961. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  58962. 0x44ab37f8, 0xff708090, /* slategrey */
  58963. 0x0035f183, 0xfffffafa, /* snow */
  58964. 0xd5440d16, 0xff00ff7f, /* springgreen */
  58965. 0x3e1524a5, 0xff4682b4, /* steelblue */
  58966. 0x0001bfa1, 0xffd2b48c, /* tan */
  58967. 0x0036425c, 0xff008080, /* teal */
  58968. 0xafc8858f, 0xffd8bfd8, /* thistle */
  58969. 0xcc41600a, 0xffff6347, /* tomato */
  58970. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  58971. 0xcf57947f, 0xffee82ee, /* violet */
  58972. 0x06bdbae7, 0xfff5deb3, /* wheat */
  58973. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  58974. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  58975. };
  58976. const int hash = colourName.trim().toLowerCase().hashCode();
  58977. for (int i = 0; i < numElementsInArray (presets); i += 2)
  58978. if (presets [i] == hash)
  58979. return Colour (presets [i + 1]);
  58980. return defaultColour;
  58981. }
  58982. END_JUCE_NAMESPACE
  58983. /********* End of inlined file: juce_Colours.cpp *********/
  58984. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  58985. BEGIN_JUCE_NAMESPACE
  58986. EdgeTable::EdgeTable (const int top_,
  58987. const int height_,
  58988. const OversamplingLevel oversampling_,
  58989. const int expectedEdgesPerLine) throw()
  58990. : top (top_),
  58991. height (height_),
  58992. maxEdgesPerLine (expectedEdgesPerLine),
  58993. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  58994. oversampling (oversampling_)
  58995. {
  58996. table = (int*) juce_calloc ((height << (int)oversampling_)
  58997. * lineStrideElements * sizeof (int));
  58998. }
  58999. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59000. : table (0)
  59001. {
  59002. operator= (other);
  59003. }
  59004. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  59005. {
  59006. juce_free (table);
  59007. top = other.top;
  59008. height = other.height;
  59009. maxEdgesPerLine = other.maxEdgesPerLine;
  59010. lineStrideElements = other.lineStrideElements;
  59011. oversampling = other.oversampling;
  59012. const int tableSize = (height << (int)oversampling)
  59013. * lineStrideElements * sizeof (int);
  59014. table = (int*) juce_malloc (tableSize);
  59015. memcpy (table, other.table, tableSize);
  59016. return *this;
  59017. }
  59018. EdgeTable::~EdgeTable() throw()
  59019. {
  59020. juce_free (table);
  59021. }
  59022. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  59023. {
  59024. if (newNumEdgesPerLine != maxEdgesPerLine)
  59025. {
  59026. maxEdgesPerLine = newNumEdgesPerLine;
  59027. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  59028. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  59029. * newLineStrideElements * sizeof (int));
  59030. for (int i = 0; i < (height << (int) oversampling); ++i)
  59031. {
  59032. const int* srcLine = table + lineStrideElements * i;
  59033. int* dstLine = newTable + newLineStrideElements * i;
  59034. int num = *srcLine++;
  59035. *dstLine++ = num;
  59036. num <<= 1;
  59037. while (--num >= 0)
  59038. *dstLine++ = *srcLine++;
  59039. }
  59040. juce_free (table);
  59041. table = newTable;
  59042. lineStrideElements = newLineStrideElements;
  59043. }
  59044. }
  59045. void EdgeTable::optimiseTable() throw()
  59046. {
  59047. int maxLineElements = 0;
  59048. for (int i = height; --i >= 0;)
  59049. maxLineElements = jmax (maxLineElements,
  59050. table [i * lineStrideElements]);
  59051. remapTableForNumEdges (maxLineElements);
  59052. }
  59053. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  59054. {
  59055. jassert (y >= 0 && y < (height << oversampling))
  59056. int* lineStart = table + lineStrideElements * y;
  59057. int n = lineStart[0];
  59058. if (n >= maxEdgesPerLine)
  59059. {
  59060. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  59061. lineStart = table + lineStrideElements * y;
  59062. }
  59063. n <<= 1;
  59064. int* const line = lineStart + 1;
  59065. while (n > 0)
  59066. {
  59067. const int cx = line [n - 2];
  59068. if (cx <= x)
  59069. break;
  59070. line [n] = cx;
  59071. line [n + 1] = line [n - 1];
  59072. n -= 2;
  59073. }
  59074. line [n] = x;
  59075. line [n + 1] = winding;
  59076. lineStart[0]++;
  59077. }
  59078. void EdgeTable::addPath (const Path& path,
  59079. const AffineTransform& transform) throw()
  59080. {
  59081. const int windingAmount = 256 / (1 << (int) oversampling);
  59082. const float timesOversampling = (float) (1 << (int) oversampling);
  59083. const int bottomLimit = (height << (int) oversampling);
  59084. PathFlatteningIterator iter (path, transform);
  59085. while (iter.next())
  59086. {
  59087. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  59088. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  59089. if (y1 != y2)
  59090. {
  59091. const double x1 = 256.0 * iter.x1;
  59092. const double x2 = 256.0 * iter.x2;
  59093. const double multiplier = (x2 - x1) / (y2 - y1);
  59094. const int oldY1 = y1;
  59095. int winding;
  59096. if (y1 > y2)
  59097. {
  59098. swapVariables (y1, y2);
  59099. winding = windingAmount;
  59100. }
  59101. else
  59102. {
  59103. winding = -windingAmount;
  59104. }
  59105. jassert (y1 < y2);
  59106. if (y1 < 0)
  59107. y1 = 0;
  59108. if (y2 > bottomLimit)
  59109. y2 = bottomLimit;
  59110. while (y1 < y2)
  59111. {
  59112. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  59113. y1,
  59114. winding);
  59115. ++y1;
  59116. }
  59117. }
  59118. }
  59119. if (! path.isUsingNonZeroWinding())
  59120. {
  59121. // if it's an alternate-winding path, we need to go through and
  59122. // make sure all the windings are alternating.
  59123. int* lineStart = table;
  59124. for (int i = height << (int) oversampling; --i >= 0;)
  59125. {
  59126. int* line = lineStart;
  59127. lineStart += lineStrideElements;
  59128. int num = *line;
  59129. while (--num >= 0)
  59130. {
  59131. line += 2;
  59132. *line = abs (*line);
  59133. if (--num >= 0)
  59134. {
  59135. line += 2;
  59136. *line = -abs (*line);
  59137. }
  59138. }
  59139. }
  59140. }
  59141. }
  59142. END_JUCE_NAMESPACE
  59143. /********* End of inlined file: juce_EdgeTable.cpp *********/
  59144. /********* Start of inlined file: juce_Graphics.cpp *********/
  59145. BEGIN_JUCE_NAMESPACE
  59146. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  59147. #define MINIMUM_COORD -0x3fffffff
  59148. #define MAXIMUM_COORD 0x3fffffff
  59149. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  59150. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  59151. jassert ((int) x >= MINIMUM_COORD \
  59152. && (int) x <= MAXIMUM_COORD \
  59153. && (int) y >= MINIMUM_COORD \
  59154. && (int) y <= MAXIMUM_COORD \
  59155. && (int) w >= MINIMUM_COORD \
  59156. && (int) w <= MAXIMUM_COORD \
  59157. && (int) h >= MINIMUM_COORD \
  59158. && (int) h <= MAXIMUM_COORD);
  59159. LowLevelGraphicsContext::LowLevelGraphicsContext()
  59160. {
  59161. }
  59162. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  59163. {
  59164. }
  59165. Graphics::Graphics (Image& imageToDrawOnto) throw()
  59166. : context (imageToDrawOnto.createLowLevelContext()),
  59167. ownsContext (true),
  59168. state (new GraphicsState()),
  59169. saveStatePending (false)
  59170. {
  59171. }
  59172. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  59173. : context (internalContext),
  59174. ownsContext (false),
  59175. state (new GraphicsState()),
  59176. saveStatePending (false)
  59177. {
  59178. }
  59179. Graphics::~Graphics() throw()
  59180. {
  59181. delete state;
  59182. if (ownsContext)
  59183. delete context;
  59184. }
  59185. void Graphics::resetToDefaultState() throw()
  59186. {
  59187. setColour (Colours::black);
  59188. state->font.resetToDefaultState();
  59189. state->quality = defaultQuality;
  59190. }
  59191. bool Graphics::isVectorDevice() const throw()
  59192. {
  59193. return context->isVectorDevice();
  59194. }
  59195. bool Graphics::reduceClipRegion (const int x, const int y,
  59196. const int w, const int h) throw()
  59197. {
  59198. saveStateIfPending();
  59199. return context->reduceClipRegion (x, y, w, h);
  59200. }
  59201. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  59202. {
  59203. saveStateIfPending();
  59204. return context->reduceClipRegion (clipRegion);
  59205. }
  59206. void Graphics::excludeClipRegion (const int x, const int y,
  59207. const int w, const int h) throw()
  59208. {
  59209. saveStateIfPending();
  59210. context->excludeClipRegion (x, y, w, h);
  59211. }
  59212. bool Graphics::isClipEmpty() const throw()
  59213. {
  59214. return context->isClipEmpty();
  59215. }
  59216. const Rectangle Graphics::getClipBounds() const throw()
  59217. {
  59218. return context->getClipBounds();
  59219. }
  59220. void Graphics::saveState() throw()
  59221. {
  59222. saveStateIfPending();
  59223. saveStatePending = true;
  59224. }
  59225. void Graphics::restoreState() throw()
  59226. {
  59227. if (saveStatePending)
  59228. {
  59229. saveStatePending = false;
  59230. }
  59231. else
  59232. {
  59233. const int stackSize = stateStack.size();
  59234. if (stackSize > 0)
  59235. {
  59236. context->restoreState();
  59237. delete state;
  59238. state = stateStack.getUnchecked (stackSize - 1);
  59239. stateStack.removeLast (1, false);
  59240. }
  59241. else
  59242. {
  59243. // Trying to call restoreState() more times than you've called saveState() !
  59244. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  59245. jassertfalse
  59246. }
  59247. }
  59248. }
  59249. void Graphics::saveStateIfPending() throw()
  59250. {
  59251. if (saveStatePending)
  59252. {
  59253. saveStatePending = false;
  59254. context->saveState();
  59255. stateStack.add (new GraphicsState (*state));
  59256. }
  59257. }
  59258. void Graphics::setOrigin (const int newOriginX,
  59259. const int newOriginY) throw()
  59260. {
  59261. saveStateIfPending();
  59262. context->setOrigin (newOriginX, newOriginY);
  59263. }
  59264. bool Graphics::clipRegionIntersects (const int x, const int y,
  59265. const int w, const int h) const throw()
  59266. {
  59267. return context->clipRegionIntersects (x, y, w, h);
  59268. }
  59269. void Graphics::setColour (const Colour& newColour) throw()
  59270. {
  59271. saveStateIfPending();
  59272. state->colour = newColour;
  59273. deleteAndZero (state->brush);
  59274. }
  59275. const Colour& Graphics::getCurrentColour() const throw()
  59276. {
  59277. return state->colour;
  59278. }
  59279. void Graphics::setOpacity (const float newOpacity) throw()
  59280. {
  59281. saveStateIfPending();
  59282. state->colour = state->colour.withAlpha (newOpacity);
  59283. }
  59284. void Graphics::setBrush (const Brush* const newBrush) throw()
  59285. {
  59286. saveStateIfPending();
  59287. delete state->brush;
  59288. if (newBrush != 0)
  59289. state->brush = newBrush->createCopy();
  59290. else
  59291. state->brush = 0;
  59292. }
  59293. Graphics::GraphicsState::GraphicsState() throw()
  59294. : colour (Colours::black),
  59295. brush (0),
  59296. quality (defaultQuality)
  59297. {
  59298. }
  59299. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  59300. : colour (other.colour),
  59301. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  59302. font (other.font),
  59303. quality (other.quality)
  59304. {
  59305. }
  59306. Graphics::GraphicsState::~GraphicsState() throw()
  59307. {
  59308. delete brush;
  59309. }
  59310. void Graphics::setFont (const Font& newFont) throw()
  59311. {
  59312. saveStateIfPending();
  59313. state->font = newFont;
  59314. }
  59315. void Graphics::setFont (const float newFontHeight,
  59316. const int newFontStyleFlags) throw()
  59317. {
  59318. saveStateIfPending();
  59319. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  59320. }
  59321. const Font& Graphics::getCurrentFont() const throw()
  59322. {
  59323. return state->font;
  59324. }
  59325. void Graphics::drawSingleLineText (const String& text,
  59326. const int startX,
  59327. const int baselineY) const throw()
  59328. {
  59329. if (text.isNotEmpty()
  59330. && startX < context->getClipBounds().getRight())
  59331. {
  59332. GlyphArrangement arr;
  59333. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  59334. arr.draw (*this);
  59335. }
  59336. }
  59337. void Graphics::drawTextAsPath (const String& text,
  59338. const AffineTransform& transform) const throw()
  59339. {
  59340. if (text.isNotEmpty())
  59341. {
  59342. GlyphArrangement arr;
  59343. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  59344. arr.draw (*this, transform);
  59345. }
  59346. }
  59347. void Graphics::drawMultiLineText (const String& text,
  59348. const int startX,
  59349. const int baselineY,
  59350. const int maximumLineWidth) const throw()
  59351. {
  59352. if (text.isNotEmpty()
  59353. && startX < context->getClipBounds().getRight())
  59354. {
  59355. GlyphArrangement arr;
  59356. arr.addJustifiedText (state->font, text,
  59357. (float) startX, (float) baselineY, (float) maximumLineWidth,
  59358. Justification::left);
  59359. arr.draw (*this);
  59360. }
  59361. }
  59362. void Graphics::drawText (const String& text,
  59363. const int x,
  59364. const int y,
  59365. const int width,
  59366. const int height,
  59367. const Justification& justificationType,
  59368. const bool useEllipsesIfTooBig) const throw()
  59369. {
  59370. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  59371. {
  59372. GlyphArrangement arr;
  59373. arr.addCurtailedLineOfText (state->font, text,
  59374. 0.0f, 0.0f, (float)width,
  59375. useEllipsesIfTooBig);
  59376. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  59377. (float) x, (float) y,
  59378. (float) width, (float) height,
  59379. justificationType);
  59380. arr.draw (*this);
  59381. }
  59382. }
  59383. void Graphics::drawFittedText (const String& text,
  59384. const int x,
  59385. const int y,
  59386. const int width,
  59387. const int height,
  59388. const Justification& justification,
  59389. const int maximumNumberOfLines,
  59390. const float minimumHorizontalScale) const throw()
  59391. {
  59392. if (text.isNotEmpty()
  59393. && width > 0 && height > 0
  59394. && context->clipRegionIntersects (x, y, width, height))
  59395. {
  59396. GlyphArrangement arr;
  59397. arr.addFittedText (state->font, text,
  59398. (float) x, (float) y,
  59399. (float) width, (float) height,
  59400. justification,
  59401. maximumNumberOfLines,
  59402. minimumHorizontalScale);
  59403. arr.draw (*this);
  59404. }
  59405. }
  59406. void Graphics::fillRect (int x,
  59407. int y,
  59408. int width,
  59409. int height) const throw()
  59410. {
  59411. // passing in a silly number can cause maths problems in rendering!
  59412. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59413. SolidColourBrush colourBrush (state->colour);
  59414. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  59415. }
  59416. void Graphics::fillRect (const Rectangle& r) const throw()
  59417. {
  59418. fillRect (r.getX(),
  59419. r.getY(),
  59420. r.getWidth(),
  59421. r.getHeight());
  59422. }
  59423. void Graphics::fillRect (const float x,
  59424. const float y,
  59425. const float width,
  59426. const float height) const throw()
  59427. {
  59428. // passing in a silly number can cause maths problems in rendering!
  59429. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59430. Path p;
  59431. p.addRectangle (x, y, width, height);
  59432. fillPath (p);
  59433. }
  59434. void Graphics::setPixel (int x, int y) const throw()
  59435. {
  59436. if (context->clipRegionIntersects (x, y, 1, 1))
  59437. {
  59438. SolidColourBrush colourBrush (state->colour);
  59439. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  59440. }
  59441. }
  59442. void Graphics::fillAll() const throw()
  59443. {
  59444. fillRect (context->getClipBounds());
  59445. }
  59446. void Graphics::fillAll (const Colour& colourToUse) const throw()
  59447. {
  59448. if (! colourToUse.isTransparent())
  59449. {
  59450. const Rectangle clip (context->getClipBounds());
  59451. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  59452. colourToUse, false);
  59453. }
  59454. }
  59455. void Graphics::fillPath (const Path& path,
  59456. const AffineTransform& transform) const throw()
  59457. {
  59458. if ((! context->isClipEmpty()) && ! path.isEmpty())
  59459. {
  59460. SolidColourBrush colourBrush (state->colour);
  59461. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  59462. }
  59463. }
  59464. void Graphics::strokePath (const Path& path,
  59465. const PathStrokeType& strokeType,
  59466. const AffineTransform& transform) const throw()
  59467. {
  59468. if (! state->colour.isTransparent())
  59469. {
  59470. Path stroke;
  59471. strokeType.createStrokedPath (stroke, path, transform);
  59472. fillPath (stroke);
  59473. }
  59474. }
  59475. void Graphics::drawRect (const int x,
  59476. const int y,
  59477. const int width,
  59478. const int height,
  59479. const int lineThickness) const throw()
  59480. {
  59481. // passing in a silly number can cause maths problems in rendering!
  59482. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59483. SolidColourBrush colourBrush (state->colour);
  59484. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  59485. b.paintRectangle (*context, x, y, width, lineThickness);
  59486. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  59487. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  59488. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  59489. }
  59490. void Graphics::drawRect (const float x,
  59491. const float y,
  59492. const float width,
  59493. const float height,
  59494. const float lineThickness) const throw()
  59495. {
  59496. // passing in a silly number can cause maths problems in rendering!
  59497. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59498. Path p;
  59499. p.addRectangle (x, y, width, lineThickness);
  59500. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  59501. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  59502. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  59503. fillPath (p);
  59504. }
  59505. void Graphics::drawRect (const Rectangle& r,
  59506. const int lineThickness) const throw()
  59507. {
  59508. drawRect (r.getX(), r.getY(),
  59509. r.getWidth(), r.getHeight(),
  59510. lineThickness);
  59511. }
  59512. void Graphics::drawBevel (const int x,
  59513. const int y,
  59514. const int width,
  59515. const int height,
  59516. const int bevelThickness,
  59517. const Colour& topLeftColour,
  59518. const Colour& bottomRightColour,
  59519. const bool useGradient) const throw()
  59520. {
  59521. // passing in a silly number can cause maths problems in rendering!
  59522. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59523. if (clipRegionIntersects (x, y, width, height))
  59524. {
  59525. const float oldOpacity = state->colour.getFloatAlpha();
  59526. const float ramp = oldOpacity / bevelThickness;
  59527. for (int i = bevelThickness; --i >= 0;)
  59528. {
  59529. const float op = useGradient ? ramp * (bevelThickness - i)
  59530. : oldOpacity;
  59531. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  59532. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  59533. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  59534. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  59535. }
  59536. }
  59537. }
  59538. void Graphics::fillEllipse (const float x,
  59539. const float y,
  59540. const float width,
  59541. const float height) const throw()
  59542. {
  59543. // passing in a silly number can cause maths problems in rendering!
  59544. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59545. Path p;
  59546. p.addEllipse (x, y, width, height);
  59547. fillPath (p);
  59548. }
  59549. void Graphics::drawEllipse (const float x,
  59550. const float y,
  59551. const float width,
  59552. const float height,
  59553. const float lineThickness) const throw()
  59554. {
  59555. // passing in a silly number can cause maths problems in rendering!
  59556. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59557. Path p;
  59558. p.addEllipse (x, y, width, height);
  59559. strokePath (p, PathStrokeType (lineThickness));
  59560. }
  59561. void Graphics::fillRoundedRectangle (const float x,
  59562. const float y,
  59563. const float width,
  59564. const float height,
  59565. const float cornerSize) const throw()
  59566. {
  59567. // passing in a silly number can cause maths problems in rendering!
  59568. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59569. Path p;
  59570. p.addRoundedRectangle (x, y, width, height, cornerSize);
  59571. fillPath (p);
  59572. }
  59573. void Graphics::fillRoundedRectangle (const Rectangle& r,
  59574. const float cornerSize) const throw()
  59575. {
  59576. fillRoundedRectangle ((float) r.getX(),
  59577. (float) r.getY(),
  59578. (float) r.getWidth(),
  59579. (float) r.getHeight(),
  59580. cornerSize);
  59581. }
  59582. void Graphics::drawRoundedRectangle (const float x,
  59583. const float y,
  59584. const float width,
  59585. const float height,
  59586. const float cornerSize,
  59587. const float lineThickness) const throw()
  59588. {
  59589. // passing in a silly number can cause maths problems in rendering!
  59590. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59591. Path p;
  59592. p.addRoundedRectangle (x, y, width, height, cornerSize);
  59593. strokePath (p, PathStrokeType (lineThickness));
  59594. }
  59595. void Graphics::drawRoundedRectangle (const Rectangle& r,
  59596. const float cornerSize,
  59597. const float lineThickness) const throw()
  59598. {
  59599. drawRoundedRectangle ((float) r.getX(),
  59600. (float) r.getY(),
  59601. (float) r.getWidth(),
  59602. (float) r.getHeight(),
  59603. cornerSize, lineThickness);
  59604. }
  59605. void Graphics::drawArrow (const float startX,
  59606. const float startY,
  59607. const float endX,
  59608. const float endY,
  59609. const float lineThickness,
  59610. const float arrowheadWidth,
  59611. const float arrowheadLength) const throw()
  59612. {
  59613. Path p;
  59614. p.addArrow (startX, startY, endX, endY,
  59615. lineThickness, arrowheadWidth, arrowheadLength);
  59616. fillPath (p);
  59617. }
  59618. void Graphics::fillCheckerBoard (int x, int y,
  59619. int width, int height,
  59620. const int checkWidth,
  59621. const int checkHeight,
  59622. const Colour& colour1,
  59623. const Colour& colour2) const throw()
  59624. {
  59625. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  59626. if (checkWidth > 0 && checkHeight > 0)
  59627. {
  59628. if (colour1 == colour2)
  59629. {
  59630. context->fillRectWithColour (x, y, width, height, colour1, false);
  59631. }
  59632. else
  59633. {
  59634. const Rectangle clip (context->getClipBounds());
  59635. const int right = jmin (x + width, clip.getRight());
  59636. const int bottom = jmin (y + height, clip.getBottom());
  59637. int cy = 0;
  59638. while (y < bottom)
  59639. {
  59640. int cx = cy;
  59641. for (int xx = x; xx < right; xx += checkWidth)
  59642. context->fillRectWithColour (xx, y,
  59643. jmin (checkWidth, right - xx),
  59644. jmin (checkHeight, bottom - y),
  59645. ((cx++ & 1) == 0) ? colour1 : colour2,
  59646. false);
  59647. ++cy;
  59648. y += checkHeight;
  59649. }
  59650. }
  59651. }
  59652. }
  59653. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  59654. {
  59655. SolidColourBrush colourBrush (state->colour);
  59656. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  59657. }
  59658. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  59659. {
  59660. SolidColourBrush colourBrush (state->colour);
  59661. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  59662. }
  59663. void Graphics::drawLine (float x1, float y1,
  59664. float x2, float y2) const throw()
  59665. {
  59666. if (! context->isClipEmpty())
  59667. {
  59668. SolidColourBrush colourBrush (state->colour);
  59669. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  59670. }
  59671. }
  59672. void Graphics::drawLine (const float startX,
  59673. const float startY,
  59674. const float endX,
  59675. const float endY,
  59676. const float lineThickness) const throw()
  59677. {
  59678. Path p;
  59679. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  59680. fillPath (p);
  59681. }
  59682. void Graphics::drawLine (const Line& line) const throw()
  59683. {
  59684. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  59685. }
  59686. void Graphics::drawLine (const Line& line,
  59687. const float lineThickness) const throw()
  59688. {
  59689. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  59690. }
  59691. void Graphics::drawDashedLine (const float startX,
  59692. const float startY,
  59693. const float endX,
  59694. const float endY,
  59695. const float* const dashLengths,
  59696. const int numDashLengths,
  59697. const float lineThickness) const throw()
  59698. {
  59699. const double dx = endX - startX;
  59700. const double dy = endY - startY;
  59701. const double totalLen = juce_hypot (dx, dy);
  59702. if (totalLen >= 0.5)
  59703. {
  59704. const double onePixAlpha = 1.0 / totalLen;
  59705. double alpha = 0.0;
  59706. float x = startX;
  59707. float y = startY;
  59708. int n = 0;
  59709. while (alpha < 1.0f)
  59710. {
  59711. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  59712. n = n % numDashLengths;
  59713. const float oldX = x;
  59714. const float oldY = y;
  59715. x = (float) (startX + dx * alpha);
  59716. y = (float) (startY + dy * alpha);
  59717. if ((n & 1) != 0)
  59718. {
  59719. if (lineThickness != 1.0f)
  59720. drawLine (oldX, oldY, x, y, lineThickness);
  59721. else
  59722. drawLine (oldX, oldY, x, y);
  59723. }
  59724. }
  59725. }
  59726. }
  59727. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  59728. {
  59729. saveStateIfPending();
  59730. state->quality = newQuality;
  59731. }
  59732. void Graphics::drawImageAt (const Image* const imageToDraw,
  59733. const int topLeftX,
  59734. const int topLeftY,
  59735. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59736. {
  59737. if (imageToDraw != 0)
  59738. {
  59739. const int imageW = imageToDraw->getWidth();
  59740. const int imageH = imageToDraw->getHeight();
  59741. drawImage (imageToDraw,
  59742. topLeftX, topLeftY, imageW, imageH,
  59743. 0, 0, imageW, imageH,
  59744. fillAlphaChannelWithCurrentBrush);
  59745. }
  59746. }
  59747. void Graphics::drawImageWithin (const Image* const imageToDraw,
  59748. const int destX,
  59749. const int destY,
  59750. const int destW,
  59751. const int destH,
  59752. const RectanglePlacement& placementWithinTarget,
  59753. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59754. {
  59755. // passing in a silly number can cause maths problems in rendering!
  59756. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  59757. if (imageToDraw != 0)
  59758. {
  59759. const int imageW = imageToDraw->getWidth();
  59760. const int imageH = imageToDraw->getHeight();
  59761. if (imageW > 0 && imageH > 0)
  59762. {
  59763. double newX = 0.0, newY = 0.0;
  59764. double newW = imageW;
  59765. double newH = imageH;
  59766. placementWithinTarget.applyTo (newX, newY, newW, newH,
  59767. destX, destY, destW, destH);
  59768. if (newW > 0 && newH > 0)
  59769. {
  59770. drawImage (imageToDraw,
  59771. roundDoubleToInt (newX), roundDoubleToInt (newY),
  59772. roundDoubleToInt (newW), roundDoubleToInt (newH),
  59773. 0, 0, imageW, imageH,
  59774. fillAlphaChannelWithCurrentBrush);
  59775. }
  59776. }
  59777. }
  59778. }
  59779. void Graphics::drawImage (const Image* const imageToDraw,
  59780. int dx, int dy, int dw, int dh,
  59781. int sx, int sy, int sw, int sh,
  59782. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59783. {
  59784. // passing in a silly number can cause maths problems in rendering!
  59785. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  59786. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  59787. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  59788. return;
  59789. if (sw == dw && sh == dh)
  59790. {
  59791. if (sx < 0)
  59792. {
  59793. dx -= sx;
  59794. dw += sx;
  59795. sw += sx;
  59796. sx = 0;
  59797. }
  59798. if (sx + sw > imageToDraw->getWidth())
  59799. {
  59800. const int amount = sx + sw - imageToDraw->getWidth();
  59801. dw -= amount;
  59802. sw -= amount;
  59803. }
  59804. if (sy < 0)
  59805. {
  59806. dy -= sy;
  59807. dh += sy;
  59808. sh += sy;
  59809. sy = 0;
  59810. }
  59811. if (sy + sh > imageToDraw->getHeight())
  59812. {
  59813. const int amount = sy + sh - imageToDraw->getHeight();
  59814. dh -= amount;
  59815. sh -= amount;
  59816. }
  59817. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  59818. return;
  59819. if (fillAlphaChannelWithCurrentBrush)
  59820. {
  59821. SolidColourBrush colourBrush (state->colour);
  59822. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  59823. .paintAlphaChannel (*context, *imageToDraw,
  59824. dx - sx, dy - sy,
  59825. dx, dy,
  59826. dw, dh);
  59827. }
  59828. else
  59829. {
  59830. context->blendImage (*imageToDraw,
  59831. dx, dy, dw, dh, sx, sy,
  59832. state->colour.getFloatAlpha());
  59833. }
  59834. }
  59835. else
  59836. {
  59837. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  59838. return;
  59839. if (fillAlphaChannelWithCurrentBrush)
  59840. {
  59841. if (imageToDraw->isRGB())
  59842. {
  59843. fillRect (dx, dy, dw, dh);
  59844. }
  59845. else
  59846. {
  59847. int tx = dx;
  59848. int ty = dy;
  59849. int tw = dw;
  59850. int th = dh;
  59851. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  59852. {
  59853. Image temp (imageToDraw->getFormat(), tw, th, true);
  59854. Graphics g (temp);
  59855. g.setImageResamplingQuality (state->quality);
  59856. g.setOrigin (dx - tx, dy - ty);
  59857. g.drawImage (imageToDraw,
  59858. 0, 0, dw, dh,
  59859. sx, sy, sw, sh,
  59860. false);
  59861. SolidColourBrush colourBrush (state->colour);
  59862. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  59863. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  59864. }
  59865. }
  59866. }
  59867. else
  59868. {
  59869. context->blendImageRescaling (*imageToDraw,
  59870. dx, dy, dw, dh,
  59871. sx, sy, sw, sh,
  59872. state->colour.getFloatAlpha(),
  59873. state->quality);
  59874. }
  59875. }
  59876. }
  59877. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  59878. int sourceClipX,
  59879. int sourceClipY,
  59880. int sourceClipWidth,
  59881. int sourceClipHeight,
  59882. const AffineTransform& transform,
  59883. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59884. {
  59885. if (imageToDraw != 0
  59886. && (! context->isClipEmpty())
  59887. && ! transform.isSingularity())
  59888. {
  59889. if (fillAlphaChannelWithCurrentBrush)
  59890. {
  59891. Path p;
  59892. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  59893. (float) sourceClipWidth, (float) sourceClipHeight);
  59894. p.applyTransform (transform);
  59895. float dx, dy, dw, dh;
  59896. p.getBounds (dx, dy, dw, dh);
  59897. int tx = (int) dx;
  59898. int ty = (int) dy;
  59899. int tw = roundFloatToInt (dw) + 2;
  59900. int th = roundFloatToInt (dh) + 2;
  59901. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  59902. {
  59903. Image temp (imageToDraw->getFormat(), tw, th, true);
  59904. Graphics g (temp);
  59905. g.setImageResamplingQuality (state->quality);
  59906. g.drawImageTransformed (imageToDraw,
  59907. sourceClipX,
  59908. sourceClipY,
  59909. sourceClipWidth,
  59910. sourceClipHeight,
  59911. transform.translated ((float) -tx, (float) -ty),
  59912. false);
  59913. SolidColourBrush colourBrush (state->colour);
  59914. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  59915. }
  59916. }
  59917. else
  59918. {
  59919. context->blendImageWarping (*imageToDraw,
  59920. sourceClipX,
  59921. sourceClipY,
  59922. sourceClipWidth,
  59923. sourceClipHeight,
  59924. transform,
  59925. state->colour.getFloatAlpha(),
  59926. state->quality);
  59927. }
  59928. }
  59929. }
  59930. END_JUCE_NAMESPACE
  59931. /********* End of inlined file: juce_Graphics.cpp *********/
  59932. /********* Start of inlined file: juce_Justification.cpp *********/
  59933. BEGIN_JUCE_NAMESPACE
  59934. Justification::Justification (const Justification& other) throw()
  59935. : flags (other.flags)
  59936. {
  59937. }
  59938. const Justification& Justification::operator= (const Justification& other) throw()
  59939. {
  59940. flags = other.flags;
  59941. return *this;
  59942. }
  59943. int Justification::getOnlyVerticalFlags() const throw()
  59944. {
  59945. return flags & (top | bottom | verticallyCentred);
  59946. }
  59947. int Justification::getOnlyHorizontalFlags() const throw()
  59948. {
  59949. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  59950. }
  59951. void Justification::applyToRectangle (int& x, int& y,
  59952. const int w, const int h,
  59953. const int spaceX, const int spaceY,
  59954. const int spaceW, const int spaceH) const throw()
  59955. {
  59956. if ((flags & horizontallyCentred) != 0)
  59957. {
  59958. x = spaceX + ((spaceW - w) >> 1);
  59959. }
  59960. else if ((flags & right) != 0)
  59961. {
  59962. x = spaceX + spaceW - w;
  59963. }
  59964. else
  59965. {
  59966. x = spaceX;
  59967. }
  59968. if ((flags & verticallyCentred) != 0)
  59969. {
  59970. y = spaceY + ((spaceH - h) >> 1);
  59971. }
  59972. else if ((flags & bottom) != 0)
  59973. {
  59974. y = spaceY + spaceH - h;
  59975. }
  59976. else
  59977. {
  59978. y = spaceY;
  59979. }
  59980. }
  59981. END_JUCE_NAMESPACE
  59982. /********* End of inlined file: juce_Justification.cpp *********/
  59983. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  59984. BEGIN_JUCE_NAMESPACE
  59985. #if JUCE_MSVC
  59986. #pragma warning (disable: 4996) // deprecated sprintf warning
  59987. #endif
  59988. // this will throw an assertion if you try to draw something that's not
  59989. // possible in postscript
  59990. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  59991. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  59992. #define notPossibleInPostscriptAssert jassertfalse
  59993. #else
  59994. #define notPossibleInPostscriptAssert
  59995. #endif
  59996. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  59997. const String& documentTitle,
  59998. const int totalWidth_,
  59999. const int totalHeight_)
  60000. : out (resultingPostScript),
  60001. totalWidth (totalWidth_),
  60002. totalHeight (totalHeight_),
  60003. xOffset (0),
  60004. yOffset (0),
  60005. needToClip (true)
  60006. {
  60007. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  60008. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  60009. out << "%!PS-Adobe-3.0 EPSF-3.0"
  60010. "\n%%BoundingBox: 0 0 600 824"
  60011. "\n%%Pages: 0"
  60012. "\n%%Creator: Raw Material Software JUCE"
  60013. "\n%%Title: " << documentTitle <<
  60014. "\n%%CreationDate: none"
  60015. "\n%%LanguageLevel: 2"
  60016. "\n%%EndComments"
  60017. "\n%%BeginProlog"
  60018. "\n%%BeginResource: JRes"
  60019. "\n/bd {bind def} bind def"
  60020. "\n/c {setrgbcolor} bd"
  60021. "\n/m {moveto} bd"
  60022. "\n/l {lineto} bd"
  60023. "\n/rl {rlineto} bd"
  60024. "\n/ct {curveto} bd"
  60025. "\n/cp {closepath} bd"
  60026. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  60027. "\n/doclip {initclip newpath} bd"
  60028. "\n/endclip {clip newpath} bd"
  60029. "\n%%EndResource"
  60030. "\n%%EndProlog"
  60031. "\n%%BeginSetup"
  60032. "\n%%EndSetup"
  60033. "\n%%Page: 1 1"
  60034. "\n%%BeginPageSetup"
  60035. "\n%%EndPageSetup\n\n"
  60036. << "40 800 translate\n"
  60037. << scale << ' ' << scale << " scale\n\n";
  60038. }
  60039. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  60040. {
  60041. delete clip;
  60042. }
  60043. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  60044. {
  60045. return true;
  60046. }
  60047. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  60048. {
  60049. if (x != 0 || y != 0)
  60050. {
  60051. xOffset += x;
  60052. yOffset += y;
  60053. needToClip = true;
  60054. }
  60055. }
  60056. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  60057. {
  60058. needToClip = true;
  60059. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  60060. }
  60061. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  60062. {
  60063. needToClip = true;
  60064. return clip->clipTo (clipRegion);
  60065. }
  60066. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  60067. {
  60068. needToClip = true;
  60069. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  60070. }
  60071. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  60072. {
  60073. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  60074. }
  60075. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  60076. {
  60077. return clip->getBounds().translated (-xOffset, -yOffset);
  60078. }
  60079. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  60080. {
  60081. return clip->isEmpty();
  60082. }
  60083. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  60084. const int xOffset_, const int yOffset_)
  60085. : clip (clip_),
  60086. xOffset (xOffset_),
  60087. yOffset (yOffset_)
  60088. {
  60089. }
  60090. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  60091. {
  60092. delete clip;
  60093. }
  60094. void LowLevelGraphicsPostScriptRenderer::saveState()
  60095. {
  60096. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  60097. }
  60098. void LowLevelGraphicsPostScriptRenderer::restoreState()
  60099. {
  60100. SavedState* const top = stateStack.getLast();
  60101. if (top != 0)
  60102. {
  60103. clip->swapWith (*top->clip);
  60104. xOffset = top->xOffset;
  60105. yOffset = top->yOffset;
  60106. stateStack.removeLast();
  60107. needToClip = true;
  60108. }
  60109. else
  60110. {
  60111. jassertfalse // trying to pop with an empty stack!
  60112. }
  60113. }
  60114. void LowLevelGraphicsPostScriptRenderer::writeClip()
  60115. {
  60116. if (needToClip)
  60117. {
  60118. needToClip = false;
  60119. out << "doclip ";
  60120. int itemsOnLine = 0;
  60121. for (RectangleList::Iterator i (*clip); i.next();)
  60122. {
  60123. if (++itemsOnLine == 6)
  60124. {
  60125. itemsOnLine = 0;
  60126. out << '\n';
  60127. }
  60128. const Rectangle& r = *i.getRectangle();
  60129. out << r.getX() << ' ' << -r.getY() << ' '
  60130. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  60131. }
  60132. out << "endclip\n";
  60133. }
  60134. }
  60135. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  60136. {
  60137. Colour c (Colours::white.overlaidWith (colour));
  60138. if (lastColour != c)
  60139. {
  60140. lastColour = c;
  60141. out << String (c.getFloatRed(), 3) << ' '
  60142. << String (c.getFloatGreen(), 3) << ' '
  60143. << String (c.getFloatBlue(), 3) << " c\n";
  60144. }
  60145. }
  60146. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  60147. {
  60148. out << String (x, 2) << ' '
  60149. << String (-y, 2) << ' ';
  60150. }
  60151. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  60152. {
  60153. out << "newpath ";
  60154. float lastX = 0.0f;
  60155. float lastY = 0.0f;
  60156. int itemsOnLine = 0;
  60157. Path::Iterator i (path);
  60158. while (i.next())
  60159. {
  60160. if (++itemsOnLine == 4)
  60161. {
  60162. itemsOnLine = 0;
  60163. out << '\n';
  60164. }
  60165. switch (i.elementType)
  60166. {
  60167. case Path::Iterator::startNewSubPath:
  60168. writeXY (i.x1, i.y1);
  60169. lastX = i.x1;
  60170. lastY = i.y1;
  60171. out << "m ";
  60172. break;
  60173. case Path::Iterator::lineTo:
  60174. writeXY (i.x1, i.y1);
  60175. lastX = i.x1;
  60176. lastY = i.y1;
  60177. out << "l ";
  60178. break;
  60179. case Path::Iterator::quadraticTo:
  60180. {
  60181. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  60182. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  60183. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  60184. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  60185. writeXY (cp1x, cp1y);
  60186. writeXY (cp2x, cp2y);
  60187. writeXY (i.x2, i.y2);
  60188. out << "ct ";
  60189. lastX = i.x2;
  60190. lastY = i.y2;
  60191. }
  60192. break;
  60193. case Path::Iterator::cubicTo:
  60194. writeXY (i.x1, i.y1);
  60195. writeXY (i.x2, i.y2);
  60196. writeXY (i.x3, i.y3);
  60197. out << "ct ";
  60198. lastX = i.x3;
  60199. lastY = i.y3;
  60200. break;
  60201. case Path::Iterator::closePath:
  60202. out << "cp ";
  60203. break;
  60204. default:
  60205. jassertfalse
  60206. break;
  60207. }
  60208. }
  60209. out << '\n';
  60210. }
  60211. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  60212. {
  60213. out << "[ "
  60214. << trans.mat00 << ' '
  60215. << trans.mat10 << ' '
  60216. << trans.mat01 << ' '
  60217. << trans.mat11 << ' '
  60218. << trans.mat02 << ' '
  60219. << trans.mat12 << " ] concat ";
  60220. }
  60221. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  60222. {
  60223. writeClip();
  60224. writeColour (colour);
  60225. x += xOffset;
  60226. y += yOffset;
  60227. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  60228. }
  60229. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  60230. {
  60231. Path p;
  60232. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  60233. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  60234. }
  60235. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  60236. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  60237. {
  60238. writeClip();
  60239. Path p (path);
  60240. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60241. writePath (p);
  60242. writeColour (colour);
  60243. out << "fill\n";
  60244. }
  60245. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  60246. {
  60247. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  60248. // postscript can't do semi-transparent ones.
  60249. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60250. writeClip();
  60251. out << "gsave ";
  60252. {
  60253. Path p (path);
  60254. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60255. writePath (p);
  60256. out << "clip\n";
  60257. }
  60258. int numColours = 256;
  60259. PixelARGB* const colours = gradient.createLookupTable (numColours);
  60260. for (int i = numColours; --i >= 0;)
  60261. colours[i].unpremultiply();
  60262. const Rectangle bounds (clip->getBounds());
  60263. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  60264. // time-being, this just fills it with the average colour..
  60265. writeColour (Colour (colours [numColours / 2].getARGB()));
  60266. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  60267. juce_free (colours);
  60268. out << "grestore\n";
  60269. }
  60270. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  60271. const Image& sourceImage,
  60272. int imageX, int imageY,
  60273. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  60274. {
  60275. writeClip();
  60276. out << "gsave ";
  60277. Path p (path);
  60278. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  60279. writePath (p);
  60280. out << "clip\n";
  60281. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  60282. out << "grestore\n";
  60283. }
  60284. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  60285. {
  60286. x += xOffset;
  60287. y += yOffset;
  60288. writeClip();
  60289. writeColour (colour);
  60290. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60291. }
  60292. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  60293. {
  60294. imageX += xOffset;
  60295. imageY += yOffset;
  60296. writeClip();
  60297. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60298. }
  60299. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  60300. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  60301. {
  60302. alphaImageX += xOffset;
  60303. alphaImageY += yOffset;
  60304. fillerImageX += xOffset;
  60305. fillerImageY += yOffset;
  60306. writeClip();
  60307. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60308. }
  60309. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  60310. int dx, int dy, int dw, int dh,
  60311. int sx, int sy, int sw, int sh,
  60312. float alpha,
  60313. const Graphics::ResamplingQuality quality)
  60314. {
  60315. if (sw > 0 && sh > 0)
  60316. {
  60317. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  60318. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  60319. if (sw == dw && sh == dh)
  60320. {
  60321. blendImage (sourceImage,
  60322. dx, dy, dw, dh,
  60323. sx, sy, alpha);
  60324. }
  60325. else
  60326. {
  60327. blendImageWarping (sourceImage,
  60328. sx, sy, sw, sh,
  60329. AffineTransform::scale (dw / (float) sw,
  60330. dh / (float) sh)
  60331. .translated ((float) (dx - sx),
  60332. (float) (dy - sy)),
  60333. alpha,
  60334. quality);
  60335. }
  60336. }
  60337. }
  60338. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  60339. {
  60340. blendImageWarping (sourceImage,
  60341. sx, sy, dw, dh,
  60342. AffineTransform::translation ((float) dx, (float) dy),
  60343. opacity, Graphics::highResamplingQuality);
  60344. }
  60345. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  60346. const int sx, const int sy,
  60347. const int maxW, const int maxH) const
  60348. {
  60349. out << "{<\n";
  60350. const int w = jmin (maxW, im.getWidth());
  60351. const int h = jmin (maxH, im.getHeight());
  60352. int charsOnLine = 0;
  60353. int lineStride, pixelStride;
  60354. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  60355. Colour pixel;
  60356. for (int y = h; --y >= 0;)
  60357. {
  60358. for (int x = 0; x < w; ++x)
  60359. {
  60360. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  60361. if (x >= sx && y >= sy)
  60362. {
  60363. if (im.isARGB())
  60364. {
  60365. PixelARGB p (*(const PixelARGB*) pixelData);
  60366. p.unpremultiply();
  60367. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  60368. }
  60369. else if (im.isRGB())
  60370. {
  60371. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  60372. }
  60373. else
  60374. {
  60375. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  60376. }
  60377. }
  60378. else
  60379. {
  60380. pixel = Colours::transparentWhite;
  60381. }
  60382. char colourString [16];
  60383. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  60384. out << (const char*) colourString;
  60385. charsOnLine += 3;
  60386. if (charsOnLine > 100)
  60387. {
  60388. out << '\n';
  60389. charsOnLine = 0;
  60390. }
  60391. }
  60392. }
  60393. im.releasePixelDataReadOnly (data);
  60394. out << "\n>}\n";
  60395. }
  60396. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  60397. int srcClipX, int srcClipY,
  60398. int srcClipW, int srcClipH,
  60399. const AffineTransform& t,
  60400. float /*opacity*/,
  60401. const Graphics::ResamplingQuality /*quality*/)
  60402. {
  60403. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  60404. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  60405. writeClip();
  60406. out << "gsave ";
  60407. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  60408. .scaled (1.0f, -1.0f));
  60409. RectangleList imageClip;
  60410. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  60411. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  60412. out << "newpath ";
  60413. int itemsOnLine = 0;
  60414. for (RectangleList::Iterator i (imageClip); i.next();)
  60415. {
  60416. if (++itemsOnLine == 6)
  60417. {
  60418. out << '\n';
  60419. itemsOnLine = 0;
  60420. }
  60421. const Rectangle& r = *i.getRectangle();
  60422. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  60423. }
  60424. out << " clip newpath\n";
  60425. out << w << ' ' << h << " scale\n";
  60426. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  60427. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  60428. out << "false 3 colorimage grestore\n";
  60429. needToClip = true;
  60430. }
  60431. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  60432. {
  60433. Path p;
  60434. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  60435. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  60436. }
  60437. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  60438. {
  60439. drawLine (x, top, x, bottom, col);
  60440. }
  60441. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  60442. {
  60443. drawLine (left, y, right, y, col);
  60444. }
  60445. END_JUCE_NAMESPACE
  60446. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60447. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  60448. BEGIN_JUCE_NAMESPACE
  60449. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  60450. #define JUCE_USE_SSE_INSTRUCTIONS 1
  60451. #endif
  60452. #if defined (JUCE_DEBUG) && JUCE_MSVC
  60453. #pragma warning (disable: 4714)
  60454. #endif
  60455. #define MINIMUM_COORD -0x3fffffff
  60456. #define MAXIMUM_COORD 0x3fffffff
  60457. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  60458. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  60459. jassert ((int) x >= MINIMUM_COORD \
  60460. && (int) x <= MAXIMUM_COORD \
  60461. && (int) y >= MINIMUM_COORD \
  60462. && (int) y <= MAXIMUM_COORD \
  60463. && (int) w >= 0 \
  60464. && (int) w < MAXIMUM_COORD \
  60465. && (int) h >= 0 \
  60466. && (int) h < MAXIMUM_COORD);
  60467. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60468. {
  60469. const PixelARGB blendColour (colour.getPixelARGB());
  60470. if (w < 32)
  60471. {
  60472. while (--h >= 0)
  60473. {
  60474. PixelRGB* dest = (PixelRGB*) pixels;
  60475. for (int i = w; --i >= 0;)
  60476. (dest++)->set (blendColour);
  60477. pixels += stride;
  60478. }
  60479. }
  60480. else
  60481. {
  60482. // for wider fills, it's worth using some optimisations..
  60483. const uint8 r = blendColour.getRed();
  60484. const uint8 g = blendColour.getGreen();
  60485. const uint8 b = blendColour.getBlue();
  60486. if (r == g && r == b) // if all the component values are the same, we can cheat..
  60487. {
  60488. while (--h >= 0)
  60489. {
  60490. memset (pixels, r, w * 3);
  60491. pixels += stride;
  60492. }
  60493. }
  60494. else
  60495. {
  60496. PixelRGB filler [4];
  60497. filler[0].set (blendColour);
  60498. filler[1].set (blendColour);
  60499. filler[2].set (blendColour);
  60500. filler[3].set (blendColour);
  60501. const int* const intFiller = (const int*) filler;
  60502. while (--h >= 0)
  60503. {
  60504. uint8* dest = (uint8*) pixels;
  60505. int i = w;
  60506. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  60507. {
  60508. ((PixelRGB*) dest)->set (blendColour);
  60509. dest += 3;
  60510. --i;
  60511. }
  60512. while (i >= 4)
  60513. {
  60514. ((int*) dest) [0] = intFiller[0];
  60515. ((int*) dest) [1] = intFiller[1];
  60516. ((int*) dest) [2] = intFiller[2];
  60517. dest += 12;
  60518. i -= 4;
  60519. }
  60520. while (--i >= 0)
  60521. {
  60522. ((PixelRGB*) dest)->set (blendColour);
  60523. dest += 3;
  60524. }
  60525. pixels += stride;
  60526. }
  60527. }
  60528. }
  60529. }
  60530. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60531. {
  60532. const PixelARGB blendColour (colour.getPixelARGB());
  60533. while (--h >= 0)
  60534. {
  60535. PixelARGB* const dest = (PixelARGB*) pixels;
  60536. for (int i = 0; i < w; ++i)
  60537. dest[i] = blendColour;
  60538. pixels += stride;
  60539. }
  60540. }
  60541. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60542. {
  60543. if (colour.isOpaque())
  60544. {
  60545. replaceRectRGB (pixels, w, h, stride, colour);
  60546. }
  60547. else
  60548. {
  60549. const PixelARGB blendColour (colour.getPixelARGB());
  60550. const int alpha = blendColour.getAlpha();
  60551. if (alpha <= 0)
  60552. return;
  60553. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  60554. if (SystemStats::hasSSE())
  60555. {
  60556. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  60557. | (int64) ((blendColour.getGreen() << 16)
  60558. | blendColour.getBlue());
  60559. const int invAlpha = 0xff - alpha;
  60560. int64 aaaa = (invAlpha << 16) | invAlpha;
  60561. aaaa = (aaaa << 16) | aaaa;
  60562. #ifndef JUCE_GCC
  60563. __asm
  60564. {
  60565. movq mm1, aaaa
  60566. movq mm2, rgb0
  60567. pxor mm7, mm7
  60568. }
  60569. while (--h >= 0)
  60570. {
  60571. __asm
  60572. {
  60573. mov edx, pixels
  60574. mov ebx, w
  60575. pixloop:
  60576. prefetchnta [edx]
  60577. mov ax, [edx + 1]
  60578. shl eax, 8
  60579. mov al, [edx]
  60580. movd mm0, eax
  60581. punpcklbw mm0, mm7
  60582. pmullw mm0, mm1
  60583. psrlw mm0, 8
  60584. paddw mm0, mm2
  60585. packuswb mm0, mm7
  60586. movd eax, mm0
  60587. mov [edx], al
  60588. inc edx
  60589. shr eax, 8
  60590. mov [edx], ax
  60591. add edx, 2
  60592. dec ebx
  60593. jg pixloop
  60594. }
  60595. pixels += stride;
  60596. }
  60597. __asm emms
  60598. #else
  60599. __asm__ __volatile__ (
  60600. "movq %[aaaa], %%mm1 \n"
  60601. "\tmovq %[rgb0], %%mm2 \n"
  60602. "\tpxor %%mm7, %%mm7 \n"
  60603. ".lineLoop2: \n"
  60604. "\tmovl %%esi,%%edx \n"
  60605. "\tmovl %[w], %%ebx \n"
  60606. ".pixLoop2: \n"
  60607. "\tprefetchnta (%%edx) \n"
  60608. "\tmov (%%edx), %%ax \n"
  60609. "\tshl $8, %%eax \n"
  60610. "\tmov 2(%%edx), %%al \n"
  60611. "\tmovd %%eax, %%mm0 \n"
  60612. "\tpunpcklbw %%mm7, %%mm0 \n"
  60613. "\tpmullw %%mm1, %%mm0 \n"
  60614. "\tpsrlw $8, %%mm0 \n"
  60615. "\tpaddw %%mm2, %%mm0 \n"
  60616. "\tpackuswb %%mm7, %%mm0 \n"
  60617. "\tmovd %%mm0, %%eax \n"
  60618. "\tmovb %%al, (%%edx) \n"
  60619. "\tinc %%edx \n"
  60620. "\tshr $8, %%eax \n"
  60621. "\tmovw %%ax, (%%edx) \n"
  60622. "\tadd $2, %%edx \n"
  60623. "\tdec %%ebx \n"
  60624. "\tjg .pixLoop2 \n"
  60625. "\tadd %%edi, %%esi \n"
  60626. "\tdec %%ecx \n"
  60627. "\tjg .lineLoop2 \n"
  60628. "\temms \n"
  60629. : /* No output registers */
  60630. : [aaaa] "m" (aaaa), /* Input registers */
  60631. [rgb0] "m" (rgb0),
  60632. [w] "m" (w),
  60633. "c" (h),
  60634. [stride] "D" (stride),
  60635. [pixels] "S" (pixels)
  60636. : "cc", "eax", "edx", "memory" /* Clobber list */
  60637. );
  60638. #endif
  60639. }
  60640. else
  60641. #endif
  60642. {
  60643. while (--h >= 0)
  60644. {
  60645. PixelRGB* dest = (PixelRGB*) pixels;
  60646. for (int i = w; --i >= 0;)
  60647. (dest++)->blend (blendColour);
  60648. pixels += stride;
  60649. }
  60650. }
  60651. }
  60652. }
  60653. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60654. {
  60655. if (colour.isOpaque())
  60656. {
  60657. replaceRectARGB (pixels, w, h, stride, colour);
  60658. }
  60659. else
  60660. {
  60661. const PixelARGB blendColour (colour.getPixelARGB());
  60662. const int alpha = blendColour.getAlpha();
  60663. if (alpha <= 0)
  60664. return;
  60665. while (--h >= 0)
  60666. {
  60667. PixelARGB* dest = (PixelARGB*) pixels;
  60668. for (int i = w; --i >= 0;)
  60669. (dest++)->blend (blendColour);
  60670. pixels += stride;
  60671. }
  60672. }
  60673. }
  60674. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  60675. const uint8* alphaValues, const int w, int h,
  60676. const int pixelStride, const int lineStride,
  60677. const Colour& colour) throw()
  60678. {
  60679. const PixelARGB srcPix (colour.getPixelARGB());
  60680. while (--h >= 0)
  60681. {
  60682. PixelARGB* dest = (PixelARGB*) destPixel;
  60683. const uint8* src = alphaValues;
  60684. int i = w;
  60685. while (--i >= 0)
  60686. {
  60687. unsigned int srcAlpha = *src;
  60688. src += pixelStride;
  60689. if (srcAlpha > 0)
  60690. dest->blend (srcPix, srcAlpha);
  60691. ++dest;
  60692. }
  60693. alphaValues += lineStride;
  60694. destPixel += imageStride;
  60695. }
  60696. }
  60697. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  60698. const uint8* alphaValues, int const width, int height,
  60699. const int pixelStride, const int lineStride,
  60700. const Colour& colour) throw()
  60701. {
  60702. const PixelARGB srcPix (colour.getPixelARGB());
  60703. while (--height >= 0)
  60704. {
  60705. PixelRGB* dest = (PixelRGB*) destPixel;
  60706. const uint8* src = alphaValues;
  60707. int i = width;
  60708. while (--i >= 0)
  60709. {
  60710. unsigned int srcAlpha = *src;
  60711. src += pixelStride;
  60712. if (srcAlpha > 0)
  60713. dest->blend (srcPix, srcAlpha);
  60714. ++dest;
  60715. }
  60716. alphaValues += lineStride;
  60717. destPixel += imageStride;
  60718. }
  60719. }
  60720. template <class PixelType>
  60721. class SolidColourEdgeTableRenderer
  60722. {
  60723. uint8* const data;
  60724. const int stride;
  60725. PixelType* linePixels;
  60726. PixelARGB sourceColour;
  60727. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  60728. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  60729. public:
  60730. SolidColourEdgeTableRenderer (uint8* const data_,
  60731. const int stride_,
  60732. const Colour& colour) throw()
  60733. : data (data_),
  60734. stride (stride_),
  60735. sourceColour (colour.getPixelARGB())
  60736. {
  60737. }
  60738. forcedinline void setEdgeTableYPos (const int y) throw()
  60739. {
  60740. linePixels = (PixelType*) (data + stride * y);
  60741. }
  60742. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60743. {
  60744. linePixels[x].blend (sourceColour, alphaLevel);
  60745. }
  60746. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  60747. {
  60748. PixelARGB p (sourceColour);
  60749. p.multiplyAlpha (alphaLevel);
  60750. PixelType* dest = linePixels + x;
  60751. if (p.getAlpha() < 0xff)
  60752. {
  60753. do
  60754. {
  60755. dest->blend (p);
  60756. ++dest;
  60757. } while (--width > 0);
  60758. }
  60759. else
  60760. {
  60761. do
  60762. {
  60763. dest->set (p);
  60764. ++dest;
  60765. } while (--width > 0);
  60766. }
  60767. }
  60768. };
  60769. class AlphaBitmapRenderer
  60770. {
  60771. uint8* data;
  60772. int stride;
  60773. uint8* lineStart;
  60774. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  60775. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  60776. public:
  60777. AlphaBitmapRenderer (uint8* const data_,
  60778. const int stride_) throw()
  60779. : data (data_),
  60780. stride (stride_)
  60781. {
  60782. }
  60783. forcedinline void setEdgeTableYPos (const int y) throw()
  60784. {
  60785. lineStart = data + (stride * y);
  60786. }
  60787. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60788. {
  60789. lineStart [x] = (uint8) alphaLevel;
  60790. }
  60791. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  60792. {
  60793. uint8* d = lineStart + x;
  60794. while (--width >= 0)
  60795. *d++ = (uint8) alphaLevel;
  60796. }
  60797. };
  60798. static const int numScaleBits = 12;
  60799. class LinearGradientPixelGenerator
  60800. {
  60801. const PixelARGB* const lookupTable;
  60802. const int numEntries;
  60803. PixelARGB linePix;
  60804. int start, scale;
  60805. double grad, yTerm;
  60806. bool vertical, horizontal;
  60807. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  60808. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  60809. public:
  60810. LinearGradientPixelGenerator (const ColourGradient& gradient,
  60811. const PixelARGB* const lookupTable_, const int numEntries_)
  60812. : lookupTable (lookupTable_),
  60813. numEntries (numEntries_)
  60814. {
  60815. jassert (numEntries_ >= 0);
  60816. float x1 = gradient.x1;
  60817. float y1 = gradient.y1;
  60818. float x2 = gradient.x2;
  60819. float y2 = gradient.y2;
  60820. if (! gradient.transform.isIdentity())
  60821. {
  60822. Line l (x2, y2, x1, y1);
  60823. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  60824. float x3 = p3.getX();
  60825. float y3 = p3.getY();
  60826. gradient.transform.transformPoint (x1, y1);
  60827. gradient.transform.transformPoint (x2, y2);
  60828. gradient.transform.transformPoint (x3, y3);
  60829. Line l2 (x2, y2, x3, y3);
  60830. float prop = l2.findNearestPointTo (x1, y1);
  60831. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  60832. x2 = newP2.getX();
  60833. y2 = newP2.getY();
  60834. }
  60835. vertical = fabs (x1 - x2) < 0.001f;
  60836. horizontal = fabs (y1 - y2) < 0.001f;
  60837. if (vertical)
  60838. {
  60839. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  60840. start = roundDoubleToInt (y1 * scale);
  60841. }
  60842. else if (horizontal)
  60843. {
  60844. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  60845. start = roundDoubleToInt (x1 * scale);
  60846. }
  60847. else
  60848. {
  60849. grad = (y2 - y1) / (double) (x1 - x2);
  60850. yTerm = y1 - x1 / grad;
  60851. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  60852. grad *= scale;
  60853. }
  60854. }
  60855. forcedinline void setY (const int y) throw()
  60856. {
  60857. if (vertical)
  60858. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  60859. else if (! horizontal)
  60860. start = roundDoubleToInt ((y - yTerm) * grad);
  60861. }
  60862. forcedinline const PixelARGB getPixel (const int x) const throw()
  60863. {
  60864. if (vertical)
  60865. return linePix;
  60866. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  60867. }
  60868. };
  60869. class RadialGradientPixelGenerator
  60870. {
  60871. protected:
  60872. const PixelARGB* const lookupTable;
  60873. const int numEntries;
  60874. const double gx1, gy1;
  60875. double maxDist, invScale;
  60876. double dy;
  60877. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  60878. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  60879. public:
  60880. RadialGradientPixelGenerator (const ColourGradient& gradient,
  60881. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  60882. : lookupTable (lookupTable_),
  60883. numEntries (numEntries_),
  60884. gx1 (gradient.x1),
  60885. gy1 (gradient.y1)
  60886. {
  60887. jassert (numEntries_ >= 0);
  60888. const float dx = gradient.x1 - gradient.x2;
  60889. const float dy = gradient.y1 - gradient.y2;
  60890. maxDist = dx * dx + dy * dy;
  60891. invScale = (numEntries + 1) / sqrt (maxDist);
  60892. }
  60893. forcedinline void setY (const int y) throw()
  60894. {
  60895. dy = y - gy1;
  60896. dy *= dy;
  60897. }
  60898. forcedinline const PixelARGB getPixel (const int px) const throw()
  60899. {
  60900. double x = px - gx1;
  60901. x *= x;
  60902. x += dy;
  60903. if (x >= maxDist)
  60904. return lookupTable [numEntries];
  60905. else
  60906. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  60907. }
  60908. };
  60909. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  60910. {
  60911. double tM10, tM00, lineYM01, lineYM11;
  60912. AffineTransform inverseTransform;
  60913. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  60914. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  60915. public:
  60916. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  60917. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  60918. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  60919. inverseTransform (gradient.transform.inverted())
  60920. {
  60921. tM10 = inverseTransform.mat10;
  60922. tM00 = inverseTransform.mat00;
  60923. }
  60924. forcedinline void setY (const int y) throw()
  60925. {
  60926. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  60927. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  60928. }
  60929. forcedinline const PixelARGB getPixel (const int px) const throw()
  60930. {
  60931. double x = px;
  60932. const double y = tM10 * x + lineYM11;
  60933. x = tM00 * x + lineYM01;
  60934. x *= x;
  60935. x += y * y;
  60936. if (x >= maxDist)
  60937. return lookupTable [numEntries];
  60938. else
  60939. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  60940. }
  60941. };
  60942. template <class PixelType, class GradientType>
  60943. class GradientEdgeTableRenderer : public GradientType
  60944. {
  60945. uint8* const data;
  60946. const int stride;
  60947. PixelType* linePixels;
  60948. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  60949. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  60950. public:
  60951. GradientEdgeTableRenderer (uint8* const data_,
  60952. const int stride_,
  60953. const ColourGradient& gradient,
  60954. const PixelARGB* const lookupTable, const int numEntries) throw()
  60955. : GradientType (gradient, lookupTable, numEntries - 1),
  60956. data (data_),
  60957. stride (stride_)
  60958. {
  60959. }
  60960. forcedinline void setEdgeTableYPos (const int y) throw()
  60961. {
  60962. linePixels = (PixelType*) (data + stride * y);
  60963. GradientType::setY (y);
  60964. }
  60965. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60966. {
  60967. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  60968. }
  60969. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  60970. {
  60971. PixelType* dest = linePixels + x;
  60972. if (alphaLevel < 0xff)
  60973. {
  60974. do
  60975. {
  60976. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  60977. } while (--width > 0);
  60978. }
  60979. else
  60980. {
  60981. do
  60982. {
  60983. (dest++)->blend (GradientType::getPixel (x++));
  60984. } while (--width > 0);
  60985. }
  60986. }
  60987. };
  60988. template <class DestPixelType, class SrcPixelType>
  60989. class ImageFillEdgeTableRenderer
  60990. {
  60991. uint8* const destImageData;
  60992. const uint8* srcImageData;
  60993. int stride, srcStride, extraAlpha;
  60994. DestPixelType* linePixels;
  60995. SrcPixelType* sourceLineStart;
  60996. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  60997. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  60998. public:
  60999. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61000. const int stride_,
  61001. const uint8* srcImageData_,
  61002. const int srcStride_,
  61003. int extraAlpha_,
  61004. SrcPixelType*) throw() // dummy param to avoid compiler error
  61005. : destImageData (destImageData_),
  61006. srcImageData (srcImageData_),
  61007. stride (stride_),
  61008. srcStride (srcStride_),
  61009. extraAlpha (extraAlpha_)
  61010. {
  61011. }
  61012. forcedinline void setEdgeTableYPos (int y) throw()
  61013. {
  61014. linePixels = (DestPixelType*) (destImageData + stride * y);
  61015. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  61016. }
  61017. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  61018. {
  61019. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61020. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  61021. }
  61022. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  61023. {
  61024. DestPixelType* dest = linePixels + x;
  61025. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61026. if (alphaLevel < 0xfe)
  61027. {
  61028. do
  61029. {
  61030. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  61031. } while (--width > 0);
  61032. }
  61033. else
  61034. {
  61035. do
  61036. {
  61037. dest++ ->blend (sourceLineStart [x++]);
  61038. } while (--width > 0);
  61039. }
  61040. }
  61041. };
  61042. static void blendRowOfPixels (PixelARGB* dst,
  61043. const PixelRGB* src,
  61044. int width) throw()
  61045. {
  61046. while (--width >= 0)
  61047. (dst++)->set (*src++);
  61048. }
  61049. static void blendRowOfPixels (PixelRGB* dst,
  61050. const PixelRGB* src,
  61051. int width) throw()
  61052. {
  61053. memcpy (dst, src, 3 * width);
  61054. }
  61055. static void blendRowOfPixels (PixelRGB* dst,
  61056. const PixelARGB* src,
  61057. int width) throw()
  61058. {
  61059. while (--width >= 0)
  61060. (dst++)->blend (*src++);
  61061. }
  61062. static void blendRowOfPixels (PixelARGB* dst,
  61063. const PixelARGB* src,
  61064. int width) throw()
  61065. {
  61066. while (--width >= 0)
  61067. (dst++)->blend (*src++);
  61068. }
  61069. static void blendRowOfPixels (PixelARGB* dst,
  61070. const PixelRGB* src,
  61071. int width,
  61072. const uint8 alpha) throw()
  61073. {
  61074. while (--width >= 0)
  61075. (dst++)->blend (*src++, alpha);
  61076. }
  61077. static void blendRowOfPixels (PixelRGB* dst,
  61078. const PixelRGB* src,
  61079. int width,
  61080. const uint8 alpha) throw()
  61081. {
  61082. uint8* d = (uint8*) dst;
  61083. const uint8* s = (const uint8*) src;
  61084. const int inverseAlpha = 0xff - alpha;
  61085. while (--width >= 0)
  61086. {
  61087. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  61088. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  61089. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  61090. d += 3;
  61091. s += 3;
  61092. }
  61093. }
  61094. static void blendRowOfPixels (PixelRGB* dst,
  61095. const PixelARGB* src,
  61096. int width,
  61097. const uint8 alpha) throw()
  61098. {
  61099. while (--width >= 0)
  61100. (dst++)->blend (*src++, alpha);
  61101. }
  61102. static void blendRowOfPixels (PixelARGB* dst,
  61103. const PixelARGB* src,
  61104. int width,
  61105. const uint8 alpha) throw()
  61106. {
  61107. while (--width >= 0)
  61108. (dst++)->blend (*src++, alpha);
  61109. }
  61110. template <class DestPixelType, class SrcPixelType>
  61111. static void overlayImage (DestPixelType* dest,
  61112. const int destStride,
  61113. const SrcPixelType* src,
  61114. const int srcStride,
  61115. const int width,
  61116. int height,
  61117. const uint8 alpha) throw()
  61118. {
  61119. if (alpha < 0xff)
  61120. {
  61121. while (--height >= 0)
  61122. {
  61123. blendRowOfPixels (dest, src, width, alpha);
  61124. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61125. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61126. }
  61127. }
  61128. else
  61129. {
  61130. while (--height >= 0)
  61131. {
  61132. blendRowOfPixels (dest, src, width);
  61133. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61134. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61135. }
  61136. }
  61137. }
  61138. template <class DestPixelType, class SrcPixelType>
  61139. static void transformedImageRender (Image& destImage,
  61140. const Image& sourceImage,
  61141. const int destClipX, const int destClipY,
  61142. const int destClipW, const int destClipH,
  61143. const int srcClipX, const int srcClipY,
  61144. const int srcClipWidth, const int srcClipHeight,
  61145. double srcX, double srcY,
  61146. const double lineDX, const double lineDY,
  61147. const double pixelDX, const double pixelDY,
  61148. const uint8 alpha,
  61149. const Graphics::ResamplingQuality quality,
  61150. DestPixelType*,
  61151. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  61152. // parameters of the templated classes to
  61153. // make it use the correct instance of this function..
  61154. {
  61155. int destStride, destPixelStride;
  61156. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  61157. int srcStride, srcPixelStride;
  61158. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  61159. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  61160. {
  61161. for (int y = 0; y < destClipH; ++y)
  61162. {
  61163. double sx = srcX;
  61164. double sy = srcY;
  61165. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61166. for (int x = 0; x < destClipW; ++x)
  61167. {
  61168. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  61169. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  61170. {
  61171. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  61172. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  61173. {
  61174. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61175. dest->blend (*src, alpha);
  61176. }
  61177. }
  61178. ++dest;
  61179. sx += pixelDX;
  61180. sy += pixelDY;
  61181. }
  61182. srcX += lineDX;
  61183. srcY += lineDY;
  61184. }
  61185. }
  61186. else
  61187. {
  61188. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  61189. for (int y = 0; y < destClipH; ++y)
  61190. {
  61191. double sx = srcX;
  61192. double sy = srcY;
  61193. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61194. for (int x = 0; x < destClipW; ++x)
  61195. {
  61196. const double fx = floor (sx);
  61197. const double fy = floor (sy);
  61198. const int ix = roundDoubleToInt (fx) - srcClipX;
  61199. const int iy = roundDoubleToInt (fy) - srcClipY;
  61200. if (ix < srcClipWidth && iy < srcClipHeight)
  61201. {
  61202. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  61203. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61204. if (iy >= 0)
  61205. {
  61206. if (ix >= 0)
  61207. p1.set (src[0]);
  61208. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61209. p2.set (src[1]);
  61210. }
  61211. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  61212. {
  61213. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61214. if (ix >= 0)
  61215. p3.set (src[0]);
  61216. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61217. p4.set (src[1]);
  61218. }
  61219. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  61220. p1.tween (p2, dx);
  61221. p3.tween (p4, dx);
  61222. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  61223. if (p1.getAlpha() > 0)
  61224. dest->blend (p1, alpha);
  61225. }
  61226. ++dest;
  61227. sx += pixelDX;
  61228. sy += pixelDY;
  61229. }
  61230. srcX += lineDX;
  61231. srcY += lineDY;
  61232. }
  61233. }
  61234. destImage.releasePixelDataReadWrite (destPixels);
  61235. sourceImage.releasePixelDataReadOnly (srcPixels);
  61236. }
  61237. template <class SrcPixelType, class DestPixelType>
  61238. static void renderAlphaMap (DestPixelType* destPixels,
  61239. int destStride,
  61240. SrcPixelType* srcPixels,
  61241. int srcStride,
  61242. const uint8* alphaValues,
  61243. const int lineStride, const int pixelStride,
  61244. int width, int height,
  61245. const int extraAlpha) throw()
  61246. {
  61247. while (--height >= 0)
  61248. {
  61249. SrcPixelType* srcPix = srcPixels;
  61250. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  61251. DestPixelType* destPix = destPixels;
  61252. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  61253. const uint8* alpha = alphaValues;
  61254. alphaValues += lineStride;
  61255. if (extraAlpha < 0x100)
  61256. {
  61257. for (int i = width; --i >= 0;)
  61258. {
  61259. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  61260. alpha += pixelStride;
  61261. }
  61262. }
  61263. else
  61264. {
  61265. for (int i = width; --i >= 0;)
  61266. {
  61267. destPix++ ->blend (*srcPix++, *alpha);
  61268. alpha += pixelStride;
  61269. }
  61270. }
  61271. }
  61272. }
  61273. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  61274. : image (image_),
  61275. xOffset (0),
  61276. yOffset (0),
  61277. stateStack (20)
  61278. {
  61279. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  61280. }
  61281. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  61282. {
  61283. delete clip;
  61284. }
  61285. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  61286. {
  61287. return false;
  61288. }
  61289. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  61290. {
  61291. xOffset += x;
  61292. yOffset += y;
  61293. }
  61294. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  61295. {
  61296. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  61297. }
  61298. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  61299. {
  61300. RectangleList temp (clipRegion);
  61301. temp.offsetAll (xOffset, yOffset);
  61302. return clip->clipTo (temp);
  61303. }
  61304. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  61305. {
  61306. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  61307. }
  61308. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  61309. {
  61310. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  61311. }
  61312. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  61313. {
  61314. return clip->getBounds().translated (-xOffset, -yOffset);
  61315. }
  61316. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  61317. {
  61318. return clip->isEmpty();
  61319. }
  61320. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  61321. const int xOffset_, const int yOffset_)
  61322. : clip (clip_),
  61323. xOffset (xOffset_),
  61324. yOffset (yOffset_)
  61325. {
  61326. }
  61327. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  61328. {
  61329. delete clip;
  61330. }
  61331. void LowLevelGraphicsSoftwareRenderer::saveState()
  61332. {
  61333. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  61334. }
  61335. void LowLevelGraphicsSoftwareRenderer::restoreState()
  61336. {
  61337. SavedState* const top = stateStack.getLast();
  61338. if (top != 0)
  61339. {
  61340. clip->swapWith (*top->clip);
  61341. xOffset = top->xOffset;
  61342. yOffset = top->yOffset;
  61343. stateStack.removeLast();
  61344. }
  61345. else
  61346. {
  61347. jassertfalse // trying to pop with an empty stack!
  61348. }
  61349. }
  61350. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  61351. {
  61352. x += xOffset;
  61353. y += yOffset;
  61354. for (RectangleList::Iterator i (*clip); i.next();)
  61355. {
  61356. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  61357. }
  61358. }
  61359. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  61360. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  61361. {
  61362. if (clipRect.intersectRectangle (x, y, w, h))
  61363. {
  61364. int stride, pixelStride;
  61365. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61366. if (image.getFormat() == Image::RGB)
  61367. {
  61368. if (replaceExistingContents)
  61369. replaceRectRGB (pixels, w, h, stride, colour);
  61370. else
  61371. blendRectRGB (pixels, w, h, stride, colour);
  61372. }
  61373. else if (image.getFormat() == Image::ARGB)
  61374. {
  61375. if (replaceExistingContents)
  61376. replaceRectARGB (pixels, w, h, stride, colour);
  61377. else
  61378. blendRectARGB (pixels, w, h, stride, colour);
  61379. }
  61380. else
  61381. {
  61382. jassertfalse // not done!
  61383. }
  61384. image.releasePixelDataReadWrite (pixels);
  61385. }
  61386. }
  61387. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  61388. {
  61389. Path p;
  61390. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  61391. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  61392. }
  61393. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  61394. const Path& path, const AffineTransform& transform,
  61395. int& x, int& y, int& w, int& h) const
  61396. {
  61397. float tx, ty, tw, th;
  61398. path.getBoundsTransformed (transform, tx, ty, tw, th);
  61399. x = roundDoubleToInt (tx) - 1;
  61400. y = roundDoubleToInt (ty) - 1;
  61401. w = roundDoubleToInt (tw) + 2;
  61402. h = roundDoubleToInt (th) + 2;
  61403. // seems like this operation is using some crazy out-of-range numbers..
  61404. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  61405. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  61406. }
  61407. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  61408. const Colour& colour, EdgeTable::OversamplingLevel quality)
  61409. {
  61410. for (RectangleList::Iterator i (*clip); i.next();)
  61411. {
  61412. const Rectangle& r = *i.getRectangle();
  61413. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  61414. }
  61415. }
  61416. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  61417. const Colour& colour, EdgeTable::OversamplingLevel quality)
  61418. {
  61419. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61420. int cx, cy, cw, ch;
  61421. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  61422. {
  61423. EdgeTable edgeTable (0, ch, quality);
  61424. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  61425. int stride, pixelStride;
  61426. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  61427. if (image.getFormat() == Image::RGB)
  61428. {
  61429. jassert (pixelStride == 3);
  61430. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  61431. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61432. }
  61433. else if (image.getFormat() == Image::ARGB)
  61434. {
  61435. jassert (pixelStride == 4);
  61436. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  61437. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61438. }
  61439. else if (image.getFormat() == Image::SingleChannel)
  61440. {
  61441. jassert (pixelStride == 1);
  61442. AlphaBitmapRenderer renderer (pixels, stride);
  61443. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61444. }
  61445. image.releasePixelDataReadWrite (pixels);
  61446. }
  61447. }
  61448. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  61449. {
  61450. for (RectangleList::Iterator i (*clip); i.next();)
  61451. {
  61452. const Rectangle& r = *i.getRectangle();
  61453. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61454. path, t, gradient, quality);
  61455. }
  61456. }
  61457. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  61458. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  61459. {
  61460. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61461. int cx, cy, cw, ch;
  61462. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  61463. {
  61464. int stride, pixelStride;
  61465. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  61466. ColourGradient g2 (gradient);
  61467. const bool isIdentity = g2.transform.isIdentity();
  61468. if (isIdentity)
  61469. {
  61470. g2.x1 += xOffset - cx;
  61471. g2.x2 += xOffset - cx;
  61472. g2.y1 += yOffset - cy;
  61473. g2.y2 += yOffset - cy;
  61474. }
  61475. else
  61476. {
  61477. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  61478. (float) (yOffset - cy));
  61479. }
  61480. int numLookupEntries;
  61481. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  61482. jassert (numLookupEntries > 0);
  61483. EdgeTable edgeTable (0, ch, quality);
  61484. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  61485. if (image.getFormat() == Image::RGB)
  61486. {
  61487. jassert (pixelStride == 3);
  61488. if (g2.isRadial)
  61489. {
  61490. if (isIdentity)
  61491. {
  61492. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61493. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61494. }
  61495. else
  61496. {
  61497. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61498. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61499. }
  61500. }
  61501. else
  61502. {
  61503. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61504. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61505. }
  61506. }
  61507. else if (image.getFormat() == Image::ARGB)
  61508. {
  61509. jassert (pixelStride == 4);
  61510. if (g2.isRadial)
  61511. {
  61512. if (isIdentity)
  61513. {
  61514. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61515. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61516. }
  61517. else
  61518. {
  61519. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61520. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61521. }
  61522. }
  61523. else
  61524. {
  61525. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61526. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61527. }
  61528. }
  61529. else if (image.getFormat() == Image::SingleChannel)
  61530. {
  61531. jassertfalse // not done!
  61532. }
  61533. juce_free (lookupTable);
  61534. image.releasePixelDataReadWrite (pixels);
  61535. }
  61536. }
  61537. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  61538. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  61539. {
  61540. imageX += xOffset;
  61541. imageY += yOffset;
  61542. for (RectangleList::Iterator i (*clip); i.next();)
  61543. {
  61544. const Rectangle& r = *i.getRectangle();
  61545. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61546. path, transform, sourceImage, imageX, imageY, opacity, quality);
  61547. }
  61548. }
  61549. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  61550. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  61551. {
  61552. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  61553. {
  61554. EdgeTable edgeTable (0, h, quality);
  61555. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  61556. int stride, pixelStride;
  61557. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61558. int srcStride, srcPixelStride;
  61559. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  61560. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  61561. if (image.getFormat() == Image::RGB)
  61562. {
  61563. if (sourceImage.getFormat() == Image::RGB)
  61564. {
  61565. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  61566. srcPix, srcStride,
  61567. alpha, (PixelRGB*) 0);
  61568. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61569. }
  61570. else if (sourceImage.getFormat() == Image::ARGB)
  61571. {
  61572. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  61573. srcPix, srcStride,
  61574. alpha, (PixelARGB*) 0);
  61575. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61576. }
  61577. else
  61578. {
  61579. jassertfalse // not done!
  61580. }
  61581. }
  61582. else if (image.getFormat() == Image::ARGB)
  61583. {
  61584. if (sourceImage.getFormat() == Image::RGB)
  61585. {
  61586. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  61587. srcPix, srcStride,
  61588. alpha, (PixelRGB*) 0);
  61589. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61590. }
  61591. else if (sourceImage.getFormat() == Image::ARGB)
  61592. {
  61593. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  61594. srcPix, srcStride,
  61595. alpha, (PixelARGB*) 0);
  61596. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61597. }
  61598. else
  61599. {
  61600. jassertfalse // not done!
  61601. }
  61602. }
  61603. else
  61604. {
  61605. jassertfalse // not done!
  61606. }
  61607. sourceImage.releasePixelDataReadOnly (srcPix);
  61608. image.releasePixelDataReadWrite (pixels);
  61609. }
  61610. }
  61611. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  61612. {
  61613. x += xOffset;
  61614. y += yOffset;
  61615. for (RectangleList::Iterator i (*clip); i.next();)
  61616. {
  61617. const Rectangle& r = *i.getRectangle();
  61618. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61619. clipImage, x, y, colour);
  61620. }
  61621. }
  61622. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  61623. {
  61624. int w = clipImage.getWidth();
  61625. int h = clipImage.getHeight();
  61626. int sx = 0;
  61627. int sy = 0;
  61628. if (x < clipX)
  61629. {
  61630. sx = clipX - x;
  61631. w -= clipX - x;
  61632. x = clipX;
  61633. }
  61634. if (y < clipY)
  61635. {
  61636. sy = clipY - y;
  61637. h -= clipY - y;
  61638. y = clipY;
  61639. }
  61640. if (x + w > clipX + clipW)
  61641. w = clipX + clipW - x;
  61642. if (y + h > clipY + clipH)
  61643. h = clipY + clipH - y;
  61644. if (w > 0 && h > 0)
  61645. {
  61646. int stride, alphaStride, pixelStride;
  61647. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61648. const uint8* const alphaValues
  61649. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  61650. #if JUCE_MAC
  61651. const uint8* const alphas = alphaValues;
  61652. #else
  61653. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  61654. #endif
  61655. if (image.getFormat() == Image::RGB)
  61656. {
  61657. blendAlphaMapRGB (pixels, stride,
  61658. alphas, w, h,
  61659. pixelStride, alphaStride,
  61660. colour);
  61661. }
  61662. else if (image.getFormat() == Image::ARGB)
  61663. {
  61664. blendAlphaMapARGB (pixels, stride,
  61665. alphas, w, h,
  61666. pixelStride, alphaStride,
  61667. colour);
  61668. }
  61669. else
  61670. {
  61671. jassertfalse // not done!
  61672. }
  61673. clipImage.releasePixelDataReadOnly (alphaValues);
  61674. image.releasePixelDataReadWrite (pixels);
  61675. }
  61676. }
  61677. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  61678. {
  61679. imageX += xOffset;
  61680. imageY += yOffset;
  61681. for (RectangleList::Iterator i (*clip); i.next();)
  61682. {
  61683. const Rectangle& r = *i.getRectangle();
  61684. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61685. alphaChannelImage, imageX, imageY, gradient);
  61686. }
  61687. }
  61688. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  61689. const Image& alphaChannelImage,
  61690. int imageX, int imageY, const ColourGradient& gradient)
  61691. {
  61692. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  61693. {
  61694. ColourGradient g2 (gradient);
  61695. g2.x1 += xOffset - x;
  61696. g2.x2 += xOffset - x;
  61697. g2.y1 += yOffset - y;
  61698. g2.y2 += yOffset - y;
  61699. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  61700. LowLevelGraphicsSoftwareRenderer tempG (temp);
  61701. tempG.fillRectWithGradient (0, 0, w, h, g2);
  61702. clippedFillAlphaChannelWithImage (x, y, w, h,
  61703. alphaChannelImage, imageX, imageY,
  61704. temp, x, y, 1.0f);
  61705. }
  61706. }
  61707. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  61708. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  61709. {
  61710. alphaImageX += xOffset;
  61711. alphaImageY += yOffset;
  61712. fillerImageX += xOffset;
  61713. fillerImageY += yOffset;
  61714. for (RectangleList::Iterator i (*clip); i.next();)
  61715. {
  61716. const Rectangle& r = *i.getRectangle();
  61717. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61718. alphaImage, alphaImageX, alphaImageY,
  61719. fillerImage, fillerImageX, fillerImageY, opacity);
  61720. }
  61721. }
  61722. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  61723. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  61724. {
  61725. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  61726. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  61727. {
  61728. int dstStride, dstPixStride;
  61729. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  61730. int srcStride, srcPixStride;
  61731. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  61732. int maskStride, maskPixStride;
  61733. const uint8* const alpha
  61734. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  61735. #if JUCE_MAC
  61736. const uint8* const alphaValues = alpha;
  61737. #else
  61738. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  61739. #endif
  61740. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  61741. if (image.getFormat() == Image::RGB)
  61742. {
  61743. if (fillerImage.getFormat() == Image::RGB)
  61744. {
  61745. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61746. }
  61747. else if (fillerImage.getFormat() == Image::ARGB)
  61748. {
  61749. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61750. }
  61751. else
  61752. {
  61753. jassertfalse // not done!
  61754. }
  61755. }
  61756. else if (image.getFormat() == Image::ARGB)
  61757. {
  61758. if (fillerImage.getFormat() == Image::RGB)
  61759. {
  61760. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61761. }
  61762. else if (fillerImage.getFormat() == Image::ARGB)
  61763. {
  61764. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61765. }
  61766. else
  61767. {
  61768. jassertfalse // not done!
  61769. }
  61770. }
  61771. else
  61772. {
  61773. jassertfalse // not done!
  61774. }
  61775. alphaImage.releasePixelDataReadOnly (alphaValues);
  61776. fillerImage.releasePixelDataReadOnly (srcPix);
  61777. image.releasePixelDataReadWrite (dstPix);
  61778. }
  61779. }
  61780. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61781. {
  61782. dx += xOffset;
  61783. dy += yOffset;
  61784. for (RectangleList::Iterator i (*clip); i.next();)
  61785. {
  61786. const Rectangle& r = *i.getRectangle();
  61787. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61788. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  61789. }
  61790. }
  61791. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  61792. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61793. {
  61794. if (dx < clipX)
  61795. {
  61796. sx += clipX - dx;
  61797. dw -= clipX - dx;
  61798. dx = clipX;
  61799. }
  61800. if (dy < clipY)
  61801. {
  61802. sy += clipY - dy;
  61803. dh -= clipY - dy;
  61804. dy = clipY;
  61805. }
  61806. if (dx + dw > clipX + clipW)
  61807. dw = clipX + clipW - dx;
  61808. if (dy + dh > clipY + clipH)
  61809. dh = clipY + clipH - dy;
  61810. if (dw <= 0 || dh <= 0)
  61811. return;
  61812. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  61813. if (alpha == 0)
  61814. return;
  61815. int dstStride, dstPixelStride;
  61816. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  61817. int srcStride, srcPixelStride;
  61818. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  61819. if (image.getFormat() == Image::ARGB)
  61820. {
  61821. if (sourceImage.getFormat() == Image::ARGB)
  61822. {
  61823. overlayImage ((PixelARGB*) dstPixels, dstStride,
  61824. (PixelARGB*) srcPixels, srcStride,
  61825. dw, dh, alpha);
  61826. }
  61827. else if (sourceImage.getFormat() == Image::RGB)
  61828. {
  61829. overlayImage ((PixelARGB*) dstPixels, dstStride,
  61830. (PixelRGB*) srcPixels, srcStride,
  61831. dw, dh, alpha);
  61832. }
  61833. else
  61834. {
  61835. jassertfalse
  61836. }
  61837. }
  61838. else if (image.getFormat() == Image::RGB)
  61839. {
  61840. if (sourceImage.getFormat() == Image::ARGB)
  61841. {
  61842. overlayImage ((PixelRGB*) dstPixels, dstStride,
  61843. (PixelARGB*) srcPixels, srcStride,
  61844. dw, dh, alpha);
  61845. }
  61846. else if (sourceImage.getFormat() == Image::RGB)
  61847. {
  61848. overlayImage ((PixelRGB*) dstPixels, dstStride,
  61849. (PixelRGB*) srcPixels, srcStride,
  61850. dw, dh, alpha);
  61851. }
  61852. else
  61853. {
  61854. jassertfalse
  61855. }
  61856. }
  61857. else
  61858. {
  61859. jassertfalse
  61860. }
  61861. image.releasePixelDataReadWrite (dstPixels);
  61862. sourceImage.releasePixelDataReadOnly (srcPixels);
  61863. }
  61864. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  61865. int dx, int dy, int dw, int dh,
  61866. int sx, int sy, int sw, int sh,
  61867. float alpha,
  61868. const Graphics::ResamplingQuality quality)
  61869. {
  61870. if (sw > 0 && sh > 0)
  61871. {
  61872. if (sw == dw && sh == dh)
  61873. {
  61874. blendImage (sourceImage,
  61875. dx, dy, dw, dh,
  61876. sx, sy, alpha);
  61877. }
  61878. else
  61879. {
  61880. blendImageWarping (sourceImage,
  61881. sx, sy, sw, sh,
  61882. AffineTransform::translation ((float) -sx,
  61883. (float) -sy)
  61884. .scaled (dw / (float) sw,
  61885. dh / (float) sh)
  61886. .translated ((float) dx,
  61887. (float) dy),
  61888. alpha,
  61889. quality);
  61890. }
  61891. }
  61892. }
  61893. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  61894. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  61895. const AffineTransform& t,
  61896. float opacity,
  61897. const Graphics::ResamplingQuality quality)
  61898. {
  61899. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61900. for (RectangleList::Iterator i (*clip); i.next();)
  61901. {
  61902. const Rectangle& r = *i.getRectangle();
  61903. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61904. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  61905. transform, opacity, quality);
  61906. }
  61907. }
  61908. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  61909. const Image& sourceImage,
  61910. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  61911. const AffineTransform& transform,
  61912. float opacity,
  61913. const Graphics::ResamplingQuality quality)
  61914. {
  61915. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  61916. {
  61917. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  61918. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  61919. if (srcClipW <= 0 || srcClipH <= 0)
  61920. return;
  61921. jassert (srcClipX >= 0 && srcClipY >= 0);
  61922. Path imageBounds;
  61923. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  61924. imageBounds.applyTransform (transform);
  61925. float imX, imY, imW, imH;
  61926. imageBounds.getBounds (imX, imY, imW, imH);
  61927. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  61928. (int) floorf (imX),
  61929. (int) floorf (imY),
  61930. 1 + roundDoubleToInt (imW),
  61931. 1 + roundDoubleToInt (imH)))
  61932. {
  61933. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  61934. float srcX1 = (float) destClipX;
  61935. float srcY1 = (float) destClipY;
  61936. float srcX2 = (float) (destClipX + destClipW);
  61937. float srcY2 = srcY1;
  61938. float srcX3 = srcX1;
  61939. float srcY3 = (float) (destClipY + destClipH);
  61940. AffineTransform inverse (transform.inverted());
  61941. inverse.transformPoint (srcX1, srcY1);
  61942. inverse.transformPoint (srcX2, srcY2);
  61943. inverse.transformPoint (srcX3, srcY3);
  61944. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  61945. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  61946. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  61947. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  61948. if (image.getFormat() == Image::ARGB)
  61949. {
  61950. if (sourceImage.getFormat() == Image::ARGB)
  61951. {
  61952. transformedImageRender (image, sourceImage,
  61953. destClipX, destClipY, destClipW, destClipH,
  61954. srcClipX, srcClipY, srcClipW, srcClipH,
  61955. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61956. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  61957. }
  61958. else if (sourceImage.getFormat() == Image::RGB)
  61959. {
  61960. transformedImageRender (image, sourceImage,
  61961. destClipX, destClipY, destClipW, destClipH,
  61962. srcClipX, srcClipY, srcClipW, srcClipH,
  61963. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61964. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  61965. }
  61966. else
  61967. {
  61968. jassertfalse
  61969. }
  61970. }
  61971. else if (image.getFormat() == Image::RGB)
  61972. {
  61973. if (sourceImage.getFormat() == Image::ARGB)
  61974. {
  61975. transformedImageRender (image, sourceImage,
  61976. destClipX, destClipY, destClipW, destClipH,
  61977. srcClipX, srcClipY, srcClipW, srcClipH,
  61978. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61979. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  61980. }
  61981. else if (sourceImage.getFormat() == Image::RGB)
  61982. {
  61983. transformedImageRender (image, sourceImage,
  61984. destClipX, destClipY, destClipW, destClipH,
  61985. srcClipX, srcClipY, srcClipW, srcClipH,
  61986. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61987. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  61988. }
  61989. else
  61990. {
  61991. jassertfalse
  61992. }
  61993. }
  61994. else
  61995. {
  61996. jassertfalse
  61997. }
  61998. }
  61999. }
  62000. }
  62001. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62002. {
  62003. x1 += xOffset;
  62004. y1 += yOffset;
  62005. x2 += xOffset;
  62006. y2 += yOffset;
  62007. for (RectangleList::Iterator i (*clip); i.next();)
  62008. {
  62009. const Rectangle& r = *i.getRectangle();
  62010. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62011. x1, y1, x2, y2, colour);
  62012. }
  62013. }
  62014. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  62015. {
  62016. if (clipW > 0 && clipH > 0)
  62017. {
  62018. if (x1 == x2)
  62019. {
  62020. if (y2 < y1)
  62021. swapVariables (y1, y2);
  62022. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  62023. }
  62024. else if (y1 == y2)
  62025. {
  62026. if (x2 < x1)
  62027. swapVariables (x1, x2);
  62028. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  62029. }
  62030. else
  62031. {
  62032. double gradient = (y2 - y1) / (x2 - x1);
  62033. if (fabs (gradient) > 1.0)
  62034. {
  62035. gradient = 1.0 / gradient;
  62036. int y = roundDoubleToInt (y1);
  62037. const int startY = y;
  62038. int endY = roundDoubleToInt (y2);
  62039. if (y > endY)
  62040. swapVariables (y, endY);
  62041. while (y < endY)
  62042. {
  62043. const double x = x1 + gradient * (y - startY);
  62044. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  62045. ++y;
  62046. }
  62047. }
  62048. else
  62049. {
  62050. int x = roundDoubleToInt (x1);
  62051. const int startX = x;
  62052. int endX = roundDoubleToInt (x2);
  62053. if (x > endX)
  62054. swapVariables (x, endX);
  62055. while (x < endX)
  62056. {
  62057. const double y = y1 + gradient * (x - startX);
  62058. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  62059. ++x;
  62060. }
  62061. }
  62062. }
  62063. }
  62064. }
  62065. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62066. {
  62067. for (RectangleList::Iterator i (*clip); i.next();)
  62068. {
  62069. const Rectangle& r = *i.getRectangle();
  62070. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62071. x + xOffset, top + yOffset, bottom + yOffset, col);
  62072. }
  62073. }
  62074. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  62075. const int x, double top, double bottom, const Colour& col)
  62076. {
  62077. jassert (top <= bottom);
  62078. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  62079. && top < clipY + clipH
  62080. && bottom > clipY
  62081. && clipW > 0)
  62082. {
  62083. if (top < clipY)
  62084. top = clipY;
  62085. if (bottom > clipY + clipH)
  62086. bottom = clipY + clipH;
  62087. if (bottom > top)
  62088. drawVertical (x, top, bottom, col);
  62089. }
  62090. }
  62091. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62092. {
  62093. for (RectangleList::Iterator i (*clip); i.next();)
  62094. {
  62095. const Rectangle& r = *i.getRectangle();
  62096. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62097. y + yOffset, left + xOffset, right + xOffset, col);
  62098. }
  62099. }
  62100. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  62101. const int y, double left, double right, const Colour& col)
  62102. {
  62103. jassert (left <= right);
  62104. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  62105. && left < clipX + clipW
  62106. && right > clipX
  62107. && clipW > 0)
  62108. {
  62109. if (left < clipX)
  62110. left = clipX;
  62111. if (right > clipX + clipW)
  62112. right = clipX + clipW;
  62113. if (right > left)
  62114. drawHorizontal (y, left, right, col);
  62115. }
  62116. }
  62117. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  62118. const double top,
  62119. const double bottom,
  62120. const Colour& col)
  62121. {
  62122. int wholeStart = (int) top;
  62123. const int wholeEnd = (int) bottom;
  62124. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62125. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62126. if (totalPixels <= 0)
  62127. return;
  62128. int lineStride, dstPixelStride;
  62129. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  62130. uint8* dest = dstPixels;
  62131. PixelARGB colour (col.getPixelARGB());
  62132. if (wholeEnd == wholeStart)
  62133. {
  62134. if (image.getFormat() == Image::ARGB)
  62135. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62136. else if (image.getFormat() == Image::RGB)
  62137. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62138. else
  62139. {
  62140. jassertfalse
  62141. }
  62142. }
  62143. else
  62144. {
  62145. if (image.getFormat() == Image::ARGB)
  62146. {
  62147. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62148. ++wholeStart;
  62149. dest += lineStride;
  62150. if (colour.getAlpha() == 0xff)
  62151. {
  62152. while (wholeEnd > wholeStart)
  62153. {
  62154. ((PixelARGB*) dest)->set (colour);
  62155. ++wholeStart;
  62156. dest += lineStride;
  62157. }
  62158. }
  62159. else
  62160. {
  62161. while (wholeEnd > wholeStart)
  62162. {
  62163. ((PixelARGB*) dest)->blend (colour);
  62164. ++wholeStart;
  62165. dest += lineStride;
  62166. }
  62167. }
  62168. if (lastAlpha > 0)
  62169. {
  62170. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62171. }
  62172. }
  62173. else if (image.getFormat() == Image::RGB)
  62174. {
  62175. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62176. ++wholeStart;
  62177. dest += lineStride;
  62178. if (colour.getAlpha() == 0xff)
  62179. {
  62180. while (wholeEnd > wholeStart)
  62181. {
  62182. ((PixelRGB*) dest)->set (colour);
  62183. ++wholeStart;
  62184. dest += lineStride;
  62185. }
  62186. }
  62187. else
  62188. {
  62189. while (wholeEnd > wholeStart)
  62190. {
  62191. ((PixelRGB*) dest)->blend (colour);
  62192. ++wholeStart;
  62193. dest += lineStride;
  62194. }
  62195. }
  62196. if (lastAlpha > 0)
  62197. {
  62198. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62199. }
  62200. }
  62201. else
  62202. {
  62203. jassertfalse
  62204. }
  62205. }
  62206. image.releasePixelDataReadWrite (dstPixels);
  62207. }
  62208. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  62209. const double top,
  62210. const double bottom,
  62211. const Colour& col)
  62212. {
  62213. int wholeStart = (int) top;
  62214. const int wholeEnd = (int) bottom;
  62215. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62216. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62217. if (totalPixels <= 0)
  62218. return;
  62219. int lineStride, dstPixelStride;
  62220. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  62221. uint8* dest = dstPixels;
  62222. PixelARGB colour (col.getPixelARGB());
  62223. if (wholeEnd == wholeStart)
  62224. {
  62225. if (image.getFormat() == Image::ARGB)
  62226. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62227. else if (image.getFormat() == Image::RGB)
  62228. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62229. else
  62230. {
  62231. jassertfalse
  62232. }
  62233. }
  62234. else
  62235. {
  62236. if (image.getFormat() == Image::ARGB)
  62237. {
  62238. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62239. dest += dstPixelStride;
  62240. ++wholeStart;
  62241. if (colour.getAlpha() == 0xff)
  62242. {
  62243. while (wholeEnd > wholeStart)
  62244. {
  62245. ((PixelARGB*) dest)->set (colour);
  62246. dest += dstPixelStride;
  62247. ++wholeStart;
  62248. }
  62249. }
  62250. else
  62251. {
  62252. while (wholeEnd > wholeStart)
  62253. {
  62254. ((PixelARGB*) dest)->blend (colour);
  62255. dest += dstPixelStride;
  62256. ++wholeStart;
  62257. }
  62258. }
  62259. if (lastAlpha > 0)
  62260. {
  62261. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62262. }
  62263. }
  62264. else if (image.getFormat() == Image::RGB)
  62265. {
  62266. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62267. dest += dstPixelStride;
  62268. ++wholeStart;
  62269. if (colour.getAlpha() == 0xff)
  62270. {
  62271. while (wholeEnd > wholeStart)
  62272. {
  62273. ((PixelRGB*) dest)->set (colour);
  62274. dest += dstPixelStride;
  62275. ++wholeStart;
  62276. }
  62277. }
  62278. else
  62279. {
  62280. while (wholeEnd > wholeStart)
  62281. {
  62282. ((PixelRGB*) dest)->blend (colour);
  62283. dest += dstPixelStride;
  62284. ++wholeStart;
  62285. }
  62286. }
  62287. if (lastAlpha > 0)
  62288. {
  62289. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62290. }
  62291. }
  62292. else
  62293. {
  62294. jassertfalse
  62295. }
  62296. }
  62297. image.releasePixelDataReadWrite (dstPixels);
  62298. }
  62299. END_JUCE_NAMESPACE
  62300. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62301. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  62302. BEGIN_JUCE_NAMESPACE
  62303. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  62304. : flags (other.flags)
  62305. {
  62306. }
  62307. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  62308. {
  62309. flags = other.flags;
  62310. return *this;
  62311. }
  62312. void RectanglePlacement::applyTo (double& x, double& y,
  62313. double& w, double& h,
  62314. const double dx, const double dy,
  62315. const double dw, const double dh) const throw()
  62316. {
  62317. if (w == 0 || h == 0)
  62318. return;
  62319. if ((flags & stretchToFit) != 0)
  62320. {
  62321. x = dx;
  62322. y = dy;
  62323. w = dw;
  62324. h = dh;
  62325. }
  62326. else
  62327. {
  62328. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  62329. : jmin (dw / w, dh / h);
  62330. if ((flags & onlyReduceInSize) != 0)
  62331. scale = jmin (scale, 1.0);
  62332. if ((flags & onlyIncreaseInSize) != 0)
  62333. scale = jmax (scale, 1.0);
  62334. w *= scale;
  62335. h *= scale;
  62336. if ((flags & xLeft) != 0)
  62337. x = dx;
  62338. else if ((flags & xRight) != 0)
  62339. x = dx + dw - w;
  62340. else
  62341. x = dx + (dw - w) * 0.5;
  62342. if ((flags & yTop) != 0)
  62343. y = dy;
  62344. else if ((flags & yBottom) != 0)
  62345. y = dy + dh - h;
  62346. else
  62347. y = dy + (dh - h) * 0.5;
  62348. }
  62349. }
  62350. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  62351. float w, float h,
  62352. const float dx, const float dy,
  62353. const float dw, const float dh) const throw()
  62354. {
  62355. if (w == 0 || h == 0)
  62356. return AffineTransform::identity;
  62357. const float scaleX = dw / w;
  62358. const float scaleY = dh / h;
  62359. if ((flags & stretchToFit) != 0)
  62360. {
  62361. return AffineTransform::translation (-x, -y)
  62362. .scaled (scaleX, scaleY)
  62363. .translated (dx - x, dy - y);
  62364. }
  62365. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  62366. : jmin (scaleX, scaleY);
  62367. if ((flags & onlyReduceInSize) != 0)
  62368. scale = jmin (scale, 1.0f);
  62369. if ((flags & onlyIncreaseInSize) != 0)
  62370. scale = jmax (scale, 1.0f);
  62371. w *= scale;
  62372. h *= scale;
  62373. float newX = dx;
  62374. if ((flags & xRight) != 0)
  62375. newX += dw - w; // right
  62376. else if ((flags & xLeft) == 0)
  62377. newX += (dw - w) / 2.0f; // centre
  62378. float newY = dy;
  62379. if ((flags & yBottom) != 0)
  62380. newY += dh - h; // bottom
  62381. else if ((flags & yTop) == 0)
  62382. newY += (dh - h) / 2.0f; // centre
  62383. return AffineTransform::translation (-x, -y)
  62384. .scaled (scale, scale)
  62385. .translated (newX, newY);
  62386. }
  62387. END_JUCE_NAMESPACE
  62388. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  62389. /********* Start of inlined file: juce_Drawable.cpp *********/
  62390. BEGIN_JUCE_NAMESPACE
  62391. Drawable::Drawable()
  62392. {
  62393. }
  62394. Drawable::~Drawable()
  62395. {
  62396. }
  62397. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  62398. {
  62399. draw (g, AffineTransform::translation (x, y));
  62400. }
  62401. void Drawable::drawWithin (Graphics& g,
  62402. const int destX,
  62403. const int destY,
  62404. const int destW,
  62405. const int destH,
  62406. const RectanglePlacement& placement) const
  62407. {
  62408. if (destW > 0 && destH > 0)
  62409. {
  62410. float x, y, w, h;
  62411. getBounds (x, y, w, h);
  62412. draw (g, placement.getTransformToFit (x, y, w, h,
  62413. (float) destX, (float) destY,
  62414. (float) destW, (float) destH));
  62415. }
  62416. }
  62417. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  62418. {
  62419. Drawable* result = 0;
  62420. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  62421. if (image != 0)
  62422. {
  62423. DrawableImage* const di = new DrawableImage();
  62424. di->setImage (image, true);
  62425. result = di;
  62426. }
  62427. else
  62428. {
  62429. const String asString (String::createStringFromData (data, numBytes));
  62430. XmlDocument doc (asString);
  62431. XmlElement* const outer = doc.getDocumentElement (true);
  62432. if (outer != 0 && outer->hasTagName (T("svg")))
  62433. {
  62434. XmlElement* const svg = doc.getDocumentElement();
  62435. if (svg != 0)
  62436. {
  62437. result = Drawable::createFromSVG (*svg);
  62438. delete svg;
  62439. }
  62440. }
  62441. delete outer;
  62442. }
  62443. return result;
  62444. }
  62445. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  62446. {
  62447. MemoryBlock mb;
  62448. dataSource.readIntoMemoryBlock (mb);
  62449. return createFromImageData (mb.getData(), mb.getSize());
  62450. }
  62451. Drawable* Drawable::createFromImageFile (const File& file)
  62452. {
  62453. FileInputStream* fin = file.createInputStream();
  62454. if (fin == 0)
  62455. return 0;
  62456. Drawable* d = createFromImageDataStream (*fin);
  62457. delete fin;
  62458. return d;
  62459. }
  62460. END_JUCE_NAMESPACE
  62461. /********* End of inlined file: juce_Drawable.cpp *********/
  62462. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  62463. BEGIN_JUCE_NAMESPACE
  62464. DrawableComposite::DrawableComposite()
  62465. {
  62466. }
  62467. DrawableComposite::~DrawableComposite()
  62468. {
  62469. }
  62470. void DrawableComposite::insertDrawable (Drawable* drawable,
  62471. const AffineTransform& transform,
  62472. const int index)
  62473. {
  62474. if (drawable != 0)
  62475. {
  62476. if (! drawables.contains (drawable))
  62477. {
  62478. drawables.insert (index, drawable);
  62479. if (transform.isIdentity())
  62480. transforms.insert (index, 0);
  62481. else
  62482. transforms.insert (index, new AffineTransform (transform));
  62483. }
  62484. else
  62485. {
  62486. jassertfalse // trying to add a drawable that's already in here!
  62487. }
  62488. }
  62489. }
  62490. void DrawableComposite::insertDrawable (const Drawable& drawable,
  62491. const AffineTransform& transform,
  62492. const int index)
  62493. {
  62494. insertDrawable (drawable.createCopy(), transform, index);
  62495. }
  62496. void DrawableComposite::removeDrawable (const int index)
  62497. {
  62498. drawables.remove (index);
  62499. transforms.remove (index);
  62500. }
  62501. void DrawableComposite::bringToFront (const int index)
  62502. {
  62503. if (index >= 0 && index < drawables.size() - 1)
  62504. {
  62505. drawables.move (index, -1);
  62506. transforms.move (index, -1);
  62507. }
  62508. }
  62509. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  62510. {
  62511. for (int i = 0; i < drawables.size(); ++i)
  62512. {
  62513. const AffineTransform* const t = transforms.getUnchecked(i);
  62514. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  62515. : t->followedBy (transform));
  62516. }
  62517. }
  62518. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  62519. {
  62520. Path totalPath;
  62521. for (int i = 0; i < drawables.size(); ++i)
  62522. {
  62523. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  62524. if (width > 0.0f && height > 0.0f)
  62525. {
  62526. Path outline;
  62527. outline.addRectangle (x, y, width, height);
  62528. const AffineTransform* const t = transforms.getUnchecked(i);
  62529. if (t == 0)
  62530. totalPath.addPath (outline);
  62531. else
  62532. totalPath.addPath (outline, *t);
  62533. }
  62534. }
  62535. totalPath.getBounds (x, y, width, height);
  62536. }
  62537. bool DrawableComposite::hitTest (float x, float y) const
  62538. {
  62539. for (int i = 0; i < drawables.size(); ++i)
  62540. {
  62541. float tx = x;
  62542. float ty = y;
  62543. const AffineTransform* const t = transforms.getUnchecked(i);
  62544. if (t != 0)
  62545. t->inverted().transformPoint (tx, ty);
  62546. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  62547. return true;
  62548. }
  62549. return false;
  62550. }
  62551. Drawable* DrawableComposite::createCopy() const
  62552. {
  62553. DrawableComposite* const dc = new DrawableComposite();
  62554. for (int i = 0; i < drawables.size(); ++i)
  62555. {
  62556. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  62557. const AffineTransform* const t = transforms.getUnchecked(i);
  62558. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  62559. }
  62560. return dc;
  62561. }
  62562. END_JUCE_NAMESPACE
  62563. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  62564. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  62565. BEGIN_JUCE_NAMESPACE
  62566. DrawableImage::DrawableImage()
  62567. : image (0),
  62568. canDeleteImage (false),
  62569. opacity (1.0f),
  62570. overlayColour (0x00000000)
  62571. {
  62572. }
  62573. DrawableImage::~DrawableImage()
  62574. {
  62575. clearImage();
  62576. }
  62577. void DrawableImage::clearImage()
  62578. {
  62579. if (canDeleteImage && image != 0)
  62580. {
  62581. if (ImageCache::isImageInCache (image))
  62582. ImageCache::release (image);
  62583. else
  62584. delete image;
  62585. }
  62586. image = 0;
  62587. }
  62588. void DrawableImage::setImage (const Image& imageToCopy)
  62589. {
  62590. clearImage();
  62591. image = new Image (imageToCopy);
  62592. canDeleteImage = true;
  62593. }
  62594. void DrawableImage::setImage (Image* imageToUse,
  62595. const bool releaseWhenNotNeeded)
  62596. {
  62597. clearImage();
  62598. image = imageToUse;
  62599. canDeleteImage = releaseWhenNotNeeded;
  62600. }
  62601. void DrawableImage::setOpacity (const float newOpacity)
  62602. {
  62603. opacity = newOpacity;
  62604. }
  62605. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  62606. {
  62607. overlayColour = newOverlayColour;
  62608. }
  62609. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  62610. {
  62611. if (image != 0)
  62612. {
  62613. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62614. if (opacity > 0.0f && ! overlayColour.isOpaque())
  62615. {
  62616. g.setColour (oldColour.withMultipliedAlpha (opacity));
  62617. g.drawImageTransformed (image,
  62618. 0, 0, image->getWidth(), image->getHeight(),
  62619. transform, false);
  62620. }
  62621. if (! overlayColour.isTransparent())
  62622. {
  62623. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  62624. g.drawImageTransformed (image,
  62625. 0, 0, image->getWidth(), image->getHeight(),
  62626. transform, true);
  62627. }
  62628. g.setColour (oldColour);
  62629. }
  62630. }
  62631. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  62632. {
  62633. x = 0.0f;
  62634. y = 0.0f;
  62635. width = 0.0f;
  62636. height = 0.0f;
  62637. if (image != 0)
  62638. {
  62639. width = (float) image->getWidth();
  62640. height = (float) image->getHeight();
  62641. }
  62642. }
  62643. bool DrawableImage::hitTest (float x, float y) const
  62644. {
  62645. return image != 0
  62646. && x >= 0.0f
  62647. && y >= 0.0f
  62648. && x < image->getWidth()
  62649. && y < image->getHeight()
  62650. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  62651. }
  62652. Drawable* DrawableImage::createCopy() const
  62653. {
  62654. DrawableImage* const di = new DrawableImage();
  62655. di->opacity = opacity;
  62656. di->overlayColour = overlayColour;
  62657. if (image != 0)
  62658. {
  62659. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  62660. {
  62661. di->setImage (*image);
  62662. }
  62663. else
  62664. {
  62665. ImageCache::incReferenceCount (image);
  62666. di->setImage (image, true);
  62667. }
  62668. }
  62669. return di;
  62670. }
  62671. END_JUCE_NAMESPACE
  62672. /********* End of inlined file: juce_DrawableImage.cpp *********/
  62673. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  62674. BEGIN_JUCE_NAMESPACE
  62675. DrawablePath::DrawablePath()
  62676. : fillBrush (new SolidColourBrush (Colours::black)),
  62677. strokeBrush (0),
  62678. strokeType (0.0f)
  62679. {
  62680. }
  62681. DrawablePath::~DrawablePath()
  62682. {
  62683. delete fillBrush;
  62684. delete strokeBrush;
  62685. }
  62686. void DrawablePath::setPath (const Path& newPath)
  62687. {
  62688. path = newPath;
  62689. updateOutline();
  62690. }
  62691. void DrawablePath::setSolidFill (const Colour& newColour)
  62692. {
  62693. delete fillBrush;
  62694. fillBrush = new SolidColourBrush (newColour);
  62695. }
  62696. void DrawablePath::setFillBrush (const Brush& newBrush)
  62697. {
  62698. delete fillBrush;
  62699. fillBrush = newBrush.createCopy();
  62700. }
  62701. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  62702. {
  62703. strokeType = PathStrokeType (thickness);
  62704. delete strokeBrush;
  62705. strokeBrush = new SolidColourBrush (colour);
  62706. updateOutline();
  62707. }
  62708. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  62709. {
  62710. strokeType = strokeType_;
  62711. delete strokeBrush;
  62712. strokeBrush = newStrokeBrush.createCopy();
  62713. updateOutline();
  62714. }
  62715. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  62716. {
  62717. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62718. const float currentOpacity = oldColour.getFloatAlpha();
  62719. {
  62720. Brush* const tempBrush = fillBrush->createCopy();
  62721. tempBrush->applyTransform (transform);
  62722. tempBrush->multiplyOpacity (currentOpacity);
  62723. g.setBrush (tempBrush);
  62724. g.fillPath (path, transform);
  62725. delete tempBrush;
  62726. }
  62727. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  62728. {
  62729. Brush* const tempBrush = strokeBrush->createCopy();
  62730. tempBrush->applyTransform (transform);
  62731. tempBrush->multiplyOpacity (currentOpacity);
  62732. g.setBrush (tempBrush);
  62733. g.fillPath (outline, transform);
  62734. delete tempBrush;
  62735. }
  62736. g.setColour (oldColour);
  62737. }
  62738. void DrawablePath::updateOutline()
  62739. {
  62740. outline.clear();
  62741. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  62742. }
  62743. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  62744. {
  62745. if (strokeType.getStrokeThickness() > 0.0f)
  62746. outline.getBounds (x, y, width, height);
  62747. else
  62748. path.getBounds (x, y, width, height);
  62749. }
  62750. bool DrawablePath::hitTest (float x, float y) const
  62751. {
  62752. return path.contains (x, y)
  62753. || outline.contains (x, y);
  62754. }
  62755. Drawable* DrawablePath::createCopy() const
  62756. {
  62757. DrawablePath* const dp = new DrawablePath();
  62758. dp->path = path;
  62759. dp->setFillBrush (*fillBrush);
  62760. if (strokeBrush != 0)
  62761. dp->setOutline (strokeType, *strokeBrush);
  62762. return dp;
  62763. }
  62764. END_JUCE_NAMESPACE
  62765. /********* End of inlined file: juce_DrawablePath.cpp *********/
  62766. /********* Start of inlined file: juce_DrawableText.cpp *********/
  62767. BEGIN_JUCE_NAMESPACE
  62768. DrawableText::DrawableText()
  62769. : colour (Colours::white)
  62770. {
  62771. }
  62772. DrawableText::~DrawableText()
  62773. {
  62774. }
  62775. void DrawableText::setText (const GlyphArrangement& newText)
  62776. {
  62777. text = newText;
  62778. }
  62779. void DrawableText::setText (const String& newText, const Font& fontToUse)
  62780. {
  62781. text.clear();
  62782. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  62783. }
  62784. void DrawableText::setColour (const Colour& newColour)
  62785. {
  62786. colour = newColour;
  62787. }
  62788. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  62789. {
  62790. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62791. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  62792. text.draw (g, transform);
  62793. g.setColour (oldColour);
  62794. }
  62795. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  62796. {
  62797. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  62798. width -= x;
  62799. height -= y;
  62800. }
  62801. bool DrawableText::hitTest (float x, float y) const
  62802. {
  62803. return text.findGlyphIndexAt (x, y) >= 0;
  62804. }
  62805. Drawable* DrawableText::createCopy() const
  62806. {
  62807. DrawableText* const dt = new DrawableText();
  62808. dt->text = text;
  62809. dt->colour = colour;
  62810. return dt;
  62811. }
  62812. END_JUCE_NAMESPACE
  62813. /********* End of inlined file: juce_DrawableText.cpp *********/
  62814. /********* Start of inlined file: juce_SVGParser.cpp *********/
  62815. BEGIN_JUCE_NAMESPACE
  62816. class SVGState
  62817. {
  62818. public:
  62819. SVGState (const XmlElement* const topLevel)
  62820. : topLevelXml (topLevel),
  62821. x (0), y (0),
  62822. width (512), height (512),
  62823. viewBoxW (0), viewBoxH (0)
  62824. {
  62825. }
  62826. ~SVGState()
  62827. {
  62828. }
  62829. Drawable* parseSVGElement (const XmlElement& xml)
  62830. {
  62831. if (! xml.hasTagName (T("svg")))
  62832. return 0;
  62833. DrawableComposite* const drawable = new DrawableComposite();
  62834. drawable->setName (xml.getStringAttribute (T("id")));
  62835. SVGState newState (*this);
  62836. if (xml.hasAttribute (T("transform")))
  62837. newState.addTransform (xml);
  62838. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  62839. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  62840. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  62841. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  62842. if (xml.hasAttribute (T("viewBox")))
  62843. {
  62844. const String viewParams (xml.getStringAttribute (T("viewBox")));
  62845. int i = 0;
  62846. float vx, vy, vw, vh;
  62847. if (parseCoords (viewParams, vx, vy, i, true)
  62848. && parseCoords (viewParams, vw, vh, i, true)
  62849. && vw > 0
  62850. && vh > 0)
  62851. {
  62852. newState.viewBoxW = vw;
  62853. newState.viewBoxH = vh;
  62854. int placementFlags = 0;
  62855. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  62856. if (aspect.containsIgnoreCase (T("none")))
  62857. {
  62858. placementFlags = RectanglePlacement::stretchToFit;
  62859. }
  62860. else
  62861. {
  62862. if (aspect.containsIgnoreCase (T("slice")))
  62863. placementFlags |= RectanglePlacement::fillDestination;
  62864. if (aspect.containsIgnoreCase (T("xMin")))
  62865. placementFlags |= RectanglePlacement::xLeft;
  62866. else if (aspect.containsIgnoreCase (T("xMax")))
  62867. placementFlags |= RectanglePlacement::xRight;
  62868. else
  62869. placementFlags |= RectanglePlacement::xMid;
  62870. if (aspect.containsIgnoreCase (T("yMin")))
  62871. placementFlags |= RectanglePlacement::yTop;
  62872. else if (aspect.containsIgnoreCase (T("yMax")))
  62873. placementFlags |= RectanglePlacement::yBottom;
  62874. else
  62875. placementFlags |= RectanglePlacement::yMid;
  62876. }
  62877. const RectanglePlacement placement (placementFlags);
  62878. newState.transform
  62879. = placement.getTransformToFit (vx, vy, vw, vh,
  62880. 0.0f, 0.0f, newState.width, newState.height)
  62881. .followedBy (newState.transform);
  62882. }
  62883. }
  62884. else
  62885. {
  62886. if (viewBoxW == 0)
  62887. newState.viewBoxW = newState.width;
  62888. if (viewBoxH == 0)
  62889. newState.viewBoxH = newState.height;
  62890. }
  62891. newState.parseSubElements (xml, drawable);
  62892. return drawable;
  62893. }
  62894. private:
  62895. const XmlElement* const topLevelXml;
  62896. float x, y, width, height, viewBoxW, viewBoxH;
  62897. AffineTransform transform;
  62898. String cssStyleText;
  62899. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  62900. {
  62901. forEachXmlChildElement (xml, e)
  62902. {
  62903. Drawable* d = 0;
  62904. if (e->hasTagName (T("g")))
  62905. d = parseGroupElement (*e);
  62906. else if (e->hasTagName (T("svg")))
  62907. d = parseSVGElement (*e);
  62908. else if (e->hasTagName (T("path")))
  62909. d = parsePath (*e);
  62910. else if (e->hasTagName (T("rect")))
  62911. d = parseRect (*e);
  62912. else if (e->hasTagName (T("circle")))
  62913. d = parseCircle (*e);
  62914. else if (e->hasTagName (T("ellipse")))
  62915. d = parseEllipse (*e);
  62916. else if (e->hasTagName (T("line")))
  62917. d = parseLine (*e);
  62918. else if (e->hasTagName (T("polyline")))
  62919. d = parsePolygon (*e, true);
  62920. else if (e->hasTagName (T("polygon")))
  62921. d = parsePolygon (*e, false);
  62922. else if (e->hasTagName (T("text")))
  62923. d = parseText (*e);
  62924. else if (e->hasTagName (T("switch")))
  62925. d = parseSwitch (*e);
  62926. else if (e->hasTagName (T("style")))
  62927. parseCSSStyle (*e);
  62928. parentDrawable->insertDrawable (d);
  62929. }
  62930. }
  62931. DrawableComposite* parseSwitch (const XmlElement& xml)
  62932. {
  62933. const XmlElement* const group = xml.getChildByName (T("g"));
  62934. if (group != 0)
  62935. return parseGroupElement (*group);
  62936. return 0;
  62937. }
  62938. DrawableComposite* parseGroupElement (const XmlElement& xml)
  62939. {
  62940. DrawableComposite* const drawable = new DrawableComposite();
  62941. drawable->setName (xml.getStringAttribute (T("id")));
  62942. if (xml.hasAttribute (T("transform")))
  62943. {
  62944. SVGState newState (*this);
  62945. newState.addTransform (xml);
  62946. newState.parseSubElements (xml, drawable);
  62947. }
  62948. else
  62949. {
  62950. parseSubElements (xml, drawable);
  62951. }
  62952. return drawable;
  62953. }
  62954. Drawable* parsePath (const XmlElement& xml) const
  62955. {
  62956. const String d (xml.getStringAttribute (T("d")).trimStart());
  62957. Path path;
  62958. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  62959. path.setUsingNonZeroWinding (false);
  62960. int index = 0;
  62961. float lastX = 0, lastY = 0;
  62962. float lastX2 = 0, lastY2 = 0;
  62963. tchar lastCommandChar = 0;
  62964. bool carryOn = true;
  62965. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  62966. for (;;)
  62967. {
  62968. float x, y, x2, y2, x3, y3;
  62969. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  62970. if (validCommandChars.containsChar (d[index]))
  62971. lastCommandChar = d [index++];
  62972. switch (lastCommandChar)
  62973. {
  62974. case T('M'):
  62975. case T('m'):
  62976. case T('L'):
  62977. case T('l'):
  62978. if (parseCoords (d, x, y, index, false))
  62979. {
  62980. if (isRelative)
  62981. {
  62982. x += lastX;
  62983. y += lastY;
  62984. }
  62985. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  62986. path.startNewSubPath (x, y);
  62987. else
  62988. path.lineTo (x, y);
  62989. lastX2 = lastX;
  62990. lastY2 = lastY;
  62991. lastX = x;
  62992. lastY = y;
  62993. }
  62994. else
  62995. {
  62996. ++index;
  62997. }
  62998. break;
  62999. case T('H'):
  63000. case T('h'):
  63001. if (parseCoord (d, x, index, false, true))
  63002. {
  63003. if (isRelative)
  63004. x += lastX;
  63005. path.lineTo (x, lastY);
  63006. lastX2 = lastX;
  63007. lastX = x;
  63008. }
  63009. else
  63010. {
  63011. ++index;
  63012. }
  63013. break;
  63014. case T('V'):
  63015. case T('v'):
  63016. if (parseCoord (d, y, index, false, false))
  63017. {
  63018. if (isRelative)
  63019. y += lastY;
  63020. path.lineTo (lastX, y);
  63021. lastY2 = lastY;
  63022. lastY = y;
  63023. }
  63024. else
  63025. {
  63026. ++index;
  63027. }
  63028. break;
  63029. case T('C'):
  63030. case T('c'):
  63031. if (parseCoords (d, x, y, index, false)
  63032. && parseCoords (d, x2, y2, index, false)
  63033. && parseCoords (d, x3, y3, index, false))
  63034. {
  63035. if (isRelative)
  63036. {
  63037. x += lastX;
  63038. y += lastY;
  63039. x2 += lastX;
  63040. y2 += lastY;
  63041. x3 += lastX;
  63042. y3 += lastY;
  63043. }
  63044. path.cubicTo (x, y, x2, y2, x3, y3);
  63045. lastX2 = x2;
  63046. lastY2 = y2;
  63047. lastX = x3;
  63048. lastY = y3;
  63049. }
  63050. else
  63051. {
  63052. ++index;
  63053. }
  63054. break;
  63055. case T('S'):
  63056. case T('s'):
  63057. if (parseCoords (d, x, y, index, false)
  63058. && parseCoords (d, x3, y3, index, false))
  63059. {
  63060. if (isRelative)
  63061. {
  63062. x += lastX;
  63063. y += lastY;
  63064. x3 += lastX;
  63065. y3 += lastY;
  63066. }
  63067. x2 = lastX + (lastX - lastX2);
  63068. y2 = lastY + (lastY - lastY2);
  63069. path.cubicTo (x2, y2, x, y, x3, y3);
  63070. lastX2 = x2;
  63071. lastY2 = y2;
  63072. lastX = x3;
  63073. lastY = y3;
  63074. }
  63075. else
  63076. {
  63077. ++index;
  63078. }
  63079. break;
  63080. case T('Q'):
  63081. case T('q'):
  63082. if (parseCoords (d, x, y, index, false)
  63083. && parseCoords (d, x2, y2, index, false))
  63084. {
  63085. if (isRelative)
  63086. {
  63087. x += lastX;
  63088. y += lastY;
  63089. x2 += lastX;
  63090. y2 += lastY;
  63091. }
  63092. path.quadraticTo (x, y, x2, y2);
  63093. lastX2 = x;
  63094. lastY2 = y;
  63095. lastX = x2;
  63096. lastY = y2;
  63097. }
  63098. else
  63099. {
  63100. ++index;
  63101. }
  63102. break;
  63103. case T('T'):
  63104. case T('t'):
  63105. if (parseCoords (d, x, y, index, false))
  63106. {
  63107. if (isRelative)
  63108. {
  63109. x += lastX;
  63110. y += lastY;
  63111. }
  63112. x2 = lastX + (lastX - lastX2);
  63113. y2 = lastY + (lastY - lastY2);
  63114. path.quadraticTo (x2, y2, x, y);
  63115. lastX2 = x2;
  63116. lastY2 = y2;
  63117. lastX = x;
  63118. lastY = y;
  63119. }
  63120. else
  63121. {
  63122. ++index;
  63123. }
  63124. break;
  63125. case T('A'):
  63126. case T('a'):
  63127. if (parseCoords (d, x, y, index, false))
  63128. {
  63129. String num;
  63130. if (parseNextNumber (d, num, index, false))
  63131. {
  63132. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  63133. if (parseNextNumber (d, num, index, false))
  63134. {
  63135. const bool largeArc = num.getIntValue() != 0;
  63136. if (parseNextNumber (d, num, index, false))
  63137. {
  63138. const bool sweep = num.getIntValue() != 0;
  63139. if (parseCoords (d, x2, y2, index, false))
  63140. {
  63141. if (isRelative)
  63142. {
  63143. x2 += lastX;
  63144. y2 += lastY;
  63145. }
  63146. if (lastX != x2 || lastY != y2)
  63147. {
  63148. double centreX, centreY, startAngle, deltaAngle;
  63149. double rx = x, ry = y;
  63150. endpointToCentreParameters (lastX, lastY, x2, y2,
  63151. angle, largeArc, sweep,
  63152. rx, ry, centreX, centreY,
  63153. startAngle, deltaAngle);
  63154. path.addCentredArc ((float) centreX, (float) centreY,
  63155. (float) rx, (float) ry,
  63156. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  63157. false);
  63158. path.lineTo (x2, y2);
  63159. }
  63160. lastX2 = lastX;
  63161. lastY2 = lastY;
  63162. lastX = x2;
  63163. lastY = y2;
  63164. }
  63165. }
  63166. }
  63167. }
  63168. }
  63169. else
  63170. {
  63171. ++index;
  63172. }
  63173. break;
  63174. case T('Z'):
  63175. case T('z'):
  63176. path.closeSubPath();
  63177. while (CharacterFunctions::isWhitespace (d [index]))
  63178. ++index;
  63179. break;
  63180. default:
  63181. carryOn = false;
  63182. break;
  63183. }
  63184. if (! carryOn)
  63185. break;
  63186. }
  63187. return parseShape (xml, path);
  63188. }
  63189. Drawable* parseRect (const XmlElement& xml) const
  63190. {
  63191. Path rect;
  63192. const bool hasRX = xml.hasAttribute (T("rx"));
  63193. const bool hasRY = xml.hasAttribute (T("ry"));
  63194. if (hasRX || hasRY)
  63195. {
  63196. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63197. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63198. if (! hasRX)
  63199. rx = ry;
  63200. else if (! hasRY)
  63201. ry = rx;
  63202. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63203. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63204. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63205. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  63206. rx, ry);
  63207. }
  63208. else
  63209. {
  63210. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63211. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63212. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63213. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  63214. }
  63215. return parseShape (xml, rect);
  63216. }
  63217. Drawable* parseCircle (const XmlElement& xml) const
  63218. {
  63219. Path circle;
  63220. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63221. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63222. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  63223. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  63224. return parseShape (xml, circle);
  63225. }
  63226. Drawable* parseEllipse (const XmlElement& xml) const
  63227. {
  63228. Path ellipse;
  63229. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63230. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63231. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63232. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63233. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  63234. return parseShape (xml, ellipse);
  63235. }
  63236. Drawable* parseLine (const XmlElement& xml) const
  63237. {
  63238. Path line;
  63239. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  63240. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  63241. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  63242. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  63243. line.startNewSubPath (x1, y1);
  63244. line.lineTo (x2, y2);
  63245. return parseShape (xml, line);
  63246. }
  63247. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  63248. {
  63249. const String points (xml.getStringAttribute (T("points")));
  63250. Path path;
  63251. int index = 0;
  63252. float x, y;
  63253. if (parseCoords (points, x, y, index, true))
  63254. {
  63255. float firstX = x;
  63256. float firstY = y;
  63257. float lastX = 0, lastY = 0;
  63258. path.startNewSubPath (x, y);
  63259. while (parseCoords (points, x, y, index, true))
  63260. {
  63261. lastX = x;
  63262. lastY = y;
  63263. path.lineTo (x, y);
  63264. }
  63265. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  63266. path.closeSubPath();
  63267. }
  63268. return parseShape (xml, path);
  63269. }
  63270. Drawable* parseShape (const XmlElement& xml, Path& path,
  63271. const bool parseTransform = true) const
  63272. {
  63273. if (parseTransform && xml.hasAttribute (T("transform")))
  63274. {
  63275. SVGState newState (*this);
  63276. newState.addTransform (xml);
  63277. return newState.parseShape (xml, path, false);
  63278. }
  63279. DrawablePath* dp = new DrawablePath();
  63280. dp->setSolidFill (Colours::transparentBlack);
  63281. path.applyTransform (transform);
  63282. dp->setPath (path);
  63283. Path::Iterator iter (path);
  63284. bool containsClosedSubPath = false;
  63285. while (iter.next())
  63286. {
  63287. if (iter.elementType == Path::Iterator::closePath)
  63288. {
  63289. containsClosedSubPath = true;
  63290. break;
  63291. }
  63292. }
  63293. Brush* const fillBrush
  63294. = getBrushForFill (path,
  63295. getStyleAttribute (&xml, T("fill")),
  63296. getStyleAttribute (&xml, T("fill-opacity")),
  63297. getStyleAttribute (&xml, T("opacity")),
  63298. containsClosedSubPath ? Colours::black
  63299. : Colours::transparentBlack);
  63300. if (fillBrush != 0)
  63301. {
  63302. if (! fillBrush->isInvisible())
  63303. {
  63304. fillBrush->applyTransform (transform);
  63305. dp->setFillBrush (*fillBrush);
  63306. }
  63307. delete fillBrush;
  63308. }
  63309. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  63310. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  63311. {
  63312. Brush* const strokeBrush
  63313. = getBrushForFill (path, strokeType,
  63314. getStyleAttribute (&xml, T("stroke-opacity")),
  63315. getStyleAttribute (&xml, T("opacity")),
  63316. Colours::transparentBlack);
  63317. if (strokeBrush != 0)
  63318. {
  63319. const PathStrokeType stroke (getStrokeFor (&xml));
  63320. if (! strokeBrush->isInvisible())
  63321. {
  63322. strokeBrush->applyTransform (transform);
  63323. dp->setOutline (stroke, *strokeBrush);
  63324. }
  63325. delete strokeBrush;
  63326. }
  63327. }
  63328. return dp;
  63329. }
  63330. const XmlElement* findLinkedElement (const XmlElement* e) const
  63331. {
  63332. const String id (e->getStringAttribute (T("xlink:href")));
  63333. if (! id.startsWithChar (T('#')))
  63334. return 0;
  63335. return findElementForId (topLevelXml, id.substring (1));
  63336. }
  63337. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  63338. {
  63339. if (fillXml == 0)
  63340. return;
  63341. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  63342. {
  63343. int index = 0;
  63344. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  63345. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  63346. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  63347. double offset = e->getDoubleAttribute (T("offset"));
  63348. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  63349. offset *= 0.01;
  63350. cg.addColour (jlimit (0.0, 1.0, offset), col);
  63351. }
  63352. }
  63353. Brush* getBrushForFill (const Path& path,
  63354. const String& fill,
  63355. const String& fillOpacity,
  63356. const String& overallOpacity,
  63357. const Colour& defaultColour) const
  63358. {
  63359. float opacity = 1.0f;
  63360. if (overallOpacity.isNotEmpty())
  63361. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  63362. if (fillOpacity.isNotEmpty())
  63363. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  63364. if (fill.startsWithIgnoreCase (T("url")))
  63365. {
  63366. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  63367. .upToLastOccurrenceOf (T(")"), false, false).trim());
  63368. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  63369. if (fillXml != 0
  63370. && (fillXml->hasTagName (T("linearGradient"))
  63371. || fillXml->hasTagName (T("radialGradient"))))
  63372. {
  63373. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  63374. ColourGradient cg;
  63375. addGradientStopsIn (cg, inheritedFrom);
  63376. addGradientStopsIn (cg, fillXml);
  63377. if (cg.getNumColours() > 0)
  63378. {
  63379. cg.addColour (0.0, cg.getColour (0));
  63380. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  63381. }
  63382. else
  63383. {
  63384. cg.addColour (0.0, Colours::black);
  63385. cg.addColour (1.0, Colours::black);
  63386. }
  63387. if (overallOpacity.isNotEmpty())
  63388. cg.multiplyOpacity (overallOpacity.getFloatValue());
  63389. jassert (cg.getNumColours() > 0);
  63390. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  63391. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  63392. float width = viewBoxW;
  63393. float height = viewBoxH;
  63394. float dx = 0.0;
  63395. float dy = 0.0;
  63396. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  63397. if (! userSpace)
  63398. path.getBounds (dx, dy, width, height);
  63399. if (cg.isRadial)
  63400. {
  63401. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  63402. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  63403. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  63404. cg.x2 = cg.x1 + radius;
  63405. cg.y2 = cg.y1;
  63406. //xxx (the fx, fy focal point isn't handled properly here..)
  63407. }
  63408. else
  63409. {
  63410. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  63411. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  63412. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  63413. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  63414. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  63415. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  63416. }
  63417. return new GradientBrush (cg);
  63418. }
  63419. }
  63420. if (fill.equalsIgnoreCase (T("none")))
  63421. return new SolidColourBrush (Colours::transparentBlack);
  63422. int i = 0;
  63423. Colour colour (parseColour (fill, i, defaultColour));
  63424. colour = colour.withMultipliedAlpha (opacity);
  63425. return new SolidColourBrush (colour);
  63426. }
  63427. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  63428. {
  63429. const String width (getStyleAttribute (xml, T("stroke-width")));
  63430. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  63431. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  63432. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  63433. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  63434. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  63435. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  63436. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  63437. if (join.equalsIgnoreCase (T("round")))
  63438. joinStyle = PathStrokeType::curved;
  63439. else if (join.equalsIgnoreCase (T("bevel")))
  63440. joinStyle = PathStrokeType::beveled;
  63441. if (cap.equalsIgnoreCase (T("round")))
  63442. capStyle = PathStrokeType::rounded;
  63443. else if (cap.equalsIgnoreCase (T("square")))
  63444. capStyle = PathStrokeType::square;
  63445. float ox = 0.0f, oy = 0.0f;
  63446. transform.transformPoint (ox, oy);
  63447. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  63448. transform.transformPoint (x, y);
  63449. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  63450. joinStyle, capStyle);
  63451. }
  63452. Drawable* parseText (const XmlElement& xml)
  63453. {
  63454. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  63455. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  63456. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  63457. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  63458. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  63459. //xxx not done text yet!
  63460. forEachXmlChildElement (xml, e)
  63461. {
  63462. if (e->isTextElement())
  63463. {
  63464. const String text (e->getText());
  63465. Path path;
  63466. parseShape (*e, path);
  63467. }
  63468. else if (e->hasTagName (T("tspan")))
  63469. {
  63470. parseText (*e);
  63471. }
  63472. }
  63473. return 0;
  63474. }
  63475. void addTransform (const XmlElement& xml)
  63476. {
  63477. transform = parseTransform (xml.getStringAttribute (T("transform")))
  63478. .followedBy (transform);
  63479. }
  63480. bool parseCoord (const String& s, float& value, int& index,
  63481. const bool allowUnits, const bool isX) const
  63482. {
  63483. String number;
  63484. if (! parseNextNumber (s, number, index, allowUnits))
  63485. {
  63486. value = 0;
  63487. return false;
  63488. }
  63489. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  63490. return true;
  63491. }
  63492. bool parseCoords (const String& s, float& x, float& y,
  63493. int& index, const bool allowUnits) const
  63494. {
  63495. return parseCoord (s, x, index, allowUnits, true)
  63496. && parseCoord (s, y, index, allowUnits, false);
  63497. }
  63498. float getCoordLength (const String& s, const float sizeForProportions) const
  63499. {
  63500. float n = s.getFloatValue();
  63501. const int len = s.length();
  63502. if (len > 2)
  63503. {
  63504. const float dpi = 96.0f;
  63505. const tchar n1 = s [len - 2];
  63506. const tchar n2 = s [len - 1];
  63507. if (n1 == T('i') && n2 == T('n'))
  63508. n *= dpi;
  63509. else if (n1 == T('m') && n2 == T('m'))
  63510. n *= dpi / 25.4f;
  63511. else if (n1 == T('c') && n2 == T('m'))
  63512. n *= dpi / 2.54f;
  63513. else if (n1 == T('p') && n2 == T('c'))
  63514. n *= 15.0f;
  63515. else if (n2 == T('%'))
  63516. n *= 0.01f * sizeForProportions;
  63517. }
  63518. return n;
  63519. }
  63520. void getCoordList (Array <float>& coords, const String& list,
  63521. const bool allowUnits, const bool isX) const
  63522. {
  63523. int index = 0;
  63524. float value;
  63525. while (parseCoord (list, value, index, allowUnits, isX))
  63526. coords.add (value);
  63527. }
  63528. void parseCSSStyle (const XmlElement& xml)
  63529. {
  63530. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  63531. }
  63532. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  63533. const String& defaultValue = String::empty) const
  63534. {
  63535. if (xml->hasAttribute (attributeName))
  63536. return xml->getStringAttribute (attributeName, defaultValue);
  63537. const String styleAtt (xml->getStringAttribute (T("style")));
  63538. if (styleAtt.isNotEmpty())
  63539. {
  63540. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  63541. if (value.isNotEmpty())
  63542. return value;
  63543. }
  63544. else if (xml->hasAttribute (T("class")))
  63545. {
  63546. const String className (T(".") + xml->getStringAttribute (T("class")));
  63547. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  63548. if (index < 0)
  63549. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  63550. if (index >= 0)
  63551. {
  63552. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  63553. if (openBracket > index)
  63554. {
  63555. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  63556. if (closeBracket > openBracket)
  63557. {
  63558. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  63559. if (value.isNotEmpty())
  63560. return value;
  63561. }
  63562. }
  63563. }
  63564. }
  63565. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  63566. if (xml != 0)
  63567. return getStyleAttribute (xml, attributeName, defaultValue);
  63568. return defaultValue;
  63569. }
  63570. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  63571. {
  63572. if (xml->hasAttribute (attributeName))
  63573. return xml->getStringAttribute (attributeName);
  63574. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  63575. if (xml != 0)
  63576. return getInheritedAttribute (xml, attributeName);
  63577. return String::empty;
  63578. }
  63579. static bool isIdentifierChar (const tchar c)
  63580. {
  63581. return CharacterFunctions::isLetter (c) || c == T('-');
  63582. }
  63583. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  63584. {
  63585. int i = 0;
  63586. for (;;)
  63587. {
  63588. i = list.indexOf (i, attributeName);
  63589. if (i < 0)
  63590. break;
  63591. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  63592. && ! isIdentifierChar (list [i + attributeName.length()]))
  63593. {
  63594. i = list.indexOfChar (i, T(':'));
  63595. if (i < 0)
  63596. break;
  63597. int end = list.indexOfChar (i, T(';'));
  63598. if (end < 0)
  63599. end = 0x7ffff;
  63600. return list.substring (i + 1, end).trim();
  63601. }
  63602. ++i;
  63603. }
  63604. return defaultValue;
  63605. }
  63606. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  63607. {
  63608. const tchar* const s = (const tchar*) source;
  63609. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  63610. ++index;
  63611. int start = index;
  63612. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  63613. ++index;
  63614. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  63615. ++index;
  63616. if ((s[index] == T('e') || s[index] == T('E'))
  63617. && (CharacterFunctions::isDigit (s[index + 1])
  63618. || s[index + 1] == T('-')
  63619. || s[index + 1] == T('+')))
  63620. {
  63621. index += 2;
  63622. while (CharacterFunctions::isDigit (s[index]))
  63623. ++index;
  63624. }
  63625. if (allowUnits)
  63626. {
  63627. while (CharacterFunctions::isLetter (s[index]))
  63628. ++index;
  63629. }
  63630. if (index == start)
  63631. return false;
  63632. value = String (s + start, index - start);
  63633. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  63634. ++index;
  63635. return true;
  63636. }
  63637. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  63638. {
  63639. if (s [index] == T('#'))
  63640. {
  63641. uint32 hex [6];
  63642. zeromem (hex, sizeof (hex));
  63643. int numChars = 0;
  63644. for (int i = 6; --i >= 0;)
  63645. {
  63646. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  63647. if (hexValue >= 0)
  63648. hex [numChars++] = hexValue;
  63649. else
  63650. break;
  63651. }
  63652. if (numChars <= 3)
  63653. return Colour ((uint8) (hex [0] * 0x11),
  63654. (uint8) (hex [1] * 0x11),
  63655. (uint8) (hex [2] * 0x11));
  63656. else
  63657. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  63658. (uint8) ((hex [2] << 4) + hex [3]),
  63659. (uint8) ((hex [4] << 4) + hex [5]));
  63660. }
  63661. else if (s [index] == T('r')
  63662. && s [index + 1] == T('g')
  63663. && s [index + 2] == T('b'))
  63664. {
  63665. const int openBracket = s.indexOfChar (index, T('('));
  63666. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  63667. if (openBracket >= 3 && closeBracket > openBracket)
  63668. {
  63669. index = closeBracket;
  63670. StringArray tokens;
  63671. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  63672. tokens.trim();
  63673. tokens.removeEmptyStrings();
  63674. if (tokens[0].containsChar T('%'))
  63675. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  63676. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  63677. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  63678. else
  63679. return Colour ((uint8) tokens[0].getIntValue(),
  63680. (uint8) tokens[1].getIntValue(),
  63681. (uint8) tokens[2].getIntValue());
  63682. }
  63683. }
  63684. return Colours::findColourForName (s, defaultColour);
  63685. }
  63686. static const AffineTransform parseTransform (String t)
  63687. {
  63688. AffineTransform result;
  63689. while (t.isNotEmpty())
  63690. {
  63691. StringArray tokens;
  63692. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  63693. .upToFirstOccurrenceOf (T(")"), false, false),
  63694. T(", "), 0);
  63695. tokens.removeEmptyStrings (true);
  63696. float numbers [6];
  63697. for (int i = 0; i < 6; ++i)
  63698. numbers[i] = tokens[i].getFloatValue();
  63699. AffineTransform trans;
  63700. if (t.startsWithIgnoreCase (T("matrix")))
  63701. {
  63702. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  63703. numbers[1], numbers[3], numbers[5]);
  63704. }
  63705. else if (t.startsWithIgnoreCase (T("translate")))
  63706. {
  63707. trans = trans.translated (numbers[0], numbers[1]);
  63708. }
  63709. else if (t.startsWithIgnoreCase (T("scale")))
  63710. {
  63711. if (tokens.size() == 1)
  63712. trans = trans.scaled (numbers[0], numbers[0]);
  63713. else
  63714. trans = trans.scaled (numbers[0], numbers[1]);
  63715. }
  63716. else if (t.startsWithIgnoreCase (T("rotate")))
  63717. {
  63718. if (tokens.size() != 3)
  63719. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  63720. else
  63721. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  63722. numbers[1], numbers[2]);
  63723. }
  63724. else if (t.startsWithIgnoreCase (T("skewX")))
  63725. {
  63726. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  63727. 0.0f, 1.0f, 0.0f);
  63728. }
  63729. else if (t.startsWithIgnoreCase (T("skewY")))
  63730. {
  63731. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  63732. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  63733. }
  63734. result = trans.followedBy (result);
  63735. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  63736. }
  63737. return result;
  63738. }
  63739. static void endpointToCentreParameters (const double x1, const double y1,
  63740. const double x2, const double y2,
  63741. const double angle,
  63742. const bool largeArc, const bool sweep,
  63743. double& rx, double& ry,
  63744. double& centreX, double& centreY,
  63745. double& startAngle, double& deltaAngle)
  63746. {
  63747. const double midX = (x1 - x2) * 0.5;
  63748. const double midY = (y1 - y2) * 0.5;
  63749. const double cosAngle = cos (angle);
  63750. const double sinAngle = sin (angle);
  63751. const double xp = cosAngle * midX + sinAngle * midY;
  63752. const double yp = cosAngle * midY - sinAngle * midX;
  63753. const double xp2 = xp * xp;
  63754. const double yp2 = yp * yp;
  63755. double rx2 = rx * rx;
  63756. double ry2 = ry * ry;
  63757. const double s = (xp2 / rx2) + (yp2 / ry2);
  63758. double c;
  63759. if (s <= 1.0)
  63760. {
  63761. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  63762. / (( rx2 * yp2) + (ry2 * xp2))));
  63763. if (largeArc == sweep)
  63764. c = -c;
  63765. }
  63766. else
  63767. {
  63768. const double s2 = sqrt (s);
  63769. rx *= s2;
  63770. ry *= s2;
  63771. rx2 = rx * rx;
  63772. ry2 = ry * ry;
  63773. c = 0;
  63774. }
  63775. const double cpx = ((rx * yp) / ry) * c;
  63776. const double cpy = ((-ry * xp) / rx) * c;
  63777. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  63778. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  63779. const double ux = (xp - cpx) / rx;
  63780. const double uy = (yp - cpy) / ry;
  63781. const double vx = (-xp - cpx) / rx;
  63782. const double vy = (-yp - cpy) / ry;
  63783. const double length = juce_hypot (ux, uy);
  63784. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  63785. if (uy < 0)
  63786. startAngle = -startAngle;
  63787. startAngle += double_Pi * 0.5;
  63788. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  63789. / (length * juce_hypot (vx, vy))));
  63790. if ((ux * vy) - (uy * vx) < 0)
  63791. deltaAngle = -deltaAngle;
  63792. if (sweep)
  63793. {
  63794. if (deltaAngle < 0)
  63795. deltaAngle += double_Pi * 2.0;
  63796. }
  63797. else
  63798. {
  63799. if (deltaAngle > 0)
  63800. deltaAngle -= double_Pi * 2.0;
  63801. }
  63802. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  63803. }
  63804. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  63805. {
  63806. forEachXmlChildElement (*parent, e)
  63807. {
  63808. if (e->compareAttribute (T("id"), id))
  63809. return e;
  63810. const XmlElement* const found = findElementForId (e, id);
  63811. if (found != 0)
  63812. return found;
  63813. }
  63814. return 0;
  63815. }
  63816. const SVGState& operator= (const SVGState&);
  63817. };
  63818. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  63819. {
  63820. SVGState state (&svgDocument);
  63821. return state.parseSVGElement (svgDocument);
  63822. }
  63823. END_JUCE_NAMESPACE
  63824. /********* End of inlined file: juce_SVGParser.cpp *********/
  63825. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  63826. BEGIN_JUCE_NAMESPACE
  63827. #if JUCE_MSVC
  63828. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  63829. #endif
  63830. DropShadowEffect::DropShadowEffect()
  63831. : offsetX (0),
  63832. offsetY (0),
  63833. radius (4),
  63834. opacity (0.6f)
  63835. {
  63836. }
  63837. DropShadowEffect::~DropShadowEffect()
  63838. {
  63839. }
  63840. void DropShadowEffect::setShadowProperties (const float newRadius,
  63841. const float newOpacity,
  63842. const int newShadowOffsetX,
  63843. const int newShadowOffsetY)
  63844. {
  63845. radius = jmax (1.1f, newRadius);
  63846. offsetX = newShadowOffsetX;
  63847. offsetY = newShadowOffsetY;
  63848. opacity = newOpacity;
  63849. }
  63850. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  63851. {
  63852. const int w = image.getWidth();
  63853. const int h = image.getHeight();
  63854. int lineStride, pixelStride;
  63855. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  63856. Image shadowImage (Image::SingleChannel, w, h, false);
  63857. int destStride, destPixelStride;
  63858. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  63859. const int filter = roundFloatToInt (63.0f / radius);
  63860. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  63861. for (int x = w; --x >= 0;)
  63862. {
  63863. int shadowAlpha = 0;
  63864. const PixelARGB* src = srcPixels + x;
  63865. uint8* shadowPix = shadowChannel + x;
  63866. for (int y = h; --y >= 0;)
  63867. {
  63868. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  63869. *shadowPix = (uint8) shadowAlpha;
  63870. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  63871. shadowPix += destStride;
  63872. }
  63873. }
  63874. for (int y = h; --y >= 0;)
  63875. {
  63876. int shadowAlpha = 0;
  63877. uint8* shadowPix = shadowChannel + y * destStride;
  63878. for (int x = w; --x >= 0;)
  63879. {
  63880. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  63881. *shadowPix++ = (uint8) shadowAlpha;
  63882. }
  63883. }
  63884. image.releasePixelDataReadOnly (srcPixels);
  63885. shadowImage.releasePixelDataReadWrite (shadowChannel);
  63886. g.setColour (Colours::black.withAlpha (opacity));
  63887. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  63888. g.setOpacity (1.0f);
  63889. g.drawImageAt (&image, 0, 0);
  63890. }
  63891. END_JUCE_NAMESPACE
  63892. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  63893. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  63894. BEGIN_JUCE_NAMESPACE
  63895. GlowEffect::GlowEffect()
  63896. : radius (2.0f),
  63897. colour (Colours::white)
  63898. {
  63899. }
  63900. GlowEffect::~GlowEffect()
  63901. {
  63902. }
  63903. void GlowEffect::setGlowProperties (const float newRadius,
  63904. const Colour& newColour)
  63905. {
  63906. radius = newRadius;
  63907. colour = newColour;
  63908. }
  63909. void GlowEffect::applyEffect (Image& image, Graphics& g)
  63910. {
  63911. const int w = image.getWidth();
  63912. const int h = image.getHeight();
  63913. Image temp (image.getFormat(), w, h, true);
  63914. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  63915. blurKernel.createGaussianBlur (radius);
  63916. blurKernel.rescaleAllValues (radius);
  63917. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  63918. g.setColour (colour);
  63919. g.drawImageAt (&temp, 0, 0, true);
  63920. g.setOpacity (1.0f);
  63921. g.drawImageAt (&image, 0, 0, false);
  63922. }
  63923. END_JUCE_NAMESPACE
  63924. /********* End of inlined file: juce_GlowEffect.cpp *********/
  63925. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  63926. BEGIN_JUCE_NAMESPACE
  63927. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  63928. : opacity (opacity_)
  63929. {
  63930. }
  63931. ReduceOpacityEffect::~ReduceOpacityEffect()
  63932. {
  63933. }
  63934. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  63935. {
  63936. opacity = jlimit (0.0f, 1.0f, newOpacity);
  63937. }
  63938. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  63939. {
  63940. g.setOpacity (opacity);
  63941. g.drawImageAt (&image, 0, 0);
  63942. }
  63943. END_JUCE_NAMESPACE
  63944. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  63945. /********* Start of inlined file: juce_Font.cpp *********/
  63946. BEGIN_JUCE_NAMESPACE
  63947. static const float minFontHeight = 0.1f;
  63948. static const float maxFontHeight = 10000.0f;
  63949. static const float defaultFontHeight = 14.0f;
  63950. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  63951. Font::Font() throw()
  63952. : typefaceName (defaultSans),
  63953. height (defaultFontHeight),
  63954. horizontalScale (1.0f),
  63955. kerning (0),
  63956. ascent (0),
  63957. styleFlags (Font::plain)
  63958. {
  63959. }
  63960. void Font::resetToDefaultState() throw()
  63961. {
  63962. typefaceName = defaultSans;
  63963. height = defaultFontHeight;
  63964. horizontalScale = 1.0f;
  63965. kerning = 0;
  63966. ascent = 0;
  63967. styleFlags = Font::plain;
  63968. typeface = 0;
  63969. }
  63970. Font::Font (const float fontHeight,
  63971. const int styleFlags_) throw()
  63972. : typefaceName (defaultSans),
  63973. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  63974. horizontalScale (1.0f),
  63975. kerning (0),
  63976. ascent (0),
  63977. styleFlags (styleFlags_)
  63978. {
  63979. }
  63980. Font::Font (const String& typefaceName_,
  63981. const float fontHeight,
  63982. const int styleFlags_) throw()
  63983. : typefaceName (typefaceName_),
  63984. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  63985. horizontalScale (1.0f),
  63986. kerning (0),
  63987. ascent (0),
  63988. styleFlags (styleFlags_)
  63989. {
  63990. }
  63991. Font::Font (const Font& other) throw()
  63992. : typefaceName (other.typefaceName),
  63993. height (other.height),
  63994. horizontalScale (other.horizontalScale),
  63995. kerning (other.kerning),
  63996. ascent (other.ascent),
  63997. styleFlags (other.styleFlags),
  63998. typeface (other.typeface)
  63999. {
  64000. }
  64001. const Font& Font::operator= (const Font& other) throw()
  64002. {
  64003. if (this != &other)
  64004. {
  64005. typefaceName = other.typefaceName;
  64006. height = other.height;
  64007. styleFlags = other.styleFlags;
  64008. horizontalScale = other.horizontalScale;
  64009. kerning = other.kerning;
  64010. ascent = other.ascent;
  64011. typeface = other.typeface;
  64012. }
  64013. return *this;
  64014. }
  64015. Font::~Font() throw()
  64016. {
  64017. }
  64018. Font::Font (const Typeface& face) throw()
  64019. : height (11.0f),
  64020. horizontalScale (1.0f),
  64021. kerning (0),
  64022. ascent (0),
  64023. styleFlags (plain)
  64024. {
  64025. typefaceName = face.getName();
  64026. setBold (face.isBold());
  64027. setItalic (face.isItalic());
  64028. typeface = new Typeface (face);
  64029. }
  64030. bool Font::operator== (const Font& other) const throw()
  64031. {
  64032. return height == other.height
  64033. && horizontalScale == other.horizontalScale
  64034. && kerning == other.kerning
  64035. && styleFlags == other.styleFlags
  64036. && typefaceName == other.typefaceName;
  64037. }
  64038. bool Font::operator!= (const Font& other) const throw()
  64039. {
  64040. return ! operator== (other);
  64041. }
  64042. void Font::setTypefaceName (const String& faceName) throw()
  64043. {
  64044. typefaceName = faceName;
  64045. typeface = 0;
  64046. ascent = 0;
  64047. }
  64048. void Font::initialiseDefaultFontNames() throw()
  64049. {
  64050. Font::getDefaultFontNames (defaultSans,
  64051. defaultSerif,
  64052. defaultFixed);
  64053. }
  64054. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  64055. {
  64056. defaultSans = String::empty;
  64057. defaultSerif = String::empty;
  64058. defaultFixed = String::empty;
  64059. fallbackFont = String::empty;
  64060. }
  64061. const String Font::getDefaultSansSerifFontName() throw()
  64062. {
  64063. return defaultSans;
  64064. }
  64065. const String Font::getDefaultSerifFontName() throw()
  64066. {
  64067. return defaultSerif;
  64068. }
  64069. const String Font::getDefaultMonospacedFontName() throw()
  64070. {
  64071. return defaultFixed;
  64072. }
  64073. void Font::setDefaultSansSerifFontName (const String& name) throw()
  64074. {
  64075. defaultSans = name;
  64076. }
  64077. const String Font::getFallbackFontName() throw()
  64078. {
  64079. return fallbackFont;
  64080. }
  64081. void Font::setFallbackFontName (const String& name) throw()
  64082. {
  64083. fallbackFont = name;
  64084. }
  64085. void Font::setHeight (float newHeight) throw()
  64086. {
  64087. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64088. }
  64089. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  64090. {
  64091. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  64092. horizontalScale *= (height / newHeight);
  64093. height = newHeight;
  64094. }
  64095. void Font::setStyleFlags (const int newFlags) throw()
  64096. {
  64097. if (styleFlags != newFlags)
  64098. {
  64099. styleFlags = newFlags;
  64100. typeface = 0;
  64101. ascent = 0;
  64102. }
  64103. }
  64104. void Font::setSizeAndStyle (const float newHeight,
  64105. const int newStyleFlags,
  64106. const float newHorizontalScale,
  64107. const float newKerningAmount) throw()
  64108. {
  64109. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64110. horizontalScale = newHorizontalScale;
  64111. kerning = newKerningAmount;
  64112. setStyleFlags (newStyleFlags);
  64113. }
  64114. void Font::setHorizontalScale (const float scaleFactor) throw()
  64115. {
  64116. horizontalScale = scaleFactor;
  64117. }
  64118. void Font::setExtraKerningFactor (const float extraKerning) throw()
  64119. {
  64120. kerning = extraKerning;
  64121. }
  64122. void Font::setBold (const bool shouldBeBold) throw()
  64123. {
  64124. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  64125. : (styleFlags & ~bold));
  64126. }
  64127. bool Font::isBold() const throw()
  64128. {
  64129. return (styleFlags & bold) != 0;
  64130. }
  64131. void Font::setItalic (const bool shouldBeItalic) throw()
  64132. {
  64133. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  64134. : (styleFlags & ~italic));
  64135. }
  64136. bool Font::isItalic() const throw()
  64137. {
  64138. return (styleFlags & italic) != 0;
  64139. }
  64140. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  64141. {
  64142. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  64143. : (styleFlags & ~underlined));
  64144. }
  64145. bool Font::isUnderlined() const throw()
  64146. {
  64147. return (styleFlags & underlined) != 0;
  64148. }
  64149. float Font::getAscent() const throw()
  64150. {
  64151. if (ascent == 0)
  64152. ascent = getTypeface()->getAscent();
  64153. return height * ascent;
  64154. }
  64155. float Font::getDescent() const throw()
  64156. {
  64157. return height - getAscent();
  64158. }
  64159. int Font::getStringWidth (const String& text) const throw()
  64160. {
  64161. return roundFloatToInt (getStringWidthFloat (text));
  64162. }
  64163. float Font::getStringWidthFloat (const String& text) const throw()
  64164. {
  64165. float x = 0.0f;
  64166. if (text.isNotEmpty())
  64167. {
  64168. Typeface* const typeface = getTypeface();
  64169. const juce_wchar* t = (const juce_wchar*) text;
  64170. do
  64171. {
  64172. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  64173. if (glyph != 0)
  64174. x += kerning + glyph->getHorizontalSpacing (*t);
  64175. }
  64176. while (*t != 0);
  64177. x *= height;
  64178. x *= horizontalScale;
  64179. }
  64180. return x;
  64181. }
  64182. Typeface* Font::getTypeface() const throw()
  64183. {
  64184. if (typeface == 0)
  64185. typeface = Typeface::getTypefaceFor (*this);
  64186. return typeface;
  64187. }
  64188. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  64189. {
  64190. const StringArray names (findAllTypefaceNames());
  64191. for (int i = 0; i < names.size(); ++i)
  64192. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  64193. }
  64194. END_JUCE_NAMESPACE
  64195. /********* End of inlined file: juce_Font.cpp *********/
  64196. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  64197. BEGIN_JUCE_NAMESPACE
  64198. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  64199. class FontGlyphAlphaMap
  64200. {
  64201. public:
  64202. bool draw (const Graphics& g, float x, const float y) const throw()
  64203. {
  64204. if (bitmap1 == 0)
  64205. return false;
  64206. x += xOrigin;
  64207. const float xFloor = floorf (x);
  64208. const int intX = (int) xFloor;
  64209. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  64210. intX, (int) floorf (y + yOrigin), true);
  64211. return true;
  64212. }
  64213. juce_UseDebuggingNewOperator
  64214. private:
  64215. Image* bitmap1;
  64216. Image* bitmap2;
  64217. float xOrigin, yOrigin;
  64218. int lastAccessCount;
  64219. Typeface::Ptr typeface;
  64220. float height, horizontalScale;
  64221. juce_wchar character;
  64222. friend class GlyphCache;
  64223. FontGlyphAlphaMap() throw()
  64224. : bitmap1 (0),
  64225. bitmap2 (0),
  64226. lastAccessCount (0),
  64227. height (0),
  64228. horizontalScale (0),
  64229. character (0)
  64230. {
  64231. }
  64232. ~FontGlyphAlphaMap() throw()
  64233. {
  64234. delete bitmap1;
  64235. delete bitmap2;
  64236. }
  64237. class AlphaBitmapRenderer
  64238. {
  64239. uint8* const data;
  64240. const int stride;
  64241. uint8* lineStart;
  64242. uint8 gammaTable [256];
  64243. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  64244. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  64245. public:
  64246. AlphaBitmapRenderer (uint8* const data_,
  64247. const int stride_) throw()
  64248. : data (data_),
  64249. stride (stride_)
  64250. {
  64251. for (int i = 0; i < 256; ++i)
  64252. gammaTable[i] = (uint8) (255.0f * powf (i * (1.0f / 255.0f), 1.2f));
  64253. }
  64254. forcedinline void setEdgeTableYPos (const int y) throw()
  64255. {
  64256. lineStart = data + (stride * y);
  64257. }
  64258. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  64259. {
  64260. lineStart [x] = (uint8) gammaTable [alphaLevel];
  64261. }
  64262. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  64263. {
  64264. uint8* d = lineStart + x;
  64265. while (--width >= 0)
  64266. *d++ = (uint8) gammaTable [alphaLevel];
  64267. }
  64268. };
  64269. Image* createAlphaMapFromPath (const Path& path,
  64270. float& topLeftX, float& topLeftY,
  64271. float xScale, float yScale,
  64272. const float subPixelOffsetX) throw()
  64273. {
  64274. Image* im = 0;
  64275. float px, py, pw, ph;
  64276. path.getBounds (px, py, pw, ph);
  64277. topLeftX = floorf (px * xScale);
  64278. topLeftY = floorf (py * yScale);
  64279. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  64280. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  64281. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  64282. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_32times);
  64283. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  64284. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  64285. int stride, pixelStride;
  64286. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  64287. jassert (pixelStride == 1);
  64288. AlphaBitmapRenderer renderer (pixels, stride);
  64289. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  64290. im->releasePixelDataReadWrite (pixels);
  64291. return im;
  64292. }
  64293. void generate (Typeface* const face,
  64294. const juce_wchar character_,
  64295. const float fontHeight,
  64296. const float fontHorizontalScale) throw()
  64297. {
  64298. character = character_;
  64299. typeface = face;
  64300. height = fontHeight;
  64301. horizontalScale = fontHorizontalScale;
  64302. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  64303. deleteAndZero (bitmap1);
  64304. deleteAndZero (bitmap2);
  64305. const float fontHScale = fontHeight * fontHorizontalScale;
  64306. if (glyphPath != 0 && ! glyphPath->isEmpty())
  64307. {
  64308. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  64309. if (fontHScale < 24.0f)
  64310. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  64311. }
  64312. else
  64313. {
  64314. xOrigin = yOrigin = 0;
  64315. }
  64316. }
  64317. };
  64318. static const int defaultNumGlyphsToCache = 120;
  64319. class GlyphCache;
  64320. static GlyphCache* cacheInstance = 0;
  64321. class GlyphCache : private DeletedAtShutdown
  64322. {
  64323. public:
  64324. static GlyphCache* getInstance() throw()
  64325. {
  64326. if (cacheInstance == 0)
  64327. cacheInstance = new GlyphCache();
  64328. return cacheInstance;
  64329. }
  64330. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  64331. const float fontHeight,
  64332. const float fontHorizontalScale,
  64333. const juce_wchar character) throw()
  64334. {
  64335. ++accessCounter;
  64336. int oldestCounter = INT_MAX;
  64337. int oldestIndex = 0;
  64338. for (int i = numGlyphs; --i >= 0;)
  64339. {
  64340. FontGlyphAlphaMap& g = glyphs[i];
  64341. if (g.character == character
  64342. && g.height == fontHeight
  64343. && g.typeface->hashCode() == typeface->hashCode()
  64344. && g.horizontalScale == fontHorizontalScale)
  64345. {
  64346. g.lastAccessCount = accessCounter;
  64347. ++hits;
  64348. return g;
  64349. }
  64350. if (oldestCounter > g.lastAccessCount)
  64351. {
  64352. oldestCounter = g.lastAccessCount;
  64353. oldestIndex = i;
  64354. }
  64355. }
  64356. ++misses;
  64357. if (hits + misses > (numGlyphs << 4))
  64358. {
  64359. if (misses * 2 > hits)
  64360. setCacheSize (numGlyphs + 32);
  64361. hits = 0;
  64362. misses = 0;
  64363. oldestIndex = 0;
  64364. }
  64365. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  64366. oldest.lastAccessCount = accessCounter;
  64367. oldest.generate (typeface,
  64368. character,
  64369. fontHeight,
  64370. fontHorizontalScale);
  64371. return oldest;
  64372. }
  64373. void setCacheSize (const int num) throw()
  64374. {
  64375. if (numGlyphs != num)
  64376. {
  64377. numGlyphs = num;
  64378. if (glyphs != 0)
  64379. delete[] glyphs;
  64380. glyphs = new FontGlyphAlphaMap [numGlyphs];
  64381. hits = 0;
  64382. misses = 0;
  64383. }
  64384. }
  64385. juce_UseDebuggingNewOperator
  64386. private:
  64387. FontGlyphAlphaMap* glyphs;
  64388. int numGlyphs, accessCounter;
  64389. int hits, misses;
  64390. GlyphCache() throw()
  64391. : glyphs (0),
  64392. numGlyphs (0),
  64393. accessCounter (0)
  64394. {
  64395. setCacheSize (defaultNumGlyphsToCache);
  64396. }
  64397. ~GlyphCache() throw()
  64398. {
  64399. delete[] glyphs;
  64400. jassert (cacheInstance == this);
  64401. cacheInstance = 0;
  64402. }
  64403. GlyphCache (const GlyphCache&);
  64404. const GlyphCache& operator= (const GlyphCache&);
  64405. };
  64406. PositionedGlyph::PositionedGlyph() throw()
  64407. {
  64408. }
  64409. void PositionedGlyph::draw (const Graphics& g) const throw()
  64410. {
  64411. if (! glyphInfo->isWhitespace())
  64412. {
  64413. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  64414. {
  64415. const FontGlyphAlphaMap& alphaMap
  64416. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  64417. fontHeight,
  64418. fontHorizontalScale,
  64419. getCharacter());
  64420. alphaMap.draw (g, x, y);
  64421. }
  64422. else
  64423. {
  64424. // that's a bit of a dodgy size, isn't it??
  64425. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  64426. draw (g, AffineTransform::identity);
  64427. }
  64428. }
  64429. }
  64430. void PositionedGlyph::draw (const Graphics& g,
  64431. const AffineTransform& transform) const throw()
  64432. {
  64433. if (! glyphInfo->isWhitespace())
  64434. {
  64435. g.fillPath (glyphInfo->getPath(),
  64436. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  64437. .translated (x, y)
  64438. .followedBy (transform));
  64439. }
  64440. }
  64441. void PositionedGlyph::createPath (Path& path) const throw()
  64442. {
  64443. if (! glyphInfo->isWhitespace())
  64444. {
  64445. path.addPath (glyphInfo->getPath(),
  64446. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  64447. .translated (x, y));
  64448. }
  64449. }
  64450. bool PositionedGlyph::hitTest (float px, float py) const throw()
  64451. {
  64452. if (px >= getLeft() && px < getRight()
  64453. && py >= getTop() && py < getBottom()
  64454. && fontHeight > 0.0f
  64455. && ! glyphInfo->isWhitespace())
  64456. {
  64457. AffineTransform::translation (-x, -y)
  64458. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  64459. .transformPoint (px, py);
  64460. return glyphInfo->getPath().contains (px, py);
  64461. }
  64462. return false;
  64463. }
  64464. void PositionedGlyph::moveBy (const float deltaX,
  64465. const float deltaY) throw()
  64466. {
  64467. x += deltaX;
  64468. y += deltaY;
  64469. }
  64470. GlyphArrangement::GlyphArrangement() throw()
  64471. : numGlyphs (0),
  64472. numAllocated (0),
  64473. glyphs (0)
  64474. {
  64475. }
  64476. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  64477. : numGlyphs (0),
  64478. numAllocated (0),
  64479. glyphs (0)
  64480. {
  64481. addGlyphArrangement (other);
  64482. }
  64483. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  64484. {
  64485. if (this != &other)
  64486. {
  64487. clear();
  64488. addGlyphArrangement (other);
  64489. }
  64490. return *this;
  64491. }
  64492. GlyphArrangement::~GlyphArrangement() throw()
  64493. {
  64494. clear();
  64495. juce_free (glyphs);
  64496. }
  64497. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  64498. {
  64499. if (numAllocated <= minGlyphs)
  64500. {
  64501. numAllocated = minGlyphs + 2;
  64502. if (glyphs == 0)
  64503. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  64504. else
  64505. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  64506. }
  64507. }
  64508. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  64509. {
  64510. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  64511. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  64512. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  64513. }
  64514. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  64515. {
  64516. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  64517. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  64518. }
  64519. void GlyphArrangement::clear() throw()
  64520. {
  64521. for (int i = numGlyphs; --i >= 0;)
  64522. decGlyphRefCount (i);
  64523. numGlyphs = 0;
  64524. }
  64525. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  64526. {
  64527. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  64528. return glyphs [index];
  64529. }
  64530. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  64531. {
  64532. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  64533. memcpy (glyphs + numGlyphs, other.glyphs,
  64534. other.numGlyphs * sizeof (PositionedGlyph));
  64535. for (int i = other.numGlyphs; --i >= 0;)
  64536. incGlyphRefCount (numGlyphs++);
  64537. }
  64538. void GlyphArrangement::removeLast() throw()
  64539. {
  64540. if (numGlyphs > 0)
  64541. decGlyphRefCount (--numGlyphs);
  64542. }
  64543. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  64544. {
  64545. jassert (startIndex >= 0);
  64546. if (startIndex < 0)
  64547. startIndex = 0;
  64548. if (num < 0 || startIndex + num >= numGlyphs)
  64549. {
  64550. while (numGlyphs > startIndex)
  64551. removeLast();
  64552. }
  64553. else if (num > 0)
  64554. {
  64555. int i;
  64556. for (i = startIndex; i < startIndex + num; ++i)
  64557. decGlyphRefCount (i);
  64558. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  64559. {
  64560. glyphs [startIndex] = glyphs [startIndex + num];
  64561. ++startIndex;
  64562. }
  64563. numGlyphs -= num;
  64564. }
  64565. }
  64566. void GlyphArrangement::addLineOfText (const Font& font,
  64567. const String& text,
  64568. const float xOffset,
  64569. const float yOffset) throw()
  64570. {
  64571. addCurtailedLineOfText (font, text,
  64572. xOffset, yOffset,
  64573. 1.0e10f, false);
  64574. }
  64575. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  64576. const String& text,
  64577. float xOffset,
  64578. const float yOffset,
  64579. const float maxWidthPixels,
  64580. const bool useEllipsis) throw()
  64581. {
  64582. const int textLen = text.length();
  64583. if (textLen > 0)
  64584. {
  64585. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  64586. Typeface* const typeface = font.getTypeface();
  64587. const float fontHeight = font.getHeight();
  64588. const float ascent = font.getAscent();
  64589. const float fontHorizontalScale = font.getHorizontalScale();
  64590. const float heightTimesScale = fontHorizontalScale * fontHeight;
  64591. const float kerningFactor = font.getExtraKerningFactor();
  64592. const float startX = xOffset;
  64593. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  64594. for (int i = 0; i < textLen; ++i)
  64595. {
  64596. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  64597. if (glyph != 0)
  64598. {
  64599. jassert (numAllocated > numGlyphs);
  64600. ensureNumGlyphsAllocated (numGlyphs);
  64601. PositionedGlyph& pg = glyphs [numGlyphs];
  64602. pg.glyphInfo = glyph;
  64603. pg.x = xOffset;
  64604. pg.y = yOffset;
  64605. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  64606. pg.fontHeight = fontHeight;
  64607. pg.fontAscent = ascent;
  64608. pg.fontHorizontalScale = fontHorizontalScale;
  64609. pg.isUnderlined = font.isUnderlined();
  64610. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  64611. if (xOffset - startX > maxWidthPixels + 1.0f)
  64612. {
  64613. // curtail the string if it's too wide..
  64614. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  64615. appendEllipsis (font, startX + maxWidthPixels);
  64616. break;
  64617. }
  64618. else
  64619. {
  64620. if (glyph->getTypeface() != 0)
  64621. glyph->getTypeface()->incReferenceCount();
  64622. ++numGlyphs;
  64623. }
  64624. }
  64625. }
  64626. }
  64627. }
  64628. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  64629. {
  64630. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  64631. if (dotGlyph != 0)
  64632. {
  64633. if (numGlyphs > 0)
  64634. {
  64635. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  64636. const float fontHeight = glyph.fontHeight;
  64637. const float fontHorizontalScale = glyph.fontHorizontalScale;
  64638. const float fontAscent = glyph.fontAscent;
  64639. const float dx = fontHeight * fontHorizontalScale
  64640. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  64641. float xOffset = 0.0f, yOffset = 0.0f;
  64642. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  64643. {
  64644. removeLast();
  64645. jassert (numAllocated > numGlyphs);
  64646. PositionedGlyph& pg = glyphs [numGlyphs];
  64647. xOffset = pg.x;
  64648. yOffset = pg.y;
  64649. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  64650. break;
  64651. }
  64652. for (int i = 3; --i >= 0;)
  64653. {
  64654. jassert (numAllocated > numGlyphs);
  64655. ensureNumGlyphsAllocated (numGlyphs);
  64656. PositionedGlyph& pg = glyphs [numGlyphs];
  64657. pg.glyphInfo = dotGlyph;
  64658. pg.x = xOffset;
  64659. pg.y = yOffset;
  64660. pg.w = dx;
  64661. pg.fontHeight = fontHeight;
  64662. pg.fontAscent = fontAscent;
  64663. pg.fontHorizontalScale = fontHorizontalScale;
  64664. pg.isUnderlined = font.isUnderlined();
  64665. xOffset += dx;
  64666. if (dotGlyph->getTypeface() != 0)
  64667. dotGlyph->getTypeface()->incReferenceCount();
  64668. ++numGlyphs;
  64669. }
  64670. }
  64671. }
  64672. }
  64673. void GlyphArrangement::addJustifiedText (const Font& font,
  64674. const String& text,
  64675. float x, float y,
  64676. const float maxLineWidth,
  64677. const Justification& horizontalLayout) throw()
  64678. {
  64679. int lineStartIndex = numGlyphs;
  64680. addLineOfText (font, text, x, y);
  64681. const float originalY = y;
  64682. while (lineStartIndex < numGlyphs)
  64683. {
  64684. int i = lineStartIndex;
  64685. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  64686. ++i;
  64687. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  64688. int lastWordBreakIndex = -1;
  64689. while (i < numGlyphs)
  64690. {
  64691. PositionedGlyph& pg = glyphs[i];
  64692. const juce_wchar c = pg.getCharacter();
  64693. if (c == T('\r') || c == T('\n'))
  64694. {
  64695. ++i;
  64696. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  64697. ++i;
  64698. break;
  64699. }
  64700. else if (pg.isWhitespace())
  64701. {
  64702. lastWordBreakIndex = i + 1;
  64703. }
  64704. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  64705. {
  64706. if (lastWordBreakIndex >= 0)
  64707. i = lastWordBreakIndex;
  64708. break;
  64709. }
  64710. ++i;
  64711. }
  64712. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  64713. float currentLineEndX = currentLineStartX;
  64714. for (int j = i; --j >= lineStartIndex;)
  64715. {
  64716. if (! glyphs[j].isWhitespace())
  64717. {
  64718. currentLineEndX = glyphs[j].getRight();
  64719. break;
  64720. }
  64721. }
  64722. float deltaX = 0.0f;
  64723. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  64724. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  64725. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  64726. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  64727. else if (horizontalLayout.testFlags (Justification::right))
  64728. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  64729. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  64730. x + deltaX - currentLineStartX, y - originalY);
  64731. lineStartIndex = i;
  64732. y += font.getHeight();
  64733. }
  64734. }
  64735. void GlyphArrangement::addFittedText (const Font& f,
  64736. const String& text,
  64737. float x, float y,
  64738. float width, float height,
  64739. const Justification& layout,
  64740. int maximumLines,
  64741. const float minimumHorizontalScale) throw()
  64742. {
  64743. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  64744. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  64745. if (text.containsAnyOf (T("\r\n")))
  64746. {
  64747. GlyphArrangement ga;
  64748. ga.addJustifiedText (f, text, x, y, width, layout);
  64749. float l, t, r, b;
  64750. ga.getBoundingBox (0, -1, l, t, r, b, false);
  64751. float dy = y - t;
  64752. if (layout.testFlags (Justification::verticallyCentred))
  64753. dy += (height - (b - t)) * 0.5f;
  64754. else if (layout.testFlags (Justification::bottom))
  64755. dy += height - (b - t);
  64756. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  64757. addGlyphArrangement (ga);
  64758. return;
  64759. }
  64760. int startIndex = numGlyphs;
  64761. addLineOfText (f, text.trim(), x, y);
  64762. if (numGlyphs > startIndex)
  64763. {
  64764. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  64765. if (lineWidth <= 0)
  64766. return;
  64767. if (lineWidth * minimumHorizontalScale < width)
  64768. {
  64769. if (lineWidth > width)
  64770. {
  64771. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  64772. width / lineWidth);
  64773. }
  64774. justifyGlyphs (startIndex, numGlyphs - startIndex,
  64775. x, y, width, height, layout);
  64776. }
  64777. else if (maximumLines <= 1)
  64778. {
  64779. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  64780. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  64781. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  64782. removeLast();
  64783. appendEllipsis (f, x + width);
  64784. justifyGlyphs (startIndex, numGlyphs - startIndex,
  64785. x, y, width, height, layout);
  64786. }
  64787. else
  64788. {
  64789. Font font (f);
  64790. String txt (text.trim());
  64791. const int length = txt.length();
  64792. int numLines = 1;
  64793. const int originalStartIndex = startIndex;
  64794. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  64795. maximumLines = 1;
  64796. maximumLines = jmin (maximumLines, length);
  64797. while (numLines < maximumLines)
  64798. {
  64799. ++numLines;
  64800. const float newFontHeight = height / (float)numLines;
  64801. if (newFontHeight < 8.0f)
  64802. break;
  64803. if (newFontHeight < font.getHeight())
  64804. {
  64805. font.setHeight (newFontHeight);
  64806. while (numGlyphs > startIndex)
  64807. removeLast();
  64808. addLineOfText (font, txt, x, y);
  64809. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  64810. }
  64811. if (numLines > lineWidth / width)
  64812. break;
  64813. }
  64814. if (numLines < 1)
  64815. numLines = 1;
  64816. float lineY = y;
  64817. float widthPerLine = lineWidth / numLines;
  64818. int lastLineStartIndex = 0;
  64819. for (int line = 0; line < numLines; ++line)
  64820. {
  64821. int i = startIndex;
  64822. lastLineStartIndex = i;
  64823. float lineStartX = glyphs[startIndex].getLeft();
  64824. while (i < numGlyphs)
  64825. {
  64826. lineWidth = (glyphs[i].getRight() - lineStartX);
  64827. if (lineWidth > widthPerLine)
  64828. {
  64829. // got to a point where the line's too long, so skip forward to find a
  64830. // good place to break it..
  64831. const int searchStartIndex = i;
  64832. while (i < numGlyphs)
  64833. {
  64834. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  64835. {
  64836. if (glyphs[i].isWhitespace()
  64837. || glyphs[i].getCharacter() == T('-'))
  64838. {
  64839. ++i;
  64840. break;
  64841. }
  64842. }
  64843. else
  64844. {
  64845. // can't find a suitable break, so try looking backwards..
  64846. i = searchStartIndex;
  64847. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  64848. {
  64849. if (glyphs[i - back].isWhitespace()
  64850. || glyphs[i - back].getCharacter() == T('-'))
  64851. {
  64852. i -= back - 1;
  64853. break;
  64854. }
  64855. }
  64856. break;
  64857. }
  64858. ++i;
  64859. }
  64860. break;
  64861. }
  64862. ++i;
  64863. }
  64864. int wsStart = i;
  64865. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  64866. --wsStart;
  64867. int wsEnd = i;
  64868. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  64869. ++wsEnd;
  64870. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  64871. i = jmax (wsStart, startIndex + 1);
  64872. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  64873. if (lineWidth > width)
  64874. {
  64875. stretchRangeOfGlyphs (startIndex, i - startIndex,
  64876. width / lineWidth);
  64877. }
  64878. justifyGlyphs (startIndex, i - startIndex,
  64879. x, lineY, width, font.getHeight(),
  64880. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  64881. startIndex = i;
  64882. lineY += font.getHeight();
  64883. if (startIndex >= numGlyphs)
  64884. break;
  64885. }
  64886. if (startIndex < numGlyphs)
  64887. {
  64888. while (numGlyphs > startIndex)
  64889. removeLast();
  64890. if (startIndex - originalStartIndex > 4)
  64891. {
  64892. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  64893. appendEllipsis (font, lineStartX + width);
  64894. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  64895. if (lineWidth > width)
  64896. {
  64897. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  64898. width / lineWidth);
  64899. }
  64900. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  64901. x, lineY - font.getHeight(), width, font.getHeight(),
  64902. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  64903. }
  64904. startIndex = numGlyphs;
  64905. }
  64906. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  64907. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  64908. }
  64909. }
  64910. }
  64911. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  64912. const float dx, const float dy) throw()
  64913. {
  64914. jassert (startIndex >= 0);
  64915. if (dx != 0.0f || dy != 0.0f)
  64916. {
  64917. if (num < 0 || startIndex + num > numGlyphs)
  64918. num = numGlyphs - startIndex;
  64919. while (--num >= 0)
  64920. {
  64921. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  64922. glyphs [startIndex++].moveBy (dx, dy);
  64923. }
  64924. }
  64925. }
  64926. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  64927. const float horizontalScaleFactor) throw()
  64928. {
  64929. jassert (startIndex >= 0);
  64930. if (num < 0 || startIndex + num > numGlyphs)
  64931. num = numGlyphs - startIndex;
  64932. if (num > 0)
  64933. {
  64934. const float xAnchor = glyphs[startIndex].getLeft();
  64935. while (--num >= 0)
  64936. {
  64937. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  64938. PositionedGlyph& pg = glyphs[startIndex++];
  64939. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  64940. pg.fontHorizontalScale *= horizontalScaleFactor;
  64941. pg.w *= horizontalScaleFactor;
  64942. }
  64943. }
  64944. }
  64945. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  64946. float& left,
  64947. float& top,
  64948. float& right,
  64949. float& bottom,
  64950. const bool includeWhitespace) const throw()
  64951. {
  64952. jassert (startIndex >= 0);
  64953. if (num < 0 || startIndex + num > numGlyphs)
  64954. num = numGlyphs - startIndex;
  64955. left = 0.0f;
  64956. top = 0.0f;
  64957. right = 0.0f;
  64958. bottom = 0.0f;
  64959. bool isFirst = true;
  64960. while (--num >= 0)
  64961. {
  64962. const PositionedGlyph& pg = glyphs [startIndex++];
  64963. if (includeWhitespace || ! pg.isWhitespace())
  64964. {
  64965. if (isFirst)
  64966. {
  64967. isFirst = false;
  64968. left = pg.getLeft();
  64969. top = pg.getTop();
  64970. right = pg.getRight();
  64971. bottom = pg.getBottom();
  64972. }
  64973. else
  64974. {
  64975. left = jmin (left, pg.getLeft());
  64976. top = jmin (top, pg.getTop());
  64977. right = jmax (right, pg.getRight());
  64978. bottom = jmax (bottom, pg.getBottom());
  64979. }
  64980. }
  64981. }
  64982. }
  64983. void GlyphArrangement::justifyGlyphs (const int startIndex,
  64984. const int num,
  64985. const float x, const float y,
  64986. const float width, const float height,
  64987. const Justification& justification) throw()
  64988. {
  64989. jassert (num >= 0 && startIndex >= 0);
  64990. if (numGlyphs > 0 && num > 0)
  64991. {
  64992. float left, top, right, bottom;
  64993. getBoundingBox (startIndex, num, left, top, right, bottom,
  64994. ! justification.testFlags (Justification::horizontallyJustified
  64995. | Justification::horizontallyCentred));
  64996. float deltaX = 0.0f;
  64997. if (justification.testFlags (Justification::horizontallyJustified))
  64998. deltaX = x - left;
  64999. else if (justification.testFlags (Justification::horizontallyCentred))
  65000. deltaX = x + (width - (right - left)) * 0.5f - left;
  65001. else if (justification.testFlags (Justification::right))
  65002. deltaX = (x + width) - right;
  65003. else
  65004. deltaX = x - left;
  65005. float deltaY = 0.0f;
  65006. if (justification.testFlags (Justification::top))
  65007. deltaY = y - top;
  65008. else if (justification.testFlags (Justification::bottom))
  65009. deltaY = (y + height) - bottom;
  65010. else
  65011. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  65012. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  65013. if (justification.testFlags (Justification::horizontallyJustified))
  65014. {
  65015. int lineStart = 0;
  65016. float baseY = glyphs [startIndex].getBaselineY();
  65017. int i;
  65018. for (i = 0; i < num; ++i)
  65019. {
  65020. const float glyphY = glyphs [startIndex + i].getBaselineY();
  65021. if (glyphY != baseY)
  65022. {
  65023. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65024. lineStart = i;
  65025. baseY = glyphY;
  65026. }
  65027. }
  65028. if (i > lineStart)
  65029. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65030. }
  65031. }
  65032. }
  65033. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  65034. {
  65035. if (start + num < numGlyphs
  65036. && glyphs [start + num - 1].getCharacter() != T('\r')
  65037. && glyphs [start + num - 1].getCharacter() != T('\n'))
  65038. {
  65039. int numSpaces = 0;
  65040. int spacesAtEnd = 0;
  65041. for (int i = 0; i < num; ++i)
  65042. {
  65043. if (glyphs [start + i].isWhitespace())
  65044. {
  65045. ++spacesAtEnd;
  65046. ++numSpaces;
  65047. }
  65048. else
  65049. {
  65050. spacesAtEnd = 0;
  65051. }
  65052. }
  65053. numSpaces -= spacesAtEnd;
  65054. if (numSpaces > 0)
  65055. {
  65056. const float startX = glyphs [start].getLeft();
  65057. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  65058. const float extraPaddingBetweenWords
  65059. = (targetWidth - (endX - startX)) / (float) numSpaces;
  65060. float deltaX = 0.0f;
  65061. for (int i = 0; i < num; ++i)
  65062. {
  65063. glyphs [start + i].moveBy (deltaX, 0.0);
  65064. if (glyphs [start + i].isWhitespace())
  65065. deltaX += extraPaddingBetweenWords;
  65066. }
  65067. }
  65068. }
  65069. }
  65070. void GlyphArrangement::draw (const Graphics& g) const throw()
  65071. {
  65072. for (int i = 0; i < numGlyphs; ++i)
  65073. {
  65074. glyphs[i].draw (g);
  65075. if (glyphs[i].isUnderlined)
  65076. {
  65077. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65078. juce_wchar nextChar = 0;
  65079. if (i < numGlyphs - 1
  65080. && glyphs[i + 1].y == glyphs[i].y)
  65081. {
  65082. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65083. }
  65084. g.fillRect (glyphs[i].x,
  65085. glyphs[i].y + lineThickness * 2.0f,
  65086. glyphs[i].fontHeight
  65087. * glyphs[i].fontHorizontalScale
  65088. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65089. lineThickness);
  65090. }
  65091. }
  65092. }
  65093. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  65094. {
  65095. for (int i = 0; i < numGlyphs; ++i)
  65096. {
  65097. glyphs[i].draw (g, transform);
  65098. if (glyphs[i].isUnderlined)
  65099. {
  65100. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65101. juce_wchar nextChar = 0;
  65102. if (i < numGlyphs - 1
  65103. && glyphs[i + 1].y == glyphs[i].y)
  65104. {
  65105. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65106. }
  65107. Path p;
  65108. p.addLineSegment (glyphs[i].x,
  65109. glyphs[i].y + lineThickness * 2.5f,
  65110. glyphs[i].x + glyphs[i].fontHeight
  65111. * glyphs[i].fontHorizontalScale
  65112. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65113. glyphs[i].y + lineThickness * 2.5f,
  65114. lineThickness);
  65115. g.fillPath (p, transform);
  65116. }
  65117. }
  65118. }
  65119. void GlyphArrangement::createPath (Path& path) const throw()
  65120. {
  65121. for (int i = 0; i < numGlyphs; ++i)
  65122. glyphs[i].createPath (path);
  65123. }
  65124. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  65125. {
  65126. for (int i = 0; i < numGlyphs; ++i)
  65127. if (glyphs[i].hitTest (x, y))
  65128. return i;
  65129. return -1;
  65130. }
  65131. END_JUCE_NAMESPACE
  65132. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  65133. /********* Start of inlined file: juce_TextLayout.cpp *********/
  65134. BEGIN_JUCE_NAMESPACE
  65135. class TextLayoutToken
  65136. {
  65137. public:
  65138. String text;
  65139. Font font;
  65140. int x, y, w, h;
  65141. int line, lineHeight;
  65142. bool isWhitespace, isNewLine;
  65143. TextLayoutToken (const String& t,
  65144. const Font& f,
  65145. const bool isWhitespace_) throw()
  65146. : text (t),
  65147. font (f),
  65148. x(0),
  65149. y(0),
  65150. isWhitespace (isWhitespace_)
  65151. {
  65152. w = font.getStringWidth (t);
  65153. h = roundFloatToInt (f.getHeight());
  65154. isNewLine = t.containsAnyOf (T("\r\n"));
  65155. }
  65156. TextLayoutToken (const TextLayoutToken& other) throw()
  65157. : text (other.text),
  65158. font (other.font),
  65159. x (other.x),
  65160. y (other.y),
  65161. w (other.w),
  65162. h (other.h),
  65163. line (other.line),
  65164. lineHeight (other.lineHeight),
  65165. isWhitespace (other.isWhitespace),
  65166. isNewLine (other.isNewLine)
  65167. {
  65168. }
  65169. ~TextLayoutToken() throw()
  65170. {
  65171. }
  65172. void draw (Graphics& g,
  65173. const int xOffset,
  65174. const int yOffset) throw()
  65175. {
  65176. if (! isWhitespace)
  65177. {
  65178. g.setFont (font);
  65179. g.drawSingleLineText (text.trimEnd(),
  65180. xOffset + x,
  65181. yOffset + y + (lineHeight - h)
  65182. + roundFloatToInt (font.getAscent()));
  65183. }
  65184. }
  65185. juce_UseDebuggingNewOperator
  65186. };
  65187. TextLayout::TextLayout() throw()
  65188. : tokens (64),
  65189. totalLines (0)
  65190. {
  65191. }
  65192. TextLayout::TextLayout (const String& text,
  65193. const Font& font) throw()
  65194. : tokens (64),
  65195. totalLines (0)
  65196. {
  65197. appendText (text, font);
  65198. }
  65199. TextLayout::TextLayout (const TextLayout& other) throw()
  65200. : tokens (64),
  65201. totalLines (0)
  65202. {
  65203. *this = other;
  65204. }
  65205. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  65206. {
  65207. if (this != &other)
  65208. {
  65209. clear();
  65210. totalLines = other.totalLines;
  65211. for (int i = 0; i < other.tokens.size(); ++i)
  65212. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  65213. }
  65214. return *this;
  65215. }
  65216. TextLayout::~TextLayout() throw()
  65217. {
  65218. clear();
  65219. }
  65220. void TextLayout::clear() throw()
  65221. {
  65222. for (int i = tokens.size(); --i >= 0;)
  65223. {
  65224. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65225. delete t;
  65226. }
  65227. tokens.clear();
  65228. totalLines = 0;
  65229. }
  65230. void TextLayout::appendText (const String& text,
  65231. const Font& font) throw()
  65232. {
  65233. const tchar* t = text;
  65234. String currentString;
  65235. int lastCharType = 0;
  65236. for (;;)
  65237. {
  65238. const tchar c = *t++;
  65239. if (c == 0)
  65240. break;
  65241. int charType;
  65242. if (c == T('\r') || c == T('\n'))
  65243. {
  65244. charType = 0;
  65245. }
  65246. else if (CharacterFunctions::isWhitespace (c))
  65247. {
  65248. charType = 2;
  65249. }
  65250. else
  65251. {
  65252. charType = 1;
  65253. }
  65254. if (charType == 0 || charType != lastCharType)
  65255. {
  65256. if (currentString.isNotEmpty())
  65257. {
  65258. tokens.add (new TextLayoutToken (currentString, font,
  65259. lastCharType == 2 || lastCharType == 0));
  65260. }
  65261. currentString = String::charToString (c);
  65262. if (c == T('\r') && *t == T('\n'))
  65263. currentString += *t++;
  65264. }
  65265. else
  65266. {
  65267. currentString += c;
  65268. }
  65269. lastCharType = charType;
  65270. }
  65271. if (currentString.isNotEmpty())
  65272. tokens.add (new TextLayoutToken (currentString,
  65273. font,
  65274. lastCharType == 2));
  65275. }
  65276. void TextLayout::setText (const String& text, const Font& font) throw()
  65277. {
  65278. clear();
  65279. appendText (text, font);
  65280. }
  65281. void TextLayout::layout (int maxWidth,
  65282. const Justification& justification,
  65283. const bool attemptToBalanceLineLengths) throw()
  65284. {
  65285. if (attemptToBalanceLineLengths)
  65286. {
  65287. const int originalW = maxWidth;
  65288. int bestWidth = maxWidth;
  65289. float bestLineProportion = 0.0f;
  65290. while (maxWidth > originalW / 2)
  65291. {
  65292. layout (maxWidth, justification, false);
  65293. if (getNumLines() <= 1)
  65294. return;
  65295. const int lastLineW = getLineWidth (getNumLines() - 1);
  65296. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  65297. const float prop = lastLineW / (float) lastButOneLineW;
  65298. if (prop > 0.9f)
  65299. return;
  65300. if (prop > bestLineProportion)
  65301. {
  65302. bestLineProportion = prop;
  65303. bestWidth = maxWidth;
  65304. }
  65305. maxWidth -= 10;
  65306. }
  65307. layout (bestWidth, justification, false);
  65308. }
  65309. else
  65310. {
  65311. int x = 0;
  65312. int y = 0;
  65313. int h = 0;
  65314. totalLines = 0;
  65315. int i;
  65316. for (i = 0; i < tokens.size(); ++i)
  65317. {
  65318. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65319. t->x = x;
  65320. t->y = y;
  65321. t->line = totalLines;
  65322. x += t->w;
  65323. h = jmax (h, t->h);
  65324. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  65325. if (nextTok == 0)
  65326. break;
  65327. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  65328. {
  65329. // finished a line, so go back and update the heights of the things on it
  65330. for (int j = i; j >= 0; --j)
  65331. {
  65332. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  65333. if (tok->line == totalLines)
  65334. tok->lineHeight = h;
  65335. else
  65336. break;
  65337. }
  65338. x = 0;
  65339. y += h;
  65340. h = 0;
  65341. ++totalLines;
  65342. }
  65343. }
  65344. // finished a line, so go back and update the heights of the things on it
  65345. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  65346. {
  65347. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  65348. if (t->line == totalLines)
  65349. t->lineHeight = h;
  65350. else
  65351. break;
  65352. }
  65353. ++totalLines;
  65354. if (! justification.testFlags (Justification::left))
  65355. {
  65356. int totalW = getWidth();
  65357. for (i = totalLines; --i >= 0;)
  65358. {
  65359. const int lineW = getLineWidth (i);
  65360. int dx = 0;
  65361. if (justification.testFlags (Justification::horizontallyCentred))
  65362. dx = (totalW - lineW) / 2;
  65363. else if (justification.testFlags (Justification::right))
  65364. dx = totalW - lineW;
  65365. for (int j = tokens.size(); --j >= 0;)
  65366. {
  65367. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  65368. if (t->line == i)
  65369. t->x += dx;
  65370. }
  65371. }
  65372. }
  65373. }
  65374. }
  65375. int TextLayout::getLineWidth (const int lineNumber) const throw()
  65376. {
  65377. int maxW = 0;
  65378. for (int i = tokens.size(); --i >= 0;)
  65379. {
  65380. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65381. if (t->line == lineNumber && ! t->isWhitespace)
  65382. maxW = jmax (maxW, t->x + t->w);
  65383. }
  65384. return maxW;
  65385. }
  65386. int TextLayout::getWidth() const throw()
  65387. {
  65388. int maxW = 0;
  65389. for (int i = tokens.size(); --i >= 0;)
  65390. {
  65391. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65392. if (! t->isWhitespace)
  65393. maxW = jmax (maxW, t->x + t->w);
  65394. }
  65395. return maxW;
  65396. }
  65397. int TextLayout::getHeight() const throw()
  65398. {
  65399. int maxH = 0;
  65400. for (int i = tokens.size(); --i >= 0;)
  65401. {
  65402. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65403. if (! t->isWhitespace)
  65404. maxH = jmax (maxH, t->y + t->h);
  65405. }
  65406. return maxH;
  65407. }
  65408. void TextLayout::draw (Graphics& g,
  65409. const int xOffset,
  65410. const int yOffset) const throw()
  65411. {
  65412. for (int i = tokens.size(); --i >= 0;)
  65413. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  65414. }
  65415. void TextLayout::drawWithin (Graphics& g,
  65416. int x, int y, int w, int h,
  65417. const Justification& justification) const throw()
  65418. {
  65419. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  65420. x, y, w, h);
  65421. draw (g, x, y);
  65422. }
  65423. END_JUCE_NAMESPACE
  65424. /********* End of inlined file: juce_TextLayout.cpp *********/
  65425. /********* Start of inlined file: juce_Typeface.cpp *********/
  65426. BEGIN_JUCE_NAMESPACE
  65427. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  65428. const Path& shape,
  65429. const float horizontalSeparation,
  65430. Typeface* const typeface_) throw()
  65431. : character (character_),
  65432. path (shape),
  65433. width (horizontalSeparation),
  65434. typeface (typeface_)
  65435. {
  65436. }
  65437. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  65438. {
  65439. }
  65440. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  65441. {
  65442. if (subsequentCharacter != 0)
  65443. {
  65444. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  65445. const int numPairs = getNumKerningPairs();
  65446. for (int i = 0; i < numPairs; ++i)
  65447. if (pairs [i].character2 == subsequentCharacter)
  65448. return width + pairs [i].kerningAmount;
  65449. }
  65450. return width;
  65451. }
  65452. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  65453. const float extraKerningAmount) throw()
  65454. {
  65455. const int numPairs = getNumKerningPairs();
  65456. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  65457. KerningPair& p = getKerningPair (numPairs);
  65458. p.character2 = subsequentCharacter;
  65459. p.kerningAmount = extraKerningAmount;
  65460. }
  65461. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  65462. {
  65463. return ((KerningPair*) kerningPairs.getData()) [index];
  65464. }
  65465. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  65466. {
  65467. return kerningPairs.getSize() / sizeof (KerningPair);
  65468. }
  65469. Typeface::Typeface() throw()
  65470. : hash (0),
  65471. isFullyPopulated (false)
  65472. {
  65473. zeromem (lookupTable, sizeof (lookupTable));
  65474. }
  65475. Typeface::Typeface (const Typeface& other)
  65476. : typefaceName (other.typefaceName),
  65477. ascent (other.ascent),
  65478. bold (other.bold),
  65479. italic (other.italic),
  65480. isFullyPopulated (other.isFullyPopulated),
  65481. defaultCharacter (other.defaultCharacter)
  65482. {
  65483. zeromem (lookupTable, sizeof (lookupTable));
  65484. for (int i = 0; i < other.glyphs.size(); ++i)
  65485. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  65486. updateHashCode();
  65487. }
  65488. Typeface::Typeface (const String& faceName,
  65489. const bool bold,
  65490. const bool italic)
  65491. : isFullyPopulated (false)
  65492. {
  65493. zeromem (lookupTable, sizeof (lookupTable));
  65494. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  65495. updateHashCode();
  65496. }
  65497. Typeface::~Typeface()
  65498. {
  65499. clear();
  65500. }
  65501. const Typeface& Typeface::operator= (const Typeface& other) throw()
  65502. {
  65503. if (this != &other)
  65504. {
  65505. clear();
  65506. typefaceName = other.typefaceName;
  65507. ascent = other.ascent;
  65508. bold = other.bold;
  65509. italic = other.italic;
  65510. isFullyPopulated = other.isFullyPopulated;
  65511. defaultCharacter = other.defaultCharacter;
  65512. for (int i = 0; i < other.glyphs.size(); ++i)
  65513. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  65514. updateHashCode();
  65515. }
  65516. return *this;
  65517. }
  65518. void Typeface::updateHashCode() throw()
  65519. {
  65520. hash = typefaceName.hashCode();
  65521. if (bold)
  65522. hash ^= 0xffff;
  65523. if (italic)
  65524. hash ^= 0xffff0000;
  65525. }
  65526. void Typeface::clear() throw()
  65527. {
  65528. zeromem (lookupTable, sizeof (lookupTable));
  65529. typefaceName = String::empty;
  65530. bold = false;
  65531. italic = false;
  65532. for (int i = glyphs.size(); --i >= 0;)
  65533. {
  65534. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  65535. delete g;
  65536. }
  65537. glyphs.clear();
  65538. updateHashCode();
  65539. }
  65540. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  65541. {
  65542. zeromem (lookupTable, sizeof (lookupTable));
  65543. isFullyPopulated = true;
  65544. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  65545. BufferedInputStream in (&gzin, 32768, false);
  65546. typefaceName = in.readString();
  65547. bold = in.readBool();
  65548. italic = in.readBool();
  65549. ascent = in.readFloat();
  65550. defaultCharacter = (juce_wchar) in.readShort();
  65551. int i, numChars = in.readInt();
  65552. for (i = 0; i < numChars; ++i)
  65553. {
  65554. const juce_wchar c = (juce_wchar) in.readShort();
  65555. const float width = in.readFloat();
  65556. Path p;
  65557. p.loadPathFromStream (in);
  65558. addGlyph (c, p, width);
  65559. }
  65560. const int numKerningPairs = in.readInt();
  65561. for (i = 0; i < numKerningPairs; ++i)
  65562. {
  65563. const juce_wchar char1 = (juce_wchar) in.readShort();
  65564. const juce_wchar char2 = (juce_wchar) in.readShort();
  65565. addKerningPair (char1, char2, in.readFloat());
  65566. }
  65567. updateHashCode();
  65568. }
  65569. void Typeface::serialise (OutputStream& outputStream)
  65570. {
  65571. GZIPCompressorOutputStream out (&outputStream);
  65572. out.writeString (typefaceName);
  65573. out.writeBool (bold);
  65574. out.writeBool (italic);
  65575. out.writeFloat (ascent);
  65576. out.writeShort ((short) (unsigned short) defaultCharacter);
  65577. out.writeInt (glyphs.size());
  65578. int i, numKerningPairs = 0;
  65579. for (i = 0; i < glyphs.size(); ++i)
  65580. {
  65581. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  65582. out.writeShort ((short) (unsigned short) g.character);
  65583. out.writeFloat (g.width);
  65584. g.path.writePathToStream (out);
  65585. numKerningPairs += g.getNumKerningPairs();
  65586. }
  65587. out.writeInt (numKerningPairs);
  65588. for (i = 0; i < glyphs.size(); ++i)
  65589. {
  65590. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  65591. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  65592. {
  65593. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  65594. out.writeShort ((short) (unsigned short) g.character);
  65595. out.writeShort ((short) (unsigned short) p.character2);
  65596. out.writeFloat (p.kerningAmount);
  65597. }
  65598. }
  65599. }
  65600. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  65601. {
  65602. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  65603. if (g != 0)
  65604. return &(g->path);
  65605. else
  65606. return 0;
  65607. }
  65608. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  65609. {
  65610. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  65611. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  65612. for (int i = 0; i < glyphs.size(); ++i)
  65613. {
  65614. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65615. if (g->character == character)
  65616. return g;
  65617. }
  65618. if ((! isFullyPopulated)
  65619. && findAndAddSystemGlyph (character))
  65620. {
  65621. for (int i = 0; i < glyphs.size(); ++i)
  65622. {
  65623. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65624. if (g->character == character)
  65625. return g;
  65626. }
  65627. }
  65628. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  65629. {
  65630. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  65631. if (spaceGlyph != 0)
  65632. {
  65633. // Add a copy of the empty glyph, mapped onto this character
  65634. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  65635. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  65636. }
  65637. return spaceGlyph;
  65638. }
  65639. else if (character != defaultCharacter)
  65640. {
  65641. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  65642. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  65643. if (fallbackTypeface != 0 && fallbackTypeface != this)
  65644. return fallbackTypeface->getGlyph (character);
  65645. return getGlyph (defaultCharacter);
  65646. }
  65647. return 0;
  65648. }
  65649. void Typeface::addGlyph (const juce_wchar character,
  65650. const Path& path,
  65651. const float horizontalSpacing) throw()
  65652. {
  65653. #ifdef JUCE_DEBUG
  65654. for (int i = 0; i < glyphs.size(); ++i)
  65655. {
  65656. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65657. if (g->character == character)
  65658. jassertfalse;
  65659. }
  65660. #endif
  65661. if (((unsigned int) character) < 128)
  65662. lookupTable [character] = (short) glyphs.size();
  65663. glyphs.add (new TypefaceGlyphInfo (character,
  65664. path,
  65665. horizontalSpacing,
  65666. this));
  65667. }
  65668. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  65669. {
  65670. if (glyphInfoToCopy != 0)
  65671. {
  65672. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  65673. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  65674. TypefaceGlyphInfo* const newOne
  65675. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  65676. glyphInfoToCopy->path,
  65677. glyphInfoToCopy->width,
  65678. this);
  65679. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  65680. glyphs.add (newOne);
  65681. }
  65682. }
  65683. void Typeface::addKerningPair (const juce_wchar char1,
  65684. const juce_wchar char2,
  65685. const float extraAmount) throw()
  65686. {
  65687. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  65688. if (g != 0)
  65689. g->addKerningPair (char2, extraAmount);
  65690. }
  65691. void Typeface::setName (const String& name) throw()
  65692. {
  65693. typefaceName = name;
  65694. updateHashCode();
  65695. }
  65696. void Typeface::setAscent (const float newAscent) throw()
  65697. {
  65698. ascent = newAscent;
  65699. }
  65700. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  65701. {
  65702. defaultCharacter = newDefaultCharacter;
  65703. }
  65704. void Typeface::setBold (const bool shouldBeBold) throw()
  65705. {
  65706. bold = shouldBeBold;
  65707. updateHashCode();
  65708. }
  65709. void Typeface::setItalic (const bool shouldBeItalic) throw()
  65710. {
  65711. italic = shouldBeItalic;
  65712. updateHashCode();
  65713. }
  65714. class TypefaceCache;
  65715. static TypefaceCache* typefaceCacheInstance = 0;
  65716. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  65717. class TypefaceCache : private DeletedAtShutdown
  65718. {
  65719. private:
  65720. struct CachedFace
  65721. {
  65722. CachedFace() throw()
  65723. : lastUsageCount (0),
  65724. flags (0)
  65725. {
  65726. }
  65727. String typefaceName;
  65728. int lastUsageCount;
  65729. int flags;
  65730. Typeface::Ptr typeFace;
  65731. };
  65732. int counter;
  65733. OwnedArray <CachedFace> faces;
  65734. TypefaceCache (const TypefaceCache&);
  65735. const TypefaceCache& operator= (const TypefaceCache&);
  65736. public:
  65737. TypefaceCache (int numToCache = 10)
  65738. : counter (1),
  65739. faces (2)
  65740. {
  65741. while (--numToCache >= 0)
  65742. {
  65743. CachedFace* const face = new CachedFace();
  65744. face->typeFace = new Typeface();
  65745. faces.add (face);
  65746. }
  65747. }
  65748. ~TypefaceCache()
  65749. {
  65750. faces.clear();
  65751. jassert (typefaceCacheInstance == this);
  65752. typefaceCacheInstance = 0;
  65753. // just a courtesy call to get avoid leaking these strings at shutdown
  65754. clearUpDefaultFontNames();
  65755. }
  65756. static TypefaceCache* getInstance() throw()
  65757. {
  65758. if (typefaceCacheInstance == 0)
  65759. typefaceCacheInstance = new TypefaceCache();
  65760. return typefaceCacheInstance;
  65761. }
  65762. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  65763. {
  65764. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  65765. int i;
  65766. for (i = faces.size(); --i >= 0;)
  65767. {
  65768. CachedFace* const face = faces.getUnchecked(i);
  65769. if (face->flags == flags
  65770. && face->typefaceName == font.getTypefaceName())
  65771. {
  65772. face->lastUsageCount = ++counter;
  65773. return face->typeFace;
  65774. }
  65775. }
  65776. int replaceIndex = 0;
  65777. int bestLastUsageCount = INT_MAX;
  65778. for (i = faces.size(); --i >= 0;)
  65779. {
  65780. const int lu = faces.getUnchecked(i)->lastUsageCount;
  65781. if (bestLastUsageCount > lu)
  65782. {
  65783. bestLastUsageCount = lu;
  65784. replaceIndex = i;
  65785. }
  65786. }
  65787. CachedFace* const face = faces.getUnchecked (replaceIndex);
  65788. face->typefaceName = font.getTypefaceName();
  65789. face->flags = flags;
  65790. face->lastUsageCount = ++counter;
  65791. face->typeFace = new Typeface (font.getTypefaceName(),
  65792. font.isBold(),
  65793. font.isItalic());
  65794. return face->typeFace;
  65795. }
  65796. };
  65797. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  65798. {
  65799. return TypefaceCache::getInstance()->findTypefaceFor (font);
  65800. }
  65801. END_JUCE_NAMESPACE
  65802. /********* End of inlined file: juce_Typeface.cpp *********/
  65803. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  65804. BEGIN_JUCE_NAMESPACE
  65805. AffineTransform::AffineTransform() throw()
  65806. : mat00 (1.0f),
  65807. mat01 (0),
  65808. mat02 (0),
  65809. mat10 (0),
  65810. mat11 (1.0f),
  65811. mat12 (0)
  65812. {
  65813. }
  65814. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  65815. : mat00 (other.mat00),
  65816. mat01 (other.mat01),
  65817. mat02 (other.mat02),
  65818. mat10 (other.mat10),
  65819. mat11 (other.mat11),
  65820. mat12 (other.mat12)
  65821. {
  65822. }
  65823. AffineTransform::AffineTransform (const float mat00_,
  65824. const float mat01_,
  65825. const float mat02_,
  65826. const float mat10_,
  65827. const float mat11_,
  65828. const float mat12_) throw()
  65829. : mat00 (mat00_),
  65830. mat01 (mat01_),
  65831. mat02 (mat02_),
  65832. mat10 (mat10_),
  65833. mat11 (mat11_),
  65834. mat12 (mat12_)
  65835. {
  65836. }
  65837. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  65838. {
  65839. mat00 = other.mat00;
  65840. mat01 = other.mat01;
  65841. mat02 = other.mat02;
  65842. mat10 = other.mat10;
  65843. mat11 = other.mat11;
  65844. mat12 = other.mat12;
  65845. return *this;
  65846. }
  65847. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  65848. {
  65849. return mat00 == other.mat00
  65850. && mat01 == other.mat01
  65851. && mat02 == other.mat02
  65852. && mat10 == other.mat10
  65853. && mat11 == other.mat11
  65854. && mat12 == other.mat12;
  65855. }
  65856. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  65857. {
  65858. return ! operator== (other);
  65859. }
  65860. bool AffineTransform::isIdentity() const throw()
  65861. {
  65862. return (mat01 == 0)
  65863. && (mat02 == 0)
  65864. && (mat10 == 0)
  65865. && (mat12 == 0)
  65866. && (mat00 == 1.0f)
  65867. && (mat11 == 1.0f);
  65868. }
  65869. const AffineTransform AffineTransform::identity;
  65870. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  65871. {
  65872. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  65873. other.mat00 * mat01 + other.mat01 * mat11,
  65874. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  65875. other.mat10 * mat00 + other.mat11 * mat10,
  65876. other.mat10 * mat01 + other.mat11 * mat11,
  65877. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  65878. }
  65879. const AffineTransform AffineTransform::followedBy (const float omat00,
  65880. const float omat01,
  65881. const float omat02,
  65882. const float omat10,
  65883. const float omat11,
  65884. const float omat12) const throw()
  65885. {
  65886. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  65887. omat00 * mat01 + omat01 * mat11,
  65888. omat00 * mat02 + omat01 * mat12 + omat02,
  65889. omat10 * mat00 + omat11 * mat10,
  65890. omat10 * mat01 + omat11 * mat11,
  65891. omat10 * mat02 + omat11 * mat12 + omat12);
  65892. }
  65893. const AffineTransform AffineTransform::translated (const float dx,
  65894. const float dy) const throw()
  65895. {
  65896. return followedBy (1.0f, 0, dx,
  65897. 0, 1.0f, dy);
  65898. }
  65899. const AffineTransform AffineTransform::translation (const float dx,
  65900. const float dy) throw()
  65901. {
  65902. return AffineTransform (1.0f, 0, dx,
  65903. 0, 1.0f, dy);
  65904. }
  65905. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  65906. {
  65907. const float cosRad = cosf (rad);
  65908. const float sinRad = sinf (rad);
  65909. return followedBy (cosRad, -sinRad, 0,
  65910. sinRad, cosRad, 0);
  65911. }
  65912. const AffineTransform AffineTransform::rotation (const float rad) throw()
  65913. {
  65914. const float cosRad = cosf (rad);
  65915. const float sinRad = sinf (rad);
  65916. return AffineTransform (cosRad, -sinRad, 0,
  65917. sinRad, cosRad, 0);
  65918. }
  65919. const AffineTransform AffineTransform::rotated (const float angle,
  65920. const float pivotX,
  65921. const float pivotY) const throw()
  65922. {
  65923. return translated (-pivotX, -pivotY)
  65924. .rotated (angle)
  65925. .translated (pivotX, pivotY);
  65926. }
  65927. const AffineTransform AffineTransform::rotation (const float angle,
  65928. const float pivotX,
  65929. const float pivotY) throw()
  65930. {
  65931. return translation (-pivotX, -pivotY)
  65932. .rotated (angle)
  65933. .translated (pivotX, pivotY);
  65934. }
  65935. const AffineTransform AffineTransform::scaled (const float factorX,
  65936. const float factorY) const throw()
  65937. {
  65938. return followedBy (factorX, 0, 0,
  65939. 0, factorY, 0);
  65940. }
  65941. const AffineTransform AffineTransform::scale (const float factorX,
  65942. const float factorY) throw()
  65943. {
  65944. return AffineTransform (factorX, 0, 0,
  65945. 0, factorY, 0);
  65946. }
  65947. const AffineTransform AffineTransform::sheared (const float shearX,
  65948. const float shearY) const throw()
  65949. {
  65950. return followedBy (1.0f, shearX, 0,
  65951. shearY, 1.0f, 0);
  65952. }
  65953. const AffineTransform AffineTransform::inverted() const throw()
  65954. {
  65955. double determinant = (mat00 * mat11 - mat10 * mat01);
  65956. if (determinant != 0.0)
  65957. {
  65958. determinant = 1.0 / determinant;
  65959. const float dst00 = (float) (mat11 * determinant);
  65960. const float dst10 = (float) (-mat10 * determinant);
  65961. const float dst01 = (float) (-mat01 * determinant);
  65962. const float dst11 = (float) (mat00 * determinant);
  65963. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  65964. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  65965. }
  65966. else
  65967. {
  65968. // singularity..
  65969. return *this;
  65970. }
  65971. }
  65972. bool AffineTransform::isSingularity() const throw()
  65973. {
  65974. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  65975. }
  65976. void AffineTransform::transformPoint (float& x,
  65977. float& y) const throw()
  65978. {
  65979. const float oldX = x;
  65980. x = mat00 * oldX + mat01 * y + mat02;
  65981. y = mat10 * oldX + mat11 * y + mat12;
  65982. }
  65983. void AffineTransform::transformPoint (double& x,
  65984. double& y) const throw()
  65985. {
  65986. const double oldX = x;
  65987. x = mat00 * oldX + mat01 * y + mat02;
  65988. y = mat10 * oldX + mat11 * y + mat12;
  65989. }
  65990. END_JUCE_NAMESPACE
  65991. /********* End of inlined file: juce_AffineTransform.cpp *********/
  65992. /********* Start of inlined file: juce_BorderSize.cpp *********/
  65993. BEGIN_JUCE_NAMESPACE
  65994. BorderSize::BorderSize() throw()
  65995. : top (0),
  65996. left (0),
  65997. bottom (0),
  65998. right (0)
  65999. {
  66000. }
  66001. BorderSize::BorderSize (const BorderSize& other) throw()
  66002. : top (other.top),
  66003. left (other.left),
  66004. bottom (other.bottom),
  66005. right (other.right)
  66006. {
  66007. }
  66008. BorderSize::BorderSize (const int topGap,
  66009. const int leftGap,
  66010. const int bottomGap,
  66011. const int rightGap) throw()
  66012. : top (topGap),
  66013. left (leftGap),
  66014. bottom (bottomGap),
  66015. right (rightGap)
  66016. {
  66017. }
  66018. BorderSize::BorderSize (const int allGaps) throw()
  66019. : top (allGaps),
  66020. left (allGaps),
  66021. bottom (allGaps),
  66022. right (allGaps)
  66023. {
  66024. }
  66025. BorderSize::~BorderSize() throw()
  66026. {
  66027. }
  66028. void BorderSize::setTop (const int newTopGap) throw()
  66029. {
  66030. top = newTopGap;
  66031. }
  66032. void BorderSize::setLeft (const int newLeftGap) throw()
  66033. {
  66034. left = newLeftGap;
  66035. }
  66036. void BorderSize::setBottom (const int newBottomGap) throw()
  66037. {
  66038. bottom = newBottomGap;
  66039. }
  66040. void BorderSize::setRight (const int newRightGap) throw()
  66041. {
  66042. right = newRightGap;
  66043. }
  66044. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  66045. {
  66046. return Rectangle (r.getX() + left,
  66047. r.getY() + top,
  66048. r.getWidth() - (left + right),
  66049. r.getHeight() - (top + bottom));
  66050. }
  66051. void BorderSize::subtractFrom (Rectangle& r) const throw()
  66052. {
  66053. r.setBounds (r.getX() + left,
  66054. r.getY() + top,
  66055. r.getWidth() - (left + right),
  66056. r.getHeight() - (top + bottom));
  66057. }
  66058. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  66059. {
  66060. return Rectangle (r.getX() - left,
  66061. r.getY() - top,
  66062. r.getWidth() + (left + right),
  66063. r.getHeight() + (top + bottom));
  66064. }
  66065. void BorderSize::addTo (Rectangle& r) const throw()
  66066. {
  66067. r.setBounds (r.getX() - left,
  66068. r.getY() - top,
  66069. r.getWidth() + (left + right),
  66070. r.getHeight() + (top + bottom));
  66071. }
  66072. bool BorderSize::operator== (const BorderSize& other) const throw()
  66073. {
  66074. return top == other.top
  66075. && left == other.left
  66076. && bottom == other.bottom
  66077. && right == other.right;
  66078. }
  66079. bool BorderSize::operator!= (const BorderSize& other) const throw()
  66080. {
  66081. return ! operator== (other);
  66082. }
  66083. END_JUCE_NAMESPACE
  66084. /********* End of inlined file: juce_BorderSize.cpp *********/
  66085. /********* Start of inlined file: juce_Line.cpp *********/
  66086. BEGIN_JUCE_NAMESPACE
  66087. static bool juce_lineIntersection (const float x1, const float y1,
  66088. const float x2, const float y2,
  66089. const float x3, const float y3,
  66090. const float x4, const float y4,
  66091. float& intersectionX,
  66092. float& intersectionY) throw()
  66093. {
  66094. if (x2 != x3 || y2 != y3)
  66095. {
  66096. const float dx1 = x2 - x1;
  66097. const float dy1 = y2 - y1;
  66098. const float dx2 = x4 - x3;
  66099. const float dy2 = y4 - y3;
  66100. const float divisor = dx1 * dy2 - dx2 * dy1;
  66101. if (divisor == 0)
  66102. {
  66103. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  66104. {
  66105. if (dy1 == 0 && dy2 != 0)
  66106. {
  66107. const float along = (y1 - y3) / dy2;
  66108. intersectionX = x3 + along * dx2;
  66109. intersectionY = y1;
  66110. return along >= 0 && along <= 1.0f;
  66111. }
  66112. else if (dy2 == 0 && dy1 != 0)
  66113. {
  66114. const float along = (y3 - y1) / dy1;
  66115. intersectionX = x1 + along * dx1;
  66116. intersectionY = y3;
  66117. return along >= 0 && along <= 1.0f;
  66118. }
  66119. else if (dx1 == 0 && dx2 != 0)
  66120. {
  66121. const float along = (x1 - x3) / dx2;
  66122. intersectionX = x1;
  66123. intersectionY = y3 + along * dy2;
  66124. return along >= 0 && along <= 1.0f;
  66125. }
  66126. else if (dx2 == 0 && dx1 != 0)
  66127. {
  66128. const float along = (x3 - x1) / dx1;
  66129. intersectionX = x3;
  66130. intersectionY = y1 + along * dy1;
  66131. return along >= 0 && along <= 1.0f;
  66132. }
  66133. }
  66134. intersectionX = 0.5f * (x2 + x3);
  66135. intersectionY = 0.5f * (y2 + y3);
  66136. return false;
  66137. }
  66138. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  66139. intersectionX = x1 + along1 * dx1;
  66140. intersectionY = y1 + along1 * dy1;
  66141. if (along1 < 0 || along1 > 1.0f)
  66142. return false;
  66143. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  66144. return along2 >= 0 && along2 <= 1.0f;
  66145. }
  66146. intersectionX = x2;
  66147. intersectionY = y2;
  66148. return true;
  66149. }
  66150. Line::Line() throw()
  66151. : startX (0.0f),
  66152. startY (0.0f),
  66153. endX (0.0f),
  66154. endY (0.0f)
  66155. {
  66156. }
  66157. Line::Line (const Line& other) throw()
  66158. : startX (other.startX),
  66159. startY (other.startY),
  66160. endX (other.endX),
  66161. endY (other.endY)
  66162. {
  66163. }
  66164. Line::Line (const float startX_, const float startY_,
  66165. const float endX_, const float endY_) throw()
  66166. : startX (startX_),
  66167. startY (startY_),
  66168. endX (endX_),
  66169. endY (endY_)
  66170. {
  66171. }
  66172. Line::Line (const Point& start,
  66173. const Point& end) throw()
  66174. : startX (start.getX()),
  66175. startY (start.getY()),
  66176. endX (end.getX()),
  66177. endY (end.getY())
  66178. {
  66179. }
  66180. const Line& Line::operator= (const Line& other) throw()
  66181. {
  66182. startX = other.startX;
  66183. startY = other.startY;
  66184. endX = other.endX;
  66185. endY = other.endY;
  66186. return *this;
  66187. }
  66188. Line::~Line() throw()
  66189. {
  66190. }
  66191. const Point Line::getStart() const throw()
  66192. {
  66193. return Point (startX, startY);
  66194. }
  66195. const Point Line::getEnd() const throw()
  66196. {
  66197. return Point (endX, endY);
  66198. }
  66199. void Line::setStart (const float newStartX,
  66200. const float newStartY) throw()
  66201. {
  66202. startX = newStartX;
  66203. startY = newStartY;
  66204. }
  66205. void Line::setStart (const Point& newStart) throw()
  66206. {
  66207. startX = newStart.getX();
  66208. startY = newStart.getY();
  66209. }
  66210. void Line::setEnd (const float newEndX,
  66211. const float newEndY) throw()
  66212. {
  66213. endX = newEndX;
  66214. endY = newEndY;
  66215. }
  66216. void Line::setEnd (const Point& newEnd) throw()
  66217. {
  66218. endX = newEnd.getX();
  66219. endY = newEnd.getY();
  66220. }
  66221. bool Line::operator== (const Line& other) const throw()
  66222. {
  66223. return startX == other.startX
  66224. && startY == other.startY
  66225. && endX == other.endX
  66226. && endY == other.endY;
  66227. }
  66228. bool Line::operator!= (const Line& other) const throw()
  66229. {
  66230. return startX != other.startX
  66231. || startY != other.startY
  66232. || endX != other.endX
  66233. || endY != other.endY;
  66234. }
  66235. void Line::applyTransform (const AffineTransform& transform) throw()
  66236. {
  66237. transform.transformPoint (startX, startY);
  66238. transform.transformPoint (endX, endY);
  66239. }
  66240. float Line::getLength() const throw()
  66241. {
  66242. return (float) juce_hypot (startX - endX,
  66243. startY - endY);
  66244. }
  66245. float Line::getAngle() const throw()
  66246. {
  66247. return atan2f (endX - startX,
  66248. endY - startY);
  66249. }
  66250. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  66251. {
  66252. const float alpha = distanceFromStart / getLength();
  66253. return Point (startX + (endX - startX) * alpha,
  66254. startY + (endY - startY) * alpha);
  66255. }
  66256. const Point Line::getPointAlongLine (const float offsetX,
  66257. const float offsetY) const throw()
  66258. {
  66259. const float dx = endX - startX;
  66260. const float dy = endY - startY;
  66261. const double length = juce_hypot (dx, dy);
  66262. if (length == 0)
  66263. return Point (startX, startY);
  66264. else
  66265. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  66266. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  66267. }
  66268. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  66269. {
  66270. return Point (startX + (endX - startX) * alpha,
  66271. startY + (endY - startY) * alpha);
  66272. }
  66273. float Line::getDistanceFromLine (const float x,
  66274. const float y) const throw()
  66275. {
  66276. const double dx = endX - startX;
  66277. const double dy = endY - startY;
  66278. const double length = dx * dx + dy * dy;
  66279. if (length > 0)
  66280. {
  66281. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  66282. if (prop >= 0.0f && prop < 1.0f)
  66283. {
  66284. return (float) juce_hypot (x - (startX + prop * dx),
  66285. y - (startY + prop * dy));
  66286. }
  66287. }
  66288. return (float) jmin (juce_hypot (x - startX, y - startY),
  66289. juce_hypot (x - endX, y - endY));
  66290. }
  66291. float Line::findNearestPointTo (const float x,
  66292. const float y) const throw()
  66293. {
  66294. const double dx = endX - startX;
  66295. const double dy = endY - startY;
  66296. const double length = dx * dx + dy * dy;
  66297. if (length <= 0.0)
  66298. return 0.0f;
  66299. return jlimit (0.0f, 1.0f,
  66300. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  66301. }
  66302. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  66303. {
  66304. const float length = getLength();
  66305. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  66306. getEnd());
  66307. }
  66308. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  66309. {
  66310. const float length = getLength();
  66311. return Line (getStart(),
  66312. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  66313. }
  66314. bool Line::clipToPath (const Path& path,
  66315. const bool keepSectionOutsidePath) throw()
  66316. {
  66317. const bool startInside = path.contains (startX, startY);
  66318. const bool endInside = path.contains (endX, endY);
  66319. if (startInside == endInside)
  66320. {
  66321. if (keepSectionOutsidePath != startInside)
  66322. {
  66323. // entirely outside the path
  66324. return false;
  66325. }
  66326. else
  66327. {
  66328. // entirely inside the path
  66329. startX = 0.0f;
  66330. startY = 0.0f;
  66331. endX = 0.0f;
  66332. endY = 0.0f;
  66333. return true;
  66334. }
  66335. }
  66336. else
  66337. {
  66338. bool changed = false;
  66339. PathFlatteningIterator iter (path, AffineTransform::identity);
  66340. while (iter.next())
  66341. {
  66342. float ix, iy;
  66343. if (intersects (Line (iter.x1, iter.y1,
  66344. iter.x2, iter.y2),
  66345. ix, iy))
  66346. {
  66347. if ((startInside && keepSectionOutsidePath)
  66348. || (endInside && ! keepSectionOutsidePath))
  66349. {
  66350. setStart (ix, iy);
  66351. }
  66352. else
  66353. {
  66354. setEnd (ix, iy);
  66355. }
  66356. changed = true;
  66357. }
  66358. }
  66359. return changed;
  66360. }
  66361. }
  66362. bool Line::intersects (const Line& line,
  66363. float& intersectionX,
  66364. float& intersectionY) const throw()
  66365. {
  66366. return juce_lineIntersection (startX, startY,
  66367. endX, endY,
  66368. line.startX, line.startY,
  66369. line.endX, line.endY,
  66370. intersectionX,
  66371. intersectionY);
  66372. }
  66373. bool Line::isVertical() const throw()
  66374. {
  66375. return startX == endX;
  66376. }
  66377. bool Line::isHorizontal() const throw()
  66378. {
  66379. return startY == endY;
  66380. }
  66381. bool Line::isPointAbove (const float x, const float y) const throw()
  66382. {
  66383. return startX != endX
  66384. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  66385. }
  66386. END_JUCE_NAMESPACE
  66387. /********* End of inlined file: juce_Line.cpp *********/
  66388. /********* Start of inlined file: juce_Path.cpp *********/
  66389. BEGIN_JUCE_NAMESPACE
  66390. // tests that some co-ords aren't NaNs
  66391. #define CHECK_COORDS_ARE_VALID(x, y) \
  66392. jassert (x == x && y == y);
  66393. const float Path::lineMarker = 100001.0f;
  66394. const float Path::moveMarker = 100002.0f;
  66395. const float Path::quadMarker = 100003.0f;
  66396. const float Path::cubicMarker = 100004.0f;
  66397. const float Path::closeSubPathMarker = 100005.0f;
  66398. static const int defaultGranularity = 32;
  66399. Path::Path() throw()
  66400. : ArrayAllocationBase <float> (defaultGranularity),
  66401. numElements (0),
  66402. pathXMin (0),
  66403. pathXMax (0),
  66404. pathYMin (0),
  66405. pathYMax (0),
  66406. useNonZeroWinding (true)
  66407. {
  66408. }
  66409. Path::~Path() throw()
  66410. {
  66411. }
  66412. Path::Path (const Path& other) throw()
  66413. : ArrayAllocationBase <float> (defaultGranularity),
  66414. numElements (other.numElements),
  66415. pathXMin (other.pathXMin),
  66416. pathXMax (other.pathXMax),
  66417. pathYMin (other.pathYMin),
  66418. pathYMax (other.pathYMax),
  66419. useNonZeroWinding (other.useNonZeroWinding)
  66420. {
  66421. if (numElements > 0)
  66422. {
  66423. setAllocatedSize (numElements);
  66424. memcpy (elements, other.elements, numElements * sizeof (float));
  66425. }
  66426. }
  66427. const Path& Path::operator= (const Path& other) throw()
  66428. {
  66429. if (this != &other)
  66430. {
  66431. ensureAllocatedSize (other.numElements);
  66432. numElements = other.numElements;
  66433. pathXMin = other.pathXMin;
  66434. pathXMax = other.pathXMax;
  66435. pathYMin = other.pathYMin;
  66436. pathYMax = other.pathYMax;
  66437. useNonZeroWinding = other.useNonZeroWinding;
  66438. if (numElements > 0)
  66439. memcpy (elements, other.elements, numElements * sizeof (float));
  66440. }
  66441. return *this;
  66442. }
  66443. void Path::clear() throw()
  66444. {
  66445. numElements = 0;
  66446. pathXMin = 0;
  66447. pathYMin = 0;
  66448. pathYMax = 0;
  66449. pathXMax = 0;
  66450. }
  66451. void Path::swapWithPath (Path& other)
  66452. {
  66453. swapVariables <int> (this->numAllocated, other.numAllocated);
  66454. swapVariables <float*> (this->elements, other.elements);
  66455. swapVariables <int> (this->numElements, other.numElements);
  66456. swapVariables <float> (this->pathXMin, other.pathXMin);
  66457. swapVariables <float> (this->pathXMax, other.pathXMax);
  66458. swapVariables <float> (this->pathYMin, other.pathYMin);
  66459. swapVariables <float> (this->pathYMax, other.pathYMax);
  66460. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  66461. }
  66462. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  66463. {
  66464. useNonZeroWinding = isNonZero;
  66465. }
  66466. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  66467. const bool preserveProportions) throw()
  66468. {
  66469. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  66470. }
  66471. bool Path::isEmpty() const throw()
  66472. {
  66473. int i = 0;
  66474. while (i < numElements)
  66475. {
  66476. const float type = elements [i++];
  66477. if (type == moveMarker)
  66478. {
  66479. i += 2;
  66480. }
  66481. else if (type == lineMarker
  66482. || type == quadMarker
  66483. || type == cubicMarker)
  66484. {
  66485. return false;
  66486. }
  66487. }
  66488. return true;
  66489. }
  66490. void Path::getBounds (float& x, float& y,
  66491. float& w, float& h) const throw()
  66492. {
  66493. x = pathXMin;
  66494. y = pathYMin;
  66495. w = pathXMax - pathXMin;
  66496. h = pathYMax - pathYMin;
  66497. }
  66498. void Path::getBoundsTransformed (const AffineTransform& transform,
  66499. float& x, float& y,
  66500. float& w, float& h) const throw()
  66501. {
  66502. float x1 = pathXMin;
  66503. float y1 = pathYMin;
  66504. transform.transformPoint (x1, y1);
  66505. float x2 = pathXMax;
  66506. float y2 = pathYMin;
  66507. transform.transformPoint (x2, y2);
  66508. float x3 = pathXMin;
  66509. float y3 = pathYMax;
  66510. transform.transformPoint (x3, y3);
  66511. float x4 = pathXMax;
  66512. float y4 = pathYMax;
  66513. transform.transformPoint (x4, y4);
  66514. x = jmin (x1, x2, x3, x4);
  66515. y = jmin (y1, y2, y3, y4);
  66516. w = jmax (x1, x2, x3, x4) - x;
  66517. h = jmax (y1, y2, y3, y4) - y;
  66518. }
  66519. void Path::startNewSubPath (const float x,
  66520. const float y) throw()
  66521. {
  66522. CHECK_COORDS_ARE_VALID (x, y);
  66523. if (numElements == 0)
  66524. {
  66525. pathXMin = pathXMax = x;
  66526. pathYMin = pathYMax = y;
  66527. }
  66528. else
  66529. {
  66530. pathXMin = jmin (pathXMin, x);
  66531. pathXMax = jmax (pathXMax, x);
  66532. pathYMin = jmin (pathYMin, y);
  66533. pathYMax = jmax (pathYMax, y);
  66534. }
  66535. ensureAllocatedSize (numElements + 3);
  66536. elements [numElements++] = moveMarker;
  66537. elements [numElements++] = x;
  66538. elements [numElements++] = y;
  66539. }
  66540. void Path::lineTo (const float x, const float y) throw()
  66541. {
  66542. CHECK_COORDS_ARE_VALID (x, y);
  66543. if (numElements == 0)
  66544. startNewSubPath (0, 0);
  66545. ensureAllocatedSize (numElements + 3);
  66546. elements [numElements++] = lineMarker;
  66547. elements [numElements++] = x;
  66548. elements [numElements++] = y;
  66549. pathXMin = jmin (pathXMin, x);
  66550. pathXMax = jmax (pathXMax, x);
  66551. pathYMin = jmin (pathYMin, y);
  66552. pathYMax = jmax (pathYMax, y);
  66553. }
  66554. void Path::quadraticTo (const float x1, const float y1,
  66555. const float x2, const float y2) throw()
  66556. {
  66557. CHECK_COORDS_ARE_VALID (x1, y1);
  66558. CHECK_COORDS_ARE_VALID (x2, y2);
  66559. if (numElements == 0)
  66560. startNewSubPath (0, 0);
  66561. ensureAllocatedSize (numElements + 5);
  66562. elements [numElements++] = quadMarker;
  66563. elements [numElements++] = x1;
  66564. elements [numElements++] = y1;
  66565. elements [numElements++] = x2;
  66566. elements [numElements++] = y2;
  66567. pathXMin = jmin (pathXMin, x1, x2);
  66568. pathXMax = jmax (pathXMax, x1, x2);
  66569. pathYMin = jmin (pathYMin, y1, y2);
  66570. pathYMax = jmax (pathYMax, y1, y2);
  66571. }
  66572. void Path::cubicTo (const float x1, const float y1,
  66573. const float x2, const float y2,
  66574. const float x3, const float y3) throw()
  66575. {
  66576. CHECK_COORDS_ARE_VALID (x1, y1);
  66577. CHECK_COORDS_ARE_VALID (x2, y2);
  66578. CHECK_COORDS_ARE_VALID (x3, y3);
  66579. if (numElements == 0)
  66580. startNewSubPath (0, 0);
  66581. ensureAllocatedSize (numElements + 7);
  66582. elements [numElements++] = cubicMarker;
  66583. elements [numElements++] = x1;
  66584. elements [numElements++] = y1;
  66585. elements [numElements++] = x2;
  66586. elements [numElements++] = y2;
  66587. elements [numElements++] = x3;
  66588. elements [numElements++] = y3;
  66589. pathXMin = jmin (pathXMin, x1, x2, x3);
  66590. pathXMax = jmax (pathXMax, x1, x2, x3);
  66591. pathYMin = jmin (pathYMin, y1, y2, y3);
  66592. pathYMax = jmax (pathYMax, y1, y2, y3);
  66593. }
  66594. void Path::closeSubPath() throw()
  66595. {
  66596. if (numElements > 0
  66597. && elements [numElements - 1] != closeSubPathMarker)
  66598. {
  66599. ensureAllocatedSize (numElements + 1);
  66600. elements [numElements++] = closeSubPathMarker;
  66601. }
  66602. }
  66603. const Point Path::getCurrentPosition() const
  66604. {
  66605. int i = numElements - 1;
  66606. if (i > 0 && elements[i] == closeSubPathMarker)
  66607. {
  66608. while (i >= 0)
  66609. {
  66610. if (elements[i] == moveMarker)
  66611. {
  66612. i += 2;
  66613. break;
  66614. }
  66615. --i;
  66616. }
  66617. }
  66618. if (i > 0)
  66619. return Point (elements [i - 1], elements [i]);
  66620. return Point (0.0f, 0.0f);
  66621. }
  66622. void Path::addRectangle (const float x, const float y,
  66623. const float w, const float h) throw()
  66624. {
  66625. startNewSubPath (x, y + h);
  66626. lineTo (x, y);
  66627. lineTo (x + w, y);
  66628. lineTo (x + w, y + h);
  66629. closeSubPath();
  66630. }
  66631. void Path::addRoundedRectangle (const float x, const float y,
  66632. const float w, const float h,
  66633. float csx,
  66634. float csy) throw()
  66635. {
  66636. csx = jmin (csx, w * 0.5f);
  66637. csy = jmin (csy, h * 0.5f);
  66638. const float cs45x = csx * 0.45f;
  66639. const float cs45y = csy * 0.45f;
  66640. const float x2 = x + w;
  66641. const float y2 = y + h;
  66642. startNewSubPath (x + csx, y);
  66643. lineTo (x2 - csx, y);
  66644. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  66645. lineTo (x2, y2 - csy);
  66646. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  66647. lineTo (x + csx, y2);
  66648. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  66649. lineTo (x, y + csy);
  66650. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  66651. closeSubPath();
  66652. }
  66653. void Path::addRoundedRectangle (const float x, const float y,
  66654. const float w, const float h,
  66655. float cs) throw()
  66656. {
  66657. addRoundedRectangle (x, y, w, h, cs, cs);
  66658. }
  66659. void Path::addTriangle (const float x1, const float y1,
  66660. const float x2, const float y2,
  66661. const float x3, const float y3) throw()
  66662. {
  66663. startNewSubPath (x1, y1);
  66664. lineTo (x2, y2);
  66665. lineTo (x3, y3);
  66666. closeSubPath();
  66667. }
  66668. void Path::addQuadrilateral (const float x1, const float y1,
  66669. const float x2, const float y2,
  66670. const float x3, const float y3,
  66671. const float x4, const float y4) throw()
  66672. {
  66673. startNewSubPath (x1, y1);
  66674. lineTo (x2, y2);
  66675. lineTo (x3, y3);
  66676. lineTo (x4, y4);
  66677. closeSubPath();
  66678. }
  66679. void Path::addEllipse (const float x, const float y,
  66680. const float w, const float h) throw()
  66681. {
  66682. const float hw = w * 0.5f;
  66683. const float hw55 = hw * 0.55f;
  66684. const float hh = h * 0.5f;
  66685. const float hh45 = hh * 0.55f;
  66686. const float cx = x + hw;
  66687. const float cy = y + hh;
  66688. startNewSubPath (cx, cy - hh);
  66689. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  66690. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  66691. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  66692. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  66693. closeSubPath();
  66694. }
  66695. void Path::addArc (const float x, const float y,
  66696. const float w, const float h,
  66697. const float fromRadians,
  66698. const float toRadians,
  66699. const bool startAsNewSubPath) throw()
  66700. {
  66701. const float radiusX = w / 2.0f;
  66702. const float radiusY = h / 2.0f;
  66703. addCentredArc (x + radiusX,
  66704. y + radiusY,
  66705. radiusX, radiusY,
  66706. 0.0f,
  66707. fromRadians, toRadians,
  66708. startAsNewSubPath);
  66709. }
  66710. static const float ellipseAngularIncrement = 0.05f;
  66711. void Path::addCentredArc (const float centreX, const float centreY,
  66712. const float radiusX, const float radiusY,
  66713. const float rotationOfEllipse,
  66714. const float fromRadians,
  66715. const float toRadians,
  66716. const bool startAsNewSubPath) throw()
  66717. {
  66718. if (radiusX > 0.0f && radiusY > 0.0f)
  66719. {
  66720. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  66721. float angle = fromRadians;
  66722. if (startAsNewSubPath)
  66723. {
  66724. float x = centreX + radiusX * sinf (angle);
  66725. float y = centreY - radiusY * cosf (angle);
  66726. if (rotationOfEllipse != 0)
  66727. rotation.transformPoint (x, y);
  66728. startNewSubPath (x, y);
  66729. }
  66730. if (fromRadians < toRadians)
  66731. {
  66732. if (startAsNewSubPath)
  66733. angle += ellipseAngularIncrement;
  66734. while (angle < toRadians)
  66735. {
  66736. float x = centreX + radiusX * sinf (angle);
  66737. float y = centreY - radiusY * cosf (angle);
  66738. if (rotationOfEllipse != 0)
  66739. rotation.transformPoint (x, y);
  66740. lineTo (x, y);
  66741. angle += ellipseAngularIncrement;
  66742. }
  66743. }
  66744. else
  66745. {
  66746. if (startAsNewSubPath)
  66747. angle -= ellipseAngularIncrement;
  66748. while (angle > toRadians)
  66749. {
  66750. float x = centreX + radiusX * sinf (angle);
  66751. float y = centreY - radiusY * cosf (angle);
  66752. if (rotationOfEllipse != 0)
  66753. rotation.transformPoint (x, y);
  66754. lineTo (x, y);
  66755. angle -= ellipseAngularIncrement;
  66756. }
  66757. }
  66758. float x = centreX + radiusX * sinf (toRadians);
  66759. float y = centreY - radiusY * cosf (toRadians);
  66760. if (rotationOfEllipse != 0)
  66761. rotation.transformPoint (x, y);
  66762. lineTo (x, y);
  66763. }
  66764. }
  66765. void Path::addPieSegment (const float x, const float y,
  66766. const float width, const float height,
  66767. const float fromRadians,
  66768. const float toRadians,
  66769. const float innerCircleProportionalSize)
  66770. {
  66771. float hw = width * 0.5f;
  66772. float hh = height * 0.5f;
  66773. const float centreX = x + hw;
  66774. const float centreY = y + hh;
  66775. startNewSubPath (centreX + hw * sinf (fromRadians),
  66776. centreY - hh * cosf (fromRadians));
  66777. addArc (x, y, width, height, fromRadians, toRadians);
  66778. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  66779. {
  66780. closeSubPath();
  66781. if (innerCircleProportionalSize > 0)
  66782. {
  66783. hw *= innerCircleProportionalSize;
  66784. hh *= innerCircleProportionalSize;
  66785. startNewSubPath (centreX + hw * sinf (toRadians),
  66786. centreY - hh * cosf (toRadians));
  66787. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  66788. toRadians, fromRadians);
  66789. }
  66790. }
  66791. else
  66792. {
  66793. if (innerCircleProportionalSize > 0)
  66794. {
  66795. hw *= innerCircleProportionalSize;
  66796. hh *= innerCircleProportionalSize;
  66797. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  66798. toRadians, fromRadians);
  66799. }
  66800. else
  66801. {
  66802. lineTo (centreX, centreY);
  66803. }
  66804. }
  66805. closeSubPath();
  66806. }
  66807. static void perpendicularOffset (const float x1, const float y1,
  66808. const float x2, const float y2,
  66809. const float offsetX, const float offsetY,
  66810. float& resultX, float& resultY) throw()
  66811. {
  66812. const float dx = x2 - x1;
  66813. const float dy = y2 - y1;
  66814. const float len = juce_hypotf (dx, dy);
  66815. if (len == 0)
  66816. {
  66817. resultX = x1;
  66818. resultY = y1;
  66819. }
  66820. else
  66821. {
  66822. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  66823. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  66824. }
  66825. }
  66826. void Path::addLineSegment (const float startX, const float startY,
  66827. const float endX, const float endY,
  66828. float lineThickness) throw()
  66829. {
  66830. lineThickness *= 0.5f;
  66831. float x, y;
  66832. perpendicularOffset (startX, startY, endX, endY,
  66833. 0, lineThickness, x, y);
  66834. startNewSubPath (x, y);
  66835. perpendicularOffset (startX, startY, endX, endY,
  66836. 0, -lineThickness, x, y);
  66837. lineTo (x, y);
  66838. perpendicularOffset (endX, endY, startX, startY,
  66839. 0, lineThickness, x, y);
  66840. lineTo (x, y);
  66841. perpendicularOffset (endX, endY, startX, startY,
  66842. 0, -lineThickness, x, y);
  66843. lineTo (x, y);
  66844. closeSubPath();
  66845. }
  66846. void Path::addArrow (const float startX, const float startY,
  66847. const float endX, const float endY,
  66848. float lineThickness,
  66849. float arrowheadWidth,
  66850. float arrowheadLength) throw()
  66851. {
  66852. lineThickness *= 0.5f;
  66853. arrowheadWidth *= 0.5f;
  66854. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  66855. startY - endY));
  66856. float x, y;
  66857. perpendicularOffset (startX, startY, endX, endY,
  66858. 0, lineThickness, x, y);
  66859. startNewSubPath (x, y);
  66860. perpendicularOffset (startX, startY, endX, endY,
  66861. 0, -lineThickness, x, y);
  66862. lineTo (x, y);
  66863. perpendicularOffset (endX, endY, startX, startY,
  66864. arrowheadLength, lineThickness, x, y);
  66865. lineTo (x, y);
  66866. perpendicularOffset (endX, endY, startX, startY,
  66867. arrowheadLength, arrowheadWidth, x, y);
  66868. lineTo (x, y);
  66869. perpendicularOffset (endX, endY, startX, startY,
  66870. 0, 0, x, y);
  66871. lineTo (x, y);
  66872. perpendicularOffset (endX, endY, startX, startY,
  66873. arrowheadLength, -arrowheadWidth, x, y);
  66874. lineTo (x, y);
  66875. perpendicularOffset (endX, endY, startX, startY,
  66876. arrowheadLength, -lineThickness, x, y);
  66877. lineTo (x, y);
  66878. closeSubPath();
  66879. }
  66880. void Path::addStar (const float centreX,
  66881. const float centreY,
  66882. const int numberOfPoints,
  66883. const float innerRadius,
  66884. const float outerRadius,
  66885. const float startAngle)
  66886. {
  66887. jassert (numberOfPoints > 1); // this would be silly.
  66888. if (numberOfPoints > 1)
  66889. {
  66890. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  66891. for (int i = 0; i < numberOfPoints; ++i)
  66892. {
  66893. float angle = startAngle + i * angleBetweenPoints;
  66894. const float x = centreX + outerRadius * sinf (angle);
  66895. const float y = centreY - outerRadius * cosf (angle);
  66896. if (i == 0)
  66897. startNewSubPath (x, y);
  66898. else
  66899. lineTo (x, y);
  66900. angle += angleBetweenPoints * 0.5f;
  66901. lineTo (centreX + innerRadius * sinf (angle),
  66902. centreY - innerRadius * cosf (angle));
  66903. }
  66904. closeSubPath();
  66905. }
  66906. }
  66907. void Path::addBubble (float x, float y,
  66908. float w, float h,
  66909. float cs,
  66910. float tipX,
  66911. float tipY,
  66912. int whichSide,
  66913. float arrowPos,
  66914. float arrowWidth)
  66915. {
  66916. if (w > 1.0f && h > 1.0f)
  66917. {
  66918. cs = jmin (cs, w * 0.5f, h * 0.5f);
  66919. const float cs2 = 2.0f * cs;
  66920. startNewSubPath (x + cs, y);
  66921. if (whichSide == 0)
  66922. {
  66923. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  66924. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  66925. lineTo (arrowX1, y);
  66926. lineTo (tipX, tipY);
  66927. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  66928. }
  66929. lineTo (x + w - cs, y);
  66930. if (cs > 0.0f)
  66931. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  66932. if (whichSide == 3)
  66933. {
  66934. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  66935. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  66936. lineTo (x + w, arrowY1);
  66937. lineTo (tipX, tipY);
  66938. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  66939. }
  66940. lineTo (x + w, y + h - cs);
  66941. if (cs > 0.0f)
  66942. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  66943. if (whichSide == 2)
  66944. {
  66945. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  66946. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  66947. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  66948. lineTo (tipX, tipY);
  66949. lineTo (arrowX1, y + h);
  66950. }
  66951. lineTo (x + cs, y + h);
  66952. if (cs > 0.0f)
  66953. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  66954. if (whichSide == 1)
  66955. {
  66956. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  66957. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  66958. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  66959. lineTo (tipX, tipY);
  66960. lineTo (x, arrowY1);
  66961. }
  66962. lineTo (x, y + cs);
  66963. if (cs > 0.0f)
  66964. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  66965. closeSubPath();
  66966. }
  66967. }
  66968. void Path::addPath (const Path& other) throw()
  66969. {
  66970. int i = 0;
  66971. while (i < other.numElements)
  66972. {
  66973. const float type = other.elements [i++];
  66974. if (type == moveMarker)
  66975. {
  66976. startNewSubPath (other.elements [i],
  66977. other.elements [i + 1]);
  66978. i += 2;
  66979. }
  66980. else if (type == lineMarker)
  66981. {
  66982. lineTo (other.elements [i],
  66983. other.elements [i + 1]);
  66984. i += 2;
  66985. }
  66986. else if (type == quadMarker)
  66987. {
  66988. quadraticTo (other.elements [i],
  66989. other.elements [i + 1],
  66990. other.elements [i + 2],
  66991. other.elements [i + 3]);
  66992. i += 4;
  66993. }
  66994. else if (type == cubicMarker)
  66995. {
  66996. cubicTo (other.elements [i],
  66997. other.elements [i + 1],
  66998. other.elements [i + 2],
  66999. other.elements [i + 3],
  67000. other.elements [i + 4],
  67001. other.elements [i + 5]);
  67002. i += 6;
  67003. }
  67004. else if (type == closeSubPathMarker)
  67005. {
  67006. closeSubPath();
  67007. }
  67008. else
  67009. {
  67010. // something's gone wrong with the element list!
  67011. jassertfalse
  67012. }
  67013. }
  67014. }
  67015. void Path::addPath (const Path& other,
  67016. const AffineTransform& transformToApply) throw()
  67017. {
  67018. int i = 0;
  67019. while (i < other.numElements)
  67020. {
  67021. const float type = other.elements [i++];
  67022. if (type == closeSubPathMarker)
  67023. {
  67024. closeSubPath();
  67025. }
  67026. else
  67027. {
  67028. float x = other.elements [i++];
  67029. float y = other.elements [i++];
  67030. transformToApply.transformPoint (x, y);
  67031. if (type == moveMarker)
  67032. {
  67033. startNewSubPath (x, y);
  67034. }
  67035. else if (type == lineMarker)
  67036. {
  67037. lineTo (x, y);
  67038. }
  67039. else if (type == quadMarker)
  67040. {
  67041. float x2 = other.elements [i++];
  67042. float y2 = other.elements [i++];
  67043. transformToApply.transformPoint (x2, y2);
  67044. quadraticTo (x, y, x2, y2);
  67045. }
  67046. else if (type == cubicMarker)
  67047. {
  67048. float x2 = other.elements [i++];
  67049. float y2 = other.elements [i++];
  67050. float x3 = other.elements [i++];
  67051. float y3 = other.elements [i++];
  67052. transformToApply.transformPoint (x2, y2);
  67053. transformToApply.transformPoint (x3, y3);
  67054. cubicTo (x, y, x2, y2, x3, y3);
  67055. }
  67056. else
  67057. {
  67058. // something's gone wrong with the element list!
  67059. jassertfalse
  67060. }
  67061. }
  67062. }
  67063. }
  67064. void Path::applyTransform (const AffineTransform& transform) throw()
  67065. {
  67066. int i = 0;
  67067. pathYMin = pathXMin = 0;
  67068. pathYMax = pathXMax = 0;
  67069. bool setMaxMin = false;
  67070. while (i < numElements)
  67071. {
  67072. const float type = elements [i++];
  67073. if (type == moveMarker)
  67074. {
  67075. transform.transformPoint (elements [i],
  67076. elements [i + 1]);
  67077. if (setMaxMin)
  67078. {
  67079. pathXMin = jmin (pathXMin, elements [i]);
  67080. pathXMax = jmax (pathXMax, elements [i]);
  67081. pathYMin = jmin (pathYMin, elements [i + 1]);
  67082. pathYMax = jmax (pathYMax, elements [i + 1]);
  67083. }
  67084. else
  67085. {
  67086. pathXMin = pathXMax = elements [i];
  67087. pathYMin = pathYMax = elements [i + 1];
  67088. setMaxMin = true;
  67089. }
  67090. i += 2;
  67091. }
  67092. else if (type == lineMarker)
  67093. {
  67094. transform.transformPoint (elements [i],
  67095. elements [i + 1]);
  67096. pathXMin = jmin (pathXMin, elements [i]);
  67097. pathXMax = jmax (pathXMax, elements [i]);
  67098. pathYMin = jmin (pathYMin, elements [i + 1]);
  67099. pathYMax = jmax (pathYMax, elements [i + 1]);
  67100. i += 2;
  67101. }
  67102. else if (type == quadMarker)
  67103. {
  67104. transform.transformPoint (elements [i],
  67105. elements [i + 1]);
  67106. transform.transformPoint (elements [i + 2],
  67107. elements [i + 3]);
  67108. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  67109. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  67110. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  67111. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  67112. i += 4;
  67113. }
  67114. else if (type == cubicMarker)
  67115. {
  67116. transform.transformPoint (elements [i],
  67117. elements [i + 1]);
  67118. transform.transformPoint (elements [i + 2],
  67119. elements [i + 3]);
  67120. transform.transformPoint (elements [i + 4],
  67121. elements [i + 5]);
  67122. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  67123. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  67124. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  67125. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  67126. i += 6;
  67127. }
  67128. }
  67129. }
  67130. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  67131. const float w, const float h,
  67132. const bool preserveProportions,
  67133. const Justification& justification) const throw()
  67134. {
  67135. float sx, sy, sw, sh;
  67136. getBounds (sx, sy, sw, sh);
  67137. if (preserveProportions)
  67138. {
  67139. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  67140. return AffineTransform::identity;
  67141. float newW, newH;
  67142. const float srcRatio = sh / sw;
  67143. if (srcRatio > h / w)
  67144. {
  67145. newW = h / srcRatio;
  67146. newH = h;
  67147. }
  67148. else
  67149. {
  67150. newW = w;
  67151. newH = w * srcRatio;
  67152. }
  67153. float newXCentre = x;
  67154. float newYCentre = y;
  67155. if (justification.testFlags (Justification::left))
  67156. newXCentre += newW * 0.5f;
  67157. else if (justification.testFlags (Justification::right))
  67158. newXCentre += w - newW * 0.5f;
  67159. else
  67160. newXCentre += w * 0.5f;
  67161. if (justification.testFlags (Justification::top))
  67162. newYCentre += newH * 0.5f;
  67163. else if (justification.testFlags (Justification::bottom))
  67164. newYCentre += h - newH * 0.5f;
  67165. else
  67166. newYCentre += h * 0.5f;
  67167. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  67168. .scaled (newW / sw, newH / sh)
  67169. .translated (newXCentre, newYCentre);
  67170. }
  67171. else
  67172. {
  67173. return AffineTransform::translation (-sx, -sy)
  67174. .scaled (w / sw, h / sh)
  67175. .translated (x, y);
  67176. }
  67177. }
  67178. static const float collisionDetectionTolerence = 20.0f;
  67179. bool Path::contains (const float x, const float y) const throw()
  67180. {
  67181. if (x <= pathXMin || x >= pathXMax
  67182. || y <= pathYMin || y >= pathYMax)
  67183. return false;
  67184. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67185. int positiveCrossings = 0;
  67186. int negativeCrossings = 0;
  67187. while (i.next())
  67188. {
  67189. if ((i.y1 <= y && i.y2 > y)
  67190. || (i.y2 <= y && i.y1 > y))
  67191. {
  67192. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  67193. if (intersectX <= x)
  67194. {
  67195. if (i.y1 < i.y2)
  67196. ++positiveCrossings;
  67197. else
  67198. ++negativeCrossings;
  67199. }
  67200. }
  67201. }
  67202. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  67203. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  67204. }
  67205. bool Path::intersectsLine (const float x1, const float y1,
  67206. const float x2, const float y2) throw()
  67207. {
  67208. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67209. const Line line1 (x1, y1, x2, y2);
  67210. while (i.next())
  67211. {
  67212. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  67213. float ix, iy;
  67214. if (line1.intersects (line2, ix, iy))
  67215. return true;
  67216. }
  67217. return false;
  67218. }
  67219. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  67220. {
  67221. if (cornerRadius <= 0.01f)
  67222. return *this;
  67223. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  67224. int n = 0;
  67225. bool lastWasLine = false, firstWasLine = false;
  67226. Path p;
  67227. while (n < numElements)
  67228. {
  67229. const float type = elements [n++];
  67230. if (type == moveMarker)
  67231. {
  67232. indexOfPathStart = p.numElements;
  67233. indexOfPathStartThis = n - 1;
  67234. const float x = elements [n++];
  67235. const float y = elements [n++];
  67236. p.startNewSubPath (x, y);
  67237. lastWasLine = false;
  67238. firstWasLine = (elements [n] == lineMarker);
  67239. }
  67240. else if (type == lineMarker || type == closeSubPathMarker)
  67241. {
  67242. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  67243. if (type == lineMarker)
  67244. {
  67245. endX = elements [n++];
  67246. endY = elements [n++];
  67247. if (n > 8)
  67248. {
  67249. startX = elements [n - 8];
  67250. startY = elements [n - 7];
  67251. joinX = elements [n - 5];
  67252. joinY = elements [n - 4];
  67253. }
  67254. }
  67255. else
  67256. {
  67257. endX = elements [indexOfPathStartThis + 1];
  67258. endY = elements [indexOfPathStartThis + 2];
  67259. if (n > 6)
  67260. {
  67261. startX = elements [n - 6];
  67262. startY = elements [n - 5];
  67263. joinX = elements [n - 3];
  67264. joinY = elements [n - 2];
  67265. }
  67266. }
  67267. if (lastWasLine)
  67268. {
  67269. const double len1 = juce_hypot (startX - joinX,
  67270. startY - joinY);
  67271. if (len1 > 0)
  67272. {
  67273. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67274. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67275. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67276. }
  67277. const double len2 = juce_hypot (endX - joinX,
  67278. endY - joinY);
  67279. if (len2 > 0)
  67280. {
  67281. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67282. p.quadraticTo (joinX, joinY,
  67283. (float) (joinX + (endX - joinX) * propNeeded),
  67284. (float) (joinY + (endY - joinY) * propNeeded));
  67285. }
  67286. p.lineTo (endX, endY);
  67287. }
  67288. else if (type == lineMarker)
  67289. {
  67290. p.lineTo (endX, endY);
  67291. lastWasLine = true;
  67292. }
  67293. if (type == closeSubPathMarker)
  67294. {
  67295. if (firstWasLine)
  67296. {
  67297. startX = elements [n - 3];
  67298. startY = elements [n - 2];
  67299. joinX = endX;
  67300. joinY = endY;
  67301. endX = elements [indexOfPathStartThis + 4];
  67302. endY = elements [indexOfPathStartThis + 5];
  67303. const double len1 = juce_hypot (startX - joinX,
  67304. startY - joinY);
  67305. if (len1 > 0)
  67306. {
  67307. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67308. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67309. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67310. }
  67311. const double len2 = juce_hypot (endX - joinX,
  67312. endY - joinY);
  67313. if (len2 > 0)
  67314. {
  67315. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67316. endX = (float) (joinX + (endX - joinX) * propNeeded);
  67317. endY = (float) (joinY + (endY - joinY) * propNeeded);
  67318. p.quadraticTo (joinX, joinY, endX, endY);
  67319. p.elements [indexOfPathStart + 1] = endX;
  67320. p.elements [indexOfPathStart + 2] = endY;
  67321. }
  67322. }
  67323. p.closeSubPath();
  67324. }
  67325. }
  67326. else if (type == quadMarker)
  67327. {
  67328. lastWasLine = false;
  67329. const float x1 = elements [n++];
  67330. const float y1 = elements [n++];
  67331. const float x2 = elements [n++];
  67332. const float y2 = elements [n++];
  67333. p.quadraticTo (x1, y1, x2, y2);
  67334. }
  67335. else if (type == cubicMarker)
  67336. {
  67337. lastWasLine = false;
  67338. const float x1 = elements [n++];
  67339. const float y1 = elements [n++];
  67340. const float x2 = elements [n++];
  67341. const float y2 = elements [n++];
  67342. const float x3 = elements [n++];
  67343. const float y3 = elements [n++];
  67344. p.cubicTo (x1, y1, x2, y2, x3, y3);
  67345. }
  67346. }
  67347. return p;
  67348. }
  67349. void Path::loadPathFromStream (InputStream& source)
  67350. {
  67351. while (! source.isExhausted())
  67352. {
  67353. switch (source.readByte())
  67354. {
  67355. case 'm':
  67356. {
  67357. const float x = source.readFloat();
  67358. const float y = source.readFloat();
  67359. startNewSubPath (x, y);
  67360. break;
  67361. }
  67362. case 'l':
  67363. {
  67364. const float x = source.readFloat();
  67365. const float y = source.readFloat();
  67366. lineTo (x, y);
  67367. break;
  67368. }
  67369. case 'q':
  67370. {
  67371. const float x1 = source.readFloat();
  67372. const float y1 = source.readFloat();
  67373. const float x2 = source.readFloat();
  67374. const float y2 = source.readFloat();
  67375. quadraticTo (x1, y1, x2, y2);
  67376. break;
  67377. }
  67378. case 'b':
  67379. {
  67380. const float x1 = source.readFloat();
  67381. const float y1 = source.readFloat();
  67382. const float x2 = source.readFloat();
  67383. const float y2 = source.readFloat();
  67384. const float x3 = source.readFloat();
  67385. const float y3 = source.readFloat();
  67386. cubicTo (x1, y1, x2, y2, x3, y3);
  67387. break;
  67388. }
  67389. case 'c':
  67390. closeSubPath();
  67391. break;
  67392. case 'n':
  67393. useNonZeroWinding = true;
  67394. break;
  67395. case 'z':
  67396. useNonZeroWinding = false;
  67397. break;
  67398. case 'e':
  67399. return; // end of path marker
  67400. default:
  67401. jassertfalse // illegal char in the stream
  67402. break;
  67403. }
  67404. }
  67405. }
  67406. void Path::loadPathFromData (const unsigned char* const data,
  67407. const int numberOfBytes) throw()
  67408. {
  67409. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  67410. loadPathFromStream (in);
  67411. }
  67412. void Path::writePathToStream (OutputStream& dest) const
  67413. {
  67414. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  67415. int i = 0;
  67416. while (i < numElements)
  67417. {
  67418. const float type = elements [i++];
  67419. if (type == moveMarker)
  67420. {
  67421. dest.writeByte ('m');
  67422. dest.writeFloat (elements [i++]);
  67423. dest.writeFloat (elements [i++]);
  67424. }
  67425. else if (type == lineMarker)
  67426. {
  67427. dest.writeByte ('l');
  67428. dest.writeFloat (elements [i++]);
  67429. dest.writeFloat (elements [i++]);
  67430. }
  67431. else if (type == quadMarker)
  67432. {
  67433. dest.writeByte ('q');
  67434. dest.writeFloat (elements [i++]);
  67435. dest.writeFloat (elements [i++]);
  67436. dest.writeFloat (elements [i++]);
  67437. dest.writeFloat (elements [i++]);
  67438. }
  67439. else if (type == cubicMarker)
  67440. {
  67441. dest.writeByte ('b');
  67442. dest.writeFloat (elements [i++]);
  67443. dest.writeFloat (elements [i++]);
  67444. dest.writeFloat (elements [i++]);
  67445. dest.writeFloat (elements [i++]);
  67446. dest.writeFloat (elements [i++]);
  67447. dest.writeFloat (elements [i++]);
  67448. }
  67449. else if (type == closeSubPathMarker)
  67450. {
  67451. dest.writeByte ('c');
  67452. }
  67453. }
  67454. dest.writeByte ('e'); // marks the end-of-path
  67455. }
  67456. const String Path::toString() const
  67457. {
  67458. String s;
  67459. s.preallocateStorage (numElements * 4);
  67460. if (! useNonZeroWinding)
  67461. s << T("a ");
  67462. int i = 0;
  67463. float lastMarker = 0.0f;
  67464. while (i < numElements)
  67465. {
  67466. const float marker = elements [i++];
  67467. tchar markerChar = 0;
  67468. int numCoords = 0;
  67469. if (marker == moveMarker)
  67470. {
  67471. markerChar = T('m');
  67472. numCoords = 2;
  67473. }
  67474. else if (marker == lineMarker)
  67475. {
  67476. markerChar = T('l');
  67477. numCoords = 2;
  67478. }
  67479. else if (marker == quadMarker)
  67480. {
  67481. markerChar = T('q');
  67482. numCoords = 4;
  67483. }
  67484. else if (marker == cubicMarker)
  67485. {
  67486. markerChar = T('c');
  67487. numCoords = 6;
  67488. }
  67489. else
  67490. {
  67491. jassert (marker == closeSubPathMarker);
  67492. markerChar = T('z');
  67493. }
  67494. if (marker != lastMarker)
  67495. {
  67496. s << markerChar << T(' ');
  67497. lastMarker = marker;
  67498. }
  67499. while (--numCoords >= 0 && i < numElements)
  67500. {
  67501. String n (elements [i++], 3);
  67502. while (n.endsWithChar (T('0')))
  67503. n = n.dropLastCharacters (1);
  67504. if (n.endsWithChar (T('.')))
  67505. n = n.dropLastCharacters (1);
  67506. s << n << T(' ');
  67507. }
  67508. }
  67509. return s.trimEnd();
  67510. }
  67511. static const String nextToken (const tchar*& t)
  67512. {
  67513. while (*t == T(' '))
  67514. ++t;
  67515. const tchar* const start = t;
  67516. while (*t != 0 && *t != T(' '))
  67517. ++t;
  67518. const int length = (int) (t - start);
  67519. while (*t == T(' '))
  67520. ++t;
  67521. return String (start, length);
  67522. }
  67523. void Path::restoreFromString (const String& stringVersion)
  67524. {
  67525. clear();
  67526. setUsingNonZeroWinding (true);
  67527. const tchar* t = stringVersion;
  67528. tchar marker = T('m');
  67529. int numValues = 2;
  67530. float values [6];
  67531. while (*t != 0)
  67532. {
  67533. const String token (nextToken (t));
  67534. const tchar firstChar = token[0];
  67535. int startNum = 0;
  67536. if (firstChar == T('m') || firstChar == T('l'))
  67537. {
  67538. marker = firstChar;
  67539. numValues = 2;
  67540. }
  67541. else if (firstChar == T('q'))
  67542. {
  67543. marker = firstChar;
  67544. numValues = 4;
  67545. }
  67546. else if (firstChar == T('c'))
  67547. {
  67548. marker = firstChar;
  67549. numValues = 6;
  67550. }
  67551. else if (firstChar == T('z'))
  67552. {
  67553. marker = firstChar;
  67554. numValues = 0;
  67555. }
  67556. else if (firstChar == T('a'))
  67557. {
  67558. setUsingNonZeroWinding (false);
  67559. continue;
  67560. }
  67561. else
  67562. {
  67563. ++startNum;
  67564. values [0] = token.getFloatValue();
  67565. }
  67566. for (int i = startNum; i < numValues; ++i)
  67567. values [i] = nextToken (t).getFloatValue();
  67568. switch (marker)
  67569. {
  67570. case T('m'):
  67571. startNewSubPath (values[0], values[1]);
  67572. break;
  67573. case T('l'):
  67574. lineTo (values[0], values[1]);
  67575. break;
  67576. case T('q'):
  67577. quadraticTo (values[0], values[1],
  67578. values[2], values[3]);
  67579. break;
  67580. case T('c'):
  67581. cubicTo (values[0], values[1],
  67582. values[2], values[3],
  67583. values[4], values[5]);
  67584. break;
  67585. case T('z'):
  67586. closeSubPath();
  67587. break;
  67588. default:
  67589. jassertfalse // illegal string format?
  67590. break;
  67591. }
  67592. }
  67593. }
  67594. Path::Iterator::Iterator (const Path& path_)
  67595. : path (path_),
  67596. index (0)
  67597. {
  67598. }
  67599. Path::Iterator::~Iterator()
  67600. {
  67601. }
  67602. bool Path::Iterator::next()
  67603. {
  67604. const float* const elements = path.elements;
  67605. if (index < path.numElements)
  67606. {
  67607. const float type = elements [index++];
  67608. if (type == moveMarker)
  67609. {
  67610. elementType = startNewSubPath;
  67611. x1 = elements [index++];
  67612. y1 = elements [index++];
  67613. }
  67614. else if (type == lineMarker)
  67615. {
  67616. elementType = lineTo;
  67617. x1 = elements [index++];
  67618. y1 = elements [index++];
  67619. }
  67620. else if (type == quadMarker)
  67621. {
  67622. elementType = quadraticTo;
  67623. x1 = elements [index++];
  67624. y1 = elements [index++];
  67625. x2 = elements [index++];
  67626. y2 = elements [index++];
  67627. }
  67628. else if (type == cubicMarker)
  67629. {
  67630. elementType = cubicTo;
  67631. x1 = elements [index++];
  67632. y1 = elements [index++];
  67633. x2 = elements [index++];
  67634. y2 = elements [index++];
  67635. x3 = elements [index++];
  67636. y3 = elements [index++];
  67637. }
  67638. else if (type == closeSubPathMarker)
  67639. {
  67640. elementType = closePath;
  67641. }
  67642. return true;
  67643. }
  67644. return false;
  67645. }
  67646. END_JUCE_NAMESPACE
  67647. /********* End of inlined file: juce_Path.cpp *********/
  67648. /********* Start of inlined file: juce_PathIterator.cpp *********/
  67649. BEGIN_JUCE_NAMESPACE
  67650. #if JUCE_MSVC
  67651. #pragma optimize ("t", on)
  67652. #endif
  67653. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  67654. const AffineTransform& transform_,
  67655. float tolerence_) throw()
  67656. : x2 (0),
  67657. y2 (0),
  67658. closesSubPath (false),
  67659. subPathIndex (-1),
  67660. path (path_),
  67661. transform (transform_),
  67662. points (path_.elements),
  67663. tolerence (tolerence_ * tolerence_),
  67664. subPathCloseX (0),
  67665. subPathCloseY (0),
  67666. index (0),
  67667. stackSize (32)
  67668. {
  67669. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  67670. isIdentityTransform = transform.isIdentity();
  67671. stackPos = stackBase;
  67672. }
  67673. PathFlatteningIterator::~PathFlatteningIterator() throw()
  67674. {
  67675. juce_free (stackBase);
  67676. }
  67677. bool PathFlatteningIterator::next() throw()
  67678. {
  67679. x1 = x2;
  67680. y1 = y2;
  67681. float x3 = 0;
  67682. float y3 = 0;
  67683. float x4 = 0;
  67684. float y4 = 0;
  67685. float type;
  67686. for (;;)
  67687. {
  67688. if (stackPos == stackBase)
  67689. {
  67690. if (index >= path.numElements)
  67691. {
  67692. return false;
  67693. }
  67694. else
  67695. {
  67696. type = points [index++];
  67697. if (type != Path::closeSubPathMarker)
  67698. {
  67699. x2 = points [index++];
  67700. y2 = points [index++];
  67701. if (! isIdentityTransform)
  67702. transform.transformPoint (x2, y2);
  67703. if (type == Path::quadMarker)
  67704. {
  67705. x3 = points [index++];
  67706. y3 = points [index++];
  67707. if (! isIdentityTransform)
  67708. transform.transformPoint (x3, y3);
  67709. }
  67710. else if (type == Path::cubicMarker)
  67711. {
  67712. x3 = points [index++];
  67713. y3 = points [index++];
  67714. x4 = points [index++];
  67715. y4 = points [index++];
  67716. if (! isIdentityTransform)
  67717. {
  67718. transform.transformPoint (x3, y3);
  67719. transform.transformPoint (x4, y4);
  67720. }
  67721. }
  67722. }
  67723. }
  67724. }
  67725. else
  67726. {
  67727. type = *--stackPos;
  67728. if (type != Path::closeSubPathMarker)
  67729. {
  67730. x2 = *--stackPos;
  67731. y2 = *--stackPos;
  67732. if (type == Path::quadMarker)
  67733. {
  67734. x3 = *--stackPos;
  67735. y3 = *--stackPos;
  67736. }
  67737. else if (type == Path::cubicMarker)
  67738. {
  67739. x3 = *--stackPos;
  67740. y3 = *--stackPos;
  67741. x4 = *--stackPos;
  67742. y4 = *--stackPos;
  67743. }
  67744. }
  67745. }
  67746. if (type == Path::lineMarker)
  67747. {
  67748. ++subPathIndex;
  67749. closesSubPath = (stackPos == stackBase)
  67750. && (index < path.numElements)
  67751. && (points [index] == Path::closeSubPathMarker)
  67752. && x2 == subPathCloseX
  67753. && y2 == subPathCloseY;
  67754. return true;
  67755. }
  67756. else if (type == Path::quadMarker)
  67757. {
  67758. const int offset = (int) (stackPos - stackBase);
  67759. if (offset >= stackSize - 10)
  67760. {
  67761. stackSize <<= 1;
  67762. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  67763. stackPos = stackBase + offset;
  67764. }
  67765. const float dx1 = x1 - x2;
  67766. const float dy1 = y1 - y2;
  67767. const float dx2 = x2 - x3;
  67768. const float dy2 = y2 - y3;
  67769. const float m1x = (x1 + x2) * 0.5f;
  67770. const float m1y = (y1 + y2) * 0.5f;
  67771. const float m2x = (x2 + x3) * 0.5f;
  67772. const float m2y = (y2 + y3) * 0.5f;
  67773. const float m3x = (m1x + m2x) * 0.5f;
  67774. const float m3y = (m1y + m2y) * 0.5f;
  67775. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  67776. {
  67777. *stackPos++ = y3;
  67778. *stackPos++ = x3;
  67779. *stackPos++ = m2y;
  67780. *stackPos++ = m2x;
  67781. *stackPos++ = Path::quadMarker;
  67782. *stackPos++ = m3y;
  67783. *stackPos++ = m3x;
  67784. *stackPos++ = m1y;
  67785. *stackPos++ = m1x;
  67786. *stackPos++ = Path::quadMarker;
  67787. }
  67788. else
  67789. {
  67790. *stackPos++ = y3;
  67791. *stackPos++ = x3;
  67792. *stackPos++ = Path::lineMarker;
  67793. *stackPos++ = m3y;
  67794. *stackPos++ = m3x;
  67795. *stackPos++ = Path::lineMarker;
  67796. }
  67797. jassert (stackPos < stackBase + stackSize);
  67798. }
  67799. else if (type == Path::cubicMarker)
  67800. {
  67801. const int offset = (int) (stackPos - stackBase);
  67802. if (offset >= stackSize - 16)
  67803. {
  67804. stackSize <<= 1;
  67805. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  67806. stackPos = stackBase + offset;
  67807. }
  67808. const float dx1 = x1 - x2;
  67809. const float dy1 = y1 - y2;
  67810. const float dx2 = x2 - x3;
  67811. const float dy2 = y2 - y3;
  67812. const float dx3 = x3 - x4;
  67813. const float dy3 = y3 - y4;
  67814. const float m1x = (x1 + x2) * 0.5f;
  67815. const float m1y = (y1 + y2) * 0.5f;
  67816. const float m2x = (x3 + x2) * 0.5f;
  67817. const float m2y = (y3 + y2) * 0.5f;
  67818. const float m3x = (x3 + x4) * 0.5f;
  67819. const float m3y = (y3 + y4) * 0.5f;
  67820. const float m4x = (m1x + m2x) * 0.5f;
  67821. const float m4y = (m1y + m2y) * 0.5f;
  67822. const float m5x = (m3x + m2x) * 0.5f;
  67823. const float m5y = (m3y + m2y) * 0.5f;
  67824. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  67825. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  67826. {
  67827. *stackPos++ = y4;
  67828. *stackPos++ = x4;
  67829. *stackPos++ = m3y;
  67830. *stackPos++ = m3x;
  67831. *stackPos++ = m5y;
  67832. *stackPos++ = m5x;
  67833. *stackPos++ = Path::cubicMarker;
  67834. *stackPos++ = (m4y + m5y) * 0.5f;
  67835. *stackPos++ = (m4x + m5x) * 0.5f;
  67836. *stackPos++ = m4y;
  67837. *stackPos++ = m4x;
  67838. *stackPos++ = m1y;
  67839. *stackPos++ = m1x;
  67840. *stackPos++ = Path::cubicMarker;
  67841. }
  67842. else
  67843. {
  67844. *stackPos++ = y4;
  67845. *stackPos++ = x4;
  67846. *stackPos++ = Path::lineMarker;
  67847. *stackPos++ = m5y;
  67848. *stackPos++ = m5x;
  67849. *stackPos++ = Path::lineMarker;
  67850. *stackPos++ = m4y;
  67851. *stackPos++ = m4x;
  67852. *stackPos++ = Path::lineMarker;
  67853. }
  67854. }
  67855. else if (type == Path::closeSubPathMarker)
  67856. {
  67857. if (x2 != subPathCloseX || y2 != subPathCloseY)
  67858. {
  67859. x1 = x2;
  67860. y1 = y2;
  67861. x2 = subPathCloseX;
  67862. y2 = subPathCloseY;
  67863. closesSubPath = true;
  67864. return true;
  67865. }
  67866. }
  67867. else
  67868. {
  67869. subPathIndex = -1;
  67870. subPathCloseX = x1 = x2;
  67871. subPathCloseY = y1 = y2;
  67872. }
  67873. }
  67874. }
  67875. END_JUCE_NAMESPACE
  67876. /********* End of inlined file: juce_PathIterator.cpp *********/
  67877. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  67878. BEGIN_JUCE_NAMESPACE
  67879. PathStrokeType::PathStrokeType (const float strokeThickness,
  67880. const JointStyle jointStyle_,
  67881. const EndCapStyle endStyle_) throw()
  67882. : thickness (strokeThickness),
  67883. jointStyle (jointStyle_),
  67884. endStyle (endStyle_)
  67885. {
  67886. }
  67887. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  67888. : thickness (other.thickness),
  67889. jointStyle (other.jointStyle),
  67890. endStyle (other.endStyle)
  67891. {
  67892. }
  67893. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  67894. {
  67895. thickness = other.thickness;
  67896. jointStyle = other.jointStyle;
  67897. endStyle = other.endStyle;
  67898. return *this;
  67899. }
  67900. PathStrokeType::~PathStrokeType() throw()
  67901. {
  67902. }
  67903. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  67904. {
  67905. return thickness == other.thickness
  67906. && jointStyle == other.jointStyle
  67907. && endStyle == other.endStyle;
  67908. }
  67909. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  67910. {
  67911. return ! operator== (other);
  67912. }
  67913. static bool lineIntersection (const float x1, const float y1,
  67914. const float x2, const float y2,
  67915. const float x3, const float y3,
  67916. const float x4, const float y4,
  67917. float& intersectionX,
  67918. float& intersectionY,
  67919. float& distanceBeyondLine1EndSquared) throw()
  67920. {
  67921. if (x2 != x3 || y2 != y3)
  67922. {
  67923. const float dx1 = x2 - x1;
  67924. const float dy1 = y2 - y1;
  67925. const float dx2 = x4 - x3;
  67926. const float dy2 = y4 - y3;
  67927. const float divisor = dx1 * dy2 - dx2 * dy1;
  67928. if (divisor == 0)
  67929. {
  67930. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  67931. {
  67932. if (dy1 == 0 && dy2 != 0)
  67933. {
  67934. const float along = (y1 - y3) / dy2;
  67935. intersectionX = x3 + along * dx2;
  67936. intersectionY = y1;
  67937. distanceBeyondLine1EndSquared = intersectionX - x2;
  67938. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67939. if ((x2 > x1) == (intersectionX < x2))
  67940. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67941. return along >= 0 && along <= 1.0f;
  67942. }
  67943. else if (dy2 == 0 && dy1 != 0)
  67944. {
  67945. const float along = (y3 - y1) / dy1;
  67946. intersectionX = x1 + along * dx1;
  67947. intersectionY = y3;
  67948. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  67949. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67950. if (along < 1.0f)
  67951. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67952. return along >= 0 && along <= 1.0f;
  67953. }
  67954. else if (dx1 == 0 && dx2 != 0)
  67955. {
  67956. const float along = (x1 - x3) / dx2;
  67957. intersectionX = x1;
  67958. intersectionY = y3 + along * dy2;
  67959. distanceBeyondLine1EndSquared = intersectionY - y2;
  67960. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67961. if ((y2 > y1) == (intersectionY < y2))
  67962. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67963. return along >= 0 && along <= 1.0f;
  67964. }
  67965. else if (dx2 == 0 && dx1 != 0)
  67966. {
  67967. const float along = (x3 - x1) / dx1;
  67968. intersectionX = x3;
  67969. intersectionY = y1 + along * dy1;
  67970. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  67971. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67972. if (along < 1.0f)
  67973. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67974. return along >= 0 && along <= 1.0f;
  67975. }
  67976. }
  67977. intersectionX = 0.5f * (x2 + x3);
  67978. intersectionY = 0.5f * (y2 + y3);
  67979. distanceBeyondLine1EndSquared = 0.0f;
  67980. return false;
  67981. }
  67982. else
  67983. {
  67984. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  67985. intersectionX = x1 + along1 * dx1;
  67986. intersectionY = y1 + along1 * dy1;
  67987. if (along1 >= 0 && along1 <= 1.0f)
  67988. {
  67989. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  67990. if (along2 >= 0 && along2 <= divisor)
  67991. {
  67992. distanceBeyondLine1EndSquared = 0.0f;
  67993. return true;
  67994. }
  67995. }
  67996. distanceBeyondLine1EndSquared = along1 - 1.0f;
  67997. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67998. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  67999. if (along1 < 1.0f)
  68000. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68001. return false;
  68002. }
  68003. }
  68004. intersectionX = x2;
  68005. intersectionY = y2;
  68006. distanceBeyondLine1EndSquared = 0.0f;
  68007. return true;
  68008. }
  68009. // part of stroke drawing stuff
  68010. static void addEdgeAndJoint (Path& destPath,
  68011. const PathStrokeType::JointStyle style,
  68012. const float maxMiterExtensionSquared, const float width,
  68013. const float x1, const float y1,
  68014. const float x2, const float y2,
  68015. const float x3, const float y3,
  68016. const float x4, const float y4,
  68017. const float midX, const float midY) throw()
  68018. {
  68019. if (style == PathStrokeType::beveled
  68020. || (x3 == x4 && y3 == y4)
  68021. || (x1 == x2 && y1 == y2))
  68022. {
  68023. destPath.lineTo (x2, y2);
  68024. destPath.lineTo (x3, y3);
  68025. }
  68026. else
  68027. {
  68028. float jx, jy, distanceBeyondLine1EndSquared;
  68029. // if they intersect, use this point..
  68030. if (lineIntersection (x1, y1, x2, y2,
  68031. x3, y3, x4, y4,
  68032. jx, jy, distanceBeyondLine1EndSquared))
  68033. {
  68034. destPath.lineTo (jx, jy);
  68035. }
  68036. else
  68037. {
  68038. if (style == PathStrokeType::mitered)
  68039. {
  68040. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  68041. && distanceBeyondLine1EndSquared > 0.0f)
  68042. {
  68043. destPath.lineTo (jx, jy);
  68044. }
  68045. else
  68046. {
  68047. // the end sticks out too far, so just use a blunt joint
  68048. destPath.lineTo (x2, y2);
  68049. destPath.lineTo (x3, y3);
  68050. }
  68051. }
  68052. else
  68053. {
  68054. // curved joints
  68055. float angle = atan2f (x2 - midX, y2 - midY);
  68056. float angle2 = atan2f (x3 - midX, y3 - midY);
  68057. while (angle < angle2 - 0.01f)
  68058. angle2 -= float_Pi * 2.0f;
  68059. destPath.lineTo (x2, y2);
  68060. while (angle > angle2)
  68061. {
  68062. destPath.lineTo (midX + width * sinf (angle),
  68063. midY + width * cosf (angle));
  68064. angle -= 0.1f;
  68065. }
  68066. destPath.lineTo (x3, y3);
  68067. }
  68068. }
  68069. }
  68070. }
  68071. static inline void addLineEnd (Path& destPath,
  68072. const PathStrokeType::EndCapStyle style,
  68073. const float x1, const float y1,
  68074. const float x2, const float y2,
  68075. const float width) throw()
  68076. {
  68077. if (style == PathStrokeType::butt)
  68078. {
  68079. destPath.lineTo (x2, y2);
  68080. }
  68081. else
  68082. {
  68083. float offx1, offy1, offx2, offy2;
  68084. float dx = x2 - x1;
  68085. float dy = y2 - y1;
  68086. const float len = juce_hypotf (dx, dy);
  68087. if (len == 0)
  68088. {
  68089. offx1 = offx2 = x1;
  68090. offy1 = offy2 = y1;
  68091. }
  68092. else
  68093. {
  68094. const float offset = width / len;
  68095. dx *= offset;
  68096. dy *= offset;
  68097. offx1 = x1 + dy;
  68098. offy1 = y1 - dx;
  68099. offx2 = x2 + dy;
  68100. offy2 = y2 - dx;
  68101. }
  68102. if (style == PathStrokeType::square)
  68103. {
  68104. // sqaure ends
  68105. destPath.lineTo (offx1, offy1);
  68106. destPath.lineTo (offx2, offy2);
  68107. destPath.lineTo (x2, y2);
  68108. }
  68109. else
  68110. {
  68111. // rounded ends
  68112. const float midx = (offx1 + offx2) * 0.5f;
  68113. const float midy = (offy1 + offy2) * 0.5f;
  68114. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  68115. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  68116. midx, midy);
  68117. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  68118. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  68119. x2, y2);
  68120. }
  68121. }
  68122. }
  68123. struct LineSection
  68124. {
  68125. LineSection() throw() {}
  68126. LineSection (int) throw() {}
  68127. float x1, y1, x2, y2; // original line
  68128. float lx1, ly1, lx2, ly2; // the left-hand stroke
  68129. float rx1, ry1, rx2, ry2; // the right-hand stroke
  68130. };
  68131. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  68132. const bool isClosed,
  68133. const float width, const float maxMiterExtensionSquared,
  68134. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  68135. {
  68136. jassert (subPath.size() > 0);
  68137. const LineSection& firstLine = subPath.getReference (0);
  68138. float lastX1 = firstLine.lx1;
  68139. float lastY1 = firstLine.ly1;
  68140. float lastX2 = firstLine.lx2;
  68141. float lastY2 = firstLine.ly2;
  68142. if (isClosed)
  68143. {
  68144. destPath.startNewSubPath (lastX1, lastY1);
  68145. }
  68146. else
  68147. {
  68148. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  68149. addLineEnd (destPath, endStyle,
  68150. firstLine.rx2, firstLine.ry2,
  68151. lastX1, lastY1,
  68152. width);
  68153. }
  68154. int i;
  68155. for (i = 1; i < subPath.size(); ++i)
  68156. {
  68157. const LineSection& l = subPath.getReference (i);
  68158. addEdgeAndJoint (destPath, jointStyle,
  68159. maxMiterExtensionSquared, width,
  68160. lastX1, lastY1, lastX2, lastY2,
  68161. l.lx1, l.ly1, l.lx2, l.ly2,
  68162. l.x1, l.y1);
  68163. lastX1 = l.lx1;
  68164. lastY1 = l.ly1;
  68165. lastX2 = l.lx2;
  68166. lastY2 = l.ly2;
  68167. }
  68168. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  68169. if (isClosed)
  68170. {
  68171. const LineSection& l = subPath.getReference (0);
  68172. addEdgeAndJoint (destPath, jointStyle,
  68173. maxMiterExtensionSquared, width,
  68174. lastX1, lastY1, lastX2, lastY2,
  68175. l.lx1, l.ly1, l.lx2, l.ly2,
  68176. l.x1, l.y1);
  68177. destPath.closeSubPath();
  68178. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  68179. }
  68180. else
  68181. {
  68182. destPath.lineTo (lastX2, lastY2);
  68183. addLineEnd (destPath, endStyle,
  68184. lastX2, lastY2,
  68185. lastLine.rx1, lastLine.ry1,
  68186. width);
  68187. }
  68188. lastX1 = lastLine.rx1;
  68189. lastY1 = lastLine.ry1;
  68190. lastX2 = lastLine.rx2;
  68191. lastY2 = lastLine.ry2;
  68192. for (i = subPath.size() - 1; --i >= 0;)
  68193. {
  68194. const LineSection& l = subPath.getReference (i);
  68195. addEdgeAndJoint (destPath, jointStyle,
  68196. maxMiterExtensionSquared, width,
  68197. lastX1, lastY1, lastX2, lastY2,
  68198. l.rx1, l.ry1, l.rx2, l.ry2,
  68199. l.x2, l.y2);
  68200. lastX1 = l.rx1;
  68201. lastY1 = l.ry1;
  68202. lastX2 = l.rx2;
  68203. lastY2 = l.ry2;
  68204. }
  68205. if (isClosed)
  68206. {
  68207. addEdgeAndJoint (destPath, jointStyle,
  68208. maxMiterExtensionSquared, width,
  68209. lastX1, lastY1, lastX2, lastY2,
  68210. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  68211. lastLine.x2, lastLine.y2);
  68212. }
  68213. else
  68214. {
  68215. // do the last line
  68216. destPath.lineTo (lastX2, lastY2);
  68217. }
  68218. destPath.closeSubPath();
  68219. }
  68220. void PathStrokeType::createStrokedPath (Path& destPath,
  68221. const Path& source,
  68222. const AffineTransform& transform,
  68223. const float extraAccuracy) const throw()
  68224. {
  68225. if (thickness <= 0)
  68226. {
  68227. destPath.clear();
  68228. return;
  68229. }
  68230. const Path* sourcePath = &source;
  68231. Path temp;
  68232. if (sourcePath == &destPath)
  68233. {
  68234. destPath.swapWithPath (temp);
  68235. sourcePath = &temp;
  68236. }
  68237. else
  68238. {
  68239. destPath.clear();
  68240. }
  68241. destPath.setUsingNonZeroWinding (true);
  68242. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  68243. const float width = 0.5f * thickness;
  68244. // Iterate the path, creating a list of the
  68245. // left/right-hand lines along either side of it...
  68246. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  68247. Array <LineSection> subPath;
  68248. LineSection l;
  68249. l.x1 = 0;
  68250. l.y1 = 0;
  68251. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  68252. while (it.next())
  68253. {
  68254. if (it.subPathIndex == 0)
  68255. {
  68256. if (subPath.size() > 0)
  68257. {
  68258. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68259. subPath.clearQuick();
  68260. }
  68261. l.x1 = it.x1;
  68262. l.y1 = it.y1;
  68263. }
  68264. l.x2 = it.x2;
  68265. l.y2 = it.y2;
  68266. float dx = l.x2 - l.x1;
  68267. float dy = l.y2 - l.y1;
  68268. const float hypotSquared = dx*dx + dy*dy;
  68269. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  68270. {
  68271. const float len = sqrtf (hypotSquared);
  68272. if (len == 0)
  68273. {
  68274. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  68275. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  68276. }
  68277. else
  68278. {
  68279. const float offset = width / len;
  68280. dx *= offset;
  68281. dy *= offset;
  68282. l.rx2 = l.x1 - dy;
  68283. l.ry2 = l.y1 + dx;
  68284. l.lx1 = l.x1 + dy;
  68285. l.ly1 = l.y1 - dx;
  68286. l.lx2 = l.x2 + dy;
  68287. l.ly2 = l.y2 - dx;
  68288. l.rx1 = l.x2 - dy;
  68289. l.ry1 = l.y2 + dx;
  68290. }
  68291. subPath.add (l);
  68292. if (it.closesSubPath)
  68293. {
  68294. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68295. subPath.clearQuick();
  68296. }
  68297. else
  68298. {
  68299. l.x1 = it.x2;
  68300. l.y1 = it.y2;
  68301. }
  68302. }
  68303. }
  68304. if (subPath.size() > 0)
  68305. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68306. }
  68307. void PathStrokeType::createDashedStroke (Path& destPath,
  68308. const Path& sourcePath,
  68309. const float* dashLengths,
  68310. int numDashLengths,
  68311. const AffineTransform& transform,
  68312. const float extraAccuracy) const throw()
  68313. {
  68314. if (thickness <= 0)
  68315. return;
  68316. // this should really be an even number..
  68317. jassert ((numDashLengths & 1) == 0);
  68318. Path newDestPath;
  68319. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  68320. bool first = true;
  68321. int dashNum = 0;
  68322. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  68323. float dx = 0.0f, dy = 0.0f;
  68324. for (;;)
  68325. {
  68326. const bool isSolid = ((dashNum & 1) == 0);
  68327. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  68328. jassert (dashLen > 0); // must be a positive increment!
  68329. if (dashLen <= 0)
  68330. break;
  68331. pos += dashLen;
  68332. while (pos > lineEndPos)
  68333. {
  68334. if (! it.next())
  68335. {
  68336. if (isSolid && ! first)
  68337. newDestPath.lineTo (it.x2, it.y2);
  68338. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  68339. return;
  68340. }
  68341. if (isSolid && ! first)
  68342. {
  68343. newDestPath.lineTo (it.x1, it.y1);
  68344. }
  68345. else
  68346. {
  68347. newDestPath.startNewSubPath (it.x1, it.y1);
  68348. first = false;
  68349. }
  68350. dx = it.x2 - it.x1;
  68351. dy = it.y2 - it.y1;
  68352. lineLen = juce_hypotf (dx, dy);
  68353. lineEndPos += lineLen;
  68354. }
  68355. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  68356. if (isSolid)
  68357. newDestPath.lineTo (it.x1 + dx * alpha,
  68358. it.y1 + dy * alpha);
  68359. else
  68360. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  68361. it.y1 + dy * alpha);
  68362. }
  68363. }
  68364. END_JUCE_NAMESPACE
  68365. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  68366. /********* Start of inlined file: juce_Point.cpp *********/
  68367. BEGIN_JUCE_NAMESPACE
  68368. Point::Point() throw()
  68369. : x (0.0f),
  68370. y (0.0f)
  68371. {
  68372. }
  68373. Point::Point (const Point& other) throw()
  68374. : x (other.x),
  68375. y (other.y)
  68376. {
  68377. }
  68378. const Point& Point::operator= (const Point& other) throw()
  68379. {
  68380. x = other.x;
  68381. y = other.y;
  68382. return *this;
  68383. }
  68384. Point::Point (const float x_,
  68385. const float y_) throw()
  68386. : x (x_),
  68387. y (y_)
  68388. {
  68389. }
  68390. Point::~Point() throw()
  68391. {
  68392. }
  68393. void Point::setXY (const float x_,
  68394. const float y_) throw()
  68395. {
  68396. x = x_;
  68397. y = y_;
  68398. }
  68399. void Point::applyTransform (const AffineTransform& transform) throw()
  68400. {
  68401. transform.transformPoint (x, y);
  68402. }
  68403. END_JUCE_NAMESPACE
  68404. /********* End of inlined file: juce_Point.cpp *********/
  68405. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  68406. BEGIN_JUCE_NAMESPACE
  68407. PositionedRectangle::PositionedRectangle() throw()
  68408. : x (0.0),
  68409. y (0.0),
  68410. w (0.0),
  68411. h (0.0),
  68412. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  68413. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  68414. wMode (absoluteSize),
  68415. hMode (absoluteSize)
  68416. {
  68417. }
  68418. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  68419. : x (other.x),
  68420. y (other.y),
  68421. w (other.w),
  68422. h (other.h),
  68423. xMode (other.xMode),
  68424. yMode (other.yMode),
  68425. wMode (other.wMode),
  68426. hMode (other.hMode)
  68427. {
  68428. }
  68429. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  68430. {
  68431. if (this != &other)
  68432. {
  68433. x = other.x;
  68434. y = other.y;
  68435. w = other.w;
  68436. h = other.h;
  68437. xMode = other.xMode;
  68438. yMode = other.yMode;
  68439. wMode = other.wMode;
  68440. hMode = other.hMode;
  68441. }
  68442. return *this;
  68443. }
  68444. PositionedRectangle::~PositionedRectangle() throw()
  68445. {
  68446. }
  68447. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  68448. {
  68449. return x == other.x
  68450. && y == other.y
  68451. && w == other.w
  68452. && h == other.h
  68453. && xMode == other.xMode
  68454. && yMode == other.yMode
  68455. && wMode == other.wMode
  68456. && hMode == other.hMode;
  68457. }
  68458. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  68459. {
  68460. return ! operator== (other);
  68461. }
  68462. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  68463. {
  68464. StringArray tokens;
  68465. tokens.addTokens (stringVersion, false);
  68466. decodePosString (tokens [0], xMode, x);
  68467. decodePosString (tokens [1], yMode, y);
  68468. decodeSizeString (tokens [2], wMode, w);
  68469. decodeSizeString (tokens [3], hMode, h);
  68470. }
  68471. const String PositionedRectangle::toString() const throw()
  68472. {
  68473. String s;
  68474. s.preallocateStorage (12);
  68475. addPosDescription (s, xMode, x);
  68476. s << T(' ');
  68477. addPosDescription (s, yMode, y);
  68478. s << T(' ');
  68479. addSizeDescription (s, wMode, w);
  68480. s << T(' ');
  68481. addSizeDescription (s, hMode, h);
  68482. return s;
  68483. }
  68484. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  68485. {
  68486. jassert (! target.isEmpty());
  68487. double x_, y_, w_, h_;
  68488. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  68489. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  68490. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  68491. roundDoubleToInt (w_), roundDoubleToInt (h_));
  68492. }
  68493. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  68494. double& x_, double& y_,
  68495. double& w_, double& h_) const throw()
  68496. {
  68497. jassert (! target.isEmpty());
  68498. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  68499. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  68500. }
  68501. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  68502. {
  68503. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  68504. }
  68505. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  68506. const Rectangle& target) throw()
  68507. {
  68508. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  68509. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  68510. }
  68511. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  68512. const double newW, const double newH,
  68513. const Rectangle& target) throw()
  68514. {
  68515. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  68516. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  68517. }
  68518. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  68519. {
  68520. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  68521. updateFrom (comp.getBounds(), Rectangle());
  68522. else
  68523. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  68524. }
  68525. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  68526. {
  68527. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  68528. }
  68529. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  68530. {
  68531. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  68532. | absoluteFromParentBottomRight
  68533. | absoluteFromParentCentre
  68534. | proportionOfParentSize));
  68535. }
  68536. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  68537. {
  68538. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  68539. }
  68540. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  68541. {
  68542. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  68543. | absoluteFromParentBottomRight
  68544. | absoluteFromParentCentre
  68545. | proportionOfParentSize));
  68546. }
  68547. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  68548. {
  68549. return (SizeMode) wMode;
  68550. }
  68551. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  68552. {
  68553. return (SizeMode) hMode;
  68554. }
  68555. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  68556. const PositionMode xMode_,
  68557. const AnchorPoint yAnchor,
  68558. const PositionMode yMode_,
  68559. const SizeMode widthMode,
  68560. const SizeMode heightMode,
  68561. const Rectangle& target) throw()
  68562. {
  68563. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  68564. {
  68565. double tx, tw;
  68566. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  68567. xMode = (uint8) (xAnchor | xMode_);
  68568. wMode = (uint8) widthMode;
  68569. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  68570. }
  68571. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  68572. {
  68573. double ty, th;
  68574. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  68575. yMode = (uint8) (yAnchor | yMode_);
  68576. hMode = (uint8) heightMode;
  68577. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  68578. }
  68579. }
  68580. bool PositionedRectangle::isPositionAbsolute() const throw()
  68581. {
  68582. return xMode == absoluteFromParentTopLeft
  68583. && yMode == absoluteFromParentTopLeft
  68584. && wMode == absoluteSize
  68585. && hMode == absoluteSize;
  68586. }
  68587. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  68588. {
  68589. if ((mode & proportionOfParentSize) != 0)
  68590. {
  68591. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  68592. }
  68593. else
  68594. {
  68595. s << (roundDoubleToInt (value * 100.0) / 100.0);
  68596. if ((mode & absoluteFromParentBottomRight) != 0)
  68597. s << T('R');
  68598. else if ((mode & absoluteFromParentCentre) != 0)
  68599. s << T('C');
  68600. }
  68601. if ((mode & anchorAtRightOrBottom) != 0)
  68602. s << T('r');
  68603. else if ((mode & anchorAtCentre) != 0)
  68604. s << T('c');
  68605. }
  68606. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  68607. {
  68608. if (mode == proportionalSize)
  68609. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  68610. else if (mode == parentSizeMinusAbsolute)
  68611. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  68612. else
  68613. s << (roundDoubleToInt (value * 100.0) / 100.0);
  68614. }
  68615. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  68616. {
  68617. if (s.containsChar (T('r')))
  68618. mode = anchorAtRightOrBottom;
  68619. else if (s.containsChar (T('c')))
  68620. mode = anchorAtCentre;
  68621. else
  68622. mode = anchorAtLeftOrTop;
  68623. if (s.containsChar (T('%')))
  68624. {
  68625. mode |= proportionOfParentSize;
  68626. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  68627. }
  68628. else
  68629. {
  68630. if (s.containsChar (T('R')))
  68631. mode |= absoluteFromParentBottomRight;
  68632. else if (s.containsChar (T('C')))
  68633. mode |= absoluteFromParentCentre;
  68634. else
  68635. mode |= absoluteFromParentTopLeft;
  68636. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  68637. }
  68638. }
  68639. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  68640. {
  68641. if (s.containsChar (T('%')))
  68642. {
  68643. mode = proportionalSize;
  68644. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  68645. }
  68646. else if (s.containsChar (T('M')))
  68647. {
  68648. mode = parentSizeMinusAbsolute;
  68649. value = s.getDoubleValue();
  68650. }
  68651. else
  68652. {
  68653. mode = absoluteSize;
  68654. value = s.getDoubleValue();
  68655. }
  68656. }
  68657. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  68658. const double x, const double w,
  68659. const uint8 xMode, const uint8 wMode,
  68660. const int parentPos,
  68661. const int parentSize) const throw()
  68662. {
  68663. if (wMode == proportionalSize)
  68664. wOut = roundDoubleToInt (w * parentSize);
  68665. else if (wMode == parentSizeMinusAbsolute)
  68666. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  68667. else
  68668. wOut = roundDoubleToInt (w);
  68669. if ((xMode & proportionOfParentSize) != 0)
  68670. xOut = parentPos + x * parentSize;
  68671. else if ((xMode & absoluteFromParentBottomRight) != 0)
  68672. xOut = (parentPos + parentSize) - x;
  68673. else if ((xMode & absoluteFromParentCentre) != 0)
  68674. xOut = x + (parentPos + parentSize / 2);
  68675. else
  68676. xOut = x + parentPos;
  68677. if ((xMode & anchorAtRightOrBottom) != 0)
  68678. xOut -= wOut;
  68679. else if ((xMode & anchorAtCentre) != 0)
  68680. xOut -= wOut / 2;
  68681. }
  68682. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  68683. double x, const double w,
  68684. const uint8 xMode, const uint8 wMode,
  68685. const int parentPos,
  68686. const int parentSize) const throw()
  68687. {
  68688. if (wMode == proportionalSize)
  68689. {
  68690. if (parentSize > 0)
  68691. wOut = w / parentSize;
  68692. }
  68693. else if (wMode == parentSizeMinusAbsolute)
  68694. wOut = parentSize - w;
  68695. else
  68696. wOut = w;
  68697. if ((xMode & anchorAtRightOrBottom) != 0)
  68698. x += w;
  68699. else if ((xMode & anchorAtCentre) != 0)
  68700. x += w / 2;
  68701. if ((xMode & proportionOfParentSize) != 0)
  68702. {
  68703. if (parentSize > 0)
  68704. xOut = (x - parentPos) / parentSize;
  68705. }
  68706. else if ((xMode & absoluteFromParentBottomRight) != 0)
  68707. xOut = (parentPos + parentSize) - x;
  68708. else if ((xMode & absoluteFromParentCentre) != 0)
  68709. xOut = x - (parentPos + parentSize / 2);
  68710. else
  68711. xOut = x - parentPos;
  68712. }
  68713. END_JUCE_NAMESPACE
  68714. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  68715. /********* Start of inlined file: juce_Rectangle.cpp *********/
  68716. BEGIN_JUCE_NAMESPACE
  68717. Rectangle::Rectangle() throw()
  68718. : x (0),
  68719. y (0),
  68720. w (0),
  68721. h (0)
  68722. {
  68723. }
  68724. Rectangle::Rectangle (const int x_, const int y_,
  68725. const int w_, const int h_) throw()
  68726. : x (x_),
  68727. y (y_),
  68728. w (w_),
  68729. h (h_)
  68730. {
  68731. }
  68732. Rectangle::Rectangle (const int w_, const int h_) throw()
  68733. : x (0),
  68734. y (0),
  68735. w (w_),
  68736. h (h_)
  68737. {
  68738. }
  68739. Rectangle::Rectangle (const Rectangle& other) throw()
  68740. : x (other.x),
  68741. y (other.y),
  68742. w (other.w),
  68743. h (other.h)
  68744. {
  68745. }
  68746. Rectangle::~Rectangle() throw()
  68747. {
  68748. }
  68749. bool Rectangle::isEmpty() const throw()
  68750. {
  68751. return w <= 0 || h <= 0;
  68752. }
  68753. void Rectangle::setBounds (const int x_,
  68754. const int y_,
  68755. const int w_,
  68756. const int h_) throw()
  68757. {
  68758. x = x_;
  68759. y = y_;
  68760. w = w_;
  68761. h = h_;
  68762. }
  68763. void Rectangle::setPosition (const int x_,
  68764. const int y_) throw()
  68765. {
  68766. x = x_;
  68767. y = y_;
  68768. }
  68769. void Rectangle::setSize (const int w_,
  68770. const int h_) throw()
  68771. {
  68772. w = w_;
  68773. h = h_;
  68774. }
  68775. void Rectangle::translate (const int dx,
  68776. const int dy) throw()
  68777. {
  68778. x += dx;
  68779. y += dy;
  68780. }
  68781. const Rectangle Rectangle::translated (const int dx,
  68782. const int dy) const throw()
  68783. {
  68784. return Rectangle (x + dx, y + dy, w, h);
  68785. }
  68786. void Rectangle::expand (const int deltaX,
  68787. const int deltaY) throw()
  68788. {
  68789. const int nw = jmax (0, w + deltaX + deltaX);
  68790. const int nh = jmax (0, h + deltaY + deltaY);
  68791. setBounds (x - deltaX,
  68792. y - deltaY,
  68793. nw, nh);
  68794. }
  68795. const Rectangle Rectangle::expanded (const int deltaX,
  68796. const int deltaY) const throw()
  68797. {
  68798. const int nw = jmax (0, w + deltaX + deltaX);
  68799. const int nh = jmax (0, h + deltaY + deltaY);
  68800. return Rectangle (x - deltaX,
  68801. y - deltaY,
  68802. nw, nh);
  68803. }
  68804. void Rectangle::reduce (const int deltaX,
  68805. const int deltaY) throw()
  68806. {
  68807. expand (-deltaX, -deltaY);
  68808. }
  68809. const Rectangle Rectangle::reduced (const int deltaX,
  68810. const int deltaY) const throw()
  68811. {
  68812. return expanded (-deltaX, -deltaY);
  68813. }
  68814. bool Rectangle::operator== (const Rectangle& other) const throw()
  68815. {
  68816. return x == other.x
  68817. && y == other.y
  68818. && w == other.w
  68819. && h == other.h;
  68820. }
  68821. bool Rectangle::operator!= (const Rectangle& other) const throw()
  68822. {
  68823. return x != other.x
  68824. || y != other.y
  68825. || w != other.w
  68826. || h != other.h;
  68827. }
  68828. bool Rectangle::contains (const int px,
  68829. const int py) const throw()
  68830. {
  68831. return px >= x
  68832. && py >= y
  68833. && px < x + w
  68834. && py < y + h;
  68835. }
  68836. bool Rectangle::contains (const Rectangle& other) const throw()
  68837. {
  68838. return x <= other.x
  68839. && y <= other.y
  68840. && x + w >= other.x + other.w
  68841. && y + h >= other.y + other.h;
  68842. }
  68843. bool Rectangle::intersects (const Rectangle& other) const throw()
  68844. {
  68845. return x + w > other.x
  68846. && y + h > other.y
  68847. && x < other.x + other.w
  68848. && y < other.y + other.h
  68849. && w > 0
  68850. && h > 0;
  68851. }
  68852. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  68853. {
  68854. const int nx = jmax (x, other.x);
  68855. const int ny = jmax (y, other.y);
  68856. const int nw = jmin (x + w, other.x + other.w) - nx;
  68857. const int nh = jmin (y + h, other.y + other.h) - ny;
  68858. if (nw >= 0 && nh >= 0)
  68859. return Rectangle (nx, ny, nw, nh);
  68860. else
  68861. return Rectangle();
  68862. }
  68863. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  68864. {
  68865. const int maxX = jmax (x1, x);
  68866. w1 = jmin (x1 + w1, x + w) - maxX;
  68867. if (w1 > 0)
  68868. {
  68869. const int maxY = jmax (y1, y);
  68870. h1 = jmin (y1 + h1, y + h) - maxY;
  68871. if (h1 > 0)
  68872. {
  68873. x1 = maxX;
  68874. y1 = maxY;
  68875. return true;
  68876. }
  68877. }
  68878. return false;
  68879. }
  68880. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  68881. int x2, int y2, int w2, int h2) throw()
  68882. {
  68883. const int x = jmax (x1, x2);
  68884. w1 = jmin (x1 + w1, x2 + w2) - x;
  68885. if (w1 > 0)
  68886. {
  68887. const int y = jmax (y1, y2);
  68888. h1 = jmin (y1 + h1, y2 + h2) - y;
  68889. if (h1 > 0)
  68890. {
  68891. x1 = x;
  68892. y1 = y;
  68893. return true;
  68894. }
  68895. }
  68896. return false;
  68897. }
  68898. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  68899. {
  68900. const int newX = jmin (x, other.x);
  68901. const int newY = jmin (y, other.y);
  68902. return Rectangle (newX, newY,
  68903. jmax (x + w, other.x + other.w) - newX,
  68904. jmax (y + h, other.y + other.h) - newY);
  68905. }
  68906. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  68907. {
  68908. if (x == other.x && getRight() == other.getRight()
  68909. && (other.getBottom() >= y && other.y <= getBottom()))
  68910. {
  68911. const int newY = jmin (y, other.y);
  68912. h = jmax (getBottom(), other.getBottom()) - newY;
  68913. y = newY;
  68914. return true;
  68915. }
  68916. else if (y == other.y && getBottom() == other.getBottom()
  68917. && (other.getRight() >= x && other.x <= getRight()))
  68918. {
  68919. const int newX = jmin (x, other.x);
  68920. w = jmax (getRight(), other.getRight()) - newX;
  68921. x = newX;
  68922. return true;
  68923. }
  68924. return false;
  68925. }
  68926. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  68927. {
  68928. int inside = 0;
  68929. const int otherR = other.getRight();
  68930. if (x >= other.x && x < otherR)
  68931. inside = 1;
  68932. const int otherB = other.getBottom();
  68933. if (y >= other.y && y < otherB)
  68934. inside |= 2;
  68935. const int r = x + w;
  68936. if (r >= other.x && r < otherR)
  68937. inside |= 4;
  68938. const int b = y + h;
  68939. if (b >= other.y && b < otherB)
  68940. inside |= 8;
  68941. switch (inside)
  68942. {
  68943. case 1 + 2 + 8:
  68944. w = r - otherR;
  68945. x = otherR;
  68946. return true;
  68947. case 1 + 2 + 4:
  68948. h = b - otherB;
  68949. y = otherB;
  68950. return true;
  68951. case 2 + 4 + 8:
  68952. w = other.x - x;
  68953. return true;
  68954. case 1 + 4 + 8:
  68955. h = other.y - y;
  68956. return true;
  68957. }
  68958. return false;
  68959. }
  68960. const String Rectangle::toString() const throw()
  68961. {
  68962. String s;
  68963. s.preallocateStorage (16);
  68964. s << x << T(' ')
  68965. << y << T(' ')
  68966. << w << T(' ')
  68967. << h;
  68968. return s;
  68969. }
  68970. const Rectangle Rectangle::fromString (const String& stringVersion)
  68971. {
  68972. StringArray toks;
  68973. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  68974. return Rectangle (toks[0].trim().getIntValue(),
  68975. toks[1].trim().getIntValue(),
  68976. toks[2].trim().getIntValue(),
  68977. toks[3].trim().getIntValue());
  68978. }
  68979. END_JUCE_NAMESPACE
  68980. /********* End of inlined file: juce_Rectangle.cpp *********/
  68981. /********* Start of inlined file: juce_RectangleList.cpp *********/
  68982. BEGIN_JUCE_NAMESPACE
  68983. RectangleList::RectangleList() throw()
  68984. {
  68985. }
  68986. RectangleList::RectangleList (const Rectangle& rect) throw()
  68987. {
  68988. if (! rect.isEmpty())
  68989. rects.add (rect);
  68990. }
  68991. RectangleList::RectangleList (const RectangleList& other) throw()
  68992. : rects (other.rects)
  68993. {
  68994. }
  68995. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  68996. {
  68997. if (this != &other)
  68998. rects = other.rects;
  68999. return *this;
  69000. }
  69001. RectangleList::~RectangleList() throw()
  69002. {
  69003. }
  69004. void RectangleList::clear() throw()
  69005. {
  69006. rects.clearQuick();
  69007. }
  69008. const Rectangle RectangleList::getRectangle (const int index) const throw()
  69009. {
  69010. if (((unsigned int) index) < (unsigned int) rects.size())
  69011. return rects.getReference (index);
  69012. return Rectangle();
  69013. }
  69014. bool RectangleList::isEmpty() const throw()
  69015. {
  69016. return rects.size() == 0;
  69017. }
  69018. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  69019. : current (0),
  69020. owner (list),
  69021. index (list.rects.size())
  69022. {
  69023. }
  69024. RectangleList::Iterator::~Iterator() throw()
  69025. {
  69026. }
  69027. bool RectangleList::Iterator::next() throw()
  69028. {
  69029. if (--index >= 0)
  69030. {
  69031. current = & (owner.rects.getReference (index));
  69032. return true;
  69033. }
  69034. return false;
  69035. }
  69036. void RectangleList::add (const Rectangle& rect) throw()
  69037. {
  69038. if (! rect.isEmpty())
  69039. {
  69040. if (rects.size() == 0)
  69041. {
  69042. rects.add (rect);
  69043. }
  69044. else
  69045. {
  69046. bool anyOverlaps = false;
  69047. int i;
  69048. for (i = rects.size(); --i >= 0;)
  69049. {
  69050. Rectangle& ourRect = rects.getReference (i);
  69051. if (rect.intersects (ourRect))
  69052. {
  69053. if (rect.contains (ourRect))
  69054. rects.remove (i);
  69055. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  69056. anyOverlaps = true;
  69057. }
  69058. }
  69059. if (anyOverlaps && rects.size() > 0)
  69060. {
  69061. RectangleList r (rect);
  69062. for (i = rects.size(); --i >= 0;)
  69063. {
  69064. const Rectangle& ourRect = rects.getReference (i);
  69065. if (rect.intersects (ourRect))
  69066. {
  69067. r.subtract (ourRect);
  69068. if (r.rects.size() == 0)
  69069. return;
  69070. }
  69071. }
  69072. for (i = r.getNumRectangles(); --i >= 0;)
  69073. rects.add (r.rects.getReference (i));
  69074. }
  69075. else
  69076. {
  69077. rects.add (rect);
  69078. }
  69079. }
  69080. }
  69081. }
  69082. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  69083. {
  69084. rects.add (rect);
  69085. }
  69086. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  69087. {
  69088. if (rects.size() == 0)
  69089. {
  69090. if (w > 0 && h > 0)
  69091. rects.add (Rectangle (x, y, w, h));
  69092. }
  69093. else
  69094. {
  69095. add (Rectangle (x, y, w, h));
  69096. }
  69097. }
  69098. void RectangleList::add (const RectangleList& other) throw()
  69099. {
  69100. for (int i = 0; i < other.rects.size(); ++i)
  69101. add (other.rects.getReference (i));
  69102. }
  69103. void RectangleList::subtract (const Rectangle& rect) throw()
  69104. {
  69105. const int originalNumRects = rects.size();
  69106. if (originalNumRects > 0)
  69107. {
  69108. const int x1 = rect.x;
  69109. const int y1 = rect.y;
  69110. const int x2 = x1 + rect.w;
  69111. const int y2 = y1 + rect.h;
  69112. for (int i = getNumRectangles(); --i >= 0;)
  69113. {
  69114. Rectangle& r = rects.getReference (i);
  69115. const int rx1 = r.x;
  69116. const int ry1 = r.y;
  69117. const int rx2 = rx1 + r.w;
  69118. const int ry2 = ry1 + r.h;
  69119. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  69120. {
  69121. if (x1 > rx1 && x1 < rx2)
  69122. {
  69123. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  69124. {
  69125. r.w = x1 - rx1;
  69126. }
  69127. else
  69128. {
  69129. r.x = x1;
  69130. r.w = rx2 - x1;
  69131. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  69132. i += 2;
  69133. }
  69134. }
  69135. else if (x2 > rx1 && x2 < rx2)
  69136. {
  69137. r.x = x2;
  69138. r.w = rx2 - x2;
  69139. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  69140. {
  69141. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  69142. i += 2;
  69143. }
  69144. }
  69145. else if (y1 > ry1 && y1 < ry2)
  69146. {
  69147. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  69148. {
  69149. r.h = y1 - ry1;
  69150. }
  69151. else
  69152. {
  69153. r.y = y1;
  69154. r.h = ry2 - y1;
  69155. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  69156. i += 2;
  69157. }
  69158. }
  69159. else if (y2 > ry1 && y2 < ry2)
  69160. {
  69161. r.y = y2;
  69162. r.h = ry2 - y2;
  69163. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  69164. {
  69165. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  69166. i += 2;
  69167. }
  69168. }
  69169. else
  69170. {
  69171. rects.remove (i);
  69172. }
  69173. }
  69174. }
  69175. if (rects.size() > originalNumRects + 10)
  69176. consolidate();
  69177. }
  69178. }
  69179. void RectangleList::subtract (const RectangleList& otherList) throw()
  69180. {
  69181. for (int i = otherList.rects.size(); --i >= 0;)
  69182. subtract (otherList.rects.getReference (i));
  69183. }
  69184. bool RectangleList::clipTo (const Rectangle& rect) throw()
  69185. {
  69186. bool notEmpty = false;
  69187. if (rect.isEmpty())
  69188. {
  69189. clear();
  69190. }
  69191. else
  69192. {
  69193. for (int i = rects.size(); --i >= 0;)
  69194. {
  69195. Rectangle& r = rects.getReference (i);
  69196. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69197. rects.remove (i);
  69198. else
  69199. notEmpty = true;
  69200. }
  69201. }
  69202. return notEmpty;
  69203. }
  69204. bool RectangleList::clipTo (const RectangleList& other) throw()
  69205. {
  69206. if (rects.size() == 0)
  69207. return false;
  69208. RectangleList result;
  69209. for (int j = 0; j < rects.size(); ++j)
  69210. {
  69211. const Rectangle& rect = rects.getReference (j);
  69212. for (int i = other.rects.size(); --i >= 0;)
  69213. {
  69214. Rectangle r (other.rects.getReference (i));
  69215. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69216. result.rects.add (r);
  69217. }
  69218. }
  69219. swapWith (result);
  69220. return ! isEmpty();
  69221. }
  69222. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  69223. {
  69224. destRegion.clear();
  69225. if (! rect.isEmpty())
  69226. {
  69227. for (int i = rects.size(); --i >= 0;)
  69228. {
  69229. Rectangle r (rects.getReference (i));
  69230. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69231. destRegion.rects.add (r);
  69232. }
  69233. }
  69234. return destRegion.rects.size() > 0;
  69235. }
  69236. void RectangleList::swapWith (RectangleList& otherList) throw()
  69237. {
  69238. rects.swapWithArray (otherList.rects);
  69239. }
  69240. void RectangleList::consolidate() throw()
  69241. {
  69242. int i;
  69243. for (i = 0; i < getNumRectangles() - 1; ++i)
  69244. {
  69245. Rectangle& r = rects.getReference (i);
  69246. const int rx1 = r.x;
  69247. const int ry1 = r.y;
  69248. const int rx2 = rx1 + r.w;
  69249. const int ry2 = ry1 + r.h;
  69250. for (int j = rects.size(); --j > i;)
  69251. {
  69252. Rectangle& r2 = rects.getReference (j);
  69253. const int jrx1 = r2.x;
  69254. const int jry1 = r2.y;
  69255. const int jrx2 = jrx1 + r2.w;
  69256. const int jry2 = jry1 + r2.h;
  69257. // if the vertical edges of any blocks are touching and their horizontals don't
  69258. // line up, split them horizontally..
  69259. if (jrx1 == rx2 || jrx2 == rx1)
  69260. {
  69261. if (jry1 > ry1 && jry1 < ry2)
  69262. {
  69263. r.h = jry1 - ry1;
  69264. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  69265. i = -1;
  69266. break;
  69267. }
  69268. if (jry2 > ry1 && jry2 < ry2)
  69269. {
  69270. r.h = jry2 - ry1;
  69271. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  69272. i = -1;
  69273. break;
  69274. }
  69275. else if (ry1 > jry1 && ry1 < jry2)
  69276. {
  69277. r2.h = ry1 - jry1;
  69278. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  69279. i = -1;
  69280. break;
  69281. }
  69282. else if (ry2 > jry1 && ry2 < jry2)
  69283. {
  69284. r2.h = ry2 - jry1;
  69285. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  69286. i = -1;
  69287. break;
  69288. }
  69289. }
  69290. }
  69291. }
  69292. for (i = 0; i < rects.size() - 1; ++i)
  69293. {
  69294. Rectangle& r = rects.getReference (i);
  69295. for (int j = rects.size(); --j > i;)
  69296. {
  69297. if (r.enlargeIfAdjacent (rects.getReference (j)))
  69298. {
  69299. rects.remove (j);
  69300. i = -1;
  69301. break;
  69302. }
  69303. }
  69304. }
  69305. }
  69306. bool RectangleList::containsPoint (const int x, const int y) const throw()
  69307. {
  69308. for (int i = getNumRectangles(); --i >= 0;)
  69309. if (rects.getReference (i).contains (x, y))
  69310. return true;
  69311. return false;
  69312. }
  69313. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  69314. {
  69315. if (rects.size() > 1)
  69316. {
  69317. RectangleList r (rectangleToCheck);
  69318. for (int i = rects.size(); --i >= 0;)
  69319. {
  69320. r.subtract (rects.getReference (i));
  69321. if (r.rects.size() == 0)
  69322. return true;
  69323. }
  69324. }
  69325. else if (rects.size() > 0)
  69326. {
  69327. return rects.getReference (0).contains (rectangleToCheck);
  69328. }
  69329. return false;
  69330. }
  69331. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  69332. {
  69333. for (int i = rects.size(); --i >= 0;)
  69334. if (rects.getReference (i).intersects (rectangleToCheck))
  69335. return true;
  69336. return false;
  69337. }
  69338. bool RectangleList::intersects (const RectangleList& other) const throw()
  69339. {
  69340. for (int i = rects.size(); --i >= 0;)
  69341. if (other.intersectsRectangle (rects.getReference (i)))
  69342. return true;
  69343. return false;
  69344. }
  69345. const Rectangle RectangleList::getBounds() const throw()
  69346. {
  69347. if (rects.size() <= 1)
  69348. {
  69349. if (rects.size() == 0)
  69350. return Rectangle();
  69351. else
  69352. return rects.getReference (0);
  69353. }
  69354. else
  69355. {
  69356. const Rectangle& r = rects.getReference (0);
  69357. int minX = r.x;
  69358. int minY = r.y;
  69359. int maxX = minX + r.w;
  69360. int maxY = minY + r.h;
  69361. for (int i = rects.size(); --i > 0;)
  69362. {
  69363. const Rectangle& r2 = rects.getReference (i);
  69364. minX = jmin (minX, r2.x);
  69365. minY = jmin (minY, r2.y);
  69366. maxX = jmax (maxX, r2.getRight());
  69367. maxY = jmax (maxY, r2.getBottom());
  69368. }
  69369. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  69370. }
  69371. }
  69372. void RectangleList::offsetAll (const int dx, const int dy) throw()
  69373. {
  69374. for (int i = rects.size(); --i >= 0;)
  69375. {
  69376. Rectangle& r = rects.getReference (i);
  69377. r.x += dx;
  69378. r.y += dy;
  69379. }
  69380. }
  69381. const Path RectangleList::toPath() const throw()
  69382. {
  69383. Path p;
  69384. for (int i = rects.size(); --i >= 0;)
  69385. {
  69386. const Rectangle& r = rects.getReference (i);
  69387. p.addRectangle ((float) r.x,
  69388. (float) r.y,
  69389. (float) r.w,
  69390. (float) r.h);
  69391. }
  69392. return p;
  69393. }
  69394. END_JUCE_NAMESPACE
  69395. /********* End of inlined file: juce_RectangleList.cpp *********/
  69396. /********* Start of inlined file: juce_Image.cpp *********/
  69397. BEGIN_JUCE_NAMESPACE
  69398. static const int fullAlphaThreshold = 253;
  69399. Image::Image (const PixelFormat format_,
  69400. const int imageWidth_,
  69401. const int imageHeight_)
  69402. : format (format_),
  69403. imageWidth (imageWidth_),
  69404. imageHeight (imageHeight_),
  69405. imageData (0)
  69406. {
  69407. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  69408. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  69409. // actual image will be at least 1x1.
  69410. }
  69411. Image::Image (const PixelFormat format_,
  69412. const int imageWidth_,
  69413. const int imageHeight_,
  69414. const bool clearImage)
  69415. : format (format_),
  69416. imageWidth (imageWidth_),
  69417. imageHeight (imageHeight_)
  69418. {
  69419. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  69420. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  69421. // actual image will be at least 1x1.
  69422. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  69423. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  69424. const int dataSize = lineStride * jmax (1, imageHeight_);
  69425. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  69426. : juce_malloc (dataSize));
  69427. }
  69428. Image::Image (const Image& other)
  69429. : format (other.format),
  69430. imageWidth (other.imageWidth),
  69431. imageHeight (other.imageHeight)
  69432. {
  69433. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  69434. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  69435. const int dataSize = lineStride * jmax (1, imageHeight);
  69436. imageData = (uint8*) juce_malloc (dataSize);
  69437. int ls, ps;
  69438. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  69439. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  69440. other.releasePixelDataReadOnly (srcData);
  69441. }
  69442. Image::~Image()
  69443. {
  69444. juce_free (imageData);
  69445. }
  69446. LowLevelGraphicsContext* Image::createLowLevelContext()
  69447. {
  69448. return new LowLevelGraphicsSoftwareRenderer (*this);
  69449. }
  69450. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  69451. {
  69452. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69453. w = w;
  69454. h = h;
  69455. ls = lineStride;
  69456. ps = pixelStride;
  69457. return imageData + x * pixelStride + y * lineStride;
  69458. }
  69459. void Image::releasePixelDataReadWrite (void*)
  69460. {
  69461. }
  69462. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  69463. {
  69464. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69465. w = w;
  69466. h = h;
  69467. ls = lineStride;
  69468. ps = pixelStride;
  69469. return imageData + x * pixelStride + y * lineStride;
  69470. }
  69471. void Image::releasePixelDataReadOnly (const void*) const
  69472. {
  69473. }
  69474. void Image::setPixelData (int x, int y, int w, int h,
  69475. const uint8* sourcePixelData, int sourceLineStride)
  69476. {
  69477. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69478. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  69479. {
  69480. int ls, ps;
  69481. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  69482. for (int i = 0; i < h; ++i)
  69483. {
  69484. memcpy (dest + ls * i,
  69485. sourcePixelData + sourceLineStride * i,
  69486. w * pixelStride);
  69487. }
  69488. releasePixelDataReadWrite (dest);
  69489. }
  69490. }
  69491. void Image::clear (int dx, int dy, int dw, int dh,
  69492. const Colour& colourToClearTo)
  69493. {
  69494. const PixelARGB col (colourToClearTo.getPixelARGB());
  69495. int ls, ps;
  69496. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  69497. uint8* dest = dstData;
  69498. while (--dh >= 0)
  69499. {
  69500. uint8* line = dest;
  69501. dest += ls;
  69502. if (isARGB())
  69503. {
  69504. for (int x = dw; --x >= 0;)
  69505. {
  69506. ((PixelARGB*) line)->set (col);
  69507. line += ps;
  69508. }
  69509. }
  69510. else if (isRGB())
  69511. {
  69512. for (int x = dw; --x >= 0;)
  69513. {
  69514. ((PixelRGB*) line)->set (col);
  69515. line += ps;
  69516. }
  69517. }
  69518. else
  69519. {
  69520. for (int x = dw; --x >= 0;)
  69521. {
  69522. *line = col.getAlpha();
  69523. line += ps;
  69524. }
  69525. }
  69526. }
  69527. releasePixelDataReadWrite (dstData);
  69528. }
  69529. Image* Image::createCopy (int newWidth, int newHeight,
  69530. const Graphics::ResamplingQuality quality) const
  69531. {
  69532. if (newWidth < 0)
  69533. newWidth = imageWidth;
  69534. if (newHeight < 0)
  69535. newHeight = imageHeight;
  69536. Image* const newImage = new Image (format, newWidth, newHeight, true);
  69537. Graphics g (*newImage);
  69538. g.setImageResamplingQuality (quality);
  69539. g.drawImage (this,
  69540. 0, 0, newWidth, newHeight,
  69541. 0, 0, imageWidth, imageHeight,
  69542. false);
  69543. return newImage;
  69544. }
  69545. const Colour Image::getPixelAt (const int x, const int y) const
  69546. {
  69547. Colour c;
  69548. if (((unsigned int) x) < (unsigned int) imageWidth
  69549. && ((unsigned int) y) < (unsigned int) imageHeight)
  69550. {
  69551. int ls, ps;
  69552. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  69553. if (isARGB())
  69554. {
  69555. PixelARGB p (*(const PixelARGB*) pixels);
  69556. p.unpremultiply();
  69557. c = Colour (p.getARGB());
  69558. }
  69559. else if (isRGB())
  69560. c = Colour (((const PixelRGB*) pixels)->getARGB());
  69561. else
  69562. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  69563. releasePixelDataReadOnly (pixels);
  69564. }
  69565. return c;
  69566. }
  69567. void Image::setPixelAt (const int x, const int y,
  69568. const Colour& colour)
  69569. {
  69570. if (((unsigned int) x) < (unsigned int) imageWidth
  69571. && ((unsigned int) y) < (unsigned int) imageHeight)
  69572. {
  69573. int ls, ps;
  69574. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  69575. const PixelARGB col (colour.getPixelARGB());
  69576. if (isARGB())
  69577. ((PixelARGB*) pixels)->set (col);
  69578. else if (isRGB())
  69579. ((PixelRGB*) pixels)->set (col);
  69580. else
  69581. *pixels = col.getAlpha();
  69582. releasePixelDataReadWrite (pixels);
  69583. }
  69584. }
  69585. void Image::multiplyAlphaAt (const int x, const int y,
  69586. const float multiplier)
  69587. {
  69588. if (((unsigned int) x) < (unsigned int) imageWidth
  69589. && ((unsigned int) y) < (unsigned int) imageHeight
  69590. && hasAlphaChannel())
  69591. {
  69592. int ls, ps;
  69593. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  69594. if (isARGB())
  69595. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  69596. else
  69597. *pixels = (uint8) (*pixels * multiplier);
  69598. releasePixelDataReadWrite (pixels);
  69599. }
  69600. }
  69601. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  69602. {
  69603. if (hasAlphaChannel())
  69604. {
  69605. int ls, ps;
  69606. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  69607. if (isARGB())
  69608. {
  69609. for (int y = 0; y < imageHeight; ++y)
  69610. {
  69611. uint8* p = pixels + y * ls;
  69612. for (int x = 0; x < imageWidth; ++x)
  69613. {
  69614. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  69615. p += ps;
  69616. }
  69617. }
  69618. }
  69619. else
  69620. {
  69621. for (int y = 0; y < imageHeight; ++y)
  69622. {
  69623. uint8* p = pixels + y * ls;
  69624. for (int x = 0; x < imageWidth; ++x)
  69625. {
  69626. *p = (uint8) (*p * amountToMultiplyBy);
  69627. p += ps;
  69628. }
  69629. }
  69630. }
  69631. releasePixelDataReadWrite (pixels);
  69632. }
  69633. else
  69634. {
  69635. jassertfalse // can't do this without an alpha-channel!
  69636. }
  69637. }
  69638. void Image::desaturate()
  69639. {
  69640. if (isARGB() || isRGB())
  69641. {
  69642. int ls, ps;
  69643. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  69644. if (isARGB())
  69645. {
  69646. for (int y = 0; y < imageHeight; ++y)
  69647. {
  69648. uint8* p = pixels + y * ls;
  69649. for (int x = 0; x < imageWidth; ++x)
  69650. {
  69651. ((PixelARGB*) p)->desaturate();
  69652. p += ps;
  69653. }
  69654. }
  69655. }
  69656. else
  69657. {
  69658. for (int y = 0; y < imageHeight; ++y)
  69659. {
  69660. uint8* p = pixels + y * ls;
  69661. for (int x = 0; x < imageWidth; ++x)
  69662. {
  69663. ((PixelRGB*) p)->desaturate();
  69664. p += ps;
  69665. }
  69666. }
  69667. }
  69668. releasePixelDataReadWrite (pixels);
  69669. }
  69670. }
  69671. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  69672. {
  69673. if (hasAlphaChannel())
  69674. {
  69675. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  69676. SparseSet <int> pixelsOnRow;
  69677. int ls, ps;
  69678. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  69679. for (int y = 0; y < imageHeight; ++y)
  69680. {
  69681. pixelsOnRow.clear();
  69682. const uint8* lineData = pixels + ls * y;
  69683. if (isARGB())
  69684. {
  69685. for (int x = 0; x < imageWidth; ++x)
  69686. {
  69687. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  69688. pixelsOnRow.addRange (x, 1);
  69689. lineData += ps;
  69690. }
  69691. }
  69692. else
  69693. {
  69694. for (int x = 0; x < imageWidth; ++x)
  69695. {
  69696. if (*lineData >= threshold)
  69697. pixelsOnRow.addRange (x, 1);
  69698. lineData += ps;
  69699. }
  69700. }
  69701. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  69702. {
  69703. int x, w;
  69704. if (pixelsOnRow.getRange (i, x, w))
  69705. result.add (Rectangle (x, y, w, 1));
  69706. }
  69707. result.consolidate();
  69708. }
  69709. releasePixelDataReadOnly (pixels);
  69710. }
  69711. else
  69712. {
  69713. result.add (0, 0, imageWidth, imageHeight);
  69714. }
  69715. }
  69716. void Image::moveImageSection (int dx, int dy,
  69717. int sx, int sy,
  69718. int w, int h)
  69719. {
  69720. if (dx < 0)
  69721. {
  69722. w += dx;
  69723. sx -= dx;
  69724. dx = 0;
  69725. }
  69726. if (dy < 0)
  69727. {
  69728. h += dy;
  69729. sy -= dy;
  69730. dy = 0;
  69731. }
  69732. if (sx < 0)
  69733. {
  69734. w += sx;
  69735. dx -= sx;
  69736. sx = 0;
  69737. }
  69738. if (sy < 0)
  69739. {
  69740. h += sy;
  69741. dy -= sy;
  69742. sy = 0;
  69743. }
  69744. const int minX = jmin (dx, sx);
  69745. const int minY = jmin (dy, sy);
  69746. w = jmin (w, getWidth() - jmax (sx, dx));
  69747. h = jmin (h, getHeight() - jmax (sy, dy));
  69748. if (w > 0 && h > 0)
  69749. {
  69750. const int maxX = jmax (dx, sx) + w;
  69751. const int maxY = jmax (dy, sy) + h;
  69752. int ls, ps;
  69753. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  69754. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  69755. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  69756. const int lineSize = ps * w;
  69757. if (dy > sy)
  69758. {
  69759. while (--h >= 0)
  69760. {
  69761. const int offset = h * ls;
  69762. memmove (dst + offset, src + offset, lineSize);
  69763. }
  69764. }
  69765. else if (dst != src)
  69766. {
  69767. while (--h >= 0)
  69768. {
  69769. memmove (dst, src, lineSize);
  69770. dst += ls;
  69771. src += ls;
  69772. }
  69773. }
  69774. releasePixelDataReadWrite (pixels);
  69775. }
  69776. }
  69777. END_JUCE_NAMESPACE
  69778. /********* End of inlined file: juce_Image.cpp *********/
  69779. /********* Start of inlined file: juce_ImageCache.cpp *********/
  69780. BEGIN_JUCE_NAMESPACE
  69781. struct CachedImageInfo
  69782. {
  69783. Image* image;
  69784. int64 hashCode;
  69785. int refCount;
  69786. unsigned int releaseTime;
  69787. juce_UseDebuggingNewOperator
  69788. };
  69789. static ImageCache* instance = 0;
  69790. static int cacheTimeout = 5000;
  69791. ImageCache::ImageCache() throw()
  69792. : images (4)
  69793. {
  69794. }
  69795. ImageCache::~ImageCache()
  69796. {
  69797. const ScopedLock sl (lock);
  69798. for (int i = images.size(); --i >= 0;)
  69799. {
  69800. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  69801. delete ci->image;
  69802. delete ci;
  69803. }
  69804. images.clear();
  69805. jassert (instance == this);
  69806. instance = 0;
  69807. }
  69808. Image* ImageCache::getFromHashCode (const int64 hashCode)
  69809. {
  69810. if (instance != 0)
  69811. {
  69812. const ScopedLock sl (instance->lock);
  69813. for (int i = instance->images.size(); --i >= 0;)
  69814. {
  69815. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69816. if (ci->hashCode == hashCode)
  69817. {
  69818. atomicIncrement (ci->refCount);
  69819. return ci->image;
  69820. }
  69821. }
  69822. }
  69823. return 0;
  69824. }
  69825. void ImageCache::addImageToCache (Image* const image,
  69826. const int64 hashCode)
  69827. {
  69828. if (image != 0)
  69829. {
  69830. if (instance == 0)
  69831. instance = new ImageCache();
  69832. CachedImageInfo* const newC = new CachedImageInfo();
  69833. newC->hashCode = hashCode;
  69834. newC->image = image;
  69835. newC->refCount = 1;
  69836. newC->releaseTime = 0;
  69837. const ScopedLock sl (instance->lock);
  69838. instance->images.add (newC);
  69839. }
  69840. }
  69841. void ImageCache::release (Image* const imageToRelease)
  69842. {
  69843. if (imageToRelease != 0 && instance != 0)
  69844. {
  69845. const ScopedLock sl (instance->lock);
  69846. for (int i = instance->images.size(); --i >= 0;)
  69847. {
  69848. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69849. if (ci->image == imageToRelease)
  69850. {
  69851. if (--(ci->refCount) == 0)
  69852. ci->releaseTime = Time::getApproximateMillisecondCounter();
  69853. if (! instance->isTimerRunning())
  69854. instance->startTimer (999);
  69855. break;
  69856. }
  69857. }
  69858. }
  69859. }
  69860. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  69861. {
  69862. if (instance != 0)
  69863. {
  69864. const ScopedLock sl (instance->lock);
  69865. for (int i = instance->images.size(); --i >= 0;)
  69866. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  69867. return true;
  69868. }
  69869. return false;
  69870. }
  69871. void ImageCache::incReferenceCount (Image* const image)
  69872. {
  69873. if (instance != 0)
  69874. {
  69875. const ScopedLock sl (instance->lock);
  69876. for (int i = instance->images.size(); --i >= 0;)
  69877. {
  69878. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69879. if (ci->image == image)
  69880. {
  69881. ci->refCount++;
  69882. return;
  69883. }
  69884. }
  69885. }
  69886. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  69887. }
  69888. void ImageCache::timerCallback()
  69889. {
  69890. int numberStillNeedingReleasing = 0;
  69891. const unsigned int now = Time::getApproximateMillisecondCounter();
  69892. const ScopedLock sl (lock);
  69893. for (int i = images.size(); --i >= 0;)
  69894. {
  69895. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  69896. if (ci->refCount <= 0)
  69897. {
  69898. if (now > ci->releaseTime + cacheTimeout
  69899. || now < ci->releaseTime - 1000)
  69900. {
  69901. images.remove (i);
  69902. delete ci->image;
  69903. delete ci;
  69904. }
  69905. else
  69906. {
  69907. ++numberStillNeedingReleasing;
  69908. }
  69909. }
  69910. }
  69911. if (numberStillNeedingReleasing == 0)
  69912. stopTimer();
  69913. }
  69914. Image* ImageCache::getFromFile (const File& file)
  69915. {
  69916. const int64 hashCode = file.getFullPathName().hashCode64();
  69917. Image* image = getFromHashCode (hashCode);
  69918. if (image == 0)
  69919. {
  69920. image = ImageFileFormat::loadFrom (file);
  69921. addImageToCache (image, hashCode);
  69922. }
  69923. return image;
  69924. }
  69925. Image* ImageCache::getFromMemory (const void* imageData,
  69926. const int dataSize)
  69927. {
  69928. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  69929. Image* image = getFromHashCode (hashCode);
  69930. if (image == 0)
  69931. {
  69932. image = ImageFileFormat::loadFrom (imageData, dataSize);
  69933. addImageToCache (image, hashCode);
  69934. }
  69935. return image;
  69936. }
  69937. void ImageCache::setCacheTimeout (const int millisecs)
  69938. {
  69939. cacheTimeout = millisecs;
  69940. }
  69941. END_JUCE_NAMESPACE
  69942. /********* End of inlined file: juce_ImageCache.cpp *********/
  69943. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  69944. BEGIN_JUCE_NAMESPACE
  69945. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  69946. : size (size_)
  69947. {
  69948. values = new float* [size];
  69949. for (int i = size; --i >= 0;)
  69950. values[i] = new float [size];
  69951. clear();
  69952. }
  69953. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  69954. {
  69955. for (int i = size; --i >= 0;)
  69956. delete[] values[i];
  69957. delete[] values;
  69958. }
  69959. void ImageConvolutionKernel::setKernelValue (const int x,
  69960. const int y,
  69961. const float value) throw()
  69962. {
  69963. if (((unsigned int) x) < (unsigned int) size
  69964. && ((unsigned int) y) < (unsigned int) size)
  69965. {
  69966. values[x][y] = value;
  69967. }
  69968. else
  69969. {
  69970. jassertfalse
  69971. }
  69972. }
  69973. void ImageConvolutionKernel::clear() throw()
  69974. {
  69975. for (int y = size; --y >= 0;)
  69976. for (int x = size; --x >= 0;)
  69977. values[x][y] = 0;
  69978. }
  69979. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  69980. {
  69981. double currentTotal = 0.0;
  69982. for (int y = size; --y >= 0;)
  69983. for (int x = size; --x >= 0;)
  69984. currentTotal += values[x][y];
  69985. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  69986. }
  69987. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  69988. {
  69989. for (int y = size; --y >= 0;)
  69990. for (int x = size; --x >= 0;)
  69991. values[x][y] *= multiplier;
  69992. }
  69993. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  69994. {
  69995. const double radiusFactor = -1.0 / (radius * radius * 2);
  69996. const int centre = size >> 1;
  69997. for (int y = size; --y >= 0;)
  69998. {
  69999. for (int x = size; --x >= 0;)
  70000. {
  70001. const int cx = x - centre;
  70002. const int cy = y - centre;
  70003. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  70004. }
  70005. }
  70006. setOverallSum (1.0f);
  70007. }
  70008. void ImageConvolutionKernel::applyToImage (Image& destImage,
  70009. const Image* sourceImage,
  70010. int dx,
  70011. int dy,
  70012. int dw,
  70013. int dh) const
  70014. {
  70015. Image* imageCreated = 0;
  70016. if (sourceImage == 0)
  70017. {
  70018. sourceImage = imageCreated = destImage.createCopy();
  70019. }
  70020. else
  70021. {
  70022. jassert (sourceImage->getWidth() == destImage.getWidth()
  70023. && sourceImage->getHeight() == destImage.getHeight()
  70024. && sourceImage->getFormat() == destImage.getFormat());
  70025. if (sourceImage->getWidth() != destImage.getWidth()
  70026. || sourceImage->getHeight() != destImage.getHeight()
  70027. || sourceImage->getFormat() != destImage.getFormat())
  70028. return;
  70029. }
  70030. const int imageWidth = destImage.getWidth();
  70031. const int imageHeight = destImage.getHeight();
  70032. if (dx >= imageWidth || dy >= imageHeight)
  70033. return;
  70034. if (dx + dw > imageWidth)
  70035. dw = imageWidth - dx;
  70036. if (dy + dh > imageHeight)
  70037. dh = imageHeight - dy;
  70038. const int dx2 = dx + dw;
  70039. const int dy2 = dy + dh;
  70040. int lineStride, pixelStride;
  70041. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  70042. uint8* line = pixels;
  70043. int srcLineStride, srcPixelStride;
  70044. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  70045. if (pixelStride == 4)
  70046. {
  70047. for (int y = dy; y < dy2; ++y)
  70048. {
  70049. uint8* dest = line;
  70050. line += lineStride;
  70051. for (int x = dx; x < dx2; ++x)
  70052. {
  70053. float c1 = 0;
  70054. float c2 = 0;
  70055. float c3 = 0;
  70056. float c4 = 0;
  70057. for (int yy = 0; yy < size; ++yy)
  70058. {
  70059. const int sy = y + yy - (size >> 1);
  70060. if (sy >= imageHeight)
  70061. break;
  70062. if (sy >= 0)
  70063. {
  70064. int sx = x - (size >> 1);
  70065. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70066. for (int xx = 0; xx < size; ++xx)
  70067. {
  70068. if (sx >= imageWidth)
  70069. break;
  70070. if (sx >= 0)
  70071. {
  70072. const float kernelMult = values[xx][yy];
  70073. c1 += kernelMult * *src++;
  70074. c2 += kernelMult * *src++;
  70075. c3 += kernelMult * *src++;
  70076. c4 += kernelMult * *src++;
  70077. }
  70078. else
  70079. {
  70080. src += 4;
  70081. }
  70082. ++sx;
  70083. }
  70084. }
  70085. }
  70086. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  70087. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  70088. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  70089. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  70090. }
  70091. }
  70092. }
  70093. else if (pixelStride == 3)
  70094. {
  70095. for (int y = dy; y < dy2; ++y)
  70096. {
  70097. uint8* dest = line;
  70098. line += lineStride;
  70099. for (int x = dx; x < dx2; ++x)
  70100. {
  70101. float c1 = 0;
  70102. float c2 = 0;
  70103. float c3 = 0;
  70104. for (int yy = 0; yy < size; ++yy)
  70105. {
  70106. const int sy = y + yy - (size >> 1);
  70107. if (sy >= imageHeight)
  70108. break;
  70109. if (sy >= 0)
  70110. {
  70111. int sx = x - (size >> 1);
  70112. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70113. for (int xx = 0; xx < size; ++xx)
  70114. {
  70115. if (sx >= imageWidth)
  70116. break;
  70117. if (sx >= 0)
  70118. {
  70119. const float kernelMult = values[xx][yy];
  70120. c1 += kernelMult * *src++;
  70121. c2 += kernelMult * *src++;
  70122. c3 += kernelMult * *src++;
  70123. }
  70124. else
  70125. {
  70126. src += 3;
  70127. }
  70128. ++sx;
  70129. }
  70130. }
  70131. }
  70132. *dest++ = (uint8) roundFloatToInt (c1);
  70133. *dest++ = (uint8) roundFloatToInt (c2);
  70134. *dest++ = (uint8) roundFloatToInt (c3);
  70135. }
  70136. }
  70137. }
  70138. sourceImage->releasePixelDataReadOnly (srcPixels);
  70139. destImage.releasePixelDataReadWrite (pixels);
  70140. if (imageCreated != 0)
  70141. delete imageCreated;
  70142. }
  70143. END_JUCE_NAMESPACE
  70144. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70145. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  70146. BEGIN_JUCE_NAMESPACE
  70147. /********* Start of inlined file: juce_GIFLoader.h *********/
  70148. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  70149. #define __JUCE_GIFLOADER_JUCEHEADER__
  70150. #ifndef DOXYGEN
  70151. static const int maxGifCode = 1 << 12;
  70152. /**
  70153. Used internally by ImageFileFormat - don't use this class directly in your
  70154. application.
  70155. @see ImageFileFormat
  70156. */
  70157. class GIFLoader
  70158. {
  70159. public:
  70160. GIFLoader (InputStream& in);
  70161. ~GIFLoader() throw();
  70162. Image* getImage() const throw() { return image; }
  70163. private:
  70164. Image* image;
  70165. InputStream& input;
  70166. uint8 buffer [300];
  70167. uint8 palette [256][4];
  70168. bool dataBlockIsZero, fresh, finished;
  70169. int currentBit, lastBit, lastByteIndex;
  70170. int codeSize, setCodeSize;
  70171. int maxCode, maxCodeSize;
  70172. int firstcode, oldcode;
  70173. int clearCode, end_code;
  70174. int table [2] [maxGifCode];
  70175. int stack [2 * maxGifCode];
  70176. int *sp;
  70177. bool getSizeFromHeader (int& width, int& height);
  70178. bool readPalette (const int numCols);
  70179. int readDataBlock (unsigned char* dest);
  70180. int processExtension (int type, int& transparent);
  70181. int readLZWByte (bool initialise, int input_code_size);
  70182. int getCode (int code_size, bool initialise);
  70183. bool readImage (int width, int height,
  70184. int interlace, int transparent);
  70185. GIFLoader (const GIFLoader&);
  70186. const GIFLoader& operator= (const GIFLoader&);
  70187. };
  70188. #endif // DOXYGEN
  70189. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  70190. /********* End of inlined file: juce_GIFLoader.h *********/
  70191. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  70192. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  70193. PNGImageFormat::PNGImageFormat() throw() {}
  70194. PNGImageFormat::~PNGImageFormat() throw() {}
  70195. const String PNGImageFormat::getFormatName()
  70196. {
  70197. return T("PNG");
  70198. }
  70199. bool PNGImageFormat::canUnderstand (InputStream& in)
  70200. {
  70201. const int bytesNeeded = 4;
  70202. char header [bytesNeeded];
  70203. return in.read (header, bytesNeeded) == bytesNeeded
  70204. && header[1] == 'P'
  70205. && header[2] == 'N'
  70206. && header[3] == 'G';
  70207. }
  70208. Image* PNGImageFormat::decodeImage (InputStream& in)
  70209. {
  70210. return juce_loadPNGImageFromStream (in);
  70211. }
  70212. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  70213. OutputStream& destStream)
  70214. {
  70215. return juce_writePNGImageToStream (sourceImage, destStream);
  70216. }
  70217. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  70218. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  70219. JPEGImageFormat::JPEGImageFormat() throw()
  70220. : quality (-1.0f)
  70221. {
  70222. }
  70223. JPEGImageFormat::~JPEGImageFormat() throw() {}
  70224. void JPEGImageFormat::setQuality (const float newQuality)
  70225. {
  70226. quality = newQuality;
  70227. }
  70228. const String JPEGImageFormat::getFormatName()
  70229. {
  70230. return T("JPEG");
  70231. }
  70232. bool JPEGImageFormat::canUnderstand (InputStream& in)
  70233. {
  70234. const int bytesNeeded = 10;
  70235. uint8 header [bytesNeeded];
  70236. if (in.read (header, bytesNeeded) == bytesNeeded)
  70237. {
  70238. return header[0] == 0xff
  70239. && header[1] == 0xd8
  70240. && header[2] == 0xff
  70241. && (header[3] == 0xe0 || header[3] == 0xe1);
  70242. }
  70243. return false;
  70244. }
  70245. Image* JPEGImageFormat::decodeImage (InputStream& in)
  70246. {
  70247. return juce_loadJPEGImageFromStream (in);
  70248. }
  70249. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  70250. OutputStream& destStream)
  70251. {
  70252. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  70253. }
  70254. class GIFImageFormat : public ImageFileFormat
  70255. {
  70256. public:
  70257. GIFImageFormat() throw() {}
  70258. ~GIFImageFormat() throw() {}
  70259. const String getFormatName()
  70260. {
  70261. return T("GIF");
  70262. }
  70263. bool canUnderstand (InputStream& in)
  70264. {
  70265. const int bytesNeeded = 4;
  70266. char header [bytesNeeded];
  70267. return (in.read (header, bytesNeeded) == bytesNeeded)
  70268. && header[0] == 'G'
  70269. && header[1] == 'I'
  70270. && header[2] == 'F';
  70271. }
  70272. Image* decodeImage (InputStream& in)
  70273. {
  70274. GIFLoader* const loader = new GIFLoader (in);
  70275. Image* const im = loader->getImage();
  70276. delete loader;
  70277. return im;
  70278. }
  70279. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  70280. {
  70281. return false;
  70282. }
  70283. };
  70284. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  70285. {
  70286. static PNGImageFormat png;
  70287. static JPEGImageFormat jpg;
  70288. static GIFImageFormat gif;
  70289. ImageFileFormat* formats[4];
  70290. int numFormats = 0;
  70291. formats [numFormats++] = &png;
  70292. formats [numFormats++] = &jpg;
  70293. formats [numFormats++] = &gif;
  70294. const int64 streamPos = input.getPosition();
  70295. for (int i = 0; i < numFormats; ++i)
  70296. {
  70297. const bool found = formats[i]->canUnderstand (input);
  70298. input.setPosition (streamPos);
  70299. if (found)
  70300. return formats[i];
  70301. }
  70302. return 0;
  70303. }
  70304. Image* ImageFileFormat::loadFrom (InputStream& input)
  70305. {
  70306. ImageFileFormat* const format = findImageFormatForStream (input);
  70307. if (format != 0)
  70308. return format->decodeImage (input);
  70309. return 0;
  70310. }
  70311. Image* ImageFileFormat::loadFrom (const File& file)
  70312. {
  70313. InputStream* const in = file.createInputStream();
  70314. if (in != 0)
  70315. {
  70316. BufferedInputStream b (in, 8192, true);
  70317. return loadFrom (b);
  70318. }
  70319. return 0;
  70320. }
  70321. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  70322. {
  70323. if (rawData != 0 && numBytes > 4)
  70324. {
  70325. MemoryInputStream stream (rawData, numBytes, false);
  70326. return loadFrom (stream);
  70327. }
  70328. return 0;
  70329. }
  70330. END_JUCE_NAMESPACE
  70331. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  70332. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  70333. BEGIN_JUCE_NAMESPACE
  70334. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  70335. {
  70336. return (b << 8) | a;
  70337. }
  70338. GIFLoader::GIFLoader (InputStream& in)
  70339. : image (0),
  70340. input (in),
  70341. dataBlockIsZero (false),
  70342. fresh (false),
  70343. finished (false)
  70344. {
  70345. currentBit = lastBit = lastByteIndex = 0;
  70346. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  70347. firstcode = oldcode = 0;
  70348. clearCode = end_code = 0;
  70349. int imageWidth, imageHeight;
  70350. int transparent = -1;
  70351. if (! getSizeFromHeader (imageWidth, imageHeight))
  70352. return;
  70353. if ((imageWidth <= 0) || (imageHeight <= 0))
  70354. return;
  70355. unsigned char buf [16];
  70356. if (in.read (buf, 3) != 3)
  70357. return;
  70358. int numColours = 2 << (buf[0] & 7);
  70359. if ((buf[0] & 0x80) != 0)
  70360. readPalette (numColours);
  70361. for (;;)
  70362. {
  70363. if (input.read (buf, 1) != 1)
  70364. break;
  70365. if (buf[0] == ';')
  70366. break;
  70367. if (buf[0] == '!')
  70368. {
  70369. if (input.read (buf, 1) != 1)
  70370. break;
  70371. if (processExtension (buf[0], transparent) < 0)
  70372. break;
  70373. continue;
  70374. }
  70375. if (buf[0] != ',')
  70376. continue;
  70377. if (input.read (buf, 9) != 9)
  70378. break;
  70379. imageWidth = makeWord (buf[4], buf[5]);
  70380. imageHeight = makeWord (buf[6], buf[7]);
  70381. numColours = 2 << (buf[8] & 7);
  70382. if ((buf[8] & 0x80) != 0)
  70383. if (! readPalette (numColours))
  70384. break;
  70385. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  70386. imageWidth, imageHeight, (transparent >= 0));
  70387. readImage (imageWidth, imageHeight,
  70388. (buf[8] & 0x40) != 0,
  70389. transparent);
  70390. break;
  70391. }
  70392. }
  70393. GIFLoader::~GIFLoader() throw()
  70394. {
  70395. }
  70396. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  70397. {
  70398. unsigned char b [8];
  70399. if (input.read (b, 6) == 6)
  70400. {
  70401. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  70402. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  70403. {
  70404. if (input.read (b, 4) == 4)
  70405. {
  70406. w = makeWord (b[0], b[1]);
  70407. h = makeWord (b[2], b[3]);
  70408. return true;
  70409. }
  70410. }
  70411. }
  70412. return false;
  70413. }
  70414. bool GIFLoader::readPalette (const int numCols)
  70415. {
  70416. unsigned char rgb[4];
  70417. for (int i = 0; i < numCols; ++i)
  70418. {
  70419. input.read (rgb, 3);
  70420. palette [i][0] = rgb[0];
  70421. palette [i][1] = rgb[1];
  70422. palette [i][2] = rgb[2];
  70423. palette [i][3] = 0xff;
  70424. }
  70425. return true;
  70426. }
  70427. int GIFLoader::readDataBlock (unsigned char* const dest)
  70428. {
  70429. unsigned char n;
  70430. if (input.read (&n, 1) == 1)
  70431. {
  70432. dataBlockIsZero = (n == 0);
  70433. if (dataBlockIsZero || (input.read (dest, n) == n))
  70434. return n;
  70435. }
  70436. return -1;
  70437. }
  70438. int GIFLoader::processExtension (const int type, int& transparent)
  70439. {
  70440. unsigned char b [300];
  70441. int n = 0;
  70442. if (type == 0xf9)
  70443. {
  70444. n = readDataBlock (b);
  70445. if (n < 0)
  70446. return 1;
  70447. if ((b[0] & 0x1) != 0)
  70448. transparent = b[3];
  70449. }
  70450. do
  70451. {
  70452. n = readDataBlock (b);
  70453. }
  70454. while (n > 0);
  70455. return n;
  70456. }
  70457. int GIFLoader::getCode (const int codeSize, const bool initialise)
  70458. {
  70459. if (initialise)
  70460. {
  70461. currentBit = 0;
  70462. lastBit = 0;
  70463. finished = false;
  70464. return 0;
  70465. }
  70466. if ((currentBit + codeSize) >= lastBit)
  70467. {
  70468. if (finished)
  70469. return -1;
  70470. buffer[0] = buffer [lastByteIndex - 2];
  70471. buffer[1] = buffer [lastByteIndex - 1];
  70472. const int n = readDataBlock (&buffer[2]);
  70473. if (n == 0)
  70474. finished = true;
  70475. lastByteIndex = 2 + n;
  70476. currentBit = (currentBit - lastBit) + 16;
  70477. lastBit = (2 + n) * 8 ;
  70478. }
  70479. int result = 0;
  70480. int i = currentBit;
  70481. for (int j = 0; j < codeSize; ++j)
  70482. {
  70483. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  70484. ++i;
  70485. }
  70486. currentBit += codeSize;
  70487. return result;
  70488. }
  70489. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  70490. {
  70491. int code, incode, i;
  70492. if (initialise)
  70493. {
  70494. setCodeSize = inputCodeSize;
  70495. codeSize = setCodeSize + 1;
  70496. clearCode = 1 << setCodeSize;
  70497. end_code = clearCode + 1;
  70498. maxCodeSize = 2 * clearCode;
  70499. maxCode = clearCode + 2;
  70500. getCode (0, true);
  70501. fresh = true;
  70502. for (i = 0; i < clearCode; ++i)
  70503. {
  70504. table[0][i] = 0;
  70505. table[1][i] = i;
  70506. }
  70507. for (; i < maxGifCode; ++i)
  70508. {
  70509. table[0][i] = 0;
  70510. table[1][i] = 0;
  70511. }
  70512. sp = stack;
  70513. return 0;
  70514. }
  70515. else if (fresh)
  70516. {
  70517. fresh = false;
  70518. do
  70519. {
  70520. firstcode = oldcode
  70521. = getCode (codeSize, false);
  70522. }
  70523. while (firstcode == clearCode);
  70524. return firstcode;
  70525. }
  70526. if (sp > stack)
  70527. return *--sp;
  70528. while ((code = getCode (codeSize, false)) >= 0)
  70529. {
  70530. if (code == clearCode)
  70531. {
  70532. for (i = 0; i < clearCode; ++i)
  70533. {
  70534. table[0][i] = 0;
  70535. table[1][i] = i;
  70536. }
  70537. for (; i < maxGifCode; ++i)
  70538. {
  70539. table[0][i] = 0;
  70540. table[1][i] = 0;
  70541. }
  70542. codeSize = setCodeSize + 1;
  70543. maxCodeSize = 2 * clearCode;
  70544. maxCode = clearCode + 2;
  70545. sp = stack;
  70546. firstcode = oldcode = getCode (codeSize, false);
  70547. return firstcode;
  70548. }
  70549. else if (code == end_code)
  70550. {
  70551. if (dataBlockIsZero)
  70552. return -2;
  70553. unsigned char buf [260];
  70554. int n;
  70555. while ((n = readDataBlock (buf)) > 0)
  70556. {}
  70557. if (n != 0)
  70558. return -2;
  70559. }
  70560. incode = code;
  70561. if (code >= maxCode)
  70562. {
  70563. *sp++ = firstcode;
  70564. code = oldcode;
  70565. }
  70566. while (code >= clearCode)
  70567. {
  70568. *sp++ = table[1][code];
  70569. if (code == table[0][code])
  70570. return -2;
  70571. code = table[0][code];
  70572. }
  70573. *sp++ = firstcode = table[1][code];
  70574. if ((code = maxCode) < maxGifCode)
  70575. {
  70576. table[0][code] = oldcode;
  70577. table[1][code] = firstcode;
  70578. ++maxCode;
  70579. if ((maxCode >= maxCodeSize)
  70580. && (maxCodeSize < maxGifCode))
  70581. {
  70582. maxCodeSize <<= 1;
  70583. ++codeSize;
  70584. }
  70585. }
  70586. oldcode = incode;
  70587. if (sp > stack)
  70588. return *--sp;
  70589. }
  70590. return code;
  70591. }
  70592. bool GIFLoader::readImage (const int width, const int height,
  70593. const int interlace, const int transparent)
  70594. {
  70595. unsigned char c;
  70596. if (input.read (&c, 1) != 1
  70597. || readLZWByte (true, c) < 0)
  70598. return false;
  70599. if (transparent >= 0)
  70600. {
  70601. palette [transparent][0] = 0;
  70602. palette [transparent][1] = 0;
  70603. palette [transparent][2] = 0;
  70604. palette [transparent][3] = 0;
  70605. }
  70606. int index;
  70607. int xpos = 0, ypos = 0, pass = 0;
  70608. int stride, pixelStride;
  70609. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  70610. uint8* p = pixels;
  70611. const bool hasAlpha = image->hasAlphaChannel();
  70612. while ((index = readLZWByte (false, c)) >= 0)
  70613. {
  70614. const uint8* const paletteEntry = palette [index];
  70615. if (hasAlpha)
  70616. {
  70617. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  70618. paletteEntry[0],
  70619. paletteEntry[1],
  70620. paletteEntry[2]);
  70621. ((PixelARGB*) p)->premultiply();
  70622. p += pixelStride;
  70623. }
  70624. else
  70625. {
  70626. ((PixelRGB*) p)->setARGB (0,
  70627. paletteEntry[0],
  70628. paletteEntry[1],
  70629. paletteEntry[2]);
  70630. p += pixelStride;
  70631. }
  70632. ++xpos;
  70633. if (xpos == width)
  70634. {
  70635. xpos = 0;
  70636. if (interlace)
  70637. {
  70638. switch (pass)
  70639. {
  70640. case 0:
  70641. case 1:
  70642. ypos += 8;
  70643. break;
  70644. case 2:
  70645. ypos += 4;
  70646. break;
  70647. case 3:
  70648. ypos += 2;
  70649. break;
  70650. }
  70651. while (ypos >= height)
  70652. {
  70653. ++pass;
  70654. switch (pass)
  70655. {
  70656. case 1:
  70657. ypos = 4;
  70658. break;
  70659. case 2:
  70660. ypos = 2;
  70661. break;
  70662. case 3:
  70663. ypos = 1;
  70664. break;
  70665. default:
  70666. return true;
  70667. }
  70668. }
  70669. }
  70670. else
  70671. {
  70672. ++ypos;
  70673. }
  70674. p = pixels + xpos * pixelStride + ypos * stride;
  70675. }
  70676. if (ypos >= height)
  70677. break;
  70678. }
  70679. image->releasePixelDataReadWrite (pixels);
  70680. return true;
  70681. }
  70682. END_JUCE_NAMESPACE
  70683. /********* End of inlined file: juce_GIFLoader.cpp *********/
  70684. #endif
  70685. //==============================================================================
  70686. // some files include lots of library code, so leave them to the end to avoid cluttering
  70687. // up the build for the clean files.
  70688. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  70689. namespace zlibNamespace
  70690. {
  70691. #undef OS_CODE
  70692. #undef fdopen
  70693. /********* Start of inlined file: zlib.h *********/
  70694. #ifndef ZLIB_H
  70695. #define ZLIB_H
  70696. /********* Start of inlined file: zconf.h *********/
  70697. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  70698. #ifndef ZCONF_H
  70699. #define ZCONF_H
  70700. // *** Just a few hacks here to make it compile nicely with Juce..
  70701. #define Z_PREFIX 1
  70702. #undef __MACTYPES__
  70703. #ifdef _MSC_VER
  70704. #pragma warning (disable : 4131 4127 4244 4267)
  70705. #endif
  70706. /*
  70707. * If you *really* need a unique prefix for all types and library functions,
  70708. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  70709. */
  70710. #ifdef Z_PREFIX
  70711. # define deflateInit_ z_deflateInit_
  70712. # define deflate z_deflate
  70713. # define deflateEnd z_deflateEnd
  70714. # define inflateInit_ z_inflateInit_
  70715. # define inflate z_inflate
  70716. # define inflateEnd z_inflateEnd
  70717. # define deflateInit2_ z_deflateInit2_
  70718. # define deflateSetDictionary z_deflateSetDictionary
  70719. # define deflateCopy z_deflateCopy
  70720. # define deflateReset z_deflateReset
  70721. # define deflateParams z_deflateParams
  70722. # define deflateBound z_deflateBound
  70723. # define deflatePrime z_deflatePrime
  70724. # define inflateInit2_ z_inflateInit2_
  70725. # define inflateSetDictionary z_inflateSetDictionary
  70726. # define inflateSync z_inflateSync
  70727. # define inflateSyncPoint z_inflateSyncPoint
  70728. # define inflateCopy z_inflateCopy
  70729. # define inflateReset z_inflateReset
  70730. # define inflateBack z_inflateBack
  70731. # define inflateBackEnd z_inflateBackEnd
  70732. # define compress z_compress
  70733. # define compress2 z_compress2
  70734. # define compressBound z_compressBound
  70735. # define uncompress z_uncompress
  70736. # define adler32 z_adler32
  70737. # define crc32 z_crc32
  70738. # define get_crc_table z_get_crc_table
  70739. # define zError z_zError
  70740. # define alloc_func z_alloc_func
  70741. # define free_func z_free_func
  70742. # define in_func z_in_func
  70743. # define out_func z_out_func
  70744. # define Byte z_Byte
  70745. # define uInt z_uInt
  70746. # define uLong z_uLong
  70747. # define Bytef z_Bytef
  70748. # define charf z_charf
  70749. # define intf z_intf
  70750. # define uIntf z_uIntf
  70751. # define uLongf z_uLongf
  70752. # define voidpf z_voidpf
  70753. # define voidp z_voidp
  70754. #endif
  70755. #if defined(__MSDOS__) && !defined(MSDOS)
  70756. # define MSDOS
  70757. #endif
  70758. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  70759. # define OS2
  70760. #endif
  70761. #if defined(_WINDOWS) && !defined(WINDOWS)
  70762. # define WINDOWS
  70763. #endif
  70764. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  70765. # ifndef WIN32
  70766. # define WIN32
  70767. # endif
  70768. #endif
  70769. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  70770. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  70771. # ifndef SYS16BIT
  70772. # define SYS16BIT
  70773. # endif
  70774. # endif
  70775. #endif
  70776. /*
  70777. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  70778. * than 64k bytes at a time (needed on systems with 16-bit int).
  70779. */
  70780. #ifdef SYS16BIT
  70781. # define MAXSEG_64K
  70782. #endif
  70783. #ifdef MSDOS
  70784. # define UNALIGNED_OK
  70785. #endif
  70786. #ifdef __STDC_VERSION__
  70787. # ifndef STDC
  70788. # define STDC
  70789. # endif
  70790. # if __STDC_VERSION__ >= 199901L
  70791. # ifndef STDC99
  70792. # define STDC99
  70793. # endif
  70794. # endif
  70795. #endif
  70796. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  70797. # define STDC
  70798. #endif
  70799. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  70800. # define STDC
  70801. #endif
  70802. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  70803. # define STDC
  70804. #endif
  70805. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  70806. # define STDC
  70807. #endif
  70808. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  70809. # define STDC
  70810. #endif
  70811. #ifndef STDC
  70812. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  70813. # define const /* note: need a more gentle solution here */
  70814. # endif
  70815. #endif
  70816. /* Some Mac compilers merge all .h files incorrectly: */
  70817. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  70818. # define NO_DUMMY_DECL
  70819. #endif
  70820. /* Maximum value for memLevel in deflateInit2 */
  70821. #ifndef MAX_MEM_LEVEL
  70822. # ifdef MAXSEG_64K
  70823. # define MAX_MEM_LEVEL 8
  70824. # else
  70825. # define MAX_MEM_LEVEL 9
  70826. # endif
  70827. #endif
  70828. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  70829. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  70830. * created by gzip. (Files created by minigzip can still be extracted by
  70831. * gzip.)
  70832. */
  70833. #ifndef MAX_WBITS
  70834. # define MAX_WBITS 15 /* 32K LZ77 window */
  70835. #endif
  70836. /* The memory requirements for deflate are (in bytes):
  70837. (1 << (windowBits+2)) + (1 << (memLevel+9))
  70838. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  70839. plus a few kilobytes for small objects. For example, if you want to reduce
  70840. the default memory requirements from 256K to 128K, compile with
  70841. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  70842. Of course this will generally degrade compression (there's no free lunch).
  70843. The memory requirements for inflate are (in bytes) 1 << windowBits
  70844. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  70845. for small objects.
  70846. */
  70847. /* Type declarations */
  70848. #ifndef OF /* function prototypes */
  70849. # ifdef STDC
  70850. # define OF(args) args
  70851. # else
  70852. # define OF(args) ()
  70853. # endif
  70854. #endif
  70855. /* The following definitions for FAR are needed only for MSDOS mixed
  70856. * model programming (small or medium model with some far allocations).
  70857. * This was tested only with MSC; for other MSDOS compilers you may have
  70858. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  70859. * just define FAR to be empty.
  70860. */
  70861. #ifdef SYS16BIT
  70862. # if defined(M_I86SM) || defined(M_I86MM)
  70863. /* MSC small or medium model */
  70864. # define SMALL_MEDIUM
  70865. # ifdef _MSC_VER
  70866. # define FAR _far
  70867. # else
  70868. # define FAR far
  70869. # endif
  70870. # endif
  70871. # if (defined(__SMALL__) || defined(__MEDIUM__))
  70872. /* Turbo C small or medium model */
  70873. # define SMALL_MEDIUM
  70874. # ifdef __BORLANDC__
  70875. # define FAR _far
  70876. # else
  70877. # define FAR far
  70878. # endif
  70879. # endif
  70880. #endif
  70881. #if defined(WINDOWS) || defined(WIN32)
  70882. /* If building or using zlib as a DLL, define ZLIB_DLL.
  70883. * This is not mandatory, but it offers a little performance increase.
  70884. */
  70885. # ifdef ZLIB_DLL
  70886. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  70887. # ifdef ZLIB_INTERNAL
  70888. # define ZEXTERN extern __declspec(dllexport)
  70889. # else
  70890. # define ZEXTERN extern __declspec(dllimport)
  70891. # endif
  70892. # endif
  70893. # endif /* ZLIB_DLL */
  70894. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  70895. * define ZLIB_WINAPI.
  70896. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  70897. */
  70898. # ifdef ZLIB_WINAPI
  70899. # ifdef FAR
  70900. # undef FAR
  70901. # endif
  70902. # include <windows.h>
  70903. /* No need for _export, use ZLIB.DEF instead. */
  70904. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  70905. # define ZEXPORT WINAPI
  70906. # ifdef WIN32
  70907. # define ZEXPORTVA WINAPIV
  70908. # else
  70909. # define ZEXPORTVA FAR CDECL
  70910. # endif
  70911. # endif
  70912. #endif
  70913. #if defined (__BEOS__)
  70914. # ifdef ZLIB_DLL
  70915. # ifdef ZLIB_INTERNAL
  70916. # define ZEXPORT __declspec(dllexport)
  70917. # define ZEXPORTVA __declspec(dllexport)
  70918. # else
  70919. # define ZEXPORT __declspec(dllimport)
  70920. # define ZEXPORTVA __declspec(dllimport)
  70921. # endif
  70922. # endif
  70923. #endif
  70924. #ifndef ZEXTERN
  70925. # define ZEXTERN extern
  70926. #endif
  70927. #ifndef ZEXPORT
  70928. # define ZEXPORT
  70929. #endif
  70930. #ifndef ZEXPORTVA
  70931. # define ZEXPORTVA
  70932. #endif
  70933. #ifndef FAR
  70934. # define FAR
  70935. #endif
  70936. #if !defined(__MACTYPES__)
  70937. typedef unsigned char Byte; /* 8 bits */
  70938. #endif
  70939. typedef unsigned int uInt; /* 16 bits or more */
  70940. typedef unsigned long uLong; /* 32 bits or more */
  70941. #ifdef SMALL_MEDIUM
  70942. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  70943. # define Bytef Byte FAR
  70944. #else
  70945. typedef Byte FAR Bytef;
  70946. #endif
  70947. typedef char FAR charf;
  70948. typedef int FAR intf;
  70949. typedef uInt FAR uIntf;
  70950. typedef uLong FAR uLongf;
  70951. #ifdef STDC
  70952. typedef void const *voidpc;
  70953. typedef void FAR *voidpf;
  70954. typedef void *voidp;
  70955. #else
  70956. typedef Byte const *voidpc;
  70957. typedef Byte FAR *voidpf;
  70958. typedef Byte *voidp;
  70959. #endif
  70960. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  70961. # include <sys/types.h> /* for off_t */
  70962. # include <unistd.h> /* for SEEK_* and off_t */
  70963. # ifdef VMS
  70964. # include <unixio.h> /* for off_t */
  70965. # endif
  70966. # define z_off_t off_t
  70967. #endif
  70968. #ifndef SEEK_SET
  70969. # define SEEK_SET 0 /* Seek from beginning of file. */
  70970. # define SEEK_CUR 1 /* Seek from current position. */
  70971. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  70972. #endif
  70973. #ifndef z_off_t
  70974. # define z_off_t long
  70975. #endif
  70976. #if defined(__OS400__)
  70977. # define NO_vsnprintf
  70978. #endif
  70979. #if defined(__MVS__)
  70980. # define NO_vsnprintf
  70981. # ifdef FAR
  70982. # undef FAR
  70983. # endif
  70984. #endif
  70985. /* MVS linker does not support external names larger than 8 bytes */
  70986. #if defined(__MVS__)
  70987. # pragma map(deflateInit_,"DEIN")
  70988. # pragma map(deflateInit2_,"DEIN2")
  70989. # pragma map(deflateEnd,"DEEND")
  70990. # pragma map(deflateBound,"DEBND")
  70991. # pragma map(inflateInit_,"ININ")
  70992. # pragma map(inflateInit2_,"ININ2")
  70993. # pragma map(inflateEnd,"INEND")
  70994. # pragma map(inflateSync,"INSY")
  70995. # pragma map(inflateSetDictionary,"INSEDI")
  70996. # pragma map(compressBound,"CMBND")
  70997. # pragma map(inflate_table,"INTABL")
  70998. # pragma map(inflate_fast,"INFA")
  70999. # pragma map(inflate_copyright,"INCOPY")
  71000. #endif
  71001. #endif /* ZCONF_H */
  71002. /********* End of inlined file: zconf.h *********/
  71003. #ifdef __cplusplus
  71004. extern "C" {
  71005. #endif
  71006. #define ZLIB_VERSION "1.2.3"
  71007. #define ZLIB_VERNUM 0x1230
  71008. /*
  71009. The 'zlib' compression library provides in-memory compression and
  71010. decompression functions, including integrity checks of the uncompressed
  71011. data. This version of the library supports only one compression method
  71012. (deflation) but other algorithms will be added later and will have the same
  71013. stream interface.
  71014. Compression can be done in a single step if the buffers are large
  71015. enough (for example if an input file is mmap'ed), or can be done by
  71016. repeated calls of the compression function. In the latter case, the
  71017. application must provide more input and/or consume the output
  71018. (providing more output space) before each call.
  71019. The compressed data format used by default by the in-memory functions is
  71020. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  71021. around a deflate stream, which is itself documented in RFC 1951.
  71022. The library also supports reading and writing files in gzip (.gz) format
  71023. with an interface similar to that of stdio using the functions that start
  71024. with "gz". The gzip format is different from the zlib format. gzip is a
  71025. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  71026. This library can optionally read and write gzip streams in memory as well.
  71027. The zlib format was designed to be compact and fast for use in memory
  71028. and on communications channels. The gzip format was designed for single-
  71029. file compression on file systems, has a larger header than zlib to maintain
  71030. directory information, and uses a different, slower check method than zlib.
  71031. The library does not install any signal handler. The decoder checks
  71032. the consistency of the compressed data, so the library should never
  71033. crash even in case of corrupted input.
  71034. */
  71035. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  71036. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  71037. struct internal_state;
  71038. typedef struct z_stream_s {
  71039. Bytef *next_in; /* next input byte */
  71040. uInt avail_in; /* number of bytes available at next_in */
  71041. uLong total_in; /* total nb of input bytes read so far */
  71042. Bytef *next_out; /* next output byte should be put there */
  71043. uInt avail_out; /* remaining free space at next_out */
  71044. uLong total_out; /* total nb of bytes output so far */
  71045. char *msg; /* last error message, NULL if no error */
  71046. struct internal_state FAR *state; /* not visible by applications */
  71047. alloc_func zalloc; /* used to allocate the internal state */
  71048. free_func zfree; /* used to free the internal state */
  71049. voidpf opaque; /* private data object passed to zalloc and zfree */
  71050. int data_type; /* best guess about the data type: binary or text */
  71051. uLong adler; /* adler32 value of the uncompressed data */
  71052. uLong reserved; /* reserved for future use */
  71053. } z_stream;
  71054. typedef z_stream FAR *z_streamp;
  71055. /*
  71056. gzip header information passed to and from zlib routines. See RFC 1952
  71057. for more details on the meanings of these fields.
  71058. */
  71059. typedef struct gz_header_s {
  71060. int text; /* true if compressed data believed to be text */
  71061. uLong time; /* modification time */
  71062. int xflags; /* extra flags (not used when writing a gzip file) */
  71063. int os; /* operating system */
  71064. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  71065. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  71066. uInt extra_max; /* space at extra (only when reading header) */
  71067. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  71068. uInt name_max; /* space at name (only when reading header) */
  71069. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  71070. uInt comm_max; /* space at comment (only when reading header) */
  71071. int hcrc; /* true if there was or will be a header crc */
  71072. int done; /* true when done reading gzip header (not used
  71073. when writing a gzip file) */
  71074. } gz_header;
  71075. typedef gz_header FAR *gz_headerp;
  71076. /*
  71077. The application must update next_in and avail_in when avail_in has
  71078. dropped to zero. It must update next_out and avail_out when avail_out
  71079. has dropped to zero. The application must initialize zalloc, zfree and
  71080. opaque before calling the init function. All other fields are set by the
  71081. compression library and must not be updated by the application.
  71082. The opaque value provided by the application will be passed as the first
  71083. parameter for calls of zalloc and zfree. This can be useful for custom
  71084. memory management. The compression library attaches no meaning to the
  71085. opaque value.
  71086. zalloc must return Z_NULL if there is not enough memory for the object.
  71087. If zlib is used in a multi-threaded application, zalloc and zfree must be
  71088. thread safe.
  71089. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  71090. exactly 65536 bytes, but will not be required to allocate more than this
  71091. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  71092. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  71093. have their offset normalized to zero. The default allocation function
  71094. provided by this library ensures this (see zutil.c). To reduce memory
  71095. requirements and avoid any allocation of 64K objects, at the expense of
  71096. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  71097. The fields total_in and total_out can be used for statistics or
  71098. progress reports. After compression, total_in holds the total size of
  71099. the uncompressed data and may be saved for use in the decompressor
  71100. (particularly if the decompressor wants to decompress everything in
  71101. a single step).
  71102. */
  71103. /* constants */
  71104. #define Z_NO_FLUSH 0
  71105. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  71106. #define Z_SYNC_FLUSH 2
  71107. #define Z_FULL_FLUSH 3
  71108. #define Z_FINISH 4
  71109. #define Z_BLOCK 5
  71110. /* Allowed flush values; see deflate() and inflate() below for details */
  71111. #define Z_OK 0
  71112. #define Z_STREAM_END 1
  71113. #define Z_NEED_DICT 2
  71114. #define Z_ERRNO (-1)
  71115. #define Z_STREAM_ERROR (-2)
  71116. #define Z_DATA_ERROR (-3)
  71117. #define Z_MEM_ERROR (-4)
  71118. #define Z_BUF_ERROR (-5)
  71119. #define Z_VERSION_ERROR (-6)
  71120. /* Return codes for the compression/decompression functions. Negative
  71121. * values are errors, positive values are used for special but normal events.
  71122. */
  71123. #define Z_NO_COMPRESSION 0
  71124. #define Z_BEST_SPEED 1
  71125. #define Z_BEST_COMPRESSION 9
  71126. #define Z_DEFAULT_COMPRESSION (-1)
  71127. /* compression levels */
  71128. #define Z_FILTERED 1
  71129. #define Z_HUFFMAN_ONLY 2
  71130. #define Z_RLE 3
  71131. #define Z_FIXED 4
  71132. #define Z_DEFAULT_STRATEGY 0
  71133. /* compression strategy; see deflateInit2() below for details */
  71134. #define Z_BINARY 0
  71135. #define Z_TEXT 1
  71136. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  71137. #define Z_UNKNOWN 2
  71138. /* Possible values of the data_type field (though see inflate()) */
  71139. #define Z_DEFLATED 8
  71140. /* The deflate compression method (the only one supported in this version) */
  71141. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  71142. #define zlib_version zlibVersion()
  71143. /* for compatibility with versions < 1.0.2 */
  71144. /* basic functions */
  71145. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  71146. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  71147. If the first character differs, the library code actually used is
  71148. not compatible with the zlib.h header file used by the application.
  71149. This check is automatically made by deflateInit and inflateInit.
  71150. */
  71151. /*
  71152. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  71153. Initializes the internal stream state for compression. The fields
  71154. zalloc, zfree and opaque must be initialized before by the caller.
  71155. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  71156. use default allocation functions.
  71157. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  71158. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  71159. all (the input data is simply copied a block at a time).
  71160. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  71161. compression (currently equivalent to level 6).
  71162. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  71163. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  71164. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  71165. with the version assumed by the caller (ZLIB_VERSION).
  71166. msg is set to null if there is no error message. deflateInit does not
  71167. perform any compression: this will be done by deflate().
  71168. */
  71169. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  71170. /*
  71171. deflate compresses as much data as possible, and stops when the input
  71172. buffer becomes empty or the output buffer becomes full. It may introduce some
  71173. output latency (reading input without producing any output) except when
  71174. forced to flush.
  71175. The detailed semantics are as follows. deflate performs one or both of the
  71176. following actions:
  71177. - Compress more input starting at next_in and update next_in and avail_in
  71178. accordingly. If not all input can be processed (because there is not
  71179. enough room in the output buffer), next_in and avail_in are updated and
  71180. processing will resume at this point for the next call of deflate().
  71181. - Provide more output starting at next_out and update next_out and avail_out
  71182. accordingly. This action is forced if the parameter flush is non zero.
  71183. Forcing flush frequently degrades the compression ratio, so this parameter
  71184. should be set only when necessary (in interactive applications).
  71185. Some output may be provided even if flush is not set.
  71186. Before the call of deflate(), the application should ensure that at least
  71187. one of the actions is possible, by providing more input and/or consuming
  71188. more output, and updating avail_in or avail_out accordingly; avail_out
  71189. should never be zero before the call. The application can consume the
  71190. compressed output when it wants, for example when the output buffer is full
  71191. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  71192. and with zero avail_out, it must be called again after making room in the
  71193. output buffer because there might be more output pending.
  71194. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  71195. decide how much data to accumualte before producing output, in order to
  71196. maximize compression.
  71197. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  71198. flushed to the output buffer and the output is aligned on a byte boundary, so
  71199. that the decompressor can get all input data available so far. (In particular
  71200. avail_in is zero after the call if enough output space has been provided
  71201. before the call.) Flushing may degrade compression for some compression
  71202. algorithms and so it should be used only when necessary.
  71203. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  71204. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  71205. restart from this point if previous compressed data has been damaged or if
  71206. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  71207. compression.
  71208. If deflate returns with avail_out == 0, this function must be called again
  71209. with the same value of the flush parameter and more output space (updated
  71210. avail_out), until the flush is complete (deflate returns with non-zero
  71211. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  71212. avail_out is greater than six to avoid repeated flush markers due to
  71213. avail_out == 0 on return.
  71214. If the parameter flush is set to Z_FINISH, pending input is processed,
  71215. pending output is flushed and deflate returns with Z_STREAM_END if there
  71216. was enough output space; if deflate returns with Z_OK, this function must be
  71217. called again with Z_FINISH and more output space (updated avail_out) but no
  71218. more input data, until it returns with Z_STREAM_END or an error. After
  71219. deflate has returned Z_STREAM_END, the only possible operations on the
  71220. stream are deflateReset or deflateEnd.
  71221. Z_FINISH can be used immediately after deflateInit if all the compression
  71222. is to be done in a single step. In this case, avail_out must be at least
  71223. the value returned by deflateBound (see below). If deflate does not return
  71224. Z_STREAM_END, then it must be called again as described above.
  71225. deflate() sets strm->adler to the adler32 checksum of all input read
  71226. so far (that is, total_in bytes).
  71227. deflate() may update strm->data_type if it can make a good guess about
  71228. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  71229. binary. This field is only for information purposes and does not affect
  71230. the compression algorithm in any manner.
  71231. deflate() returns Z_OK if some progress has been made (more input
  71232. processed or more output produced), Z_STREAM_END if all input has been
  71233. consumed and all output has been produced (only when flush is set to
  71234. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  71235. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  71236. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  71237. fatal, and deflate() can be called again with more input and more output
  71238. space to continue compressing.
  71239. */
  71240. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  71241. /*
  71242. All dynamically allocated data structures for this stream are freed.
  71243. This function discards any unprocessed input and does not flush any
  71244. pending output.
  71245. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  71246. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  71247. prematurely (some input or output was discarded). In the error case,
  71248. msg may be set but then points to a static string (which must not be
  71249. deallocated).
  71250. */
  71251. /*
  71252. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  71253. Initializes the internal stream state for decompression. The fields
  71254. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  71255. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  71256. value depends on the compression method), inflateInit determines the
  71257. compression method from the zlib header and allocates all data structures
  71258. accordingly; otherwise the allocation will be deferred to the first call of
  71259. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  71260. use default allocation functions.
  71261. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71262. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  71263. version assumed by the caller. msg is set to null if there is no error
  71264. message. inflateInit does not perform any decompression apart from reading
  71265. the zlib header if present: this will be done by inflate(). (So next_in and
  71266. avail_in may be modified, but next_out and avail_out are unchanged.)
  71267. */
  71268. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  71269. /*
  71270. inflate decompresses as much data as possible, and stops when the input
  71271. buffer becomes empty or the output buffer becomes full. It may introduce
  71272. some output latency (reading input without producing any output) except when
  71273. forced to flush.
  71274. The detailed semantics are as follows. inflate performs one or both of the
  71275. following actions:
  71276. - Decompress more input starting at next_in and update next_in and avail_in
  71277. accordingly. If not all input can be processed (because there is not
  71278. enough room in the output buffer), next_in is updated and processing
  71279. will resume at this point for the next call of inflate().
  71280. - Provide more output starting at next_out and update next_out and avail_out
  71281. accordingly. inflate() provides as much output as possible, until there
  71282. is no more input data or no more space in the output buffer (see below
  71283. about the flush parameter).
  71284. Before the call of inflate(), the application should ensure that at least
  71285. one of the actions is possible, by providing more input and/or consuming
  71286. more output, and updating the next_* and avail_* values accordingly.
  71287. The application can consume the uncompressed output when it wants, for
  71288. example when the output buffer is full (avail_out == 0), or after each
  71289. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  71290. must be called again after making room in the output buffer because there
  71291. might be more output pending.
  71292. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  71293. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  71294. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  71295. if and when it gets to the next deflate block boundary. When decoding the
  71296. zlib or gzip format, this will cause inflate() to return immediately after
  71297. the header and before the first block. When doing a raw inflate, inflate()
  71298. will go ahead and process the first block, and will return when it gets to
  71299. the end of that block, or when it runs out of data.
  71300. The Z_BLOCK option assists in appending to or combining deflate streams.
  71301. Also to assist in this, on return inflate() will set strm->data_type to the
  71302. number of unused bits in the last byte taken from strm->next_in, plus 64
  71303. if inflate() is currently decoding the last block in the deflate stream,
  71304. plus 128 if inflate() returned immediately after decoding an end-of-block
  71305. code or decoding the complete header up to just before the first byte of the
  71306. deflate stream. The end-of-block will not be indicated until all of the
  71307. uncompressed data from that block has been written to strm->next_out. The
  71308. number of unused bits may in general be greater than seven, except when
  71309. bit 7 of data_type is set, in which case the number of unused bits will be
  71310. less than eight.
  71311. inflate() should normally be called until it returns Z_STREAM_END or an
  71312. error. However if all decompression is to be performed in a single step
  71313. (a single call of inflate), the parameter flush should be set to
  71314. Z_FINISH. In this case all pending input is processed and all pending
  71315. output is flushed; avail_out must be large enough to hold all the
  71316. uncompressed data. (The size of the uncompressed data may have been saved
  71317. by the compressor for this purpose.) The next operation on this stream must
  71318. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  71319. is never required, but can be used to inform inflate that a faster approach
  71320. may be used for the single inflate() call.
  71321. In this implementation, inflate() always flushes as much output as
  71322. possible to the output buffer, and always uses the faster approach on the
  71323. first call. So the only effect of the flush parameter in this implementation
  71324. is on the return value of inflate(), as noted below, or when it returns early
  71325. because Z_BLOCK is used.
  71326. If a preset dictionary is needed after this call (see inflateSetDictionary
  71327. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  71328. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  71329. strm->adler to the adler32 checksum of all output produced so far (that is,
  71330. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  71331. below. At the end of the stream, inflate() checks that its computed adler32
  71332. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  71333. only if the checksum is correct.
  71334. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  71335. deflate data. The header type is detected automatically. Any information
  71336. contained in the gzip header is not retained, so applications that need that
  71337. information should instead use raw inflate, see inflateInit2() below, or
  71338. inflateBack() and perform their own processing of the gzip header and
  71339. trailer.
  71340. inflate() returns Z_OK if some progress has been made (more input processed
  71341. or more output produced), Z_STREAM_END if the end of the compressed data has
  71342. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  71343. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  71344. corrupted (input stream not conforming to the zlib format or incorrect check
  71345. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  71346. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  71347. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  71348. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  71349. inflate() can be called again with more input and more output space to
  71350. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  71351. call inflateSync() to look for a good compression block if a partial recovery
  71352. of the data is desired.
  71353. */
  71354. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  71355. /*
  71356. All dynamically allocated data structures for this stream are freed.
  71357. This function discards any unprocessed input and does not flush any
  71358. pending output.
  71359. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  71360. was inconsistent. In the error case, msg may be set but then points to a
  71361. static string (which must not be deallocated).
  71362. */
  71363. /* Advanced functions */
  71364. /*
  71365. The following functions are needed only in some special applications.
  71366. */
  71367. /*
  71368. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  71369. int level,
  71370. int method,
  71371. int windowBits,
  71372. int memLevel,
  71373. int strategy));
  71374. This is another version of deflateInit with more compression options. The
  71375. fields next_in, zalloc, zfree and opaque must be initialized before by
  71376. the caller.
  71377. The method parameter is the compression method. It must be Z_DEFLATED in
  71378. this version of the library.
  71379. The windowBits parameter is the base two logarithm of the window size
  71380. (the size of the history buffer). It should be in the range 8..15 for this
  71381. version of the library. Larger values of this parameter result in better
  71382. compression at the expense of memory usage. The default value is 15 if
  71383. deflateInit is used instead.
  71384. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  71385. determines the window size. deflate() will then generate raw deflate data
  71386. with no zlib header or trailer, and will not compute an adler32 check value.
  71387. windowBits can also be greater than 15 for optional gzip encoding. Add
  71388. 16 to windowBits to write a simple gzip header and trailer around the
  71389. compressed data instead of a zlib wrapper. The gzip header will have no
  71390. file name, no extra data, no comment, no modification time (set to zero),
  71391. no header crc, and the operating system will be set to 255 (unknown). If a
  71392. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  71393. The memLevel parameter specifies how much memory should be allocated
  71394. for the internal compression state. memLevel=1 uses minimum memory but
  71395. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  71396. for optimal speed. The default value is 8. See zconf.h for total memory
  71397. usage as a function of windowBits and memLevel.
  71398. The strategy parameter is used to tune the compression algorithm. Use the
  71399. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  71400. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  71401. string match), or Z_RLE to limit match distances to one (run-length
  71402. encoding). Filtered data consists mostly of small values with a somewhat
  71403. random distribution. In this case, the compression algorithm is tuned to
  71404. compress them better. The effect of Z_FILTERED is to force more Huffman
  71405. coding and less string matching; it is somewhat intermediate between
  71406. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  71407. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  71408. parameter only affects the compression ratio but not the correctness of the
  71409. compressed output even if it is not set appropriately. Z_FIXED prevents the
  71410. use of dynamic Huffman codes, allowing for a simpler decoder for special
  71411. applications.
  71412. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71413. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  71414. method). msg is set to null if there is no error message. deflateInit2 does
  71415. not perform any compression: this will be done by deflate().
  71416. */
  71417. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  71418. const Bytef *dictionary,
  71419. uInt dictLength));
  71420. /*
  71421. Initializes the compression dictionary from the given byte sequence
  71422. without producing any compressed output. This function must be called
  71423. immediately after deflateInit, deflateInit2 or deflateReset, before any
  71424. call of deflate. The compressor and decompressor must use exactly the same
  71425. dictionary (see inflateSetDictionary).
  71426. The dictionary should consist of strings (byte sequences) that are likely
  71427. to be encountered later in the data to be compressed, with the most commonly
  71428. used strings preferably put towards the end of the dictionary. Using a
  71429. dictionary is most useful when the data to be compressed is short and can be
  71430. predicted with good accuracy; the data can then be compressed better than
  71431. with the default empty dictionary.
  71432. Depending on the size of the compression data structures selected by
  71433. deflateInit or deflateInit2, a part of the dictionary may in effect be
  71434. discarded, for example if the dictionary is larger than the window size in
  71435. deflate or deflate2. Thus the strings most likely to be useful should be
  71436. put at the end of the dictionary, not at the front. In addition, the
  71437. current implementation of deflate will use at most the window size minus
  71438. 262 bytes of the provided dictionary.
  71439. Upon return of this function, strm->adler is set to the adler32 value
  71440. of the dictionary; the decompressor may later use this value to determine
  71441. which dictionary has been used by the compressor. (The adler32 value
  71442. applies to the whole dictionary even if only a subset of the dictionary is
  71443. actually used by the compressor.) If a raw deflate was requested, then the
  71444. adler32 value is not computed and strm->adler is not set.
  71445. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  71446. parameter is invalid (such as NULL dictionary) or the stream state is
  71447. inconsistent (for example if deflate has already been called for this stream
  71448. or if the compression method is bsort). deflateSetDictionary does not
  71449. perform any compression: this will be done by deflate().
  71450. */
  71451. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  71452. z_streamp source));
  71453. /*
  71454. Sets the destination stream as a complete copy of the source stream.
  71455. This function can be useful when several compression strategies will be
  71456. tried, for example when there are several ways of pre-processing the input
  71457. data with a filter. The streams that will be discarded should then be freed
  71458. by calling deflateEnd. Note that deflateCopy duplicates the internal
  71459. compression state which can be quite large, so this strategy is slow and
  71460. can consume lots of memory.
  71461. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  71462. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  71463. (such as zalloc being NULL). msg is left unchanged in both source and
  71464. destination.
  71465. */
  71466. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  71467. /*
  71468. This function is equivalent to deflateEnd followed by deflateInit,
  71469. but does not free and reallocate all the internal compression state.
  71470. The stream will keep the same compression level and any other attributes
  71471. that may have been set by deflateInit2.
  71472. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  71473. stream state was inconsistent (such as zalloc or state being NULL).
  71474. */
  71475. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  71476. int level,
  71477. int strategy));
  71478. /*
  71479. Dynamically update the compression level and compression strategy. The
  71480. interpretation of level and strategy is as in deflateInit2. This can be
  71481. used to switch between compression and straight copy of the input data, or
  71482. to switch to a different kind of input data requiring a different
  71483. strategy. If the compression level is changed, the input available so far
  71484. is compressed with the old level (and may be flushed); the new level will
  71485. take effect only at the next call of deflate().
  71486. Before the call of deflateParams, the stream state must be set as for
  71487. a call of deflate(), since the currently available input may have to
  71488. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  71489. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  71490. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  71491. if strm->avail_out was zero.
  71492. */
  71493. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  71494. int good_length,
  71495. int max_lazy,
  71496. int nice_length,
  71497. int max_chain));
  71498. /*
  71499. Fine tune deflate's internal compression parameters. This should only be
  71500. used by someone who understands the algorithm used by zlib's deflate for
  71501. searching for the best matching string, and even then only by the most
  71502. fanatic optimizer trying to squeeze out the last compressed bit for their
  71503. specific input data. Read the deflate.c source code for the meaning of the
  71504. max_lazy, good_length, nice_length, and max_chain parameters.
  71505. deflateTune() can be called after deflateInit() or deflateInit2(), and
  71506. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  71507. */
  71508. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  71509. uLong sourceLen));
  71510. /*
  71511. deflateBound() returns an upper bound on the compressed size after
  71512. deflation of sourceLen bytes. It must be called after deflateInit()
  71513. or deflateInit2(). This would be used to allocate an output buffer
  71514. for deflation in a single pass, and so would be called before deflate().
  71515. */
  71516. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  71517. int bits,
  71518. int value));
  71519. /*
  71520. deflatePrime() inserts bits in the deflate output stream. The intent
  71521. is that this function is used to start off the deflate output with the
  71522. bits leftover from a previous deflate stream when appending to it. As such,
  71523. this function can only be used for raw deflate, and must be used before the
  71524. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  71525. less than or equal to 16, and that many of the least significant bits of
  71526. value will be inserted in the output.
  71527. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  71528. stream state was inconsistent.
  71529. */
  71530. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  71531. gz_headerp head));
  71532. /*
  71533. deflateSetHeader() provides gzip header information for when a gzip
  71534. stream is requested by deflateInit2(). deflateSetHeader() may be called
  71535. after deflateInit2() or deflateReset() and before the first call of
  71536. deflate(). The text, time, os, extra field, name, and comment information
  71537. in the provided gz_header structure are written to the gzip header (xflag is
  71538. ignored -- the extra flags are set according to the compression level). The
  71539. caller must assure that, if not Z_NULL, name and comment are terminated with
  71540. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  71541. available there. If hcrc is true, a gzip header crc is included. Note that
  71542. the current versions of the command-line version of gzip (up through version
  71543. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  71544. gzip file" and give up.
  71545. If deflateSetHeader is not used, the default gzip header has text false,
  71546. the time set to zero, and os set to 255, with no extra, name, or comment
  71547. fields. The gzip header is returned to the default state by deflateReset().
  71548. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  71549. stream state was inconsistent.
  71550. */
  71551. /*
  71552. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  71553. int windowBits));
  71554. This is another version of inflateInit with an extra parameter. The
  71555. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  71556. before by the caller.
  71557. The windowBits parameter is the base two logarithm of the maximum window
  71558. size (the size of the history buffer). It should be in the range 8..15 for
  71559. this version of the library. The default value is 15 if inflateInit is used
  71560. instead. windowBits must be greater than or equal to the windowBits value
  71561. provided to deflateInit2() while compressing, or it must be equal to 15 if
  71562. deflateInit2() was not used. If a compressed stream with a larger window
  71563. size is given as input, inflate() will return with the error code
  71564. Z_DATA_ERROR instead of trying to allocate a larger window.
  71565. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  71566. determines the window size. inflate() will then process raw deflate data,
  71567. not looking for a zlib or gzip header, not generating a check value, and not
  71568. looking for any check values for comparison at the end of the stream. This
  71569. is for use with other formats that use the deflate compressed data format
  71570. such as zip. Those formats provide their own check values. If a custom
  71571. format is developed using the raw deflate format for compressed data, it is
  71572. recommended that a check value such as an adler32 or a crc32 be applied to
  71573. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  71574. most applications, the zlib format should be used as is. Note that comments
  71575. above on the use in deflateInit2() applies to the magnitude of windowBits.
  71576. windowBits can also be greater than 15 for optional gzip decoding. Add
  71577. 32 to windowBits to enable zlib and gzip decoding with automatic header
  71578. detection, or add 16 to decode only the gzip format (the zlib format will
  71579. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  71580. a crc32 instead of an adler32.
  71581. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71582. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  71583. is set to null if there is no error message. inflateInit2 does not perform
  71584. any decompression apart from reading the zlib header if present: this will
  71585. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  71586. and avail_out are unchanged.)
  71587. */
  71588. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  71589. const Bytef *dictionary,
  71590. uInt dictLength));
  71591. /*
  71592. Initializes the decompression dictionary from the given uncompressed byte
  71593. sequence. This function must be called immediately after a call of inflate,
  71594. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  71595. can be determined from the adler32 value returned by that call of inflate.
  71596. The compressor and decompressor must use exactly the same dictionary (see
  71597. deflateSetDictionary). For raw inflate, this function can be called
  71598. immediately after inflateInit2() or inflateReset() and before any call of
  71599. inflate() to set the dictionary. The application must insure that the
  71600. dictionary that was used for compression is provided.
  71601. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  71602. parameter is invalid (such as NULL dictionary) or the stream state is
  71603. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  71604. expected one (incorrect adler32 value). inflateSetDictionary does not
  71605. perform any decompression: this will be done by subsequent calls of
  71606. inflate().
  71607. */
  71608. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  71609. /*
  71610. Skips invalid compressed data until a full flush point (see above the
  71611. description of deflate with Z_FULL_FLUSH) can be found, or until all
  71612. available input is skipped. No output is provided.
  71613. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  71614. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  71615. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  71616. case, the application may save the current current value of total_in which
  71617. indicates where valid compressed data was found. In the error case, the
  71618. application may repeatedly call inflateSync, providing more input each time,
  71619. until success or end of the input data.
  71620. */
  71621. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  71622. z_streamp source));
  71623. /*
  71624. Sets the destination stream as a complete copy of the source stream.
  71625. This function can be useful when randomly accessing a large stream. The
  71626. first pass through the stream can periodically record the inflate state,
  71627. allowing restarting inflate at those points when randomly accessing the
  71628. stream.
  71629. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  71630. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  71631. (such as zalloc being NULL). msg is left unchanged in both source and
  71632. destination.
  71633. */
  71634. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  71635. /*
  71636. This function is equivalent to inflateEnd followed by inflateInit,
  71637. but does not free and reallocate all the internal decompression state.
  71638. The stream will keep attributes that may have been set by inflateInit2.
  71639. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  71640. stream state was inconsistent (such as zalloc or state being NULL).
  71641. */
  71642. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  71643. int bits,
  71644. int value));
  71645. /*
  71646. This function inserts bits in the inflate input stream. The intent is
  71647. that this function is used to start inflating at a bit position in the
  71648. middle of a byte. The provided bits will be used before any bytes are used
  71649. from next_in. This function should only be used with raw inflate, and
  71650. should be used before the first inflate() call after inflateInit2() or
  71651. inflateReset(). bits must be less than or equal to 16, and that many of the
  71652. least significant bits of value will be inserted in the input.
  71653. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  71654. stream state was inconsistent.
  71655. */
  71656. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  71657. gz_headerp head));
  71658. /*
  71659. inflateGetHeader() requests that gzip header information be stored in the
  71660. provided gz_header structure. inflateGetHeader() may be called after
  71661. inflateInit2() or inflateReset(), and before the first call of inflate().
  71662. As inflate() processes the gzip stream, head->done is zero until the header
  71663. is completed, at which time head->done is set to one. If a zlib stream is
  71664. being decoded, then head->done is set to -1 to indicate that there will be
  71665. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  71666. force inflate() to return immediately after header processing is complete
  71667. and before any actual data is decompressed.
  71668. The text, time, xflags, and os fields are filled in with the gzip header
  71669. contents. hcrc is set to true if there is a header CRC. (The header CRC
  71670. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  71671. contains the maximum number of bytes to write to extra. Once done is true,
  71672. extra_len contains the actual extra field length, and extra contains the
  71673. extra field, or that field truncated if extra_max is less than extra_len.
  71674. If name is not Z_NULL, then up to name_max characters are written there,
  71675. terminated with a zero unless the length is greater than name_max. If
  71676. comment is not Z_NULL, then up to comm_max characters are written there,
  71677. terminated with a zero unless the length is greater than comm_max. When
  71678. any of extra, name, or comment are not Z_NULL and the respective field is
  71679. not present in the header, then that field is set to Z_NULL to signal its
  71680. absence. This allows the use of deflateSetHeader() with the returned
  71681. structure to duplicate the header. However if those fields are set to
  71682. allocated memory, then the application will need to save those pointers
  71683. elsewhere so that they can be eventually freed.
  71684. If inflateGetHeader is not used, then the header information is simply
  71685. discarded. The header is always checked for validity, including the header
  71686. CRC if present. inflateReset() will reset the process to discard the header
  71687. information. The application would need to call inflateGetHeader() again to
  71688. retrieve the header from the next gzip stream.
  71689. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  71690. stream state was inconsistent.
  71691. */
  71692. /*
  71693. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  71694. unsigned char FAR *window));
  71695. Initialize the internal stream state for decompression using inflateBack()
  71696. calls. The fields zalloc, zfree and opaque in strm must be initialized
  71697. before the call. If zalloc and zfree are Z_NULL, then the default library-
  71698. derived memory allocation routines are used. windowBits is the base two
  71699. logarithm of the window size, in the range 8..15. window is a caller
  71700. supplied buffer of that size. Except for special applications where it is
  71701. assured that deflate was used with small window sizes, windowBits must be 15
  71702. and a 32K byte window must be supplied to be able to decompress general
  71703. deflate streams.
  71704. See inflateBack() for the usage of these routines.
  71705. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  71706. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  71707. be allocated, or Z_VERSION_ERROR if the version of the library does not
  71708. match the version of the header file.
  71709. */
  71710. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  71711. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  71712. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  71713. in_func in, void FAR *in_desc,
  71714. out_func out, void FAR *out_desc));
  71715. /*
  71716. inflateBack() does a raw inflate with a single call using a call-back
  71717. interface for input and output. This is more efficient than inflate() for
  71718. file i/o applications in that it avoids copying between the output and the
  71719. sliding window by simply making the window itself the output buffer. This
  71720. function trusts the application to not change the output buffer passed by
  71721. the output function, at least until inflateBack() returns.
  71722. inflateBackInit() must be called first to allocate the internal state
  71723. and to initialize the state with the user-provided window buffer.
  71724. inflateBack() may then be used multiple times to inflate a complete, raw
  71725. deflate stream with each call. inflateBackEnd() is then called to free
  71726. the allocated state.
  71727. A raw deflate stream is one with no zlib or gzip header or trailer.
  71728. This routine would normally be used in a utility that reads zip or gzip
  71729. files and writes out uncompressed files. The utility would decode the
  71730. header and process the trailer on its own, hence this routine expects
  71731. only the raw deflate stream to decompress. This is different from the
  71732. normal behavior of inflate(), which expects either a zlib or gzip header and
  71733. trailer around the deflate stream.
  71734. inflateBack() uses two subroutines supplied by the caller that are then
  71735. called by inflateBack() for input and output. inflateBack() calls those
  71736. routines until it reads a complete deflate stream and writes out all of the
  71737. uncompressed data, or until it encounters an error. The function's
  71738. parameters and return types are defined above in the in_func and out_func
  71739. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  71740. number of bytes of provided input, and a pointer to that input in buf. If
  71741. there is no input available, in() must return zero--buf is ignored in that
  71742. case--and inflateBack() will return a buffer error. inflateBack() will call
  71743. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  71744. should return zero on success, or non-zero on failure. If out() returns
  71745. non-zero, inflateBack() will return with an error. Neither in() nor out()
  71746. are permitted to change the contents of the window provided to
  71747. inflateBackInit(), which is also the buffer that out() uses to write from.
  71748. The length written by out() will be at most the window size. Any non-zero
  71749. amount of input may be provided by in().
  71750. For convenience, inflateBack() can be provided input on the first call by
  71751. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  71752. in() will be called. Therefore strm->next_in must be initialized before
  71753. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  71754. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  71755. must also be initialized, and then if strm->avail_in is not zero, input will
  71756. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  71757. The in_desc and out_desc parameters of inflateBack() is passed as the
  71758. first parameter of in() and out() respectively when they are called. These
  71759. descriptors can be optionally used to pass any information that the caller-
  71760. supplied in() and out() functions need to do their job.
  71761. On return, inflateBack() will set strm->next_in and strm->avail_in to
  71762. pass back any unused input that was provided by the last in() call. The
  71763. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  71764. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  71765. error in the deflate stream (in which case strm->msg is set to indicate the
  71766. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  71767. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  71768. distinguished using strm->next_in which will be Z_NULL only if in() returned
  71769. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  71770. out() returning non-zero. (in() will always be called before out(), so
  71771. strm->next_in is assured to be defined if out() returns non-zero.) Note
  71772. that inflateBack() cannot return Z_OK.
  71773. */
  71774. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  71775. /*
  71776. All memory allocated by inflateBackInit() is freed.
  71777. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  71778. state was inconsistent.
  71779. */
  71780. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  71781. /* Return flags indicating compile-time options.
  71782. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  71783. 1.0: size of uInt
  71784. 3.2: size of uLong
  71785. 5.4: size of voidpf (pointer)
  71786. 7.6: size of z_off_t
  71787. Compiler, assembler, and debug options:
  71788. 8: DEBUG
  71789. 9: ASMV or ASMINF -- use ASM code
  71790. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  71791. 11: 0 (reserved)
  71792. One-time table building (smaller code, but not thread-safe if true):
  71793. 12: BUILDFIXED -- build static block decoding tables when needed
  71794. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  71795. 14,15: 0 (reserved)
  71796. Library content (indicates missing functionality):
  71797. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  71798. deflate code when not needed)
  71799. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  71800. and decode gzip streams (to avoid linking crc code)
  71801. 18-19: 0 (reserved)
  71802. Operation variations (changes in library functionality):
  71803. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  71804. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  71805. 22,23: 0 (reserved)
  71806. The sprintf variant used by gzprintf (zero is best):
  71807. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  71808. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  71809. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  71810. Remainder:
  71811. 27-31: 0 (reserved)
  71812. */
  71813. /* utility functions */
  71814. /*
  71815. The following utility functions are implemented on top of the
  71816. basic stream-oriented functions. To simplify the interface, some
  71817. default options are assumed (compression level and memory usage,
  71818. standard memory allocation functions). The source code of these
  71819. utility functions can easily be modified if you need special options.
  71820. */
  71821. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  71822. const Bytef *source, uLong sourceLen));
  71823. /*
  71824. Compresses the source buffer into the destination buffer. sourceLen is
  71825. the byte length of the source buffer. Upon entry, destLen is the total
  71826. size of the destination buffer, which must be at least the value returned
  71827. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  71828. compressed buffer.
  71829. This function can be used to compress a whole file at once if the
  71830. input file is mmap'ed.
  71831. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  71832. enough memory, Z_BUF_ERROR if there was not enough room in the output
  71833. buffer.
  71834. */
  71835. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  71836. const Bytef *source, uLong sourceLen,
  71837. int level));
  71838. /*
  71839. Compresses the source buffer into the destination buffer. The level
  71840. parameter has the same meaning as in deflateInit. sourceLen is the byte
  71841. length of the source buffer. Upon entry, destLen is the total size of the
  71842. destination buffer, which must be at least the value returned by
  71843. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  71844. compressed buffer.
  71845. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71846. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  71847. Z_STREAM_ERROR if the level parameter is invalid.
  71848. */
  71849. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  71850. /*
  71851. compressBound() returns an upper bound on the compressed size after
  71852. compress() or compress2() on sourceLen bytes. It would be used before
  71853. a compress() or compress2() call to allocate the destination buffer.
  71854. */
  71855. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  71856. const Bytef *source, uLong sourceLen));
  71857. /*
  71858. Decompresses the source buffer into the destination buffer. sourceLen is
  71859. the byte length of the source buffer. Upon entry, destLen is the total
  71860. size of the destination buffer, which must be large enough to hold the
  71861. entire uncompressed data. (The size of the uncompressed data must have
  71862. been saved previously by the compressor and transmitted to the decompressor
  71863. by some mechanism outside the scope of this compression library.)
  71864. Upon exit, destLen is the actual size of the compressed buffer.
  71865. This function can be used to decompress a whole file at once if the
  71866. input file is mmap'ed.
  71867. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  71868. enough memory, Z_BUF_ERROR if there was not enough room in the output
  71869. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  71870. */
  71871. typedef voidp gzFile;
  71872. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  71873. /*
  71874. Opens a gzip (.gz) file for reading or writing. The mode parameter
  71875. is as in fopen ("rb" or "wb") but can also include a compression level
  71876. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  71877. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  71878. as in "wb1R". (See the description of deflateInit2 for more information
  71879. about the strategy parameter.)
  71880. gzopen can be used to read a file which is not in gzip format; in this
  71881. case gzread will directly read from the file without decompression.
  71882. gzopen returns NULL if the file could not be opened or if there was
  71883. insufficient memory to allocate the (de)compression state; errno
  71884. can be checked to distinguish the two cases (if errno is zero, the
  71885. zlib error is Z_MEM_ERROR). */
  71886. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  71887. /*
  71888. gzdopen() associates a gzFile with the file descriptor fd. File
  71889. descriptors are obtained from calls like open, dup, creat, pipe or
  71890. fileno (in the file has been previously opened with fopen).
  71891. The mode parameter is as in gzopen.
  71892. The next call of gzclose on the returned gzFile will also close the
  71893. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  71894. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  71895. gzdopen returns NULL if there was insufficient memory to allocate
  71896. the (de)compression state.
  71897. */
  71898. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  71899. /*
  71900. Dynamically update the compression level or strategy. See the description
  71901. of deflateInit2 for the meaning of these parameters.
  71902. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  71903. opened for writing.
  71904. */
  71905. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  71906. /*
  71907. Reads the given number of uncompressed bytes from the compressed file.
  71908. If the input file was not in gzip format, gzread copies the given number
  71909. of bytes into the buffer.
  71910. gzread returns the number of uncompressed bytes actually read (0 for
  71911. end of file, -1 for error). */
  71912. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  71913. voidpc buf, unsigned len));
  71914. /*
  71915. Writes the given number of uncompressed bytes into the compressed file.
  71916. gzwrite returns the number of uncompressed bytes actually written
  71917. (0 in case of error).
  71918. */
  71919. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  71920. /*
  71921. Converts, formats, and writes the args to the compressed file under
  71922. control of the format string, as in fprintf. gzprintf returns the number of
  71923. uncompressed bytes actually written (0 in case of error). The number of
  71924. uncompressed bytes written is limited to 4095. The caller should assure that
  71925. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  71926. return an error (0) with nothing written. In this case, there may also be a
  71927. buffer overflow with unpredictable consequences, which is possible only if
  71928. zlib was compiled with the insecure functions sprintf() or vsprintf()
  71929. because the secure snprintf() or vsnprintf() functions were not available.
  71930. */
  71931. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  71932. /*
  71933. Writes the given null-terminated string to the compressed file, excluding
  71934. the terminating null character.
  71935. gzputs returns the number of characters written, or -1 in case of error.
  71936. */
  71937. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  71938. /*
  71939. Reads bytes from the compressed file until len-1 characters are read, or
  71940. a newline character is read and transferred to buf, or an end-of-file
  71941. condition is encountered. The string is then terminated with a null
  71942. character.
  71943. gzgets returns buf, or Z_NULL in case of error.
  71944. */
  71945. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  71946. /*
  71947. Writes c, converted to an unsigned char, into the compressed file.
  71948. gzputc returns the value that was written, or -1 in case of error.
  71949. */
  71950. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  71951. /*
  71952. Reads one byte from the compressed file. gzgetc returns this byte
  71953. or -1 in case of end of file or error.
  71954. */
  71955. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  71956. /*
  71957. Push one character back onto the stream to be read again later.
  71958. Only one character of push-back is allowed. gzungetc() returns the
  71959. character pushed, or -1 on failure. gzungetc() will fail if a
  71960. character has been pushed but not read yet, or if c is -1. The pushed
  71961. character will be discarded if the stream is repositioned with gzseek()
  71962. or gzrewind().
  71963. */
  71964. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  71965. /*
  71966. Flushes all pending output into the compressed file. The parameter
  71967. flush is as in the deflate() function. The return value is the zlib
  71968. error number (see function gzerror below). gzflush returns Z_OK if
  71969. the flush parameter is Z_FINISH and all output could be flushed.
  71970. gzflush should be called only when strictly necessary because it can
  71971. degrade compression.
  71972. */
  71973. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  71974. z_off_t offset, int whence));
  71975. /*
  71976. Sets the starting position for the next gzread or gzwrite on the
  71977. given compressed file. The offset represents a number of bytes in the
  71978. uncompressed data stream. The whence parameter is defined as in lseek(2);
  71979. the value SEEK_END is not supported.
  71980. If the file is opened for reading, this function is emulated but can be
  71981. extremely slow. If the file is opened for writing, only forward seeks are
  71982. supported; gzseek then compresses a sequence of zeroes up to the new
  71983. starting position.
  71984. gzseek returns the resulting offset location as measured in bytes from
  71985. the beginning of the uncompressed stream, or -1 in case of error, in
  71986. particular if the file is opened for writing and the new starting position
  71987. would be before the current position.
  71988. */
  71989. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  71990. /*
  71991. Rewinds the given file. This function is supported only for reading.
  71992. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  71993. */
  71994. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  71995. /*
  71996. Returns the starting position for the next gzread or gzwrite on the
  71997. given compressed file. This position represents a number of bytes in the
  71998. uncompressed data stream.
  71999. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72000. */
  72001. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72002. /*
  72003. Returns 1 when EOF has previously been detected reading the given
  72004. input stream, otherwise zero.
  72005. */
  72006. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  72007. /*
  72008. Returns 1 if file is being read directly without decompression, otherwise
  72009. zero.
  72010. */
  72011. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  72012. /*
  72013. Flushes all pending output if necessary, closes the compressed file
  72014. and deallocates all the (de)compression state. The return value is the zlib
  72015. error number (see function gzerror below).
  72016. */
  72017. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  72018. /*
  72019. Returns the error message for the last error which occurred on the
  72020. given compressed file. errnum is set to zlib error number. If an
  72021. error occurred in the file system and not in the compression library,
  72022. errnum is set to Z_ERRNO and the application may consult errno
  72023. to get the exact error code.
  72024. */
  72025. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  72026. /*
  72027. Clears the error and end-of-file flags for file. This is analogous to the
  72028. clearerr() function in stdio. This is useful for continuing to read a gzip
  72029. file that is being written concurrently.
  72030. */
  72031. /* checksum functions */
  72032. /*
  72033. These functions are not related to compression but are exported
  72034. anyway because they might be useful in applications using the
  72035. compression library.
  72036. */
  72037. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  72038. /*
  72039. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  72040. return the updated checksum. If buf is NULL, this function returns
  72041. the required initial value for the checksum.
  72042. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  72043. much faster. Usage example:
  72044. uLong adler = adler32(0L, Z_NULL, 0);
  72045. while (read_buffer(buffer, length) != EOF) {
  72046. adler = adler32(adler, buffer, length);
  72047. }
  72048. if (adler != original_adler) error();
  72049. */
  72050. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  72051. z_off_t len2));
  72052. /*
  72053. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  72054. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  72055. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  72056. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  72057. */
  72058. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  72059. /*
  72060. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  72061. updated CRC-32. If buf is NULL, this function returns the required initial
  72062. value for the for the crc. Pre- and post-conditioning (one's complement) is
  72063. performed within this function so it shouldn't be done by the application.
  72064. Usage example:
  72065. uLong crc = crc32(0L, Z_NULL, 0);
  72066. while (read_buffer(buffer, length) != EOF) {
  72067. crc = crc32(crc, buffer, length);
  72068. }
  72069. if (crc != original_crc) error();
  72070. */
  72071. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  72072. /*
  72073. Combine two CRC-32 check values into one. For two sequences of bytes,
  72074. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  72075. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  72076. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  72077. len2.
  72078. */
  72079. /* various hacks, don't look :) */
  72080. /* deflateInit and inflateInit are macros to allow checking the zlib version
  72081. * and the compiler's view of z_stream:
  72082. */
  72083. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  72084. const char *version, int stream_size));
  72085. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  72086. const char *version, int stream_size));
  72087. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  72088. int windowBits, int memLevel,
  72089. int strategy, const char *version,
  72090. int stream_size));
  72091. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  72092. const char *version, int stream_size));
  72093. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  72094. unsigned char FAR *window,
  72095. const char *version,
  72096. int stream_size));
  72097. #define deflateInit(strm, level) \
  72098. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  72099. #define inflateInit(strm) \
  72100. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  72101. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  72102. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  72103. (strategy), ZLIB_VERSION, sizeof(z_stream))
  72104. #define inflateInit2(strm, windowBits) \
  72105. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  72106. #define inflateBackInit(strm, windowBits, window) \
  72107. inflateBackInit_((strm), (windowBits), (window), \
  72108. ZLIB_VERSION, sizeof(z_stream))
  72109. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  72110. struct internal_state {int dummy;}; /* hack for buggy compilers */
  72111. #endif
  72112. ZEXTERN const char * ZEXPORT zError OF((int));
  72113. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  72114. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  72115. #ifdef __cplusplus
  72116. }
  72117. #endif
  72118. #endif /* ZLIB_H */
  72119. /********* End of inlined file: zlib.h *********/
  72120. #undef OS_CODE
  72121. }
  72122. BEGIN_JUCE_NAMESPACE
  72123. using namespace zlibNamespace;
  72124. // internal helper object that holds the zlib structures so they don't have to be
  72125. // included publicly.
  72126. class GZIPCompressorHelper
  72127. {
  72128. private:
  72129. z_stream* stream;
  72130. uint8* data;
  72131. int dataSize, compLevel, strategy;
  72132. bool setParams;
  72133. public:
  72134. bool finished, shouldFinish;
  72135. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  72136. : data (0),
  72137. dataSize (0),
  72138. compLevel (compressionLevel),
  72139. strategy (0),
  72140. setParams (true),
  72141. finished (false),
  72142. shouldFinish (false)
  72143. {
  72144. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  72145. if (deflateInit2 (stream,
  72146. compLevel,
  72147. Z_DEFLATED,
  72148. nowrap ? -MAX_WBITS : MAX_WBITS,
  72149. 8,
  72150. strategy) != Z_OK)
  72151. {
  72152. juce_free (stream);
  72153. stream = 0;
  72154. }
  72155. }
  72156. ~GZIPCompressorHelper()
  72157. {
  72158. if (stream != 0)
  72159. {
  72160. deflateEnd (stream);
  72161. juce_free (stream);
  72162. }
  72163. }
  72164. bool needsInput() const throw()
  72165. {
  72166. return dataSize <= 0;
  72167. }
  72168. void setInput (uint8* const newData, const int size) throw()
  72169. {
  72170. data = newData;
  72171. dataSize = size;
  72172. }
  72173. int doNextBlock (uint8* const dest, const int destSize) throw()
  72174. {
  72175. if (stream != 0)
  72176. {
  72177. stream->next_in = data;
  72178. stream->next_out = dest;
  72179. stream->avail_in = dataSize;
  72180. stream->avail_out = destSize;
  72181. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  72182. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  72183. setParams = false;
  72184. switch (result)
  72185. {
  72186. case Z_STREAM_END:
  72187. finished = true;
  72188. case Z_OK:
  72189. data += dataSize - stream->avail_in;
  72190. dataSize = stream->avail_in;
  72191. return destSize - stream->avail_out;
  72192. default:
  72193. break;
  72194. }
  72195. }
  72196. return 0;
  72197. }
  72198. };
  72199. const int gzipCompBufferSize = 32768;
  72200. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  72201. int compressionLevel,
  72202. const bool deleteDestStream_,
  72203. const bool noWrap)
  72204. : destStream (destStream_),
  72205. deleteDestStream (deleteDestStream_)
  72206. {
  72207. if (compressionLevel < 1 || compressionLevel > 9)
  72208. compressionLevel = -1;
  72209. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  72210. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  72211. }
  72212. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  72213. {
  72214. flush();
  72215. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72216. delete h;
  72217. juce_free (buffer);
  72218. if (deleteDestStream)
  72219. delete destStream;
  72220. }
  72221. void GZIPCompressorOutputStream::flush()
  72222. {
  72223. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72224. if (! h->finished)
  72225. {
  72226. h->shouldFinish = true;
  72227. while (! h->finished)
  72228. doNextBlock();
  72229. }
  72230. destStream->flush();
  72231. }
  72232. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  72233. {
  72234. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72235. if (! h->finished)
  72236. {
  72237. h->setInput ((uint8*) destBuffer, howMany);
  72238. while (! h->needsInput())
  72239. {
  72240. if (! doNextBlock())
  72241. return false;
  72242. }
  72243. }
  72244. return true;
  72245. }
  72246. bool GZIPCompressorOutputStream::doNextBlock()
  72247. {
  72248. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72249. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  72250. if (len > 0)
  72251. return destStream->write (buffer, len);
  72252. else
  72253. return true;
  72254. }
  72255. int64 GZIPCompressorOutputStream::getPosition()
  72256. {
  72257. return destStream->getPosition();
  72258. }
  72259. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  72260. {
  72261. jassertfalse // can't do it!
  72262. return false;
  72263. }
  72264. END_JUCE_NAMESPACE
  72265. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  72266. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  72267. #if JUCE_MSVC
  72268. #pragma warning (push)
  72269. #pragma warning (disable: 4309 4305)
  72270. #endif
  72271. namespace zlibNamespace
  72272. {
  72273. extern "C"
  72274. {
  72275. #undef OS_CODE
  72276. #undef fdopen
  72277. #define ZLIB_INTERNAL
  72278. #define NO_DUMMY_DECL
  72279. /********* Start of inlined file: adler32.c *********/
  72280. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72281. #define ZLIB_INTERNAL
  72282. #define BASE 65521UL /* largest prime smaller than 65536 */
  72283. #define NMAX 5552
  72284. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  72285. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  72286. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  72287. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  72288. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  72289. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  72290. /* use NO_DIVIDE if your processor does not do division in hardware */
  72291. #ifdef NO_DIVIDE
  72292. # define MOD(a) \
  72293. do { \
  72294. if (a >= (BASE << 16)) a -= (BASE << 16); \
  72295. if (a >= (BASE << 15)) a -= (BASE << 15); \
  72296. if (a >= (BASE << 14)) a -= (BASE << 14); \
  72297. if (a >= (BASE << 13)) a -= (BASE << 13); \
  72298. if (a >= (BASE << 12)) a -= (BASE << 12); \
  72299. if (a >= (BASE << 11)) a -= (BASE << 11); \
  72300. if (a >= (BASE << 10)) a -= (BASE << 10); \
  72301. if (a >= (BASE << 9)) a -= (BASE << 9); \
  72302. if (a >= (BASE << 8)) a -= (BASE << 8); \
  72303. if (a >= (BASE << 7)) a -= (BASE << 7); \
  72304. if (a >= (BASE << 6)) a -= (BASE << 6); \
  72305. if (a >= (BASE << 5)) a -= (BASE << 5); \
  72306. if (a >= (BASE << 4)) a -= (BASE << 4); \
  72307. if (a >= (BASE << 3)) a -= (BASE << 3); \
  72308. if (a >= (BASE << 2)) a -= (BASE << 2); \
  72309. if (a >= (BASE << 1)) a -= (BASE << 1); \
  72310. if (a >= BASE) a -= BASE; \
  72311. } while (0)
  72312. # define MOD4(a) \
  72313. do { \
  72314. if (a >= (BASE << 4)) a -= (BASE << 4); \
  72315. if (a >= (BASE << 3)) a -= (BASE << 3); \
  72316. if (a >= (BASE << 2)) a -= (BASE << 2); \
  72317. if (a >= (BASE << 1)) a -= (BASE << 1); \
  72318. if (a >= BASE) a -= BASE; \
  72319. } while (0)
  72320. #else
  72321. # define MOD(a) a %= BASE
  72322. # define MOD4(a) a %= BASE
  72323. #endif
  72324. /* ========================================================================= */
  72325. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  72326. {
  72327. unsigned long sum2;
  72328. unsigned n;
  72329. /* split Adler-32 into component sums */
  72330. sum2 = (adler >> 16) & 0xffff;
  72331. adler &= 0xffff;
  72332. /* in case user likes doing a byte at a time, keep it fast */
  72333. if (len == 1) {
  72334. adler += buf[0];
  72335. if (adler >= BASE)
  72336. adler -= BASE;
  72337. sum2 += adler;
  72338. if (sum2 >= BASE)
  72339. sum2 -= BASE;
  72340. return adler | (sum2 << 16);
  72341. }
  72342. /* initial Adler-32 value (deferred check for len == 1 speed) */
  72343. if (buf == Z_NULL)
  72344. return 1L;
  72345. /* in case short lengths are provided, keep it somewhat fast */
  72346. if (len < 16) {
  72347. while (len--) {
  72348. adler += *buf++;
  72349. sum2 += adler;
  72350. }
  72351. if (adler >= BASE)
  72352. adler -= BASE;
  72353. MOD4(sum2); /* only added so many BASE's */
  72354. return adler | (sum2 << 16);
  72355. }
  72356. /* do length NMAX blocks -- requires just one modulo operation */
  72357. while (len >= NMAX) {
  72358. len -= NMAX;
  72359. n = NMAX / 16; /* NMAX is divisible by 16 */
  72360. do {
  72361. DO16(buf); /* 16 sums unrolled */
  72362. buf += 16;
  72363. } while (--n);
  72364. MOD(adler);
  72365. MOD(sum2);
  72366. }
  72367. /* do remaining bytes (less than NMAX, still just one modulo) */
  72368. if (len) { /* avoid modulos if none remaining */
  72369. while (len >= 16) {
  72370. len -= 16;
  72371. DO16(buf);
  72372. buf += 16;
  72373. }
  72374. while (len--) {
  72375. adler += *buf++;
  72376. sum2 += adler;
  72377. }
  72378. MOD(adler);
  72379. MOD(sum2);
  72380. }
  72381. /* return recombined sums */
  72382. return adler | (sum2 << 16);
  72383. }
  72384. /* ========================================================================= */
  72385. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  72386. {
  72387. unsigned long sum1;
  72388. unsigned long sum2;
  72389. unsigned rem;
  72390. /* the derivation of this formula is left as an exercise for the reader */
  72391. rem = (unsigned)(len2 % BASE);
  72392. sum1 = adler1 & 0xffff;
  72393. sum2 = rem * sum1;
  72394. MOD(sum2);
  72395. sum1 += (adler2 & 0xffff) + BASE - 1;
  72396. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  72397. if (sum1 > BASE) sum1 -= BASE;
  72398. if (sum1 > BASE) sum1 -= BASE;
  72399. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  72400. if (sum2 > BASE) sum2 -= BASE;
  72401. return sum1 | (sum2 << 16);
  72402. }
  72403. /********* End of inlined file: adler32.c *********/
  72404. /********* Start of inlined file: compress.c *********/
  72405. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72406. #define ZLIB_INTERNAL
  72407. /* ===========================================================================
  72408. Compresses the source buffer into the destination buffer. The level
  72409. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72410. length of the source buffer. Upon entry, destLen is the total size of the
  72411. destination buffer, which must be at least 0.1% larger than sourceLen plus
  72412. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  72413. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72414. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72415. Z_STREAM_ERROR if the level parameter is invalid.
  72416. */
  72417. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  72418. uLong sourceLen, int level)
  72419. {
  72420. z_stream stream;
  72421. int err;
  72422. stream.next_in = (Bytef*)source;
  72423. stream.avail_in = (uInt)sourceLen;
  72424. #ifdef MAXSEG_64K
  72425. /* Check for source > 64K on 16-bit machine: */
  72426. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  72427. #endif
  72428. stream.next_out = dest;
  72429. stream.avail_out = (uInt)*destLen;
  72430. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  72431. stream.zalloc = (alloc_func)0;
  72432. stream.zfree = (free_func)0;
  72433. stream.opaque = (voidpf)0;
  72434. err = deflateInit(&stream, level);
  72435. if (err != Z_OK) return err;
  72436. err = deflate(&stream, Z_FINISH);
  72437. if (err != Z_STREAM_END) {
  72438. deflateEnd(&stream);
  72439. return err == Z_OK ? Z_BUF_ERROR : err;
  72440. }
  72441. *destLen = stream.total_out;
  72442. err = deflateEnd(&stream);
  72443. return err;
  72444. }
  72445. /* ===========================================================================
  72446. */
  72447. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  72448. {
  72449. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  72450. }
  72451. /* ===========================================================================
  72452. If the default memLevel or windowBits for deflateInit() is changed, then
  72453. this function needs to be updated.
  72454. */
  72455. uLong ZEXPORT compressBound (uLong sourceLen)
  72456. {
  72457. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  72458. }
  72459. /********* End of inlined file: compress.c *********/
  72460. #undef DO1
  72461. #undef DO8
  72462. /********* Start of inlined file: crc32.c *********/
  72463. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72464. /*
  72465. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  72466. protection on the static variables used to control the first-use generation
  72467. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  72468. first call get_crc_table() to initialize the tables before allowing more than
  72469. one thread to use crc32().
  72470. */
  72471. #ifdef MAKECRCH
  72472. # include <stdio.h>
  72473. # ifndef DYNAMIC_CRC_TABLE
  72474. # define DYNAMIC_CRC_TABLE
  72475. # endif /* !DYNAMIC_CRC_TABLE */
  72476. #endif /* MAKECRCH */
  72477. /********* Start of inlined file: zutil.h *********/
  72478. /* WARNING: this file should *not* be used by applications. It is
  72479. part of the implementation of the compression library and is
  72480. subject to change. Applications should only use zlib.h.
  72481. */
  72482. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72483. #ifndef ZUTIL_H
  72484. #define ZUTIL_H
  72485. #define ZLIB_INTERNAL
  72486. #ifdef STDC
  72487. # ifndef _WIN32_WCE
  72488. # include <stddef.h>
  72489. # endif
  72490. # include <string.h>
  72491. # include <stdlib.h>
  72492. #endif
  72493. #ifdef NO_ERRNO_H
  72494. # ifdef _WIN32_WCE
  72495. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  72496. * errno. We define it as a global variable to simplify porting.
  72497. * Its value is always 0 and should not be used. We rename it to
  72498. * avoid conflict with other libraries that use the same workaround.
  72499. */
  72500. # define errno z_errno
  72501. # endif
  72502. extern int errno;
  72503. #else
  72504. # ifndef _WIN32_WCE
  72505. # include <errno.h>
  72506. # endif
  72507. #endif
  72508. #ifndef local
  72509. # define local static
  72510. #endif
  72511. /* compile with -Dlocal if your debugger can't find static symbols */
  72512. typedef unsigned char uch;
  72513. typedef uch FAR uchf;
  72514. typedef unsigned short ush;
  72515. typedef ush FAR ushf;
  72516. typedef unsigned long ulg;
  72517. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  72518. /* (size given to avoid silly warnings with Visual C++) */
  72519. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  72520. #define ERR_RETURN(strm,err) \
  72521. return (strm->msg = (char*)ERR_MSG(err), (err))
  72522. /* To be used only when the state is known to be valid */
  72523. /* common constants */
  72524. #ifndef DEF_WBITS
  72525. # define DEF_WBITS MAX_WBITS
  72526. #endif
  72527. /* default windowBits for decompression. MAX_WBITS is for compression only */
  72528. #if MAX_MEM_LEVEL >= 8
  72529. # define DEF_MEM_LEVEL 8
  72530. #else
  72531. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  72532. #endif
  72533. /* default memLevel */
  72534. #define STORED_BLOCK 0
  72535. #define STATIC_TREES 1
  72536. #define DYN_TREES 2
  72537. /* The three kinds of block type */
  72538. #define MIN_MATCH 3
  72539. #define MAX_MATCH 258
  72540. /* The minimum and maximum match lengths */
  72541. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  72542. /* target dependencies */
  72543. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  72544. # define OS_CODE 0x00
  72545. # if defined(__TURBOC__) || defined(__BORLANDC__)
  72546. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  72547. /* Allow compilation with ANSI keywords only enabled */
  72548. void _Cdecl farfree( void *block );
  72549. void *_Cdecl farmalloc( unsigned long nbytes );
  72550. # else
  72551. # include <alloc.h>
  72552. # endif
  72553. # else /* MSC or DJGPP */
  72554. # include <malloc.h>
  72555. # endif
  72556. #endif
  72557. #ifdef AMIGA
  72558. # define OS_CODE 0x01
  72559. #endif
  72560. #if defined(VAXC) || defined(VMS)
  72561. # define OS_CODE 0x02
  72562. # define F_OPEN(name, mode) \
  72563. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  72564. #endif
  72565. #if defined(ATARI) || defined(atarist)
  72566. # define OS_CODE 0x05
  72567. #endif
  72568. #ifdef OS2
  72569. # define OS_CODE 0x06
  72570. # ifdef M_I86
  72571. #include <malloc.h>
  72572. # endif
  72573. #endif
  72574. #if defined(MACOS) || TARGET_OS_MAC
  72575. # define OS_CODE 0x07
  72576. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  72577. # include <unix.h> /* for fdopen */
  72578. # else
  72579. # ifndef fdopen
  72580. # define fdopen(fd,mode) NULL /* No fdopen() */
  72581. # endif
  72582. # endif
  72583. #endif
  72584. #ifdef TOPS20
  72585. # define OS_CODE 0x0a
  72586. #endif
  72587. #ifdef WIN32
  72588. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  72589. # define OS_CODE 0x0b
  72590. # endif
  72591. #endif
  72592. #ifdef __50SERIES /* Prime/PRIMOS */
  72593. # define OS_CODE 0x0f
  72594. #endif
  72595. #if defined(_BEOS_) || defined(RISCOS)
  72596. # define fdopen(fd,mode) NULL /* No fdopen() */
  72597. #endif
  72598. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  72599. # if defined(_WIN32_WCE)
  72600. # define fdopen(fd,mode) NULL /* No fdopen() */
  72601. # ifndef _PTRDIFF_T_DEFINED
  72602. typedef int ptrdiff_t;
  72603. # define _PTRDIFF_T_DEFINED
  72604. # endif
  72605. # else
  72606. # define fdopen(fd,type) _fdopen(fd,type)
  72607. # endif
  72608. #endif
  72609. /* common defaults */
  72610. #ifndef OS_CODE
  72611. # define OS_CODE 0x03 /* assume Unix */
  72612. #endif
  72613. #ifndef F_OPEN
  72614. # define F_OPEN(name, mode) fopen((name), (mode))
  72615. #endif
  72616. /* functions */
  72617. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  72618. # ifndef HAVE_VSNPRINTF
  72619. # define HAVE_VSNPRINTF
  72620. # endif
  72621. #endif
  72622. #if defined(__CYGWIN__)
  72623. # ifndef HAVE_VSNPRINTF
  72624. # define HAVE_VSNPRINTF
  72625. # endif
  72626. #endif
  72627. #ifndef HAVE_VSNPRINTF
  72628. # ifdef MSDOS
  72629. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  72630. but for now we just assume it doesn't. */
  72631. # define NO_vsnprintf
  72632. # endif
  72633. # ifdef __TURBOC__
  72634. # define NO_vsnprintf
  72635. # endif
  72636. # ifdef WIN32
  72637. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  72638. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  72639. # define vsnprintf _vsnprintf
  72640. # endif
  72641. # endif
  72642. # ifdef __SASC
  72643. # define NO_vsnprintf
  72644. # endif
  72645. #endif
  72646. #ifdef VMS
  72647. # define NO_vsnprintf
  72648. #endif
  72649. #if defined(pyr)
  72650. # define NO_MEMCPY
  72651. #endif
  72652. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  72653. /* Use our own functions for small and medium model with MSC <= 5.0.
  72654. * You may have to use the same strategy for Borland C (untested).
  72655. * The __SC__ check is for Symantec.
  72656. */
  72657. # define NO_MEMCPY
  72658. #endif
  72659. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  72660. # define HAVE_MEMCPY
  72661. #endif
  72662. #ifdef HAVE_MEMCPY
  72663. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  72664. # define zmemcpy _fmemcpy
  72665. # define zmemcmp _fmemcmp
  72666. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  72667. # else
  72668. # define zmemcpy memcpy
  72669. # define zmemcmp memcmp
  72670. # define zmemzero(dest, len) memset(dest, 0, len)
  72671. # endif
  72672. #else
  72673. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  72674. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  72675. extern void zmemzero OF((Bytef* dest, uInt len));
  72676. #endif
  72677. /* Diagnostic functions */
  72678. #ifdef DEBUG
  72679. # include <stdio.h>
  72680. extern int z_verbose;
  72681. extern void z_error OF((char *m));
  72682. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  72683. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  72684. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  72685. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  72686. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  72687. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  72688. #else
  72689. # define Assert(cond,msg)
  72690. # define Trace(x)
  72691. # define Tracev(x)
  72692. # define Tracevv(x)
  72693. # define Tracec(c,x)
  72694. # define Tracecv(c,x)
  72695. #endif
  72696. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  72697. void zcfree OF((voidpf opaque, voidpf ptr));
  72698. #define ZALLOC(strm, items, size) \
  72699. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  72700. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  72701. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  72702. #endif /* ZUTIL_H */
  72703. /********* End of inlined file: zutil.h *********/
  72704. /* for STDC and FAR definitions */
  72705. #define local static
  72706. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  72707. #ifndef NOBYFOUR
  72708. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  72709. # include <limits.h>
  72710. # define BYFOUR
  72711. # if (UINT_MAX == 0xffffffffUL)
  72712. typedef unsigned int u4;
  72713. # else
  72714. # if (ULONG_MAX == 0xffffffffUL)
  72715. typedef unsigned long u4;
  72716. # else
  72717. # if (USHRT_MAX == 0xffffffffUL)
  72718. typedef unsigned short u4;
  72719. # else
  72720. # undef BYFOUR /* can't find a four-byte integer type! */
  72721. # endif
  72722. # endif
  72723. # endif
  72724. # endif /* STDC */
  72725. #endif /* !NOBYFOUR */
  72726. /* Definitions for doing the crc four data bytes at a time. */
  72727. #ifdef BYFOUR
  72728. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  72729. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  72730. local unsigned long crc32_little OF((unsigned long,
  72731. const unsigned char FAR *, unsigned));
  72732. local unsigned long crc32_big OF((unsigned long,
  72733. const unsigned char FAR *, unsigned));
  72734. # define TBLS 8
  72735. #else
  72736. # define TBLS 1
  72737. #endif /* BYFOUR */
  72738. /* Local functions for crc concatenation */
  72739. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  72740. unsigned long vec));
  72741. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  72742. #ifdef DYNAMIC_CRC_TABLE
  72743. local volatile int crc_table_empty = 1;
  72744. local unsigned long FAR crc_table[TBLS][256];
  72745. local void make_crc_table OF((void));
  72746. #ifdef MAKECRCH
  72747. local void write_table OF((FILE *, const unsigned long FAR *));
  72748. #endif /* MAKECRCH */
  72749. /*
  72750. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  72751. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  72752. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  72753. with the lowest powers in the most significant bit. Then adding polynomials
  72754. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  72755. one. If we call the above polynomial p, and represent a byte as the
  72756. polynomial q, also with the lowest power in the most significant bit (so the
  72757. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  72758. where a mod b means the remainder after dividing a by b.
  72759. This calculation is done using the shift-register method of multiplying and
  72760. taking the remainder. The register is initialized to zero, and for each
  72761. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  72762. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  72763. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  72764. out is a one). We start with the highest power (least significant bit) of
  72765. q and repeat for all eight bits of q.
  72766. The first table is simply the CRC of all possible eight bit values. This is
  72767. all the information needed to generate CRCs on data a byte at a time for all
  72768. combinations of CRC register values and incoming bytes. The remaining tables
  72769. allow for word-at-a-time CRC calculation for both big-endian and little-
  72770. endian machines, where a word is four bytes.
  72771. */
  72772. local void make_crc_table()
  72773. {
  72774. unsigned long c;
  72775. int n, k;
  72776. unsigned long poly; /* polynomial exclusive-or pattern */
  72777. /* terms of polynomial defining this crc (except x^32): */
  72778. static volatile int first = 1; /* flag to limit concurrent making */
  72779. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  72780. /* See if another task is already doing this (not thread-safe, but better
  72781. than nothing -- significantly reduces duration of vulnerability in
  72782. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  72783. if (first) {
  72784. first = 0;
  72785. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  72786. poly = 0UL;
  72787. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  72788. poly |= 1UL << (31 - p[n]);
  72789. /* generate a crc for every 8-bit value */
  72790. for (n = 0; n < 256; n++) {
  72791. c = (unsigned long)n;
  72792. for (k = 0; k < 8; k++)
  72793. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  72794. crc_table[0][n] = c;
  72795. }
  72796. #ifdef BYFOUR
  72797. /* generate crc for each value followed by one, two, and three zeros,
  72798. and then the byte reversal of those as well as the first table */
  72799. for (n = 0; n < 256; n++) {
  72800. c = crc_table[0][n];
  72801. crc_table[4][n] = REV(c);
  72802. for (k = 1; k < 4; k++) {
  72803. c = crc_table[0][c & 0xff] ^ (c >> 8);
  72804. crc_table[k][n] = c;
  72805. crc_table[k + 4][n] = REV(c);
  72806. }
  72807. }
  72808. #endif /* BYFOUR */
  72809. crc_table_empty = 0;
  72810. }
  72811. else { /* not first */
  72812. /* wait for the other guy to finish (not efficient, but rare) */
  72813. while (crc_table_empty)
  72814. ;
  72815. }
  72816. #ifdef MAKECRCH
  72817. /* write out CRC tables to crc32.h */
  72818. {
  72819. FILE *out;
  72820. out = fopen("crc32.h", "w");
  72821. if (out == NULL) return;
  72822. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  72823. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  72824. fprintf(out, "local const unsigned long FAR ");
  72825. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  72826. write_table(out, crc_table[0]);
  72827. # ifdef BYFOUR
  72828. fprintf(out, "#ifdef BYFOUR\n");
  72829. for (k = 1; k < 8; k++) {
  72830. fprintf(out, " },\n {\n");
  72831. write_table(out, crc_table[k]);
  72832. }
  72833. fprintf(out, "#endif\n");
  72834. # endif /* BYFOUR */
  72835. fprintf(out, " }\n};\n");
  72836. fclose(out);
  72837. }
  72838. #endif /* MAKECRCH */
  72839. }
  72840. #ifdef MAKECRCH
  72841. local void write_table(out, table)
  72842. FILE *out;
  72843. const unsigned long FAR *table;
  72844. {
  72845. int n;
  72846. for (n = 0; n < 256; n++)
  72847. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  72848. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  72849. }
  72850. #endif /* MAKECRCH */
  72851. #else /* !DYNAMIC_CRC_TABLE */
  72852. /* ========================================================================
  72853. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  72854. */
  72855. /********* Start of inlined file: crc32.h *********/
  72856. local const unsigned long FAR crc_table[TBLS][256] =
  72857. {
  72858. {
  72859. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  72860. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  72861. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  72862. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  72863. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  72864. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  72865. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  72866. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  72867. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  72868. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  72869. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  72870. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  72871. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  72872. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  72873. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  72874. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  72875. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  72876. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  72877. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  72878. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  72879. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  72880. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  72881. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  72882. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  72883. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  72884. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  72885. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  72886. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  72887. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  72888. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  72889. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  72890. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  72891. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  72892. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  72893. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  72894. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  72895. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  72896. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  72897. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  72898. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  72899. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  72900. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  72901. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  72902. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  72903. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  72904. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  72905. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  72906. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  72907. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  72908. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  72909. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  72910. 0x2d02ef8dUL
  72911. #ifdef BYFOUR
  72912. },
  72913. {
  72914. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  72915. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  72916. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  72917. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  72918. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  72919. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  72920. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  72921. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  72922. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  72923. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  72924. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  72925. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  72926. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  72927. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  72928. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  72929. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  72930. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  72931. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  72932. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  72933. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  72934. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  72935. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  72936. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  72937. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  72938. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  72939. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  72940. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  72941. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  72942. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  72943. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  72944. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  72945. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  72946. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  72947. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  72948. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  72949. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  72950. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  72951. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  72952. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  72953. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  72954. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  72955. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  72956. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  72957. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  72958. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  72959. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  72960. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  72961. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  72962. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  72963. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  72964. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  72965. 0x9324fd72UL
  72966. },
  72967. {
  72968. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  72969. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  72970. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  72971. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  72972. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  72973. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  72974. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  72975. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  72976. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  72977. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  72978. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  72979. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  72980. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  72981. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  72982. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  72983. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  72984. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  72985. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  72986. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  72987. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  72988. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  72989. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  72990. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  72991. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  72992. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  72993. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  72994. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  72995. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  72996. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  72997. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  72998. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  72999. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  73000. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  73001. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  73002. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  73003. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  73004. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  73005. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  73006. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  73007. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  73008. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  73009. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  73010. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  73011. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  73012. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  73013. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  73014. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  73015. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  73016. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  73017. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  73018. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  73019. 0xbe9834edUL
  73020. },
  73021. {
  73022. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  73023. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  73024. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  73025. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  73026. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  73027. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  73028. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  73029. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  73030. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  73031. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  73032. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  73033. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  73034. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  73035. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  73036. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  73037. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  73038. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  73039. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  73040. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  73041. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  73042. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  73043. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  73044. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  73045. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  73046. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  73047. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  73048. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  73049. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  73050. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  73051. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  73052. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  73053. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  73054. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  73055. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  73056. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  73057. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  73058. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  73059. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  73060. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  73061. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  73062. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  73063. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  73064. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  73065. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  73066. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  73067. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  73068. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  73069. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  73070. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  73071. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  73072. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  73073. 0xde0506f1UL
  73074. },
  73075. {
  73076. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  73077. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  73078. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  73079. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  73080. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  73081. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  73082. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  73083. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  73084. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  73085. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  73086. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  73087. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  73088. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  73089. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  73090. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  73091. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  73092. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  73093. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  73094. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  73095. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  73096. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  73097. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  73098. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  73099. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  73100. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  73101. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  73102. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  73103. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  73104. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  73105. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  73106. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  73107. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  73108. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  73109. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  73110. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  73111. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  73112. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  73113. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  73114. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  73115. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  73116. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  73117. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  73118. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  73119. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  73120. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  73121. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  73122. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  73123. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  73124. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  73125. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  73126. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  73127. 0x8def022dUL
  73128. },
  73129. {
  73130. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  73131. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  73132. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  73133. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  73134. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  73135. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  73136. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  73137. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  73138. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  73139. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  73140. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  73141. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  73142. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  73143. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  73144. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  73145. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  73146. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  73147. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  73148. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  73149. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  73150. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  73151. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  73152. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  73153. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  73154. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  73155. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  73156. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  73157. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  73158. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  73159. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  73160. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  73161. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  73162. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  73163. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  73164. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  73165. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  73166. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  73167. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  73168. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  73169. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  73170. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  73171. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  73172. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  73173. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  73174. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  73175. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  73176. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  73177. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  73178. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  73179. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  73180. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  73181. 0x72fd2493UL
  73182. },
  73183. {
  73184. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  73185. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  73186. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  73187. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  73188. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  73189. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  73190. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  73191. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  73192. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  73193. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  73194. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  73195. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  73196. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  73197. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  73198. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  73199. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  73200. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  73201. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  73202. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  73203. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  73204. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  73205. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  73206. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  73207. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  73208. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  73209. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  73210. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  73211. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  73212. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  73213. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  73214. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  73215. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  73216. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  73217. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  73218. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  73219. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  73220. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  73221. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  73222. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  73223. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  73224. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  73225. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  73226. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  73227. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  73228. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  73229. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  73230. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  73231. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  73232. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  73233. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  73234. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  73235. 0xed3498beUL
  73236. },
  73237. {
  73238. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  73239. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  73240. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  73241. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  73242. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  73243. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  73244. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  73245. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  73246. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  73247. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  73248. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  73249. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  73250. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  73251. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  73252. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  73253. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  73254. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  73255. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  73256. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  73257. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  73258. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  73259. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  73260. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  73261. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  73262. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  73263. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  73264. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  73265. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  73266. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  73267. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  73268. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  73269. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  73270. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  73271. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  73272. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  73273. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  73274. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  73275. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  73276. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  73277. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  73278. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  73279. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  73280. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  73281. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  73282. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  73283. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  73284. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  73285. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  73286. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  73287. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  73288. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  73289. 0xf10605deUL
  73290. #endif
  73291. }
  73292. };
  73293. /********* End of inlined file: crc32.h *********/
  73294. #endif /* DYNAMIC_CRC_TABLE */
  73295. /* =========================================================================
  73296. * This function can be used by asm versions of crc32()
  73297. */
  73298. const unsigned long FAR * ZEXPORT get_crc_table()
  73299. {
  73300. #ifdef DYNAMIC_CRC_TABLE
  73301. if (crc_table_empty)
  73302. make_crc_table();
  73303. #endif /* DYNAMIC_CRC_TABLE */
  73304. return (const unsigned long FAR *)crc_table;
  73305. }
  73306. /* ========================================================================= */
  73307. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  73308. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  73309. /* ========================================================================= */
  73310. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73311. {
  73312. if (buf == Z_NULL) return 0UL;
  73313. #ifdef DYNAMIC_CRC_TABLE
  73314. if (crc_table_empty)
  73315. make_crc_table();
  73316. #endif /* DYNAMIC_CRC_TABLE */
  73317. #ifdef BYFOUR
  73318. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  73319. u4 endian;
  73320. endian = 1;
  73321. if (*((unsigned char *)(&endian)))
  73322. return crc32_little(crc, buf, len);
  73323. else
  73324. return crc32_big(crc, buf, len);
  73325. }
  73326. #endif /* BYFOUR */
  73327. crc = crc ^ 0xffffffffUL;
  73328. while (len >= 8) {
  73329. DO8;
  73330. len -= 8;
  73331. }
  73332. if (len) do {
  73333. DO1;
  73334. } while (--len);
  73335. return crc ^ 0xffffffffUL;
  73336. }
  73337. #ifdef BYFOUR
  73338. /* ========================================================================= */
  73339. #define DOLIT4 c ^= *buf4++; \
  73340. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  73341. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  73342. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  73343. /* ========================================================================= */
  73344. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73345. {
  73346. register u4 c;
  73347. register const u4 FAR *buf4;
  73348. c = (u4)crc;
  73349. c = ~c;
  73350. while (len && ((ptrdiff_t)buf & 3)) {
  73351. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  73352. len--;
  73353. }
  73354. buf4 = (const u4 FAR *)(const void FAR *)buf;
  73355. while (len >= 32) {
  73356. DOLIT32;
  73357. len -= 32;
  73358. }
  73359. while (len >= 4) {
  73360. DOLIT4;
  73361. len -= 4;
  73362. }
  73363. buf = (const unsigned char FAR *)buf4;
  73364. if (len) do {
  73365. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  73366. } while (--len);
  73367. c = ~c;
  73368. return (unsigned long)c;
  73369. }
  73370. /* ========================================================================= */
  73371. #define DOBIG4 c ^= *++buf4; \
  73372. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  73373. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  73374. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  73375. /* ========================================================================= */
  73376. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73377. {
  73378. register u4 c;
  73379. register const u4 FAR *buf4;
  73380. c = REV((u4)crc);
  73381. c = ~c;
  73382. while (len && ((ptrdiff_t)buf & 3)) {
  73383. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  73384. len--;
  73385. }
  73386. buf4 = (const u4 FAR *)(const void FAR *)buf;
  73387. buf4--;
  73388. while (len >= 32) {
  73389. DOBIG32;
  73390. len -= 32;
  73391. }
  73392. while (len >= 4) {
  73393. DOBIG4;
  73394. len -= 4;
  73395. }
  73396. buf4++;
  73397. buf = (const unsigned char FAR *)buf4;
  73398. if (len) do {
  73399. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  73400. } while (--len);
  73401. c = ~c;
  73402. return (unsigned long)(REV(c));
  73403. }
  73404. #endif /* BYFOUR */
  73405. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  73406. /* ========================================================================= */
  73407. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  73408. {
  73409. unsigned long sum;
  73410. sum = 0;
  73411. while (vec) {
  73412. if (vec & 1)
  73413. sum ^= *mat;
  73414. vec >>= 1;
  73415. mat++;
  73416. }
  73417. return sum;
  73418. }
  73419. /* ========================================================================= */
  73420. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  73421. {
  73422. int n;
  73423. for (n = 0; n < GF2_DIM; n++)
  73424. square[n] = gf2_matrix_times(mat, mat[n]);
  73425. }
  73426. /* ========================================================================= */
  73427. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  73428. {
  73429. int n;
  73430. unsigned long row;
  73431. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  73432. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  73433. /* degenerate case */
  73434. if (len2 == 0)
  73435. return crc1;
  73436. /* put operator for one zero bit in odd */
  73437. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  73438. row = 1;
  73439. for (n = 1; n < GF2_DIM; n++) {
  73440. odd[n] = row;
  73441. row <<= 1;
  73442. }
  73443. /* put operator for two zero bits in even */
  73444. gf2_matrix_square(even, odd);
  73445. /* put operator for four zero bits in odd */
  73446. gf2_matrix_square(odd, even);
  73447. /* apply len2 zeros to crc1 (first square will put the operator for one
  73448. zero byte, eight zero bits, in even) */
  73449. do {
  73450. /* apply zeros operator for this bit of len2 */
  73451. gf2_matrix_square(even, odd);
  73452. if (len2 & 1)
  73453. crc1 = gf2_matrix_times(even, crc1);
  73454. len2 >>= 1;
  73455. /* if no more bits set, then done */
  73456. if (len2 == 0)
  73457. break;
  73458. /* another iteration of the loop with odd and even swapped */
  73459. gf2_matrix_square(odd, even);
  73460. if (len2 & 1)
  73461. crc1 = gf2_matrix_times(odd, crc1);
  73462. len2 >>= 1;
  73463. /* if no more bits set, then done */
  73464. } while (len2 != 0);
  73465. /* return combined crc */
  73466. crc1 ^= crc2;
  73467. return crc1;
  73468. }
  73469. /********* End of inlined file: crc32.c *********/
  73470. /********* Start of inlined file: deflate.c *********/
  73471. /*
  73472. * ALGORITHM
  73473. *
  73474. * The "deflation" process depends on being able to identify portions
  73475. * of the input text which are identical to earlier input (within a
  73476. * sliding window trailing behind the input currently being processed).
  73477. *
  73478. * The most straightforward technique turns out to be the fastest for
  73479. * most input files: try all possible matches and select the longest.
  73480. * The key feature of this algorithm is that insertions into the string
  73481. * dictionary are very simple and thus fast, and deletions are avoided
  73482. * completely. Insertions are performed at each input character, whereas
  73483. * string matches are performed only when the previous match ends. So it
  73484. * is preferable to spend more time in matches to allow very fast string
  73485. * insertions and avoid deletions. The matching algorithm for small
  73486. * strings is inspired from that of Rabin & Karp. A brute force approach
  73487. * is used to find longer strings when a small match has been found.
  73488. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  73489. * (by Leonid Broukhis).
  73490. * A previous version of this file used a more sophisticated algorithm
  73491. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  73492. * time, but has a larger average cost, uses more memory and is patented.
  73493. * However the F&G algorithm may be faster for some highly redundant
  73494. * files if the parameter max_chain_length (described below) is too large.
  73495. *
  73496. * ACKNOWLEDGEMENTS
  73497. *
  73498. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  73499. * I found it in 'freeze' written by Leonid Broukhis.
  73500. * Thanks to many people for bug reports and testing.
  73501. *
  73502. * REFERENCES
  73503. *
  73504. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  73505. * Available in http://www.ietf.org/rfc/rfc1951.txt
  73506. *
  73507. * A description of the Rabin and Karp algorithm is given in the book
  73508. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  73509. *
  73510. * Fiala,E.R., and Greene,D.H.
  73511. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  73512. *
  73513. */
  73514. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73515. /********* Start of inlined file: deflate.h *********/
  73516. /* WARNING: this file should *not* be used by applications. It is
  73517. part of the implementation of the compression library and is
  73518. subject to change. Applications should only use zlib.h.
  73519. */
  73520. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73521. #ifndef DEFLATE_H
  73522. #define DEFLATE_H
  73523. /* define NO_GZIP when compiling if you want to disable gzip header and
  73524. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  73525. the crc code when it is not needed. For shared libraries, gzip encoding
  73526. should be left enabled. */
  73527. #ifndef NO_GZIP
  73528. # define GZIP
  73529. #endif
  73530. #define NO_DUMMY_DECL
  73531. /* ===========================================================================
  73532. * Internal compression state.
  73533. */
  73534. #define LENGTH_CODES 29
  73535. /* number of length codes, not counting the special END_BLOCK code */
  73536. #define LITERALS 256
  73537. /* number of literal bytes 0..255 */
  73538. #define L_CODES (LITERALS+1+LENGTH_CODES)
  73539. /* number of Literal or Length codes, including the END_BLOCK code */
  73540. #define D_CODES 30
  73541. /* number of distance codes */
  73542. #define BL_CODES 19
  73543. /* number of codes used to transfer the bit lengths */
  73544. #define HEAP_SIZE (2*L_CODES+1)
  73545. /* maximum heap size */
  73546. #define MAX_BITS 15
  73547. /* All codes must not exceed MAX_BITS bits */
  73548. #define INIT_STATE 42
  73549. #define EXTRA_STATE 69
  73550. #define NAME_STATE 73
  73551. #define COMMENT_STATE 91
  73552. #define HCRC_STATE 103
  73553. #define BUSY_STATE 113
  73554. #define FINISH_STATE 666
  73555. /* Stream status */
  73556. /* Data structure describing a single value and its code string. */
  73557. typedef struct ct_data_s {
  73558. union {
  73559. ush freq; /* frequency count */
  73560. ush code; /* bit string */
  73561. } fc;
  73562. union {
  73563. ush dad; /* father node in Huffman tree */
  73564. ush len; /* length of bit string */
  73565. } dl;
  73566. } FAR ct_data;
  73567. #define Freq fc.freq
  73568. #define Code fc.code
  73569. #define Dad dl.dad
  73570. #define Len dl.len
  73571. typedef struct static_tree_desc_s static_tree_desc;
  73572. typedef struct tree_desc_s {
  73573. ct_data *dyn_tree; /* the dynamic tree */
  73574. int max_code; /* largest code with non zero frequency */
  73575. static_tree_desc *stat_desc; /* the corresponding static tree */
  73576. } FAR tree_desc;
  73577. typedef ush Pos;
  73578. typedef Pos FAR Posf;
  73579. typedef unsigned IPos;
  73580. /* A Pos is an index in the character window. We use short instead of int to
  73581. * save space in the various tables. IPos is used only for parameter passing.
  73582. */
  73583. typedef struct internal_state {
  73584. z_streamp strm; /* pointer back to this zlib stream */
  73585. int status; /* as the name implies */
  73586. Bytef *pending_buf; /* output still pending */
  73587. ulg pending_buf_size; /* size of pending_buf */
  73588. Bytef *pending_out; /* next pending byte to output to the stream */
  73589. uInt pending; /* nb of bytes in the pending buffer */
  73590. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  73591. gz_headerp gzhead; /* gzip header information to write */
  73592. uInt gzindex; /* where in extra, name, or comment */
  73593. Byte method; /* STORED (for zip only) or DEFLATED */
  73594. int last_flush; /* value of flush param for previous deflate call */
  73595. /* used by deflate.c: */
  73596. uInt w_size; /* LZ77 window size (32K by default) */
  73597. uInt w_bits; /* log2(w_size) (8..16) */
  73598. uInt w_mask; /* w_size - 1 */
  73599. Bytef *window;
  73600. /* Sliding window. Input bytes are read into the second half of the window,
  73601. * and move to the first half later to keep a dictionary of at least wSize
  73602. * bytes. With this organization, matches are limited to a distance of
  73603. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  73604. * performed with a length multiple of the block size. Also, it limits
  73605. * the window size to 64K, which is quite useful on MSDOS.
  73606. * To do: use the user input buffer as sliding window.
  73607. */
  73608. ulg window_size;
  73609. /* Actual size of window: 2*wSize, except when the user input buffer
  73610. * is directly used as sliding window.
  73611. */
  73612. Posf *prev;
  73613. /* Link to older string with same hash index. To limit the size of this
  73614. * array to 64K, this link is maintained only for the last 32K strings.
  73615. * An index in this array is thus a window index modulo 32K.
  73616. */
  73617. Posf *head; /* Heads of the hash chains or NIL. */
  73618. uInt ins_h; /* hash index of string to be inserted */
  73619. uInt hash_size; /* number of elements in hash table */
  73620. uInt hash_bits; /* log2(hash_size) */
  73621. uInt hash_mask; /* hash_size-1 */
  73622. uInt hash_shift;
  73623. /* Number of bits by which ins_h must be shifted at each input
  73624. * step. It must be such that after MIN_MATCH steps, the oldest
  73625. * byte no longer takes part in the hash key, that is:
  73626. * hash_shift * MIN_MATCH >= hash_bits
  73627. */
  73628. long block_start;
  73629. /* Window position at the beginning of the current output block. Gets
  73630. * negative when the window is moved backwards.
  73631. */
  73632. uInt match_length; /* length of best match */
  73633. IPos prev_match; /* previous match */
  73634. int match_available; /* set if previous match exists */
  73635. uInt strstart; /* start of string to insert */
  73636. uInt match_start; /* start of matching string */
  73637. uInt lookahead; /* number of valid bytes ahead in window */
  73638. uInt prev_length;
  73639. /* Length of the best match at previous step. Matches not greater than this
  73640. * are discarded. This is used in the lazy match evaluation.
  73641. */
  73642. uInt max_chain_length;
  73643. /* To speed up deflation, hash chains are never searched beyond this
  73644. * length. A higher limit improves compression ratio but degrades the
  73645. * speed.
  73646. */
  73647. uInt max_lazy_match;
  73648. /* Attempt to find a better match only when the current match is strictly
  73649. * smaller than this value. This mechanism is used only for compression
  73650. * levels >= 4.
  73651. */
  73652. # define max_insert_length max_lazy_match
  73653. /* Insert new strings in the hash table only if the match length is not
  73654. * greater than this length. This saves time but degrades compression.
  73655. * max_insert_length is used only for compression levels <= 3.
  73656. */
  73657. int level; /* compression level (1..9) */
  73658. int strategy; /* favor or force Huffman coding*/
  73659. uInt good_match;
  73660. /* Use a faster search when the previous match is longer than this */
  73661. int nice_match; /* Stop searching when current match exceeds this */
  73662. /* used by trees.c: */
  73663. /* Didn't use ct_data typedef below to supress compiler warning */
  73664. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  73665. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  73666. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  73667. struct tree_desc_s l_desc; /* desc. for literal tree */
  73668. struct tree_desc_s d_desc; /* desc. for distance tree */
  73669. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  73670. ush bl_count[MAX_BITS+1];
  73671. /* number of codes at each bit length for an optimal tree */
  73672. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  73673. int heap_len; /* number of elements in the heap */
  73674. int heap_max; /* element of largest frequency */
  73675. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  73676. * The same heap array is used to build all trees.
  73677. */
  73678. uch depth[2*L_CODES+1];
  73679. /* Depth of each subtree used as tie breaker for trees of equal frequency
  73680. */
  73681. uchf *l_buf; /* buffer for literals or lengths */
  73682. uInt lit_bufsize;
  73683. /* Size of match buffer for literals/lengths. There are 4 reasons for
  73684. * limiting lit_bufsize to 64K:
  73685. * - frequencies can be kept in 16 bit counters
  73686. * - if compression is not successful for the first block, all input
  73687. * data is still in the window so we can still emit a stored block even
  73688. * when input comes from standard input. (This can also be done for
  73689. * all blocks if lit_bufsize is not greater than 32K.)
  73690. * - if compression is not successful for a file smaller than 64K, we can
  73691. * even emit a stored file instead of a stored block (saving 5 bytes).
  73692. * This is applicable only for zip (not gzip or zlib).
  73693. * - creating new Huffman trees less frequently may not provide fast
  73694. * adaptation to changes in the input data statistics. (Take for
  73695. * example a binary file with poorly compressible code followed by
  73696. * a highly compressible string table.) Smaller buffer sizes give
  73697. * fast adaptation but have of course the overhead of transmitting
  73698. * trees more frequently.
  73699. * - I can't count above 4
  73700. */
  73701. uInt last_lit; /* running index in l_buf */
  73702. ushf *d_buf;
  73703. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  73704. * the same number of elements. To use different lengths, an extra flag
  73705. * array would be necessary.
  73706. */
  73707. ulg opt_len; /* bit length of current block with optimal trees */
  73708. ulg static_len; /* bit length of current block with static trees */
  73709. uInt matches; /* number of string matches in current block */
  73710. int last_eob_len; /* bit length of EOB code for last block */
  73711. #ifdef DEBUG
  73712. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  73713. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  73714. #endif
  73715. ush bi_buf;
  73716. /* Output buffer. bits are inserted starting at the bottom (least
  73717. * significant bits).
  73718. */
  73719. int bi_valid;
  73720. /* Number of valid bits in bi_buf. All bits above the last valid bit
  73721. * are always zero.
  73722. */
  73723. } FAR deflate_state;
  73724. /* Output a byte on the stream.
  73725. * IN assertion: there is enough room in pending_buf.
  73726. */
  73727. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  73728. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  73729. /* Minimum amount of lookahead, except at the end of the input file.
  73730. * See deflate.c for comments about the MIN_MATCH+1.
  73731. */
  73732. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  73733. /* In order to simplify the code, particularly on 16 bit machines, match
  73734. * distances are limited to MAX_DIST instead of WSIZE.
  73735. */
  73736. /* in trees.c */
  73737. void _tr_init OF((deflate_state *s));
  73738. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  73739. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  73740. int eof));
  73741. void _tr_align OF((deflate_state *s));
  73742. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  73743. int eof));
  73744. #define d_code(dist) \
  73745. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  73746. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  73747. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  73748. * used.
  73749. */
  73750. #ifndef DEBUG
  73751. /* Inline versions of _tr_tally for speed: */
  73752. #if defined(GEN_TREES_H) || !defined(STDC)
  73753. extern uch _length_code[];
  73754. extern uch _dist_code[];
  73755. #else
  73756. extern const uch _length_code[];
  73757. extern const uch _dist_code[];
  73758. #endif
  73759. # define _tr_tally_lit(s, c, flush) \
  73760. { uch cc = (c); \
  73761. s->d_buf[s->last_lit] = 0; \
  73762. s->l_buf[s->last_lit++] = cc; \
  73763. s->dyn_ltree[cc].Freq++; \
  73764. flush = (s->last_lit == s->lit_bufsize-1); \
  73765. }
  73766. # define _tr_tally_dist(s, distance, length, flush) \
  73767. { uch len = (length); \
  73768. ush dist = (distance); \
  73769. s->d_buf[s->last_lit] = dist; \
  73770. s->l_buf[s->last_lit++] = len; \
  73771. dist--; \
  73772. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  73773. s->dyn_dtree[d_code(dist)].Freq++; \
  73774. flush = (s->last_lit == s->lit_bufsize-1); \
  73775. }
  73776. #else
  73777. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  73778. # define _tr_tally_dist(s, distance, length, flush) \
  73779. flush = _tr_tally(s, distance, length)
  73780. #endif
  73781. #endif /* DEFLATE_H */
  73782. /********* End of inlined file: deflate.h *********/
  73783. const char deflate_copyright[] =
  73784. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  73785. /*
  73786. If you use the zlib library in a product, an acknowledgment is welcome
  73787. in the documentation of your product. If for some reason you cannot
  73788. include such an acknowledgment, I would appreciate that you keep this
  73789. copyright string in the executable of your product.
  73790. */
  73791. /* ===========================================================================
  73792. * Function prototypes.
  73793. */
  73794. typedef enum {
  73795. need_more, /* block not completed, need more input or more output */
  73796. block_done, /* block flush performed */
  73797. finish_started, /* finish started, need only more output at next deflate */
  73798. finish_done /* finish done, accept no more input or output */
  73799. } block_state;
  73800. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  73801. /* Compression function. Returns the block state after the call. */
  73802. local void fill_window OF((deflate_state *s));
  73803. local block_state deflate_stored OF((deflate_state *s, int flush));
  73804. local block_state deflate_fast OF((deflate_state *s, int flush));
  73805. #ifndef FASTEST
  73806. local block_state deflate_slow OF((deflate_state *s, int flush));
  73807. #endif
  73808. local void lm_init OF((deflate_state *s));
  73809. local void putShortMSB OF((deflate_state *s, uInt b));
  73810. local void flush_pending OF((z_streamp strm));
  73811. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  73812. #ifndef FASTEST
  73813. #ifdef ASMV
  73814. void match_init OF((void)); /* asm code initialization */
  73815. uInt longest_match OF((deflate_state *s, IPos cur_match));
  73816. #else
  73817. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  73818. #endif
  73819. #endif
  73820. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  73821. #ifdef DEBUG
  73822. local void check_match OF((deflate_state *s, IPos start, IPos match,
  73823. int length));
  73824. #endif
  73825. /* ===========================================================================
  73826. * Local data
  73827. */
  73828. #define NIL 0
  73829. /* Tail of hash chains */
  73830. #ifndef TOO_FAR
  73831. # define TOO_FAR 4096
  73832. #endif
  73833. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  73834. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  73835. /* Minimum amount of lookahead, except at the end of the input file.
  73836. * See deflate.c for comments about the MIN_MATCH+1.
  73837. */
  73838. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  73839. * the desired pack level (0..9). The values given below have been tuned to
  73840. * exclude worst case performance for pathological files. Better values may be
  73841. * found for specific files.
  73842. */
  73843. typedef struct config_s {
  73844. ush good_length; /* reduce lazy search above this match length */
  73845. ush max_lazy; /* do not perform lazy search above this match length */
  73846. ush nice_length; /* quit search above this match length */
  73847. ush max_chain;
  73848. compress_func func;
  73849. } config;
  73850. #ifdef FASTEST
  73851. local const config configuration_table[2] = {
  73852. /* good lazy nice chain */
  73853. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  73854. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  73855. #else
  73856. local const config configuration_table[10] = {
  73857. /* good lazy nice chain */
  73858. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  73859. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  73860. /* 2 */ {4, 5, 16, 8, deflate_fast},
  73861. /* 3 */ {4, 6, 32, 32, deflate_fast},
  73862. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  73863. /* 5 */ {8, 16, 32, 32, deflate_slow},
  73864. /* 6 */ {8, 16, 128, 128, deflate_slow},
  73865. /* 7 */ {8, 32, 128, 256, deflate_slow},
  73866. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  73867. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  73868. #endif
  73869. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  73870. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  73871. * meaning.
  73872. */
  73873. #define EQUAL 0
  73874. /* result of memcmp for equal strings */
  73875. #ifndef NO_DUMMY_DECL
  73876. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  73877. #endif
  73878. /* ===========================================================================
  73879. * Update a hash value with the given input byte
  73880. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  73881. * input characters, so that a running hash key can be computed from the
  73882. * previous key instead of complete recalculation each time.
  73883. */
  73884. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  73885. /* ===========================================================================
  73886. * Insert string str in the dictionary and set match_head to the previous head
  73887. * of the hash chain (the most recent string with same hash key). Return
  73888. * the previous length of the hash chain.
  73889. * If this file is compiled with -DFASTEST, the compression level is forced
  73890. * to 1, and no hash chains are maintained.
  73891. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  73892. * input characters and the first MIN_MATCH bytes of str are valid
  73893. * (except for the last MIN_MATCH-1 bytes of the input file).
  73894. */
  73895. #ifdef FASTEST
  73896. #define INSERT_STRING(s, str, match_head) \
  73897. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  73898. match_head = s->head[s->ins_h], \
  73899. s->head[s->ins_h] = (Pos)(str))
  73900. #else
  73901. #define INSERT_STRING(s, str, match_head) \
  73902. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  73903. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  73904. s->head[s->ins_h] = (Pos)(str))
  73905. #endif
  73906. /* ===========================================================================
  73907. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  73908. * prev[] will be initialized on the fly.
  73909. */
  73910. #define CLEAR_HASH(s) \
  73911. s->head[s->hash_size-1] = NIL; \
  73912. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  73913. /* ========================================================================= */
  73914. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  73915. {
  73916. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  73917. Z_DEFAULT_STRATEGY, version, stream_size);
  73918. /* To do: ignore strm->next_in if we use it as window */
  73919. }
  73920. /* ========================================================================= */
  73921. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  73922. {
  73923. deflate_state *s;
  73924. int wrap = 1;
  73925. static const char my_version[] = ZLIB_VERSION;
  73926. ushf *overlay;
  73927. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  73928. * output size for (length,distance) codes is <= 24 bits.
  73929. */
  73930. if (version == Z_NULL || version[0] != my_version[0] ||
  73931. stream_size != sizeof(z_stream)) {
  73932. return Z_VERSION_ERROR;
  73933. }
  73934. if (strm == Z_NULL) return Z_STREAM_ERROR;
  73935. strm->msg = Z_NULL;
  73936. if (strm->zalloc == (alloc_func)0) {
  73937. strm->zalloc = zcalloc;
  73938. strm->opaque = (voidpf)0;
  73939. }
  73940. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  73941. #ifdef FASTEST
  73942. if (level != 0) level = 1;
  73943. #else
  73944. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  73945. #endif
  73946. if (windowBits < 0) { /* suppress zlib wrapper */
  73947. wrap = 0;
  73948. windowBits = -windowBits;
  73949. }
  73950. #ifdef GZIP
  73951. else if (windowBits > 15) {
  73952. wrap = 2; /* write gzip wrapper instead */
  73953. windowBits -= 16;
  73954. }
  73955. #endif
  73956. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  73957. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  73958. strategy < 0 || strategy > Z_FIXED) {
  73959. return Z_STREAM_ERROR;
  73960. }
  73961. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  73962. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  73963. if (s == Z_NULL) return Z_MEM_ERROR;
  73964. strm->state = (struct internal_state FAR *)s;
  73965. s->strm = strm;
  73966. s->wrap = wrap;
  73967. s->gzhead = Z_NULL;
  73968. s->w_bits = windowBits;
  73969. s->w_size = 1 << s->w_bits;
  73970. s->w_mask = s->w_size - 1;
  73971. s->hash_bits = memLevel + 7;
  73972. s->hash_size = 1 << s->hash_bits;
  73973. s->hash_mask = s->hash_size - 1;
  73974. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  73975. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  73976. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  73977. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  73978. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  73979. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  73980. s->pending_buf = (uchf *) overlay;
  73981. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  73982. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  73983. s->pending_buf == Z_NULL) {
  73984. s->status = FINISH_STATE;
  73985. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  73986. deflateEnd (strm);
  73987. return Z_MEM_ERROR;
  73988. }
  73989. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  73990. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  73991. s->level = level;
  73992. s->strategy = strategy;
  73993. s->method = (Byte)method;
  73994. return deflateReset(strm);
  73995. }
  73996. /* ========================================================================= */
  73997. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  73998. {
  73999. deflate_state *s;
  74000. uInt length = dictLength;
  74001. uInt n;
  74002. IPos hash_head = 0;
  74003. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  74004. strm->state->wrap == 2 ||
  74005. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  74006. return Z_STREAM_ERROR;
  74007. s = strm->state;
  74008. if (s->wrap)
  74009. strm->adler = adler32(strm->adler, dictionary, dictLength);
  74010. if (length < MIN_MATCH) return Z_OK;
  74011. if (length > MAX_DIST(s)) {
  74012. length = MAX_DIST(s);
  74013. dictionary += dictLength - length; /* use the tail of the dictionary */
  74014. }
  74015. zmemcpy(s->window, dictionary, length);
  74016. s->strstart = length;
  74017. s->block_start = (long)length;
  74018. /* Insert all strings in the hash table (except for the last two bytes).
  74019. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  74020. * call of fill_window.
  74021. */
  74022. s->ins_h = s->window[0];
  74023. UPDATE_HASH(s, s->ins_h, s->window[1]);
  74024. for (n = 0; n <= length - MIN_MATCH; n++) {
  74025. INSERT_STRING(s, n, hash_head);
  74026. }
  74027. if (hash_head) hash_head = 0; /* to make compiler happy */
  74028. return Z_OK;
  74029. }
  74030. /* ========================================================================= */
  74031. int ZEXPORT deflateReset (z_streamp strm)
  74032. {
  74033. deflate_state *s;
  74034. if (strm == Z_NULL || strm->state == Z_NULL ||
  74035. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  74036. return Z_STREAM_ERROR;
  74037. }
  74038. strm->total_in = strm->total_out = 0;
  74039. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  74040. strm->data_type = Z_UNKNOWN;
  74041. s = (deflate_state *)strm->state;
  74042. s->pending = 0;
  74043. s->pending_out = s->pending_buf;
  74044. if (s->wrap < 0) {
  74045. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  74046. }
  74047. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  74048. strm->adler =
  74049. #ifdef GZIP
  74050. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  74051. #endif
  74052. adler32(0L, Z_NULL, 0);
  74053. s->last_flush = Z_NO_FLUSH;
  74054. _tr_init(s);
  74055. lm_init(s);
  74056. return Z_OK;
  74057. }
  74058. /* ========================================================================= */
  74059. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  74060. {
  74061. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74062. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  74063. strm->state->gzhead = head;
  74064. return Z_OK;
  74065. }
  74066. /* ========================================================================= */
  74067. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  74068. {
  74069. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74070. strm->state->bi_valid = bits;
  74071. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  74072. return Z_OK;
  74073. }
  74074. /* ========================================================================= */
  74075. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  74076. {
  74077. deflate_state *s;
  74078. compress_func func;
  74079. int err = Z_OK;
  74080. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74081. s = strm->state;
  74082. #ifdef FASTEST
  74083. if (level != 0) level = 1;
  74084. #else
  74085. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74086. #endif
  74087. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  74088. return Z_STREAM_ERROR;
  74089. }
  74090. func = configuration_table[s->level].func;
  74091. if (func != configuration_table[level].func && strm->total_in != 0) {
  74092. /* Flush the last buffer: */
  74093. err = deflate(strm, Z_PARTIAL_FLUSH);
  74094. }
  74095. if (s->level != level) {
  74096. s->level = level;
  74097. s->max_lazy_match = configuration_table[level].max_lazy;
  74098. s->good_match = configuration_table[level].good_length;
  74099. s->nice_match = configuration_table[level].nice_length;
  74100. s->max_chain_length = configuration_table[level].max_chain;
  74101. }
  74102. s->strategy = strategy;
  74103. return err;
  74104. }
  74105. /* ========================================================================= */
  74106. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  74107. {
  74108. deflate_state *s;
  74109. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74110. s = strm->state;
  74111. s->good_match = good_length;
  74112. s->max_lazy_match = max_lazy;
  74113. s->nice_match = nice_length;
  74114. s->max_chain_length = max_chain;
  74115. return Z_OK;
  74116. }
  74117. /* =========================================================================
  74118. * For the default windowBits of 15 and memLevel of 8, this function returns
  74119. * a close to exact, as well as small, upper bound on the compressed size.
  74120. * They are coded as constants here for a reason--if the #define's are
  74121. * changed, then this function needs to be changed as well. The return
  74122. * value for 15 and 8 only works for those exact settings.
  74123. *
  74124. * For any setting other than those defaults for windowBits and memLevel,
  74125. * the value returned is a conservative worst case for the maximum expansion
  74126. * resulting from using fixed blocks instead of stored blocks, which deflate
  74127. * can emit on compressed data for some combinations of the parameters.
  74128. *
  74129. * This function could be more sophisticated to provide closer upper bounds
  74130. * for every combination of windowBits and memLevel, as well as wrap.
  74131. * But even the conservative upper bound of about 14% expansion does not
  74132. * seem onerous for output buffer allocation.
  74133. */
  74134. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  74135. {
  74136. deflate_state *s;
  74137. uLong destLen;
  74138. /* conservative upper bound */
  74139. destLen = sourceLen +
  74140. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  74141. /* if can't get parameters, return conservative bound */
  74142. if (strm == Z_NULL || strm->state == Z_NULL)
  74143. return destLen;
  74144. /* if not default parameters, return conservative bound */
  74145. s = strm->state;
  74146. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  74147. return destLen;
  74148. /* default settings: return tight bound for that case */
  74149. return compressBound(sourceLen);
  74150. }
  74151. /* =========================================================================
  74152. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  74153. * IN assertion: the stream state is correct and there is enough room in
  74154. * pending_buf.
  74155. */
  74156. local void putShortMSB (deflate_state *s, uInt b)
  74157. {
  74158. put_byte(s, (Byte)(b >> 8));
  74159. put_byte(s, (Byte)(b & 0xff));
  74160. }
  74161. /* =========================================================================
  74162. * Flush as much pending output as possible. All deflate() output goes
  74163. * through this function so some applications may wish to modify it
  74164. * to avoid allocating a large strm->next_out buffer and copying into it.
  74165. * (See also read_buf()).
  74166. */
  74167. local void flush_pending (z_streamp strm)
  74168. {
  74169. unsigned len = strm->state->pending;
  74170. if (len > strm->avail_out) len = strm->avail_out;
  74171. if (len == 0) return;
  74172. zmemcpy(strm->next_out, strm->state->pending_out, len);
  74173. strm->next_out += len;
  74174. strm->state->pending_out += len;
  74175. strm->total_out += len;
  74176. strm->avail_out -= len;
  74177. strm->state->pending -= len;
  74178. if (strm->state->pending == 0) {
  74179. strm->state->pending_out = strm->state->pending_buf;
  74180. }
  74181. }
  74182. /* ========================================================================= */
  74183. int ZEXPORT deflate (z_streamp strm, int flush)
  74184. {
  74185. int old_flush; /* value of flush param for previous deflate call */
  74186. deflate_state *s;
  74187. if (strm == Z_NULL || strm->state == Z_NULL ||
  74188. flush > Z_FINISH || flush < 0) {
  74189. return Z_STREAM_ERROR;
  74190. }
  74191. s = strm->state;
  74192. if (strm->next_out == Z_NULL ||
  74193. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  74194. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  74195. ERR_RETURN(strm, Z_STREAM_ERROR);
  74196. }
  74197. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  74198. s->strm = strm; /* just in case */
  74199. old_flush = s->last_flush;
  74200. s->last_flush = flush;
  74201. /* Write the header */
  74202. if (s->status == INIT_STATE) {
  74203. #ifdef GZIP
  74204. if (s->wrap == 2) {
  74205. strm->adler = crc32(0L, Z_NULL, 0);
  74206. put_byte(s, 31);
  74207. put_byte(s, 139);
  74208. put_byte(s, 8);
  74209. if (s->gzhead == NULL) {
  74210. put_byte(s, 0);
  74211. put_byte(s, 0);
  74212. put_byte(s, 0);
  74213. put_byte(s, 0);
  74214. put_byte(s, 0);
  74215. put_byte(s, s->level == 9 ? 2 :
  74216. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74217. 4 : 0));
  74218. put_byte(s, OS_CODE);
  74219. s->status = BUSY_STATE;
  74220. }
  74221. else {
  74222. put_byte(s, (s->gzhead->text ? 1 : 0) +
  74223. (s->gzhead->hcrc ? 2 : 0) +
  74224. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  74225. (s->gzhead->name == Z_NULL ? 0 : 8) +
  74226. (s->gzhead->comment == Z_NULL ? 0 : 16)
  74227. );
  74228. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  74229. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  74230. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  74231. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  74232. put_byte(s, s->level == 9 ? 2 :
  74233. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74234. 4 : 0));
  74235. put_byte(s, s->gzhead->os & 0xff);
  74236. if (s->gzhead->extra != NULL) {
  74237. put_byte(s, s->gzhead->extra_len & 0xff);
  74238. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  74239. }
  74240. if (s->gzhead->hcrc)
  74241. strm->adler = crc32(strm->adler, s->pending_buf,
  74242. s->pending);
  74243. s->gzindex = 0;
  74244. s->status = EXTRA_STATE;
  74245. }
  74246. }
  74247. else
  74248. #endif
  74249. {
  74250. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  74251. uInt level_flags;
  74252. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  74253. level_flags = 0;
  74254. else if (s->level < 6)
  74255. level_flags = 1;
  74256. else if (s->level == 6)
  74257. level_flags = 2;
  74258. else
  74259. level_flags = 3;
  74260. header |= (level_flags << 6);
  74261. if (s->strstart != 0) header |= PRESET_DICT;
  74262. header += 31 - (header % 31);
  74263. s->status = BUSY_STATE;
  74264. putShortMSB(s, header);
  74265. /* Save the adler32 of the preset dictionary: */
  74266. if (s->strstart != 0) {
  74267. putShortMSB(s, (uInt)(strm->adler >> 16));
  74268. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74269. }
  74270. strm->adler = adler32(0L, Z_NULL, 0);
  74271. }
  74272. }
  74273. #ifdef GZIP
  74274. if (s->status == EXTRA_STATE) {
  74275. if (s->gzhead->extra != NULL) {
  74276. uInt beg = s->pending; /* start of bytes to update crc */
  74277. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  74278. if (s->pending == s->pending_buf_size) {
  74279. if (s->gzhead->hcrc && s->pending > beg)
  74280. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74281. s->pending - beg);
  74282. flush_pending(strm);
  74283. beg = s->pending;
  74284. if (s->pending == s->pending_buf_size)
  74285. break;
  74286. }
  74287. put_byte(s, s->gzhead->extra[s->gzindex]);
  74288. s->gzindex++;
  74289. }
  74290. if (s->gzhead->hcrc && s->pending > beg)
  74291. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74292. s->pending - beg);
  74293. if (s->gzindex == s->gzhead->extra_len) {
  74294. s->gzindex = 0;
  74295. s->status = NAME_STATE;
  74296. }
  74297. }
  74298. else
  74299. s->status = NAME_STATE;
  74300. }
  74301. if (s->status == NAME_STATE) {
  74302. if (s->gzhead->name != NULL) {
  74303. uInt beg = s->pending; /* start of bytes to update crc */
  74304. int val;
  74305. do {
  74306. if (s->pending == s->pending_buf_size) {
  74307. if (s->gzhead->hcrc && s->pending > beg)
  74308. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74309. s->pending - beg);
  74310. flush_pending(strm);
  74311. beg = s->pending;
  74312. if (s->pending == s->pending_buf_size) {
  74313. val = 1;
  74314. break;
  74315. }
  74316. }
  74317. val = s->gzhead->name[s->gzindex++];
  74318. put_byte(s, val);
  74319. } while (val != 0);
  74320. if (s->gzhead->hcrc && s->pending > beg)
  74321. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74322. s->pending - beg);
  74323. if (val == 0) {
  74324. s->gzindex = 0;
  74325. s->status = COMMENT_STATE;
  74326. }
  74327. }
  74328. else
  74329. s->status = COMMENT_STATE;
  74330. }
  74331. if (s->status == COMMENT_STATE) {
  74332. if (s->gzhead->comment != NULL) {
  74333. uInt beg = s->pending; /* start of bytes to update crc */
  74334. int val;
  74335. do {
  74336. if (s->pending == s->pending_buf_size) {
  74337. if (s->gzhead->hcrc && s->pending > beg)
  74338. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74339. s->pending - beg);
  74340. flush_pending(strm);
  74341. beg = s->pending;
  74342. if (s->pending == s->pending_buf_size) {
  74343. val = 1;
  74344. break;
  74345. }
  74346. }
  74347. val = s->gzhead->comment[s->gzindex++];
  74348. put_byte(s, val);
  74349. } while (val != 0);
  74350. if (s->gzhead->hcrc && s->pending > beg)
  74351. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74352. s->pending - beg);
  74353. if (val == 0)
  74354. s->status = HCRC_STATE;
  74355. }
  74356. else
  74357. s->status = HCRC_STATE;
  74358. }
  74359. if (s->status == HCRC_STATE) {
  74360. if (s->gzhead->hcrc) {
  74361. if (s->pending + 2 > s->pending_buf_size)
  74362. flush_pending(strm);
  74363. if (s->pending + 2 <= s->pending_buf_size) {
  74364. put_byte(s, (Byte)(strm->adler & 0xff));
  74365. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  74366. strm->adler = crc32(0L, Z_NULL, 0);
  74367. s->status = BUSY_STATE;
  74368. }
  74369. }
  74370. else
  74371. s->status = BUSY_STATE;
  74372. }
  74373. #endif
  74374. /* Flush as much pending output as possible */
  74375. if (s->pending != 0) {
  74376. flush_pending(strm);
  74377. if (strm->avail_out == 0) {
  74378. /* Since avail_out is 0, deflate will be called again with
  74379. * more output space, but possibly with both pending and
  74380. * avail_in equal to zero. There won't be anything to do,
  74381. * but this is not an error situation so make sure we
  74382. * return OK instead of BUF_ERROR at next call of deflate:
  74383. */
  74384. s->last_flush = -1;
  74385. return Z_OK;
  74386. }
  74387. /* Make sure there is something to do and avoid duplicate consecutive
  74388. * flushes. For repeated and useless calls with Z_FINISH, we keep
  74389. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  74390. */
  74391. } else if (strm->avail_in == 0 && flush <= old_flush &&
  74392. flush != Z_FINISH) {
  74393. ERR_RETURN(strm, Z_BUF_ERROR);
  74394. }
  74395. /* User must not provide more input after the first FINISH: */
  74396. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  74397. ERR_RETURN(strm, Z_BUF_ERROR);
  74398. }
  74399. /* Start a new block or continue the current one.
  74400. */
  74401. if (strm->avail_in != 0 || s->lookahead != 0 ||
  74402. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  74403. block_state bstate;
  74404. bstate = (*(configuration_table[s->level].func))(s, flush);
  74405. if (bstate == finish_started || bstate == finish_done) {
  74406. s->status = FINISH_STATE;
  74407. }
  74408. if (bstate == need_more || bstate == finish_started) {
  74409. if (strm->avail_out == 0) {
  74410. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  74411. }
  74412. return Z_OK;
  74413. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  74414. * of deflate should use the same flush parameter to make sure
  74415. * that the flush is complete. So we don't have to output an
  74416. * empty block here, this will be done at next call. This also
  74417. * ensures that for a very small output buffer, we emit at most
  74418. * one empty block.
  74419. */
  74420. }
  74421. if (bstate == block_done) {
  74422. if (flush == Z_PARTIAL_FLUSH) {
  74423. _tr_align(s);
  74424. } else { /* FULL_FLUSH or SYNC_FLUSH */
  74425. _tr_stored_block(s, (char*)0, 0L, 0);
  74426. /* For a full flush, this empty block will be recognized
  74427. * as a special marker by inflate_sync().
  74428. */
  74429. if (flush == Z_FULL_FLUSH) {
  74430. CLEAR_HASH(s); /* forget history */
  74431. }
  74432. }
  74433. flush_pending(strm);
  74434. if (strm->avail_out == 0) {
  74435. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  74436. return Z_OK;
  74437. }
  74438. }
  74439. }
  74440. Assert(strm->avail_out > 0, "bug2");
  74441. if (flush != Z_FINISH) return Z_OK;
  74442. if (s->wrap <= 0) return Z_STREAM_END;
  74443. /* Write the trailer */
  74444. #ifdef GZIP
  74445. if (s->wrap == 2) {
  74446. put_byte(s, (Byte)(strm->adler & 0xff));
  74447. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  74448. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  74449. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  74450. put_byte(s, (Byte)(strm->total_in & 0xff));
  74451. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  74452. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  74453. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  74454. }
  74455. else
  74456. #endif
  74457. {
  74458. putShortMSB(s, (uInt)(strm->adler >> 16));
  74459. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74460. }
  74461. flush_pending(strm);
  74462. /* If avail_out is zero, the application will call deflate again
  74463. * to flush the rest.
  74464. */
  74465. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  74466. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  74467. }
  74468. /* ========================================================================= */
  74469. int ZEXPORT deflateEnd (z_streamp strm)
  74470. {
  74471. int status;
  74472. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74473. status = strm->state->status;
  74474. if (status != INIT_STATE &&
  74475. status != EXTRA_STATE &&
  74476. status != NAME_STATE &&
  74477. status != COMMENT_STATE &&
  74478. status != HCRC_STATE &&
  74479. status != BUSY_STATE &&
  74480. status != FINISH_STATE) {
  74481. return Z_STREAM_ERROR;
  74482. }
  74483. /* Deallocate in reverse order of allocations: */
  74484. TRY_FREE(strm, strm->state->pending_buf);
  74485. TRY_FREE(strm, strm->state->head);
  74486. TRY_FREE(strm, strm->state->prev);
  74487. TRY_FREE(strm, strm->state->window);
  74488. ZFREE(strm, strm->state);
  74489. strm->state = Z_NULL;
  74490. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  74491. }
  74492. /* =========================================================================
  74493. * Copy the source state to the destination state.
  74494. * To simplify the source, this is not supported for 16-bit MSDOS (which
  74495. * doesn't have enough memory anyway to duplicate compression states).
  74496. */
  74497. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  74498. {
  74499. #ifdef MAXSEG_64K
  74500. return Z_STREAM_ERROR;
  74501. #else
  74502. deflate_state *ds;
  74503. deflate_state *ss;
  74504. ushf *overlay;
  74505. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  74506. return Z_STREAM_ERROR;
  74507. }
  74508. ss = source->state;
  74509. zmemcpy(dest, source, sizeof(z_stream));
  74510. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  74511. if (ds == Z_NULL) return Z_MEM_ERROR;
  74512. dest->state = (struct internal_state FAR *) ds;
  74513. zmemcpy(ds, ss, sizeof(deflate_state));
  74514. ds->strm = dest;
  74515. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  74516. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  74517. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  74518. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  74519. ds->pending_buf = (uchf *) overlay;
  74520. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  74521. ds->pending_buf == Z_NULL) {
  74522. deflateEnd (dest);
  74523. return Z_MEM_ERROR;
  74524. }
  74525. /* following zmemcpy do not work for 16-bit MSDOS */
  74526. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  74527. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  74528. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  74529. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  74530. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  74531. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  74532. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  74533. ds->l_desc.dyn_tree = ds->dyn_ltree;
  74534. ds->d_desc.dyn_tree = ds->dyn_dtree;
  74535. ds->bl_desc.dyn_tree = ds->bl_tree;
  74536. return Z_OK;
  74537. #endif /* MAXSEG_64K */
  74538. }
  74539. /* ===========================================================================
  74540. * Read a new buffer from the current input stream, update the adler32
  74541. * and total number of bytes read. All deflate() input goes through
  74542. * this function so some applications may wish to modify it to avoid
  74543. * allocating a large strm->next_in buffer and copying from it.
  74544. * (See also flush_pending()).
  74545. */
  74546. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  74547. {
  74548. unsigned len = strm->avail_in;
  74549. if (len > size) len = size;
  74550. if (len == 0) return 0;
  74551. strm->avail_in -= len;
  74552. if (strm->state->wrap == 1) {
  74553. strm->adler = adler32(strm->adler, strm->next_in, len);
  74554. }
  74555. #ifdef GZIP
  74556. else if (strm->state->wrap == 2) {
  74557. strm->adler = crc32(strm->adler, strm->next_in, len);
  74558. }
  74559. #endif
  74560. zmemcpy(buf, strm->next_in, len);
  74561. strm->next_in += len;
  74562. strm->total_in += len;
  74563. return (int)len;
  74564. }
  74565. /* ===========================================================================
  74566. * Initialize the "longest match" routines for a new zlib stream
  74567. */
  74568. local void lm_init (deflate_state *s)
  74569. {
  74570. s->window_size = (ulg)2L*s->w_size;
  74571. CLEAR_HASH(s);
  74572. /* Set the default configuration parameters:
  74573. */
  74574. s->max_lazy_match = configuration_table[s->level].max_lazy;
  74575. s->good_match = configuration_table[s->level].good_length;
  74576. s->nice_match = configuration_table[s->level].nice_length;
  74577. s->max_chain_length = configuration_table[s->level].max_chain;
  74578. s->strstart = 0;
  74579. s->block_start = 0L;
  74580. s->lookahead = 0;
  74581. s->match_length = s->prev_length = MIN_MATCH-1;
  74582. s->match_available = 0;
  74583. s->ins_h = 0;
  74584. #ifndef FASTEST
  74585. #ifdef ASMV
  74586. match_init(); /* initialize the asm code */
  74587. #endif
  74588. #endif
  74589. }
  74590. #ifndef FASTEST
  74591. /* ===========================================================================
  74592. * Set match_start to the longest match starting at the given string and
  74593. * return its length. Matches shorter or equal to prev_length are discarded,
  74594. * in which case the result is equal to prev_length and match_start is
  74595. * garbage.
  74596. * IN assertions: cur_match is the head of the hash chain for the current
  74597. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  74598. * OUT assertion: the match length is not greater than s->lookahead.
  74599. */
  74600. #ifndef ASMV
  74601. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  74602. * match.S. The code will be functionally equivalent.
  74603. */
  74604. local uInt longest_match(deflate_state *s, IPos cur_match)
  74605. {
  74606. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  74607. register Bytef *scan = s->window + s->strstart; /* current string */
  74608. register Bytef *match; /* matched string */
  74609. register int len; /* length of current match */
  74610. int best_len = s->prev_length; /* best match length so far */
  74611. int nice_match = s->nice_match; /* stop if match long enough */
  74612. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  74613. s->strstart - (IPos)MAX_DIST(s) : NIL;
  74614. /* Stop when cur_match becomes <= limit. To simplify the code,
  74615. * we prevent matches with the string of window index 0.
  74616. */
  74617. Posf *prev = s->prev;
  74618. uInt wmask = s->w_mask;
  74619. #ifdef UNALIGNED_OK
  74620. /* Compare two bytes at a time. Note: this is not always beneficial.
  74621. * Try with and without -DUNALIGNED_OK to check.
  74622. */
  74623. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  74624. register ush scan_start = *(ushf*)scan;
  74625. register ush scan_end = *(ushf*)(scan+best_len-1);
  74626. #else
  74627. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  74628. register Byte scan_end1 = scan[best_len-1];
  74629. register Byte scan_end = scan[best_len];
  74630. #endif
  74631. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  74632. * It is easy to get rid of this optimization if necessary.
  74633. */
  74634. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  74635. /* Do not waste too much time if we already have a good match: */
  74636. if (s->prev_length >= s->good_match) {
  74637. chain_length >>= 2;
  74638. }
  74639. /* Do not look for matches beyond the end of the input. This is necessary
  74640. * to make deflate deterministic.
  74641. */
  74642. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  74643. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  74644. do {
  74645. Assert(cur_match < s->strstart, "no future");
  74646. match = s->window + cur_match;
  74647. /* Skip to next match if the match length cannot increase
  74648. * or if the match length is less than 2. Note that the checks below
  74649. * for insufficient lookahead only occur occasionally for performance
  74650. * reasons. Therefore uninitialized memory will be accessed, and
  74651. * conditional jumps will be made that depend on those values.
  74652. * However the length of the match is limited to the lookahead, so
  74653. * the output of deflate is not affected by the uninitialized values.
  74654. */
  74655. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  74656. /* This code assumes sizeof(unsigned short) == 2. Do not use
  74657. * UNALIGNED_OK if your compiler uses a different size.
  74658. */
  74659. if (*(ushf*)(match+best_len-1) != scan_end ||
  74660. *(ushf*)match != scan_start) continue;
  74661. /* It is not necessary to compare scan[2] and match[2] since they are
  74662. * always equal when the other bytes match, given that the hash keys
  74663. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  74664. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  74665. * lookahead only every 4th comparison; the 128th check will be made
  74666. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  74667. * necessary to put more guard bytes at the end of the window, or
  74668. * to check more often for insufficient lookahead.
  74669. */
  74670. Assert(scan[2] == match[2], "scan[2]?");
  74671. scan++, match++;
  74672. do {
  74673. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74674. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74675. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74676. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74677. scan < strend);
  74678. /* The funny "do {}" generates better code on most compilers */
  74679. /* Here, scan <= window+strstart+257 */
  74680. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74681. if (*scan == *match) scan++;
  74682. len = (MAX_MATCH - 1) - (int)(strend-scan);
  74683. scan = strend - (MAX_MATCH-1);
  74684. #else /* UNALIGNED_OK */
  74685. if (match[best_len] != scan_end ||
  74686. match[best_len-1] != scan_end1 ||
  74687. *match != *scan ||
  74688. *++match != scan[1]) continue;
  74689. /* The check at best_len-1 can be removed because it will be made
  74690. * again later. (This heuristic is not always a win.)
  74691. * It is not necessary to compare scan[2] and match[2] since they
  74692. * are always equal when the other bytes match, given that
  74693. * the hash keys are equal and that HASH_BITS >= 8.
  74694. */
  74695. scan += 2, match++;
  74696. Assert(*scan == *match, "match[2]?");
  74697. /* We check for insufficient lookahead only every 8th comparison;
  74698. * the 256th check will be made at strstart+258.
  74699. */
  74700. do {
  74701. } while (*++scan == *++match && *++scan == *++match &&
  74702. *++scan == *++match && *++scan == *++match &&
  74703. *++scan == *++match && *++scan == *++match &&
  74704. *++scan == *++match && *++scan == *++match &&
  74705. scan < strend);
  74706. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74707. len = MAX_MATCH - (int)(strend - scan);
  74708. scan = strend - MAX_MATCH;
  74709. #endif /* UNALIGNED_OK */
  74710. if (len > best_len) {
  74711. s->match_start = cur_match;
  74712. best_len = len;
  74713. if (len >= nice_match) break;
  74714. #ifdef UNALIGNED_OK
  74715. scan_end = *(ushf*)(scan+best_len-1);
  74716. #else
  74717. scan_end1 = scan[best_len-1];
  74718. scan_end = scan[best_len];
  74719. #endif
  74720. }
  74721. } while ((cur_match = prev[cur_match & wmask]) > limit
  74722. && --chain_length != 0);
  74723. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  74724. return s->lookahead;
  74725. }
  74726. #endif /* ASMV */
  74727. #endif /* FASTEST */
  74728. /* ---------------------------------------------------------------------------
  74729. * Optimized version for level == 1 or strategy == Z_RLE only
  74730. */
  74731. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  74732. {
  74733. register Bytef *scan = s->window + s->strstart; /* current string */
  74734. register Bytef *match; /* matched string */
  74735. register int len; /* length of current match */
  74736. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  74737. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  74738. * It is easy to get rid of this optimization if necessary.
  74739. */
  74740. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  74741. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  74742. Assert(cur_match < s->strstart, "no future");
  74743. match = s->window + cur_match;
  74744. /* Return failure if the match length is less than 2:
  74745. */
  74746. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  74747. /* The check at best_len-1 can be removed because it will be made
  74748. * again later. (This heuristic is not always a win.)
  74749. * It is not necessary to compare scan[2] and match[2] since they
  74750. * are always equal when the other bytes match, given that
  74751. * the hash keys are equal and that HASH_BITS >= 8.
  74752. */
  74753. scan += 2, match += 2;
  74754. Assert(*scan == *match, "match[2]?");
  74755. /* We check for insufficient lookahead only every 8th comparison;
  74756. * the 256th check will be made at strstart+258.
  74757. */
  74758. do {
  74759. } while (*++scan == *++match && *++scan == *++match &&
  74760. *++scan == *++match && *++scan == *++match &&
  74761. *++scan == *++match && *++scan == *++match &&
  74762. *++scan == *++match && *++scan == *++match &&
  74763. scan < strend);
  74764. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74765. len = MAX_MATCH - (int)(strend - scan);
  74766. if (len < MIN_MATCH) return MIN_MATCH - 1;
  74767. s->match_start = cur_match;
  74768. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  74769. }
  74770. #ifdef DEBUG
  74771. /* ===========================================================================
  74772. * Check that the match at match_start is indeed a match.
  74773. */
  74774. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  74775. {
  74776. /* check that the match is indeed a match */
  74777. if (zmemcmp(s->window + match,
  74778. s->window + start, length) != EQUAL) {
  74779. fprintf(stderr, " start %u, match %u, length %d\n",
  74780. start, match, length);
  74781. do {
  74782. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  74783. } while (--length != 0);
  74784. z_error("invalid match");
  74785. }
  74786. if (z_verbose > 1) {
  74787. fprintf(stderr,"\\[%d,%d]", start-match, length);
  74788. do { putc(s->window[start++], stderr); } while (--length != 0);
  74789. }
  74790. }
  74791. #else
  74792. # define check_match(s, start, match, length)
  74793. #endif /* DEBUG */
  74794. /* ===========================================================================
  74795. * Fill the window when the lookahead becomes insufficient.
  74796. * Updates strstart and lookahead.
  74797. *
  74798. * IN assertion: lookahead < MIN_LOOKAHEAD
  74799. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  74800. * At least one byte has been read, or avail_in == 0; reads are
  74801. * performed for at least two bytes (required for the zip translate_eol
  74802. * option -- not supported here).
  74803. */
  74804. local void fill_window (deflate_state *s)
  74805. {
  74806. register unsigned n, m;
  74807. register Posf *p;
  74808. unsigned more; /* Amount of free space at the end of the window. */
  74809. uInt wsize = s->w_size;
  74810. do {
  74811. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  74812. /* Deal with !@#$% 64K limit: */
  74813. if (sizeof(int) <= 2) {
  74814. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  74815. more = wsize;
  74816. } else if (more == (unsigned)(-1)) {
  74817. /* Very unlikely, but possible on 16 bit machine if
  74818. * strstart == 0 && lookahead == 1 (input done a byte at time)
  74819. */
  74820. more--;
  74821. }
  74822. }
  74823. /* If the window is almost full and there is insufficient lookahead,
  74824. * move the upper half to the lower one to make room in the upper half.
  74825. */
  74826. if (s->strstart >= wsize+MAX_DIST(s)) {
  74827. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  74828. s->match_start -= wsize;
  74829. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  74830. s->block_start -= (long) wsize;
  74831. /* Slide the hash table (could be avoided with 32 bit values
  74832. at the expense of memory usage). We slide even when level == 0
  74833. to keep the hash table consistent if we switch back to level > 0
  74834. later. (Using level 0 permanently is not an optimal usage of
  74835. zlib, so we don't care about this pathological case.)
  74836. */
  74837. /* %%% avoid this when Z_RLE */
  74838. n = s->hash_size;
  74839. p = &s->head[n];
  74840. do {
  74841. m = *--p;
  74842. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  74843. } while (--n);
  74844. n = wsize;
  74845. #ifndef FASTEST
  74846. p = &s->prev[n];
  74847. do {
  74848. m = *--p;
  74849. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  74850. /* If n is not on any hash chain, prev[n] is garbage but
  74851. * its value will never be used.
  74852. */
  74853. } while (--n);
  74854. #endif
  74855. more += wsize;
  74856. }
  74857. if (s->strm->avail_in == 0) return;
  74858. /* If there was no sliding:
  74859. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  74860. * more == window_size - lookahead - strstart
  74861. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  74862. * => more >= window_size - 2*WSIZE + 2
  74863. * In the BIG_MEM or MMAP case (not yet supported),
  74864. * window_size == input_size + MIN_LOOKAHEAD &&
  74865. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  74866. * Otherwise, window_size == 2*WSIZE so more >= 2.
  74867. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  74868. */
  74869. Assert(more >= 2, "more < 2");
  74870. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  74871. s->lookahead += n;
  74872. /* Initialize the hash value now that we have some input: */
  74873. if (s->lookahead >= MIN_MATCH) {
  74874. s->ins_h = s->window[s->strstart];
  74875. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  74876. #if MIN_MATCH != 3
  74877. Call UPDATE_HASH() MIN_MATCH-3 more times
  74878. #endif
  74879. }
  74880. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  74881. * but this is not important since only literal bytes will be emitted.
  74882. */
  74883. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  74884. }
  74885. /* ===========================================================================
  74886. * Flush the current block, with given end-of-file flag.
  74887. * IN assertion: strstart is set to the end of the current match.
  74888. */
  74889. #define FLUSH_BLOCK_ONLY(s, eof) { \
  74890. _tr_flush_block(s, (s->block_start >= 0L ? \
  74891. (charf *)&s->window[(unsigned)s->block_start] : \
  74892. (charf *)Z_NULL), \
  74893. (ulg)((long)s->strstart - s->block_start), \
  74894. (eof)); \
  74895. s->block_start = s->strstart; \
  74896. flush_pending(s->strm); \
  74897. Tracev((stderr,"[FLUSH]")); \
  74898. }
  74899. /* Same but force premature exit if necessary. */
  74900. #define FLUSH_BLOCK(s, eof) { \
  74901. FLUSH_BLOCK_ONLY(s, eof); \
  74902. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  74903. }
  74904. /* ===========================================================================
  74905. * Copy without compression as much as possible from the input stream, return
  74906. * the current block state.
  74907. * This function does not insert new strings in the dictionary since
  74908. * uncompressible data is probably not useful. This function is used
  74909. * only for the level=0 compression option.
  74910. * NOTE: this function should be optimized to avoid extra copying from
  74911. * window to pending_buf.
  74912. */
  74913. local block_state deflate_stored(deflate_state *s, int flush)
  74914. {
  74915. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  74916. * to pending_buf_size, and each stored block has a 5 byte header:
  74917. */
  74918. ulg max_block_size = 0xffff;
  74919. ulg max_start;
  74920. if (max_block_size > s->pending_buf_size - 5) {
  74921. max_block_size = s->pending_buf_size - 5;
  74922. }
  74923. /* Copy as much as possible from input to output: */
  74924. for (;;) {
  74925. /* Fill the window as much as possible: */
  74926. if (s->lookahead <= 1) {
  74927. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  74928. s->block_start >= (long)s->w_size, "slide too late");
  74929. fill_window(s);
  74930. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  74931. if (s->lookahead == 0) break; /* flush the current block */
  74932. }
  74933. Assert(s->block_start >= 0L, "block gone");
  74934. s->strstart += s->lookahead;
  74935. s->lookahead = 0;
  74936. /* Emit a stored block if pending_buf will be full: */
  74937. max_start = s->block_start + max_block_size;
  74938. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  74939. /* strstart == 0 is possible when wraparound on 16-bit machine */
  74940. s->lookahead = (uInt)(s->strstart - max_start);
  74941. s->strstart = (uInt)max_start;
  74942. FLUSH_BLOCK(s, 0);
  74943. }
  74944. /* Flush if we may have to slide, otherwise block_start may become
  74945. * negative and the data will be gone:
  74946. */
  74947. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  74948. FLUSH_BLOCK(s, 0);
  74949. }
  74950. }
  74951. FLUSH_BLOCK(s, flush == Z_FINISH);
  74952. return flush == Z_FINISH ? finish_done : block_done;
  74953. }
  74954. /* ===========================================================================
  74955. * Compress as much as possible from the input stream, return the current
  74956. * block state.
  74957. * This function does not perform lazy evaluation of matches and inserts
  74958. * new strings in the dictionary only for unmatched strings or for short
  74959. * matches. It is used only for the fast compression options.
  74960. */
  74961. local block_state deflate_fast(deflate_state *s, int flush)
  74962. {
  74963. IPos hash_head = NIL; /* head of the hash chain */
  74964. int bflush; /* set if current block must be flushed */
  74965. for (;;) {
  74966. /* Make sure that we always have enough lookahead, except
  74967. * at the end of the input file. We need MAX_MATCH bytes
  74968. * for the next match, plus MIN_MATCH bytes to insert the
  74969. * string following the next match.
  74970. */
  74971. if (s->lookahead < MIN_LOOKAHEAD) {
  74972. fill_window(s);
  74973. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  74974. return need_more;
  74975. }
  74976. if (s->lookahead == 0) break; /* flush the current block */
  74977. }
  74978. /* Insert the string window[strstart .. strstart+2] in the
  74979. * dictionary, and set hash_head to the head of the hash chain:
  74980. */
  74981. if (s->lookahead >= MIN_MATCH) {
  74982. INSERT_STRING(s, s->strstart, hash_head);
  74983. }
  74984. /* Find the longest match, discarding those <= prev_length.
  74985. * At this point we have always match_length < MIN_MATCH
  74986. */
  74987. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  74988. /* To simplify the code, we prevent matches with the string
  74989. * of window index 0 (in particular we have to avoid a match
  74990. * of the string with itself at the start of the input file).
  74991. */
  74992. #ifdef FASTEST
  74993. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  74994. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  74995. s->match_length = longest_match_fast (s, hash_head);
  74996. }
  74997. #else
  74998. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  74999. s->match_length = longest_match (s, hash_head);
  75000. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75001. s->match_length = longest_match_fast (s, hash_head);
  75002. }
  75003. #endif
  75004. /* longest_match() or longest_match_fast() sets match_start */
  75005. }
  75006. if (s->match_length >= MIN_MATCH) {
  75007. check_match(s, s->strstart, s->match_start, s->match_length);
  75008. _tr_tally_dist(s, s->strstart - s->match_start,
  75009. s->match_length - MIN_MATCH, bflush);
  75010. s->lookahead -= s->match_length;
  75011. /* Insert new strings in the hash table only if the match length
  75012. * is not too large. This saves time but degrades compression.
  75013. */
  75014. #ifndef FASTEST
  75015. if (s->match_length <= s->max_insert_length &&
  75016. s->lookahead >= MIN_MATCH) {
  75017. s->match_length--; /* string at strstart already in table */
  75018. do {
  75019. s->strstart++;
  75020. INSERT_STRING(s, s->strstart, hash_head);
  75021. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  75022. * always MIN_MATCH bytes ahead.
  75023. */
  75024. } while (--s->match_length != 0);
  75025. s->strstart++;
  75026. } else
  75027. #endif
  75028. {
  75029. s->strstart += s->match_length;
  75030. s->match_length = 0;
  75031. s->ins_h = s->window[s->strstart];
  75032. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75033. #if MIN_MATCH != 3
  75034. Call UPDATE_HASH() MIN_MATCH-3 more times
  75035. #endif
  75036. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  75037. * matter since it will be recomputed at next deflate call.
  75038. */
  75039. }
  75040. } else {
  75041. /* No match, output a literal byte */
  75042. Tracevv((stderr,"%c", s->window[s->strstart]));
  75043. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75044. s->lookahead--;
  75045. s->strstart++;
  75046. }
  75047. if (bflush) FLUSH_BLOCK(s, 0);
  75048. }
  75049. FLUSH_BLOCK(s, flush == Z_FINISH);
  75050. return flush == Z_FINISH ? finish_done : block_done;
  75051. }
  75052. #ifndef FASTEST
  75053. /* ===========================================================================
  75054. * Same as above, but achieves better compression. We use a lazy
  75055. * evaluation for matches: a match is finally adopted only if there is
  75056. * no better match at the next window position.
  75057. */
  75058. local block_state deflate_slow(deflate_state *s, int flush)
  75059. {
  75060. IPos hash_head = NIL; /* head of hash chain */
  75061. int bflush; /* set if current block must be flushed */
  75062. /* Process the input block. */
  75063. for (;;) {
  75064. /* Make sure that we always have enough lookahead, except
  75065. * at the end of the input file. We need MAX_MATCH bytes
  75066. * for the next match, plus MIN_MATCH bytes to insert the
  75067. * string following the next match.
  75068. */
  75069. if (s->lookahead < MIN_LOOKAHEAD) {
  75070. fill_window(s);
  75071. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75072. return need_more;
  75073. }
  75074. if (s->lookahead == 0) break; /* flush the current block */
  75075. }
  75076. /* Insert the string window[strstart .. strstart+2] in the
  75077. * dictionary, and set hash_head to the head of the hash chain:
  75078. */
  75079. if (s->lookahead >= MIN_MATCH) {
  75080. INSERT_STRING(s, s->strstart, hash_head);
  75081. }
  75082. /* Find the longest match, discarding those <= prev_length.
  75083. */
  75084. s->prev_length = s->match_length, s->prev_match = s->match_start;
  75085. s->match_length = MIN_MATCH-1;
  75086. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  75087. s->strstart - hash_head <= MAX_DIST(s)) {
  75088. /* To simplify the code, we prevent matches with the string
  75089. * of window index 0 (in particular we have to avoid a match
  75090. * of the string with itself at the start of the input file).
  75091. */
  75092. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75093. s->match_length = longest_match (s, hash_head);
  75094. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75095. s->match_length = longest_match_fast (s, hash_head);
  75096. }
  75097. /* longest_match() or longest_match_fast() sets match_start */
  75098. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  75099. #if TOO_FAR <= 32767
  75100. || (s->match_length == MIN_MATCH &&
  75101. s->strstart - s->match_start > TOO_FAR)
  75102. #endif
  75103. )) {
  75104. /* If prev_match is also MIN_MATCH, match_start is garbage
  75105. * but we will ignore the current match anyway.
  75106. */
  75107. s->match_length = MIN_MATCH-1;
  75108. }
  75109. }
  75110. /* If there was a match at the previous step and the current
  75111. * match is not better, output the previous match:
  75112. */
  75113. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  75114. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  75115. /* Do not insert strings in hash table beyond this. */
  75116. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  75117. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  75118. s->prev_length - MIN_MATCH, bflush);
  75119. /* Insert in hash table all strings up to the end of the match.
  75120. * strstart-1 and strstart are already inserted. If there is not
  75121. * enough lookahead, the last two strings are not inserted in
  75122. * the hash table.
  75123. */
  75124. s->lookahead -= s->prev_length-1;
  75125. s->prev_length -= 2;
  75126. do {
  75127. if (++s->strstart <= max_insert) {
  75128. INSERT_STRING(s, s->strstart, hash_head);
  75129. }
  75130. } while (--s->prev_length != 0);
  75131. s->match_available = 0;
  75132. s->match_length = MIN_MATCH-1;
  75133. s->strstart++;
  75134. if (bflush) FLUSH_BLOCK(s, 0);
  75135. } else if (s->match_available) {
  75136. /* If there was no match at the previous position, output a
  75137. * single literal. If there was a match but the current match
  75138. * is longer, truncate the previous match to a single literal.
  75139. */
  75140. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75141. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75142. if (bflush) {
  75143. FLUSH_BLOCK_ONLY(s, 0);
  75144. }
  75145. s->strstart++;
  75146. s->lookahead--;
  75147. if (s->strm->avail_out == 0) return need_more;
  75148. } else {
  75149. /* There is no previous match to compare with, wait for
  75150. * the next step to decide.
  75151. */
  75152. s->match_available = 1;
  75153. s->strstart++;
  75154. s->lookahead--;
  75155. }
  75156. }
  75157. Assert (flush != Z_NO_FLUSH, "no flush?");
  75158. if (s->match_available) {
  75159. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75160. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75161. s->match_available = 0;
  75162. }
  75163. FLUSH_BLOCK(s, flush == Z_FINISH);
  75164. return flush == Z_FINISH ? finish_done : block_done;
  75165. }
  75166. #endif /* FASTEST */
  75167. #if 0
  75168. /* ===========================================================================
  75169. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  75170. * one. Do not maintain a hash table. (It will be regenerated if this run of
  75171. * deflate switches away from Z_RLE.)
  75172. */
  75173. local block_state deflate_rle(s, flush)
  75174. deflate_state *s;
  75175. int flush;
  75176. {
  75177. int bflush; /* set if current block must be flushed */
  75178. uInt run; /* length of run */
  75179. uInt max; /* maximum length of run */
  75180. uInt prev; /* byte at distance one to match */
  75181. Bytef *scan; /* scan for end of run */
  75182. for (;;) {
  75183. /* Make sure that we always have enough lookahead, except
  75184. * at the end of the input file. We need MAX_MATCH bytes
  75185. * for the longest encodable run.
  75186. */
  75187. if (s->lookahead < MAX_MATCH) {
  75188. fill_window(s);
  75189. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  75190. return need_more;
  75191. }
  75192. if (s->lookahead == 0) break; /* flush the current block */
  75193. }
  75194. /* See how many times the previous byte repeats */
  75195. run = 0;
  75196. if (s->strstart > 0) { /* if there is a previous byte, that is */
  75197. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  75198. scan = s->window + s->strstart - 1;
  75199. prev = *scan++;
  75200. do {
  75201. if (*scan++ != prev)
  75202. break;
  75203. } while (++run < max);
  75204. }
  75205. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  75206. if (run >= MIN_MATCH) {
  75207. check_match(s, s->strstart, s->strstart - 1, run);
  75208. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  75209. s->lookahead -= run;
  75210. s->strstart += run;
  75211. } else {
  75212. /* No match, output a literal byte */
  75213. Tracevv((stderr,"%c", s->window[s->strstart]));
  75214. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75215. s->lookahead--;
  75216. s->strstart++;
  75217. }
  75218. if (bflush) FLUSH_BLOCK(s, 0);
  75219. }
  75220. FLUSH_BLOCK(s, flush == Z_FINISH);
  75221. return flush == Z_FINISH ? finish_done : block_done;
  75222. }
  75223. #endif
  75224. /********* End of inlined file: deflate.c *********/
  75225. /********* Start of inlined file: infback.c *********/
  75226. /*
  75227. This code is largely copied from inflate.c. Normally either infback.o or
  75228. inflate.o would be linked into an application--not both. The interface
  75229. with inffast.c is retained so that optimized assembler-coded versions of
  75230. inflate_fast() can be used with either inflate.c or infback.c.
  75231. */
  75232. /********* Start of inlined file: inftrees.h *********/
  75233. /* WARNING: this file should *not* be used by applications. It is
  75234. part of the implementation of the compression library and is
  75235. subject to change. Applications should only use zlib.h.
  75236. */
  75237. #ifndef _INFTREES_H_
  75238. #define _INFTREES_H_
  75239. /* Structure for decoding tables. Each entry provides either the
  75240. information needed to do the operation requested by the code that
  75241. indexed that table entry, or it provides a pointer to another
  75242. table that indexes more bits of the code. op indicates whether
  75243. the entry is a pointer to another table, a literal, a length or
  75244. distance, an end-of-block, or an invalid code. For a table
  75245. pointer, the low four bits of op is the number of index bits of
  75246. that table. For a length or distance, the low four bits of op
  75247. is the number of extra bits to get after the code. bits is
  75248. the number of bits in this code or part of the code to drop off
  75249. of the bit buffer. val is the actual byte to output in the case
  75250. of a literal, the base length or distance, or the offset from
  75251. the current table to the next table. Each entry is four bytes. */
  75252. typedef struct {
  75253. unsigned char op; /* operation, extra bits, table bits */
  75254. unsigned char bits; /* bits in this part of the code */
  75255. unsigned short val; /* offset in table or code value */
  75256. } code;
  75257. /* op values as set by inflate_table():
  75258. 00000000 - literal
  75259. 0000tttt - table link, tttt != 0 is the number of table index bits
  75260. 0001eeee - length or distance, eeee is the number of extra bits
  75261. 01100000 - end of block
  75262. 01000000 - invalid code
  75263. */
  75264. /* Maximum size of dynamic tree. The maximum found in a long but non-
  75265. exhaustive search was 1444 code structures (852 for length/literals
  75266. and 592 for distances, the latter actually the result of an
  75267. exhaustive search). The true maximum is not known, but the value
  75268. below is more than safe. */
  75269. #define ENOUGH 2048
  75270. #define MAXD 592
  75271. /* Type of code to build for inftable() */
  75272. typedef enum {
  75273. CODES,
  75274. LENS,
  75275. DISTS
  75276. } codetype;
  75277. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  75278. unsigned codes, code FAR * FAR *table,
  75279. unsigned FAR *bits, unsigned short FAR *work));
  75280. #endif
  75281. /********* End of inlined file: inftrees.h *********/
  75282. /********* Start of inlined file: inflate.h *********/
  75283. /* WARNING: this file should *not* be used by applications. It is
  75284. part of the implementation of the compression library and is
  75285. subject to change. Applications should only use zlib.h.
  75286. */
  75287. #ifndef _INFLATE_H_
  75288. #define _INFLATE_H_
  75289. /* define NO_GZIP when compiling if you want to disable gzip header and
  75290. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  75291. the crc code when it is not needed. For shared libraries, gzip decoding
  75292. should be left enabled. */
  75293. #ifndef NO_GZIP
  75294. # define GUNZIP
  75295. #endif
  75296. /* Possible inflate modes between inflate() calls */
  75297. typedef enum {
  75298. HEAD, /* i: waiting for magic header */
  75299. FLAGS, /* i: waiting for method and flags (gzip) */
  75300. TIME, /* i: waiting for modification time (gzip) */
  75301. OS, /* i: waiting for extra flags and operating system (gzip) */
  75302. EXLEN, /* i: waiting for extra length (gzip) */
  75303. EXTRA, /* i: waiting for extra bytes (gzip) */
  75304. NAME, /* i: waiting for end of file name (gzip) */
  75305. COMMENT, /* i: waiting for end of comment (gzip) */
  75306. HCRC, /* i: waiting for header crc (gzip) */
  75307. DICTID, /* i: waiting for dictionary check value */
  75308. DICT, /* waiting for inflateSetDictionary() call */
  75309. TYPE, /* i: waiting for type bits, including last-flag bit */
  75310. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  75311. STORED, /* i: waiting for stored size (length and complement) */
  75312. COPY, /* i/o: waiting for input or output to copy stored block */
  75313. TABLE, /* i: waiting for dynamic block table lengths */
  75314. LENLENS, /* i: waiting for code length code lengths */
  75315. CODELENS, /* i: waiting for length/lit and distance code lengths */
  75316. LEN, /* i: waiting for length/lit code */
  75317. LENEXT, /* i: waiting for length extra bits */
  75318. DIST, /* i: waiting for distance code */
  75319. DISTEXT, /* i: waiting for distance extra bits */
  75320. MATCH, /* o: waiting for output space to copy string */
  75321. LIT, /* o: waiting for output space to write literal */
  75322. CHECK, /* i: waiting for 32-bit check value */
  75323. LENGTH, /* i: waiting for 32-bit length (gzip) */
  75324. DONE, /* finished check, done -- remain here until reset */
  75325. BAD, /* got a data error -- remain here until reset */
  75326. MEM, /* got an inflate() memory error -- remain here until reset */
  75327. SYNC /* looking for synchronization bytes to restart inflate() */
  75328. } inflate_mode;
  75329. /*
  75330. State transitions between above modes -
  75331. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  75332. Process header:
  75333. HEAD -> (gzip) or (zlib)
  75334. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  75335. NAME -> COMMENT -> HCRC -> TYPE
  75336. (zlib) -> DICTID or TYPE
  75337. DICTID -> DICT -> TYPE
  75338. Read deflate blocks:
  75339. TYPE -> STORED or TABLE or LEN or CHECK
  75340. STORED -> COPY -> TYPE
  75341. TABLE -> LENLENS -> CODELENS -> LEN
  75342. Read deflate codes:
  75343. LEN -> LENEXT or LIT or TYPE
  75344. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  75345. LIT -> LEN
  75346. Process trailer:
  75347. CHECK -> LENGTH -> DONE
  75348. */
  75349. /* state maintained between inflate() calls. Approximately 7K bytes. */
  75350. struct inflate_state {
  75351. inflate_mode mode; /* current inflate mode */
  75352. int last; /* true if processing last block */
  75353. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  75354. int havedict; /* true if dictionary provided */
  75355. int flags; /* gzip header method and flags (0 if zlib) */
  75356. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  75357. unsigned long check; /* protected copy of check value */
  75358. unsigned long total; /* protected copy of output count */
  75359. gz_headerp head; /* where to save gzip header information */
  75360. /* sliding window */
  75361. unsigned wbits; /* log base 2 of requested window size */
  75362. unsigned wsize; /* window size or zero if not using window */
  75363. unsigned whave; /* valid bytes in the window */
  75364. unsigned write; /* window write index */
  75365. unsigned char FAR *window; /* allocated sliding window, if needed */
  75366. /* bit accumulator */
  75367. unsigned long hold; /* input bit accumulator */
  75368. unsigned bits; /* number of bits in "in" */
  75369. /* for string and stored block copying */
  75370. unsigned length; /* literal or length of data to copy */
  75371. unsigned offset; /* distance back to copy string from */
  75372. /* for table and code decoding */
  75373. unsigned extra; /* extra bits needed */
  75374. /* fixed and dynamic code tables */
  75375. code const FAR *lencode; /* starting table for length/literal codes */
  75376. code const FAR *distcode; /* starting table for distance codes */
  75377. unsigned lenbits; /* index bits for lencode */
  75378. unsigned distbits; /* index bits for distcode */
  75379. /* dynamic table building */
  75380. unsigned ncode; /* number of code length code lengths */
  75381. unsigned nlen; /* number of length code lengths */
  75382. unsigned ndist; /* number of distance code lengths */
  75383. unsigned have; /* number of code lengths in lens[] */
  75384. code FAR *next; /* next available space in codes[] */
  75385. unsigned short lens[320]; /* temporary storage for code lengths */
  75386. unsigned short work[288]; /* work area for code table building */
  75387. code codes[ENOUGH]; /* space for code tables */
  75388. };
  75389. #endif
  75390. /********* End of inlined file: inflate.h *********/
  75391. /********* Start of inlined file: inffast.h *********/
  75392. /* WARNING: this file should *not* be used by applications. It is
  75393. part of the implementation of the compression library and is
  75394. subject to change. Applications should only use zlib.h.
  75395. */
  75396. void inflate_fast OF((z_streamp strm, unsigned start));
  75397. /********* End of inlined file: inffast.h *********/
  75398. /* function prototypes */
  75399. local void fixedtables1 OF((struct inflate_state FAR *state));
  75400. /*
  75401. strm provides memory allocation functions in zalloc and zfree, or
  75402. Z_NULL to use the library memory allocation functions.
  75403. windowBits is in the range 8..15, and window is a user-supplied
  75404. window and output buffer that is 2**windowBits bytes.
  75405. */
  75406. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  75407. {
  75408. struct inflate_state FAR *state;
  75409. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  75410. stream_size != (int)(sizeof(z_stream)))
  75411. return Z_VERSION_ERROR;
  75412. if (strm == Z_NULL || window == Z_NULL ||
  75413. windowBits < 8 || windowBits > 15)
  75414. return Z_STREAM_ERROR;
  75415. strm->msg = Z_NULL; /* in case we return an error */
  75416. if (strm->zalloc == (alloc_func)0) {
  75417. strm->zalloc = zcalloc;
  75418. strm->opaque = (voidpf)0;
  75419. }
  75420. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  75421. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  75422. sizeof(struct inflate_state));
  75423. if (state == Z_NULL) return Z_MEM_ERROR;
  75424. Tracev((stderr, "inflate: allocated\n"));
  75425. strm->state = (struct internal_state FAR *)state;
  75426. state->dmax = 32768U;
  75427. state->wbits = windowBits;
  75428. state->wsize = 1U << windowBits;
  75429. state->window = window;
  75430. state->write = 0;
  75431. state->whave = 0;
  75432. return Z_OK;
  75433. }
  75434. /*
  75435. Return state with length and distance decoding tables and index sizes set to
  75436. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  75437. If BUILDFIXED is defined, then instead this routine builds the tables the
  75438. first time it's called, and returns those tables the first time and
  75439. thereafter. This reduces the size of the code by about 2K bytes, in
  75440. exchange for a little execution time. However, BUILDFIXED should not be
  75441. used for threaded applications, since the rewriting of the tables and virgin
  75442. may not be thread-safe.
  75443. */
  75444. local void fixedtables1 (struct inflate_state FAR *state)
  75445. {
  75446. #ifdef BUILDFIXED
  75447. static int virgin = 1;
  75448. static code *lenfix, *distfix;
  75449. static code fixed[544];
  75450. /* build fixed huffman tables if first call (may not be thread safe) */
  75451. if (virgin) {
  75452. unsigned sym, bits;
  75453. static code *next;
  75454. /* literal/length table */
  75455. sym = 0;
  75456. while (sym < 144) state->lens[sym++] = 8;
  75457. while (sym < 256) state->lens[sym++] = 9;
  75458. while (sym < 280) state->lens[sym++] = 7;
  75459. while (sym < 288) state->lens[sym++] = 8;
  75460. next = fixed;
  75461. lenfix = next;
  75462. bits = 9;
  75463. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  75464. /* distance table */
  75465. sym = 0;
  75466. while (sym < 32) state->lens[sym++] = 5;
  75467. distfix = next;
  75468. bits = 5;
  75469. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  75470. /* do this just once */
  75471. virgin = 0;
  75472. }
  75473. #else /* !BUILDFIXED */
  75474. /********* Start of inlined file: inffixed.h *********/
  75475. /* inffixed.h -- table for decoding fixed codes
  75476. * Generated automatically by makefixed().
  75477. */
  75478. /* WARNING: this file should *not* be used by applications. It
  75479. is part of the implementation of the compression library and
  75480. is subject to change. Applications should only use zlib.h.
  75481. */
  75482. static const code lenfix[512] = {
  75483. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  75484. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  75485. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  75486. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  75487. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  75488. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  75489. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  75490. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  75491. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  75492. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  75493. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  75494. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  75495. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  75496. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  75497. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  75498. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  75499. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  75500. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  75501. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  75502. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  75503. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  75504. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  75505. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  75506. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  75507. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  75508. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  75509. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  75510. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  75511. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  75512. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  75513. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  75514. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  75515. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  75516. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  75517. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  75518. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  75519. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  75520. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  75521. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  75522. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  75523. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  75524. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  75525. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  75526. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  75527. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  75528. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  75529. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  75530. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  75531. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  75532. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  75533. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  75534. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  75535. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  75536. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  75537. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  75538. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  75539. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  75540. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  75541. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  75542. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  75543. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  75544. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  75545. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  75546. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  75547. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  75548. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  75549. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  75550. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  75551. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  75552. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  75553. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  75554. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  75555. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  75556. {0,9,255}
  75557. };
  75558. static const code distfix[32] = {
  75559. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  75560. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  75561. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  75562. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  75563. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  75564. {22,5,193},{64,5,0}
  75565. };
  75566. /********* End of inlined file: inffixed.h *********/
  75567. #endif /* BUILDFIXED */
  75568. state->lencode = lenfix;
  75569. state->lenbits = 9;
  75570. state->distcode = distfix;
  75571. state->distbits = 5;
  75572. }
  75573. /* Macros for inflateBack(): */
  75574. /* Load returned state from inflate_fast() */
  75575. #define LOAD() \
  75576. do { \
  75577. put = strm->next_out; \
  75578. left = strm->avail_out; \
  75579. next = strm->next_in; \
  75580. have = strm->avail_in; \
  75581. hold = state->hold; \
  75582. bits = state->bits; \
  75583. } while (0)
  75584. /* Set state from registers for inflate_fast() */
  75585. #define RESTORE() \
  75586. do { \
  75587. strm->next_out = put; \
  75588. strm->avail_out = left; \
  75589. strm->next_in = next; \
  75590. strm->avail_in = have; \
  75591. state->hold = hold; \
  75592. state->bits = bits; \
  75593. } while (0)
  75594. /* Clear the input bit accumulator */
  75595. #define INITBITS() \
  75596. do { \
  75597. hold = 0; \
  75598. bits = 0; \
  75599. } while (0)
  75600. /* Assure that some input is available. If input is requested, but denied,
  75601. then return a Z_BUF_ERROR from inflateBack(). */
  75602. #define PULL() \
  75603. do { \
  75604. if (have == 0) { \
  75605. have = in(in_desc, &next); \
  75606. if (have == 0) { \
  75607. next = Z_NULL; \
  75608. ret = Z_BUF_ERROR; \
  75609. goto inf_leave; \
  75610. } \
  75611. } \
  75612. } while (0)
  75613. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  75614. with an error if there is no input available. */
  75615. #define PULLBYTE() \
  75616. do { \
  75617. PULL(); \
  75618. have--; \
  75619. hold += (unsigned long)(*next++) << bits; \
  75620. bits += 8; \
  75621. } while (0)
  75622. /* Assure that there are at least n bits in the bit accumulator. If there is
  75623. not enough available input to do that, then return from inflateBack() with
  75624. an error. */
  75625. #define NEEDBITS(n) \
  75626. do { \
  75627. while (bits < (unsigned)(n)) \
  75628. PULLBYTE(); \
  75629. } while (0)
  75630. /* Return the low n bits of the bit accumulator (n < 16) */
  75631. #define BITS(n) \
  75632. ((unsigned)hold & ((1U << (n)) - 1))
  75633. /* Remove n bits from the bit accumulator */
  75634. #define DROPBITS(n) \
  75635. do { \
  75636. hold >>= (n); \
  75637. bits -= (unsigned)(n); \
  75638. } while (0)
  75639. /* Remove zero to seven bits as needed to go to a byte boundary */
  75640. #define BYTEBITS() \
  75641. do { \
  75642. hold >>= bits & 7; \
  75643. bits -= bits & 7; \
  75644. } while (0)
  75645. /* Assure that some output space is available, by writing out the window
  75646. if it's full. If the write fails, return from inflateBack() with a
  75647. Z_BUF_ERROR. */
  75648. #define ROOM() \
  75649. do { \
  75650. if (left == 0) { \
  75651. put = state->window; \
  75652. left = state->wsize; \
  75653. state->whave = left; \
  75654. if (out(out_desc, put, left)) { \
  75655. ret = Z_BUF_ERROR; \
  75656. goto inf_leave; \
  75657. } \
  75658. } \
  75659. } while (0)
  75660. /*
  75661. strm provides the memory allocation functions and window buffer on input,
  75662. and provides information on the unused input on return. For Z_DATA_ERROR
  75663. returns, strm will also provide an error message.
  75664. in() and out() are the call-back input and output functions. When
  75665. inflateBack() needs more input, it calls in(). When inflateBack() has
  75666. filled the window with output, or when it completes with data in the
  75667. window, it calls out() to write out the data. The application must not
  75668. change the provided input until in() is called again or inflateBack()
  75669. returns. The application must not change the window/output buffer until
  75670. inflateBack() returns.
  75671. in() and out() are called with a descriptor parameter provided in the
  75672. inflateBack() call. This parameter can be a structure that provides the
  75673. information required to do the read or write, as well as accumulated
  75674. information on the input and output such as totals and check values.
  75675. in() should return zero on failure. out() should return non-zero on
  75676. failure. If either in() or out() fails, than inflateBack() returns a
  75677. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  75678. was in() or out() that caused in the error. Otherwise, inflateBack()
  75679. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  75680. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  75681. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  75682. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  75683. */
  75684. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  75685. {
  75686. struct inflate_state FAR *state;
  75687. unsigned char FAR *next; /* next input */
  75688. unsigned char FAR *put; /* next output */
  75689. unsigned have, left; /* available input and output */
  75690. unsigned long hold; /* bit buffer */
  75691. unsigned bits; /* bits in bit buffer */
  75692. unsigned copy; /* number of stored or match bytes to copy */
  75693. unsigned char FAR *from; /* where to copy match bytes from */
  75694. code thisx; /* current decoding table entry */
  75695. code last; /* parent table entry */
  75696. unsigned len; /* length to copy for repeats, bits to drop */
  75697. int ret; /* return code */
  75698. static const unsigned short order[19] = /* permutation of code lengths */
  75699. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  75700. /* Check that the strm exists and that the state was initialized */
  75701. if (strm == Z_NULL || strm->state == Z_NULL)
  75702. return Z_STREAM_ERROR;
  75703. state = (struct inflate_state FAR *)strm->state;
  75704. /* Reset the state */
  75705. strm->msg = Z_NULL;
  75706. state->mode = TYPE;
  75707. state->last = 0;
  75708. state->whave = 0;
  75709. next = strm->next_in;
  75710. have = next != Z_NULL ? strm->avail_in : 0;
  75711. hold = 0;
  75712. bits = 0;
  75713. put = state->window;
  75714. left = state->wsize;
  75715. /* Inflate until end of block marked as last */
  75716. for (;;)
  75717. switch (state->mode) {
  75718. case TYPE:
  75719. /* determine and dispatch block type */
  75720. if (state->last) {
  75721. BYTEBITS();
  75722. state->mode = DONE;
  75723. break;
  75724. }
  75725. NEEDBITS(3);
  75726. state->last = BITS(1);
  75727. DROPBITS(1);
  75728. switch (BITS(2)) {
  75729. case 0: /* stored block */
  75730. Tracev((stderr, "inflate: stored block%s\n",
  75731. state->last ? " (last)" : ""));
  75732. state->mode = STORED;
  75733. break;
  75734. case 1: /* fixed block */
  75735. fixedtables1(state);
  75736. Tracev((stderr, "inflate: fixed codes block%s\n",
  75737. state->last ? " (last)" : ""));
  75738. state->mode = LEN; /* decode codes */
  75739. break;
  75740. case 2: /* dynamic block */
  75741. Tracev((stderr, "inflate: dynamic codes block%s\n",
  75742. state->last ? " (last)" : ""));
  75743. state->mode = TABLE;
  75744. break;
  75745. case 3:
  75746. strm->msg = (char *)"invalid block type";
  75747. state->mode = BAD;
  75748. }
  75749. DROPBITS(2);
  75750. break;
  75751. case STORED:
  75752. /* get and verify stored block length */
  75753. BYTEBITS(); /* go to byte boundary */
  75754. NEEDBITS(32);
  75755. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  75756. strm->msg = (char *)"invalid stored block lengths";
  75757. state->mode = BAD;
  75758. break;
  75759. }
  75760. state->length = (unsigned)hold & 0xffff;
  75761. Tracev((stderr, "inflate: stored length %u\n",
  75762. state->length));
  75763. INITBITS();
  75764. /* copy stored block from input to output */
  75765. while (state->length != 0) {
  75766. copy = state->length;
  75767. PULL();
  75768. ROOM();
  75769. if (copy > have) copy = have;
  75770. if (copy > left) copy = left;
  75771. zmemcpy(put, next, copy);
  75772. have -= copy;
  75773. next += copy;
  75774. left -= copy;
  75775. put += copy;
  75776. state->length -= copy;
  75777. }
  75778. Tracev((stderr, "inflate: stored end\n"));
  75779. state->mode = TYPE;
  75780. break;
  75781. case TABLE:
  75782. /* get dynamic table entries descriptor */
  75783. NEEDBITS(14);
  75784. state->nlen = BITS(5) + 257;
  75785. DROPBITS(5);
  75786. state->ndist = BITS(5) + 1;
  75787. DROPBITS(5);
  75788. state->ncode = BITS(4) + 4;
  75789. DROPBITS(4);
  75790. #ifndef PKZIP_BUG_WORKAROUND
  75791. if (state->nlen > 286 || state->ndist > 30) {
  75792. strm->msg = (char *)"too many length or distance symbols";
  75793. state->mode = BAD;
  75794. break;
  75795. }
  75796. #endif
  75797. Tracev((stderr, "inflate: table sizes ok\n"));
  75798. /* get code length code lengths (not a typo) */
  75799. state->have = 0;
  75800. while (state->have < state->ncode) {
  75801. NEEDBITS(3);
  75802. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  75803. DROPBITS(3);
  75804. }
  75805. while (state->have < 19)
  75806. state->lens[order[state->have++]] = 0;
  75807. state->next = state->codes;
  75808. state->lencode = (code const FAR *)(state->next);
  75809. state->lenbits = 7;
  75810. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  75811. &(state->lenbits), state->work);
  75812. if (ret) {
  75813. strm->msg = (char *)"invalid code lengths set";
  75814. state->mode = BAD;
  75815. break;
  75816. }
  75817. Tracev((stderr, "inflate: code lengths ok\n"));
  75818. /* get length and distance code code lengths */
  75819. state->have = 0;
  75820. while (state->have < state->nlen + state->ndist) {
  75821. for (;;) {
  75822. thisx = state->lencode[BITS(state->lenbits)];
  75823. if ((unsigned)(thisx.bits) <= bits) break;
  75824. PULLBYTE();
  75825. }
  75826. if (thisx.val < 16) {
  75827. NEEDBITS(thisx.bits);
  75828. DROPBITS(thisx.bits);
  75829. state->lens[state->have++] = thisx.val;
  75830. }
  75831. else {
  75832. if (thisx.val == 16) {
  75833. NEEDBITS(thisx.bits + 2);
  75834. DROPBITS(thisx.bits);
  75835. if (state->have == 0) {
  75836. strm->msg = (char *)"invalid bit length repeat";
  75837. state->mode = BAD;
  75838. break;
  75839. }
  75840. len = (unsigned)(state->lens[state->have - 1]);
  75841. copy = 3 + BITS(2);
  75842. DROPBITS(2);
  75843. }
  75844. else if (thisx.val == 17) {
  75845. NEEDBITS(thisx.bits + 3);
  75846. DROPBITS(thisx.bits);
  75847. len = 0;
  75848. copy = 3 + BITS(3);
  75849. DROPBITS(3);
  75850. }
  75851. else {
  75852. NEEDBITS(thisx.bits + 7);
  75853. DROPBITS(thisx.bits);
  75854. len = 0;
  75855. copy = 11 + BITS(7);
  75856. DROPBITS(7);
  75857. }
  75858. if (state->have + copy > state->nlen + state->ndist) {
  75859. strm->msg = (char *)"invalid bit length repeat";
  75860. state->mode = BAD;
  75861. break;
  75862. }
  75863. while (copy--)
  75864. state->lens[state->have++] = (unsigned short)len;
  75865. }
  75866. }
  75867. /* handle error breaks in while */
  75868. if (state->mode == BAD) break;
  75869. /* build code tables */
  75870. state->next = state->codes;
  75871. state->lencode = (code const FAR *)(state->next);
  75872. state->lenbits = 9;
  75873. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  75874. &(state->lenbits), state->work);
  75875. if (ret) {
  75876. strm->msg = (char *)"invalid literal/lengths set";
  75877. state->mode = BAD;
  75878. break;
  75879. }
  75880. state->distcode = (code const FAR *)(state->next);
  75881. state->distbits = 6;
  75882. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  75883. &(state->next), &(state->distbits), state->work);
  75884. if (ret) {
  75885. strm->msg = (char *)"invalid distances set";
  75886. state->mode = BAD;
  75887. break;
  75888. }
  75889. Tracev((stderr, "inflate: codes ok\n"));
  75890. state->mode = LEN;
  75891. case LEN:
  75892. /* use inflate_fast() if we have enough input and output */
  75893. if (have >= 6 && left >= 258) {
  75894. RESTORE();
  75895. if (state->whave < state->wsize)
  75896. state->whave = state->wsize - left;
  75897. inflate_fast(strm, state->wsize);
  75898. LOAD();
  75899. break;
  75900. }
  75901. /* get a literal, length, or end-of-block code */
  75902. for (;;) {
  75903. thisx = state->lencode[BITS(state->lenbits)];
  75904. if ((unsigned)(thisx.bits) <= bits) break;
  75905. PULLBYTE();
  75906. }
  75907. if (thisx.op && (thisx.op & 0xf0) == 0) {
  75908. last = thisx;
  75909. for (;;) {
  75910. thisx = state->lencode[last.val +
  75911. (BITS(last.bits + last.op) >> last.bits)];
  75912. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  75913. PULLBYTE();
  75914. }
  75915. DROPBITS(last.bits);
  75916. }
  75917. DROPBITS(thisx.bits);
  75918. state->length = (unsigned)thisx.val;
  75919. /* process literal */
  75920. if (thisx.op == 0) {
  75921. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  75922. "inflate: literal '%c'\n" :
  75923. "inflate: literal 0x%02x\n", thisx.val));
  75924. ROOM();
  75925. *put++ = (unsigned char)(state->length);
  75926. left--;
  75927. state->mode = LEN;
  75928. break;
  75929. }
  75930. /* process end of block */
  75931. if (thisx.op & 32) {
  75932. Tracevv((stderr, "inflate: end of block\n"));
  75933. state->mode = TYPE;
  75934. break;
  75935. }
  75936. /* invalid code */
  75937. if (thisx.op & 64) {
  75938. strm->msg = (char *)"invalid literal/length code";
  75939. state->mode = BAD;
  75940. break;
  75941. }
  75942. /* length code -- get extra bits, if any */
  75943. state->extra = (unsigned)(thisx.op) & 15;
  75944. if (state->extra != 0) {
  75945. NEEDBITS(state->extra);
  75946. state->length += BITS(state->extra);
  75947. DROPBITS(state->extra);
  75948. }
  75949. Tracevv((stderr, "inflate: length %u\n", state->length));
  75950. /* get distance code */
  75951. for (;;) {
  75952. thisx = state->distcode[BITS(state->distbits)];
  75953. if ((unsigned)(thisx.bits) <= bits) break;
  75954. PULLBYTE();
  75955. }
  75956. if ((thisx.op & 0xf0) == 0) {
  75957. last = thisx;
  75958. for (;;) {
  75959. thisx = state->distcode[last.val +
  75960. (BITS(last.bits + last.op) >> last.bits)];
  75961. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  75962. PULLBYTE();
  75963. }
  75964. DROPBITS(last.bits);
  75965. }
  75966. DROPBITS(thisx.bits);
  75967. if (thisx.op & 64) {
  75968. strm->msg = (char *)"invalid distance code";
  75969. state->mode = BAD;
  75970. break;
  75971. }
  75972. state->offset = (unsigned)thisx.val;
  75973. /* get distance extra bits, if any */
  75974. state->extra = (unsigned)(thisx.op) & 15;
  75975. if (state->extra != 0) {
  75976. NEEDBITS(state->extra);
  75977. state->offset += BITS(state->extra);
  75978. DROPBITS(state->extra);
  75979. }
  75980. if (state->offset > state->wsize - (state->whave < state->wsize ?
  75981. left : 0)) {
  75982. strm->msg = (char *)"invalid distance too far back";
  75983. state->mode = BAD;
  75984. break;
  75985. }
  75986. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  75987. /* copy match from window to output */
  75988. do {
  75989. ROOM();
  75990. copy = state->wsize - state->offset;
  75991. if (copy < left) {
  75992. from = put + copy;
  75993. copy = left - copy;
  75994. }
  75995. else {
  75996. from = put - state->offset;
  75997. copy = left;
  75998. }
  75999. if (copy > state->length) copy = state->length;
  76000. state->length -= copy;
  76001. left -= copy;
  76002. do {
  76003. *put++ = *from++;
  76004. } while (--copy);
  76005. } while (state->length != 0);
  76006. break;
  76007. case DONE:
  76008. /* inflate stream terminated properly -- write leftover output */
  76009. ret = Z_STREAM_END;
  76010. if (left < state->wsize) {
  76011. if (out(out_desc, state->window, state->wsize - left))
  76012. ret = Z_BUF_ERROR;
  76013. }
  76014. goto inf_leave;
  76015. case BAD:
  76016. ret = Z_DATA_ERROR;
  76017. goto inf_leave;
  76018. default: /* can't happen, but makes compilers happy */
  76019. ret = Z_STREAM_ERROR;
  76020. goto inf_leave;
  76021. }
  76022. /* Return unused input */
  76023. inf_leave:
  76024. strm->next_in = next;
  76025. strm->avail_in = have;
  76026. return ret;
  76027. }
  76028. int ZEXPORT inflateBackEnd (z_streamp strm)
  76029. {
  76030. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  76031. return Z_STREAM_ERROR;
  76032. ZFREE(strm, strm->state);
  76033. strm->state = Z_NULL;
  76034. Tracev((stderr, "inflate: end\n"));
  76035. return Z_OK;
  76036. }
  76037. /********* End of inlined file: infback.c *********/
  76038. /********* Start of inlined file: inffast.c *********/
  76039. /********* Start of inlined file: inffast.h *********/
  76040. /* WARNING: this file should *not* be used by applications. It is
  76041. part of the implementation of the compression library and is
  76042. subject to change. Applications should only use zlib.h.
  76043. */
  76044. void inflate_fast OF((z_streamp strm, unsigned start));
  76045. /********* End of inlined file: inffast.h *********/
  76046. #ifndef ASMINF
  76047. /* Allow machine dependent optimization for post-increment or pre-increment.
  76048. Based on testing to date,
  76049. Pre-increment preferred for:
  76050. - PowerPC G3 (Adler)
  76051. - MIPS R5000 (Randers-Pehrson)
  76052. Post-increment preferred for:
  76053. - none
  76054. No measurable difference:
  76055. - Pentium III (Anderson)
  76056. - M68060 (Nikl)
  76057. */
  76058. #ifdef POSTINC
  76059. # define OFF 0
  76060. # define PUP(a) *(a)++
  76061. #else
  76062. # define OFF 1
  76063. # define PUP(a) *++(a)
  76064. #endif
  76065. /*
  76066. Decode literal, length, and distance codes and write out the resulting
  76067. literal and match bytes until either not enough input or output is
  76068. available, an end-of-block is encountered, or a data error is encountered.
  76069. When large enough input and output buffers are supplied to inflate(), for
  76070. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  76071. inflate execution time is spent in this routine.
  76072. Entry assumptions:
  76073. state->mode == LEN
  76074. strm->avail_in >= 6
  76075. strm->avail_out >= 258
  76076. start >= strm->avail_out
  76077. state->bits < 8
  76078. On return, state->mode is one of:
  76079. LEN -- ran out of enough output space or enough available input
  76080. TYPE -- reached end of block code, inflate() to interpret next block
  76081. BAD -- error in block data
  76082. Notes:
  76083. - The maximum input bits used by a length/distance pair is 15 bits for the
  76084. length code, 5 bits for the length extra, 15 bits for the distance code,
  76085. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  76086. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  76087. checking for available input while decoding.
  76088. - The maximum bytes that a single length/distance pair can output is 258
  76089. bytes, which is the maximum length that can be coded. inflate_fast()
  76090. requires strm->avail_out >= 258 for each loop to avoid checking for
  76091. output space.
  76092. */
  76093. void inflate_fast (z_streamp strm, unsigned start)
  76094. {
  76095. struct inflate_state FAR *state;
  76096. unsigned char FAR *in; /* local strm->next_in */
  76097. unsigned char FAR *last; /* while in < last, enough input available */
  76098. unsigned char FAR *out; /* local strm->next_out */
  76099. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  76100. unsigned char FAR *end; /* while out < end, enough space available */
  76101. #ifdef INFLATE_STRICT
  76102. unsigned dmax; /* maximum distance from zlib header */
  76103. #endif
  76104. unsigned wsize; /* window size or zero if not using window */
  76105. unsigned whave; /* valid bytes in the window */
  76106. unsigned write; /* window write index */
  76107. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  76108. unsigned long hold; /* local strm->hold */
  76109. unsigned bits; /* local strm->bits */
  76110. code const FAR *lcode; /* local strm->lencode */
  76111. code const FAR *dcode; /* local strm->distcode */
  76112. unsigned lmask; /* mask for first level of length codes */
  76113. unsigned dmask; /* mask for first level of distance codes */
  76114. code thisx; /* retrieved table entry */
  76115. unsigned op; /* code bits, operation, extra bits, or */
  76116. /* window position, window bytes to copy */
  76117. unsigned len; /* match length, unused bytes */
  76118. unsigned dist; /* match distance */
  76119. unsigned char FAR *from; /* where to copy match from */
  76120. /* copy state to local variables */
  76121. state = (struct inflate_state FAR *)strm->state;
  76122. in = strm->next_in - OFF;
  76123. last = in + (strm->avail_in - 5);
  76124. out = strm->next_out - OFF;
  76125. beg = out - (start - strm->avail_out);
  76126. end = out + (strm->avail_out - 257);
  76127. #ifdef INFLATE_STRICT
  76128. dmax = state->dmax;
  76129. #endif
  76130. wsize = state->wsize;
  76131. whave = state->whave;
  76132. write = state->write;
  76133. window = state->window;
  76134. hold = state->hold;
  76135. bits = state->bits;
  76136. lcode = state->lencode;
  76137. dcode = state->distcode;
  76138. lmask = (1U << state->lenbits) - 1;
  76139. dmask = (1U << state->distbits) - 1;
  76140. /* decode literals and length/distances until end-of-block or not enough
  76141. input data or output space */
  76142. do {
  76143. if (bits < 15) {
  76144. hold += (unsigned long)(PUP(in)) << bits;
  76145. bits += 8;
  76146. hold += (unsigned long)(PUP(in)) << bits;
  76147. bits += 8;
  76148. }
  76149. thisx = lcode[hold & lmask];
  76150. dolen:
  76151. op = (unsigned)(thisx.bits);
  76152. hold >>= op;
  76153. bits -= op;
  76154. op = (unsigned)(thisx.op);
  76155. if (op == 0) { /* literal */
  76156. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76157. "inflate: literal '%c'\n" :
  76158. "inflate: literal 0x%02x\n", thisx.val));
  76159. PUP(out) = (unsigned char)(thisx.val);
  76160. }
  76161. else if (op & 16) { /* length base */
  76162. len = (unsigned)(thisx.val);
  76163. op &= 15; /* number of extra bits */
  76164. if (op) {
  76165. if (bits < op) {
  76166. hold += (unsigned long)(PUP(in)) << bits;
  76167. bits += 8;
  76168. }
  76169. len += (unsigned)hold & ((1U << op) - 1);
  76170. hold >>= op;
  76171. bits -= op;
  76172. }
  76173. Tracevv((stderr, "inflate: length %u\n", len));
  76174. if (bits < 15) {
  76175. hold += (unsigned long)(PUP(in)) << bits;
  76176. bits += 8;
  76177. hold += (unsigned long)(PUP(in)) << bits;
  76178. bits += 8;
  76179. }
  76180. thisx = dcode[hold & dmask];
  76181. dodist:
  76182. op = (unsigned)(thisx.bits);
  76183. hold >>= op;
  76184. bits -= op;
  76185. op = (unsigned)(thisx.op);
  76186. if (op & 16) { /* distance base */
  76187. dist = (unsigned)(thisx.val);
  76188. op &= 15; /* number of extra bits */
  76189. if (bits < op) {
  76190. hold += (unsigned long)(PUP(in)) << bits;
  76191. bits += 8;
  76192. if (bits < op) {
  76193. hold += (unsigned long)(PUP(in)) << bits;
  76194. bits += 8;
  76195. }
  76196. }
  76197. dist += (unsigned)hold & ((1U << op) - 1);
  76198. #ifdef INFLATE_STRICT
  76199. if (dist > dmax) {
  76200. strm->msg = (char *)"invalid distance too far back";
  76201. state->mode = BAD;
  76202. break;
  76203. }
  76204. #endif
  76205. hold >>= op;
  76206. bits -= op;
  76207. Tracevv((stderr, "inflate: distance %u\n", dist));
  76208. op = (unsigned)(out - beg); /* max distance in output */
  76209. if (dist > op) { /* see if copy from window */
  76210. op = dist - op; /* distance back in window */
  76211. if (op > whave) {
  76212. strm->msg = (char *)"invalid distance too far back";
  76213. state->mode = BAD;
  76214. break;
  76215. }
  76216. from = window - OFF;
  76217. if (write == 0) { /* very common case */
  76218. from += wsize - op;
  76219. if (op < len) { /* some from window */
  76220. len -= op;
  76221. do {
  76222. PUP(out) = PUP(from);
  76223. } while (--op);
  76224. from = out - dist; /* rest from output */
  76225. }
  76226. }
  76227. else if (write < op) { /* wrap around window */
  76228. from += wsize + write - op;
  76229. op -= write;
  76230. if (op < len) { /* some from end of window */
  76231. len -= op;
  76232. do {
  76233. PUP(out) = PUP(from);
  76234. } while (--op);
  76235. from = window - OFF;
  76236. if (write < len) { /* some from start of window */
  76237. op = write;
  76238. len -= op;
  76239. do {
  76240. PUP(out) = PUP(from);
  76241. } while (--op);
  76242. from = out - dist; /* rest from output */
  76243. }
  76244. }
  76245. }
  76246. else { /* contiguous in window */
  76247. from += write - op;
  76248. if (op < len) { /* some from window */
  76249. len -= op;
  76250. do {
  76251. PUP(out) = PUP(from);
  76252. } while (--op);
  76253. from = out - dist; /* rest from output */
  76254. }
  76255. }
  76256. while (len > 2) {
  76257. PUP(out) = PUP(from);
  76258. PUP(out) = PUP(from);
  76259. PUP(out) = PUP(from);
  76260. len -= 3;
  76261. }
  76262. if (len) {
  76263. PUP(out) = PUP(from);
  76264. if (len > 1)
  76265. PUP(out) = PUP(from);
  76266. }
  76267. }
  76268. else {
  76269. from = out - dist; /* copy direct from output */
  76270. do { /* minimum length is three */
  76271. PUP(out) = PUP(from);
  76272. PUP(out) = PUP(from);
  76273. PUP(out) = PUP(from);
  76274. len -= 3;
  76275. } while (len > 2);
  76276. if (len) {
  76277. PUP(out) = PUP(from);
  76278. if (len > 1)
  76279. PUP(out) = PUP(from);
  76280. }
  76281. }
  76282. }
  76283. else if ((op & 64) == 0) { /* 2nd level distance code */
  76284. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  76285. goto dodist;
  76286. }
  76287. else {
  76288. strm->msg = (char *)"invalid distance code";
  76289. state->mode = BAD;
  76290. break;
  76291. }
  76292. }
  76293. else if ((op & 64) == 0) { /* 2nd level length code */
  76294. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  76295. goto dolen;
  76296. }
  76297. else if (op & 32) { /* end-of-block */
  76298. Tracevv((stderr, "inflate: end of block\n"));
  76299. state->mode = TYPE;
  76300. break;
  76301. }
  76302. else {
  76303. strm->msg = (char *)"invalid literal/length code";
  76304. state->mode = BAD;
  76305. break;
  76306. }
  76307. } while (in < last && out < end);
  76308. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  76309. len = bits >> 3;
  76310. in -= len;
  76311. bits -= len << 3;
  76312. hold &= (1U << bits) - 1;
  76313. /* update state and return */
  76314. strm->next_in = in + OFF;
  76315. strm->next_out = out + OFF;
  76316. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  76317. strm->avail_out = (unsigned)(out < end ?
  76318. 257 + (end - out) : 257 - (out - end));
  76319. state->hold = hold;
  76320. state->bits = bits;
  76321. return;
  76322. }
  76323. /*
  76324. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  76325. - Using bit fields for code structure
  76326. - Different op definition to avoid & for extra bits (do & for table bits)
  76327. - Three separate decoding do-loops for direct, window, and write == 0
  76328. - Special case for distance > 1 copies to do overlapped load and store copy
  76329. - Explicit branch predictions (based on measured branch probabilities)
  76330. - Deferring match copy and interspersed it with decoding subsequent codes
  76331. - Swapping literal/length else
  76332. - Swapping window/direct else
  76333. - Larger unrolled copy loops (three is about right)
  76334. - Moving len -= 3 statement into middle of loop
  76335. */
  76336. #endif /* !ASMINF */
  76337. /********* End of inlined file: inffast.c *********/
  76338. #undef PULLBYTE
  76339. #undef LOAD
  76340. #undef RESTORE
  76341. #undef INITBITS
  76342. #undef NEEDBITS
  76343. #undef DROPBITS
  76344. #undef BYTEBITS
  76345. /********* Start of inlined file: inflate.c *********/
  76346. /*
  76347. * Change history:
  76348. *
  76349. * 1.2.beta0 24 Nov 2002
  76350. * - First version -- complete rewrite of inflate to simplify code, avoid
  76351. * creation of window when not needed, minimize use of window when it is
  76352. * needed, make inffast.c even faster, implement gzip decoding, and to
  76353. * improve code readability and style over the previous zlib inflate code
  76354. *
  76355. * 1.2.beta1 25 Nov 2002
  76356. * - Use pointers for available input and output checking in inffast.c
  76357. * - Remove input and output counters in inffast.c
  76358. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  76359. * - Remove unnecessary second byte pull from length extra in inffast.c
  76360. * - Unroll direct copy to three copies per loop in inffast.c
  76361. *
  76362. * 1.2.beta2 4 Dec 2002
  76363. * - Change external routine names to reduce potential conflicts
  76364. * - Correct filename to inffixed.h for fixed tables in inflate.c
  76365. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  76366. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  76367. * to avoid negation problem on Alphas (64 bit) in inflate.c
  76368. *
  76369. * 1.2.beta3 22 Dec 2002
  76370. * - Add comments on state->bits assertion in inffast.c
  76371. * - Add comments on op field in inftrees.h
  76372. * - Fix bug in reuse of allocated window after inflateReset()
  76373. * - Remove bit fields--back to byte structure for speed
  76374. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  76375. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  76376. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  76377. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  76378. * - Use local copies of stream next and avail values, as well as local bit
  76379. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  76380. *
  76381. * 1.2.beta4 1 Jan 2003
  76382. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  76383. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  76384. * - Add comments in inffast.c to introduce the inflate_fast() routine
  76385. * - Rearrange window copies in inflate_fast() for speed and simplification
  76386. * - Unroll last copy for window match in inflate_fast()
  76387. * - Use local copies of window variables in inflate_fast() for speed
  76388. * - Pull out common write == 0 case for speed in inflate_fast()
  76389. * - Make op and len in inflate_fast() unsigned for consistency
  76390. * - Add FAR to lcode and dcode declarations in inflate_fast()
  76391. * - Simplified bad distance check in inflate_fast()
  76392. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  76393. * source file infback.c to provide a call-back interface to inflate for
  76394. * programs like gzip and unzip -- uses window as output buffer to avoid
  76395. * window copying
  76396. *
  76397. * 1.2.beta5 1 Jan 2003
  76398. * - Improved inflateBack() interface to allow the caller to provide initial
  76399. * input in strm.
  76400. * - Fixed stored blocks bug in inflateBack()
  76401. *
  76402. * 1.2.beta6 4 Jan 2003
  76403. * - Added comments in inffast.c on effectiveness of POSTINC
  76404. * - Typecasting all around to reduce compiler warnings
  76405. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  76406. * make compilers happy
  76407. * - Changed type of window in inflateBackInit() to unsigned char *
  76408. *
  76409. * 1.2.beta7 27 Jan 2003
  76410. * - Changed many types to unsigned or unsigned short to avoid warnings
  76411. * - Added inflateCopy() function
  76412. *
  76413. * 1.2.0 9 Mar 2003
  76414. * - Changed inflateBack() interface to provide separate opaque descriptors
  76415. * for the in() and out() functions
  76416. * - Changed inflateBack() argument and in_func typedef to swap the length
  76417. * and buffer address return values for the input function
  76418. * - Check next_in and next_out for Z_NULL on entry to inflate()
  76419. *
  76420. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  76421. */
  76422. /********* Start of inlined file: inffast.h *********/
  76423. /* WARNING: this file should *not* be used by applications. It is
  76424. part of the implementation of the compression library and is
  76425. subject to change. Applications should only use zlib.h.
  76426. */
  76427. void inflate_fast OF((z_streamp strm, unsigned start));
  76428. /********* End of inlined file: inffast.h *********/
  76429. #ifdef MAKEFIXED
  76430. # ifndef BUILDFIXED
  76431. # define BUILDFIXED
  76432. # endif
  76433. #endif
  76434. /* function prototypes */
  76435. local void fixedtables OF((struct inflate_state FAR *state));
  76436. local int updatewindow OF((z_streamp strm, unsigned out));
  76437. #ifdef BUILDFIXED
  76438. void makefixed OF((void));
  76439. #endif
  76440. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  76441. unsigned len));
  76442. int ZEXPORT inflateReset (z_streamp strm)
  76443. {
  76444. struct inflate_state FAR *state;
  76445. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76446. state = (struct inflate_state FAR *)strm->state;
  76447. strm->total_in = strm->total_out = state->total = 0;
  76448. strm->msg = Z_NULL;
  76449. strm->adler = 1; /* to support ill-conceived Java test suite */
  76450. state->mode = HEAD;
  76451. state->last = 0;
  76452. state->havedict = 0;
  76453. state->dmax = 32768U;
  76454. state->head = Z_NULL;
  76455. state->wsize = 0;
  76456. state->whave = 0;
  76457. state->write = 0;
  76458. state->hold = 0;
  76459. state->bits = 0;
  76460. state->lencode = state->distcode = state->next = state->codes;
  76461. Tracev((stderr, "inflate: reset\n"));
  76462. return Z_OK;
  76463. }
  76464. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  76465. {
  76466. struct inflate_state FAR *state;
  76467. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76468. state = (struct inflate_state FAR *)strm->state;
  76469. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  76470. value &= (1L << bits) - 1;
  76471. state->hold += value << state->bits;
  76472. state->bits += bits;
  76473. return Z_OK;
  76474. }
  76475. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  76476. {
  76477. struct inflate_state FAR *state;
  76478. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76479. stream_size != (int)(sizeof(z_stream)))
  76480. return Z_VERSION_ERROR;
  76481. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76482. strm->msg = Z_NULL; /* in case we return an error */
  76483. if (strm->zalloc == (alloc_func)0) {
  76484. strm->zalloc = zcalloc;
  76485. strm->opaque = (voidpf)0;
  76486. }
  76487. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76488. state = (struct inflate_state FAR *)
  76489. ZALLOC(strm, 1, sizeof(struct inflate_state));
  76490. if (state == Z_NULL) return Z_MEM_ERROR;
  76491. Tracev((stderr, "inflate: allocated\n"));
  76492. strm->state = (struct internal_state FAR *)state;
  76493. if (windowBits < 0) {
  76494. state->wrap = 0;
  76495. windowBits = -windowBits;
  76496. }
  76497. else {
  76498. state->wrap = (windowBits >> 4) + 1;
  76499. #ifdef GUNZIP
  76500. if (windowBits < 48) windowBits &= 15;
  76501. #endif
  76502. }
  76503. if (windowBits < 8 || windowBits > 15) {
  76504. ZFREE(strm, state);
  76505. strm->state = Z_NULL;
  76506. return Z_STREAM_ERROR;
  76507. }
  76508. state->wbits = (unsigned)windowBits;
  76509. state->window = Z_NULL;
  76510. return inflateReset(strm);
  76511. }
  76512. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  76513. {
  76514. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  76515. }
  76516. /*
  76517. Return state with length and distance decoding tables and index sizes set to
  76518. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76519. If BUILDFIXED is defined, then instead this routine builds the tables the
  76520. first time it's called, and returns those tables the first time and
  76521. thereafter. This reduces the size of the code by about 2K bytes, in
  76522. exchange for a little execution time. However, BUILDFIXED should not be
  76523. used for threaded applications, since the rewriting of the tables and virgin
  76524. may not be thread-safe.
  76525. */
  76526. local void fixedtables (struct inflate_state FAR *state)
  76527. {
  76528. #ifdef BUILDFIXED
  76529. static int virgin = 1;
  76530. static code *lenfix, *distfix;
  76531. static code fixed[544];
  76532. /* build fixed huffman tables if first call (may not be thread safe) */
  76533. if (virgin) {
  76534. unsigned sym, bits;
  76535. static code *next;
  76536. /* literal/length table */
  76537. sym = 0;
  76538. while (sym < 144) state->lens[sym++] = 8;
  76539. while (sym < 256) state->lens[sym++] = 9;
  76540. while (sym < 280) state->lens[sym++] = 7;
  76541. while (sym < 288) state->lens[sym++] = 8;
  76542. next = fixed;
  76543. lenfix = next;
  76544. bits = 9;
  76545. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76546. /* distance table */
  76547. sym = 0;
  76548. while (sym < 32) state->lens[sym++] = 5;
  76549. distfix = next;
  76550. bits = 5;
  76551. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76552. /* do this just once */
  76553. virgin = 0;
  76554. }
  76555. #else /* !BUILDFIXED */
  76556. /********* Start of inlined file: inffixed.h *********/
  76557. /* inffixed.h -- table for decoding fixed codes
  76558. * Generated automatically by makefixed().
  76559. */
  76560. /* WARNING: this file should *not* be used by applications. It
  76561. is part of the implementation of the compression library and
  76562. is subject to change. Applications should only use zlib.h.
  76563. */
  76564. static const code lenfix[512] = {
  76565. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76566. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76567. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76568. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76569. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76570. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76571. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76572. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76573. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76574. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76575. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76576. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76577. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76578. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76579. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76580. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76581. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76582. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76583. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76584. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76585. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76586. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76587. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76588. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76589. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76590. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76591. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76592. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76593. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76594. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76595. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76596. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76597. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76598. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76599. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76600. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76601. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76602. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76603. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76604. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76605. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76606. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76607. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76608. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76609. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76610. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76611. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76612. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76613. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76614. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76615. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76616. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76617. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76618. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76619. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76620. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76621. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76622. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76623. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76624. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76625. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76626. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76627. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76628. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76629. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76630. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76631. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76632. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76633. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76634. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76635. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76636. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76637. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76638. {0,9,255}
  76639. };
  76640. static const code distfix[32] = {
  76641. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76642. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76643. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76644. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76645. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76646. {22,5,193},{64,5,0}
  76647. };
  76648. /********* End of inlined file: inffixed.h *********/
  76649. #endif /* BUILDFIXED */
  76650. state->lencode = lenfix;
  76651. state->lenbits = 9;
  76652. state->distcode = distfix;
  76653. state->distbits = 5;
  76654. }
  76655. #ifdef MAKEFIXED
  76656. #include <stdio.h>
  76657. /*
  76658. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  76659. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  76660. those tables to stdout, which would be piped to inffixed.h. A small program
  76661. can simply call makefixed to do this:
  76662. void makefixed(void);
  76663. int main(void)
  76664. {
  76665. makefixed();
  76666. return 0;
  76667. }
  76668. Then that can be linked with zlib built with MAKEFIXED defined and run:
  76669. a.out > inffixed.h
  76670. */
  76671. void makefixed()
  76672. {
  76673. unsigned low, size;
  76674. struct inflate_state state;
  76675. fixedtables(&state);
  76676. puts(" /* inffixed.h -- table for decoding fixed codes");
  76677. puts(" * Generated automatically by makefixed().");
  76678. puts(" */");
  76679. puts("");
  76680. puts(" /* WARNING: this file should *not* be used by applications.");
  76681. puts(" It is part of the implementation of this library and is");
  76682. puts(" subject to change. Applications should only use zlib.h.");
  76683. puts(" */");
  76684. puts("");
  76685. size = 1U << 9;
  76686. printf(" static const code lenfix[%u] = {", size);
  76687. low = 0;
  76688. for (;;) {
  76689. if ((low % 7) == 0) printf("\n ");
  76690. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  76691. state.lencode[low].val);
  76692. if (++low == size) break;
  76693. putchar(',');
  76694. }
  76695. puts("\n };");
  76696. size = 1U << 5;
  76697. printf("\n static const code distfix[%u] = {", size);
  76698. low = 0;
  76699. for (;;) {
  76700. if ((low % 6) == 0) printf("\n ");
  76701. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  76702. state.distcode[low].val);
  76703. if (++low == size) break;
  76704. putchar(',');
  76705. }
  76706. puts("\n };");
  76707. }
  76708. #endif /* MAKEFIXED */
  76709. /*
  76710. Update the window with the last wsize (normally 32K) bytes written before
  76711. returning. If window does not exist yet, create it. This is only called
  76712. when a window is already in use, or when output has been written during this
  76713. inflate call, but the end of the deflate stream has not been reached yet.
  76714. It is also called to create a window for dictionary data when a dictionary
  76715. is loaded.
  76716. Providing output buffers larger than 32K to inflate() should provide a speed
  76717. advantage, since only the last 32K of output is copied to the sliding window
  76718. upon return from inflate(), and since all distances after the first 32K of
  76719. output will fall in the output data, making match copies simpler and faster.
  76720. The advantage may be dependent on the size of the processor's data caches.
  76721. */
  76722. local int updatewindow (z_streamp strm, unsigned out)
  76723. {
  76724. struct inflate_state FAR *state;
  76725. unsigned copy, dist;
  76726. state = (struct inflate_state FAR *)strm->state;
  76727. /* if it hasn't been done already, allocate space for the window */
  76728. if (state->window == Z_NULL) {
  76729. state->window = (unsigned char FAR *)
  76730. ZALLOC(strm, 1U << state->wbits,
  76731. sizeof(unsigned char));
  76732. if (state->window == Z_NULL) return 1;
  76733. }
  76734. /* if window not in use yet, initialize */
  76735. if (state->wsize == 0) {
  76736. state->wsize = 1U << state->wbits;
  76737. state->write = 0;
  76738. state->whave = 0;
  76739. }
  76740. /* copy state->wsize or less output bytes into the circular window */
  76741. copy = out - strm->avail_out;
  76742. if (copy >= state->wsize) {
  76743. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  76744. state->write = 0;
  76745. state->whave = state->wsize;
  76746. }
  76747. else {
  76748. dist = state->wsize - state->write;
  76749. if (dist > copy) dist = copy;
  76750. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  76751. copy -= dist;
  76752. if (copy) {
  76753. zmemcpy(state->window, strm->next_out - copy, copy);
  76754. state->write = copy;
  76755. state->whave = state->wsize;
  76756. }
  76757. else {
  76758. state->write += dist;
  76759. if (state->write == state->wsize) state->write = 0;
  76760. if (state->whave < state->wsize) state->whave += dist;
  76761. }
  76762. }
  76763. return 0;
  76764. }
  76765. /* Macros for inflate(): */
  76766. /* check function to use adler32() for zlib or crc32() for gzip */
  76767. #ifdef GUNZIP
  76768. # define UPDATE(check, buf, len) \
  76769. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  76770. #else
  76771. # define UPDATE(check, buf, len) adler32(check, buf, len)
  76772. #endif
  76773. /* check macros for header crc */
  76774. #ifdef GUNZIP
  76775. # define CRC2(check, word) \
  76776. do { \
  76777. hbuf[0] = (unsigned char)(word); \
  76778. hbuf[1] = (unsigned char)((word) >> 8); \
  76779. check = crc32(check, hbuf, 2); \
  76780. } while (0)
  76781. # define CRC4(check, word) \
  76782. do { \
  76783. hbuf[0] = (unsigned char)(word); \
  76784. hbuf[1] = (unsigned char)((word) >> 8); \
  76785. hbuf[2] = (unsigned char)((word) >> 16); \
  76786. hbuf[3] = (unsigned char)((word) >> 24); \
  76787. check = crc32(check, hbuf, 4); \
  76788. } while (0)
  76789. #endif
  76790. /* Load registers with state in inflate() for speed */
  76791. #define LOAD() \
  76792. do { \
  76793. put = strm->next_out; \
  76794. left = strm->avail_out; \
  76795. next = strm->next_in; \
  76796. have = strm->avail_in; \
  76797. hold = state->hold; \
  76798. bits = state->bits; \
  76799. } while (0)
  76800. /* Restore state from registers in inflate() */
  76801. #define RESTORE() \
  76802. do { \
  76803. strm->next_out = put; \
  76804. strm->avail_out = left; \
  76805. strm->next_in = next; \
  76806. strm->avail_in = have; \
  76807. state->hold = hold; \
  76808. state->bits = bits; \
  76809. } while (0)
  76810. /* Clear the input bit accumulator */
  76811. #define INITBITS() \
  76812. do { \
  76813. hold = 0; \
  76814. bits = 0; \
  76815. } while (0)
  76816. /* Get a byte of input into the bit accumulator, or return from inflate()
  76817. if there is no input available. */
  76818. #define PULLBYTE() \
  76819. do { \
  76820. if (have == 0) goto inf_leave; \
  76821. have--; \
  76822. hold += (unsigned long)(*next++) << bits; \
  76823. bits += 8; \
  76824. } while (0)
  76825. /* Assure that there are at least n bits in the bit accumulator. If there is
  76826. not enough available input to do that, then return from inflate(). */
  76827. #define NEEDBITS(n) \
  76828. do { \
  76829. while (bits < (unsigned)(n)) \
  76830. PULLBYTE(); \
  76831. } while (0)
  76832. /* Return the low n bits of the bit accumulator (n < 16) */
  76833. #define BITS(n) \
  76834. ((unsigned)hold & ((1U << (n)) - 1))
  76835. /* Remove n bits from the bit accumulator */
  76836. #define DROPBITS(n) \
  76837. do { \
  76838. hold >>= (n); \
  76839. bits -= (unsigned)(n); \
  76840. } while (0)
  76841. /* Remove zero to seven bits as needed to go to a byte boundary */
  76842. #define BYTEBITS() \
  76843. do { \
  76844. hold >>= bits & 7; \
  76845. bits -= bits & 7; \
  76846. } while (0)
  76847. /* Reverse the bytes in a 32-bit value */
  76848. #define REVERSE(q) \
  76849. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  76850. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  76851. /*
  76852. inflate() uses a state machine to process as much input data and generate as
  76853. much output data as possible before returning. The state machine is
  76854. structured roughly as follows:
  76855. for (;;) switch (state) {
  76856. ...
  76857. case STATEn:
  76858. if (not enough input data or output space to make progress)
  76859. return;
  76860. ... make progress ...
  76861. state = STATEm;
  76862. break;
  76863. ...
  76864. }
  76865. so when inflate() is called again, the same case is attempted again, and
  76866. if the appropriate resources are provided, the machine proceeds to the
  76867. next state. The NEEDBITS() macro is usually the way the state evaluates
  76868. whether it can proceed or should return. NEEDBITS() does the return if
  76869. the requested bits are not available. The typical use of the BITS macros
  76870. is:
  76871. NEEDBITS(n);
  76872. ... do something with BITS(n) ...
  76873. DROPBITS(n);
  76874. where NEEDBITS(n) either returns from inflate() if there isn't enough
  76875. input left to load n bits into the accumulator, or it continues. BITS(n)
  76876. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  76877. the low n bits off the accumulator. INITBITS() clears the accumulator
  76878. and sets the number of available bits to zero. BYTEBITS() discards just
  76879. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  76880. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  76881. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  76882. if there is no input available. The decoding of variable length codes uses
  76883. PULLBYTE() directly in order to pull just enough bytes to decode the next
  76884. code, and no more.
  76885. Some states loop until they get enough input, making sure that enough
  76886. state information is maintained to continue the loop where it left off
  76887. if NEEDBITS() returns in the loop. For example, want, need, and keep
  76888. would all have to actually be part of the saved state in case NEEDBITS()
  76889. returns:
  76890. case STATEw:
  76891. while (want < need) {
  76892. NEEDBITS(n);
  76893. keep[want++] = BITS(n);
  76894. DROPBITS(n);
  76895. }
  76896. state = STATEx;
  76897. case STATEx:
  76898. As shown above, if the next state is also the next case, then the break
  76899. is omitted.
  76900. A state may also return if there is not enough output space available to
  76901. complete that state. Those states are copying stored data, writing a
  76902. literal byte, and copying a matching string.
  76903. When returning, a "goto inf_leave" is used to update the total counters,
  76904. update the check value, and determine whether any progress has been made
  76905. during that inflate() call in order to return the proper return code.
  76906. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  76907. When there is a window, goto inf_leave will update the window with the last
  76908. output written. If a goto inf_leave occurs in the middle of decompression
  76909. and there is no window currently, goto inf_leave will create one and copy
  76910. output to the window for the next call of inflate().
  76911. In this implementation, the flush parameter of inflate() only affects the
  76912. return code (per zlib.h). inflate() always writes as much as possible to
  76913. strm->next_out, given the space available and the provided input--the effect
  76914. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  76915. the allocation of and copying into a sliding window until necessary, which
  76916. provides the effect documented in zlib.h for Z_FINISH when the entire input
  76917. stream available. So the only thing the flush parameter actually does is:
  76918. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  76919. will return Z_BUF_ERROR if it has not reached the end of the stream.
  76920. */
  76921. int ZEXPORT inflate (z_streamp strm, int flush)
  76922. {
  76923. struct inflate_state FAR *state;
  76924. unsigned char FAR *next; /* next input */
  76925. unsigned char FAR *put; /* next output */
  76926. unsigned have, left; /* available input and output */
  76927. unsigned long hold; /* bit buffer */
  76928. unsigned bits; /* bits in bit buffer */
  76929. unsigned in, out; /* save starting available input and output */
  76930. unsigned copy; /* number of stored or match bytes to copy */
  76931. unsigned char FAR *from; /* where to copy match bytes from */
  76932. code thisx; /* current decoding table entry */
  76933. code last; /* parent table entry */
  76934. unsigned len; /* length to copy for repeats, bits to drop */
  76935. int ret; /* return code */
  76936. #ifdef GUNZIP
  76937. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  76938. #endif
  76939. static const unsigned short order[19] = /* permutation of code lengths */
  76940. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76941. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  76942. (strm->next_in == Z_NULL && strm->avail_in != 0))
  76943. return Z_STREAM_ERROR;
  76944. state = (struct inflate_state FAR *)strm->state;
  76945. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  76946. LOAD();
  76947. in = have;
  76948. out = left;
  76949. ret = Z_OK;
  76950. for (;;)
  76951. switch (state->mode) {
  76952. case HEAD:
  76953. if (state->wrap == 0) {
  76954. state->mode = TYPEDO;
  76955. break;
  76956. }
  76957. NEEDBITS(16);
  76958. #ifdef GUNZIP
  76959. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  76960. state->check = crc32(0L, Z_NULL, 0);
  76961. CRC2(state->check, hold);
  76962. INITBITS();
  76963. state->mode = FLAGS;
  76964. break;
  76965. }
  76966. state->flags = 0; /* expect zlib header */
  76967. if (state->head != Z_NULL)
  76968. state->head->done = -1;
  76969. if (!(state->wrap & 1) || /* check if zlib header allowed */
  76970. #else
  76971. if (
  76972. #endif
  76973. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  76974. strm->msg = (char *)"incorrect header check";
  76975. state->mode = BAD;
  76976. break;
  76977. }
  76978. if (BITS(4) != Z_DEFLATED) {
  76979. strm->msg = (char *)"unknown compression method";
  76980. state->mode = BAD;
  76981. break;
  76982. }
  76983. DROPBITS(4);
  76984. len = BITS(4) + 8;
  76985. if (len > state->wbits) {
  76986. strm->msg = (char *)"invalid window size";
  76987. state->mode = BAD;
  76988. break;
  76989. }
  76990. state->dmax = 1U << len;
  76991. Tracev((stderr, "inflate: zlib header ok\n"));
  76992. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  76993. state->mode = hold & 0x200 ? DICTID : TYPE;
  76994. INITBITS();
  76995. break;
  76996. #ifdef GUNZIP
  76997. case FLAGS:
  76998. NEEDBITS(16);
  76999. state->flags = (int)(hold);
  77000. if ((state->flags & 0xff) != Z_DEFLATED) {
  77001. strm->msg = (char *)"unknown compression method";
  77002. state->mode = BAD;
  77003. break;
  77004. }
  77005. if (state->flags & 0xe000) {
  77006. strm->msg = (char *)"unknown header flags set";
  77007. state->mode = BAD;
  77008. break;
  77009. }
  77010. if (state->head != Z_NULL)
  77011. state->head->text = (int)((hold >> 8) & 1);
  77012. if (state->flags & 0x0200) CRC2(state->check, hold);
  77013. INITBITS();
  77014. state->mode = TIME;
  77015. case TIME:
  77016. NEEDBITS(32);
  77017. if (state->head != Z_NULL)
  77018. state->head->time = hold;
  77019. if (state->flags & 0x0200) CRC4(state->check, hold);
  77020. INITBITS();
  77021. state->mode = OS;
  77022. case OS:
  77023. NEEDBITS(16);
  77024. if (state->head != Z_NULL) {
  77025. state->head->xflags = (int)(hold & 0xff);
  77026. state->head->os = (int)(hold >> 8);
  77027. }
  77028. if (state->flags & 0x0200) CRC2(state->check, hold);
  77029. INITBITS();
  77030. state->mode = EXLEN;
  77031. case EXLEN:
  77032. if (state->flags & 0x0400) {
  77033. NEEDBITS(16);
  77034. state->length = (unsigned)(hold);
  77035. if (state->head != Z_NULL)
  77036. state->head->extra_len = (unsigned)hold;
  77037. if (state->flags & 0x0200) CRC2(state->check, hold);
  77038. INITBITS();
  77039. }
  77040. else if (state->head != Z_NULL)
  77041. state->head->extra = Z_NULL;
  77042. state->mode = EXTRA;
  77043. case EXTRA:
  77044. if (state->flags & 0x0400) {
  77045. copy = state->length;
  77046. if (copy > have) copy = have;
  77047. if (copy) {
  77048. if (state->head != Z_NULL &&
  77049. state->head->extra != Z_NULL) {
  77050. len = state->head->extra_len - state->length;
  77051. zmemcpy(state->head->extra + len, next,
  77052. len + copy > state->head->extra_max ?
  77053. state->head->extra_max - len : copy);
  77054. }
  77055. if (state->flags & 0x0200)
  77056. state->check = crc32(state->check, next, copy);
  77057. have -= copy;
  77058. next += copy;
  77059. state->length -= copy;
  77060. }
  77061. if (state->length) goto inf_leave;
  77062. }
  77063. state->length = 0;
  77064. state->mode = NAME;
  77065. case NAME:
  77066. if (state->flags & 0x0800) {
  77067. if (have == 0) goto inf_leave;
  77068. copy = 0;
  77069. do {
  77070. len = (unsigned)(next[copy++]);
  77071. if (state->head != Z_NULL &&
  77072. state->head->name != Z_NULL &&
  77073. state->length < state->head->name_max)
  77074. state->head->name[state->length++] = len;
  77075. } while (len && copy < have);
  77076. if (state->flags & 0x0200)
  77077. state->check = crc32(state->check, next, copy);
  77078. have -= copy;
  77079. next += copy;
  77080. if (len) goto inf_leave;
  77081. }
  77082. else if (state->head != Z_NULL)
  77083. state->head->name = Z_NULL;
  77084. state->length = 0;
  77085. state->mode = COMMENT;
  77086. case COMMENT:
  77087. if (state->flags & 0x1000) {
  77088. if (have == 0) goto inf_leave;
  77089. copy = 0;
  77090. do {
  77091. len = (unsigned)(next[copy++]);
  77092. if (state->head != Z_NULL &&
  77093. state->head->comment != Z_NULL &&
  77094. state->length < state->head->comm_max)
  77095. state->head->comment[state->length++] = len;
  77096. } while (len && copy < have);
  77097. if (state->flags & 0x0200)
  77098. state->check = crc32(state->check, next, copy);
  77099. have -= copy;
  77100. next += copy;
  77101. if (len) goto inf_leave;
  77102. }
  77103. else if (state->head != Z_NULL)
  77104. state->head->comment = Z_NULL;
  77105. state->mode = HCRC;
  77106. case HCRC:
  77107. if (state->flags & 0x0200) {
  77108. NEEDBITS(16);
  77109. if (hold != (state->check & 0xffff)) {
  77110. strm->msg = (char *)"header crc mismatch";
  77111. state->mode = BAD;
  77112. break;
  77113. }
  77114. INITBITS();
  77115. }
  77116. if (state->head != Z_NULL) {
  77117. state->head->hcrc = (int)((state->flags >> 9) & 1);
  77118. state->head->done = 1;
  77119. }
  77120. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  77121. state->mode = TYPE;
  77122. break;
  77123. #endif
  77124. case DICTID:
  77125. NEEDBITS(32);
  77126. strm->adler = state->check = REVERSE(hold);
  77127. INITBITS();
  77128. state->mode = DICT;
  77129. case DICT:
  77130. if (state->havedict == 0) {
  77131. RESTORE();
  77132. return Z_NEED_DICT;
  77133. }
  77134. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77135. state->mode = TYPE;
  77136. case TYPE:
  77137. if (flush == Z_BLOCK) goto inf_leave;
  77138. case TYPEDO:
  77139. if (state->last) {
  77140. BYTEBITS();
  77141. state->mode = CHECK;
  77142. break;
  77143. }
  77144. NEEDBITS(3);
  77145. state->last = BITS(1);
  77146. DROPBITS(1);
  77147. switch (BITS(2)) {
  77148. case 0: /* stored block */
  77149. Tracev((stderr, "inflate: stored block%s\n",
  77150. state->last ? " (last)" : ""));
  77151. state->mode = STORED;
  77152. break;
  77153. case 1: /* fixed block */
  77154. fixedtables(state);
  77155. Tracev((stderr, "inflate: fixed codes block%s\n",
  77156. state->last ? " (last)" : ""));
  77157. state->mode = LEN; /* decode codes */
  77158. break;
  77159. case 2: /* dynamic block */
  77160. Tracev((stderr, "inflate: dynamic codes block%s\n",
  77161. state->last ? " (last)" : ""));
  77162. state->mode = TABLE;
  77163. break;
  77164. case 3:
  77165. strm->msg = (char *)"invalid block type";
  77166. state->mode = BAD;
  77167. }
  77168. DROPBITS(2);
  77169. break;
  77170. case STORED:
  77171. BYTEBITS(); /* go to byte boundary */
  77172. NEEDBITS(32);
  77173. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  77174. strm->msg = (char *)"invalid stored block lengths";
  77175. state->mode = BAD;
  77176. break;
  77177. }
  77178. state->length = (unsigned)hold & 0xffff;
  77179. Tracev((stderr, "inflate: stored length %u\n",
  77180. state->length));
  77181. INITBITS();
  77182. state->mode = COPY;
  77183. case COPY:
  77184. copy = state->length;
  77185. if (copy) {
  77186. if (copy > have) copy = have;
  77187. if (copy > left) copy = left;
  77188. if (copy == 0) goto inf_leave;
  77189. zmemcpy(put, next, copy);
  77190. have -= copy;
  77191. next += copy;
  77192. left -= copy;
  77193. put += copy;
  77194. state->length -= copy;
  77195. break;
  77196. }
  77197. Tracev((stderr, "inflate: stored end\n"));
  77198. state->mode = TYPE;
  77199. break;
  77200. case TABLE:
  77201. NEEDBITS(14);
  77202. state->nlen = BITS(5) + 257;
  77203. DROPBITS(5);
  77204. state->ndist = BITS(5) + 1;
  77205. DROPBITS(5);
  77206. state->ncode = BITS(4) + 4;
  77207. DROPBITS(4);
  77208. #ifndef PKZIP_BUG_WORKAROUND
  77209. if (state->nlen > 286 || state->ndist > 30) {
  77210. strm->msg = (char *)"too many length or distance symbols";
  77211. state->mode = BAD;
  77212. break;
  77213. }
  77214. #endif
  77215. Tracev((stderr, "inflate: table sizes ok\n"));
  77216. state->have = 0;
  77217. state->mode = LENLENS;
  77218. case LENLENS:
  77219. while (state->have < state->ncode) {
  77220. NEEDBITS(3);
  77221. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  77222. DROPBITS(3);
  77223. }
  77224. while (state->have < 19)
  77225. state->lens[order[state->have++]] = 0;
  77226. state->next = state->codes;
  77227. state->lencode = (code const FAR *)(state->next);
  77228. state->lenbits = 7;
  77229. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  77230. &(state->lenbits), state->work);
  77231. if (ret) {
  77232. strm->msg = (char *)"invalid code lengths set";
  77233. state->mode = BAD;
  77234. break;
  77235. }
  77236. Tracev((stderr, "inflate: code lengths ok\n"));
  77237. state->have = 0;
  77238. state->mode = CODELENS;
  77239. case CODELENS:
  77240. while (state->have < state->nlen + state->ndist) {
  77241. for (;;) {
  77242. thisx = state->lencode[BITS(state->lenbits)];
  77243. if ((unsigned)(thisx.bits) <= bits) break;
  77244. PULLBYTE();
  77245. }
  77246. if (thisx.val < 16) {
  77247. NEEDBITS(thisx.bits);
  77248. DROPBITS(thisx.bits);
  77249. state->lens[state->have++] = thisx.val;
  77250. }
  77251. else {
  77252. if (thisx.val == 16) {
  77253. NEEDBITS(thisx.bits + 2);
  77254. DROPBITS(thisx.bits);
  77255. if (state->have == 0) {
  77256. strm->msg = (char *)"invalid bit length repeat";
  77257. state->mode = BAD;
  77258. break;
  77259. }
  77260. len = state->lens[state->have - 1];
  77261. copy = 3 + BITS(2);
  77262. DROPBITS(2);
  77263. }
  77264. else if (thisx.val == 17) {
  77265. NEEDBITS(thisx.bits + 3);
  77266. DROPBITS(thisx.bits);
  77267. len = 0;
  77268. copy = 3 + BITS(3);
  77269. DROPBITS(3);
  77270. }
  77271. else {
  77272. NEEDBITS(thisx.bits + 7);
  77273. DROPBITS(thisx.bits);
  77274. len = 0;
  77275. copy = 11 + BITS(7);
  77276. DROPBITS(7);
  77277. }
  77278. if (state->have + copy > state->nlen + state->ndist) {
  77279. strm->msg = (char *)"invalid bit length repeat";
  77280. state->mode = BAD;
  77281. break;
  77282. }
  77283. while (copy--)
  77284. state->lens[state->have++] = (unsigned short)len;
  77285. }
  77286. }
  77287. /* handle error breaks in while */
  77288. if (state->mode == BAD) break;
  77289. /* build code tables */
  77290. state->next = state->codes;
  77291. state->lencode = (code const FAR *)(state->next);
  77292. state->lenbits = 9;
  77293. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  77294. &(state->lenbits), state->work);
  77295. if (ret) {
  77296. strm->msg = (char *)"invalid literal/lengths set";
  77297. state->mode = BAD;
  77298. break;
  77299. }
  77300. state->distcode = (code const FAR *)(state->next);
  77301. state->distbits = 6;
  77302. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  77303. &(state->next), &(state->distbits), state->work);
  77304. if (ret) {
  77305. strm->msg = (char *)"invalid distances set";
  77306. state->mode = BAD;
  77307. break;
  77308. }
  77309. Tracev((stderr, "inflate: codes ok\n"));
  77310. state->mode = LEN;
  77311. case LEN:
  77312. if (have >= 6 && left >= 258) {
  77313. RESTORE();
  77314. inflate_fast(strm, out);
  77315. LOAD();
  77316. break;
  77317. }
  77318. for (;;) {
  77319. thisx = state->lencode[BITS(state->lenbits)];
  77320. if ((unsigned)(thisx.bits) <= bits) break;
  77321. PULLBYTE();
  77322. }
  77323. if (thisx.op && (thisx.op & 0xf0) == 0) {
  77324. last = thisx;
  77325. for (;;) {
  77326. thisx = state->lencode[last.val +
  77327. (BITS(last.bits + last.op) >> last.bits)];
  77328. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  77329. PULLBYTE();
  77330. }
  77331. DROPBITS(last.bits);
  77332. }
  77333. DROPBITS(thisx.bits);
  77334. state->length = (unsigned)thisx.val;
  77335. if ((int)(thisx.op) == 0) {
  77336. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  77337. "inflate: literal '%c'\n" :
  77338. "inflate: literal 0x%02x\n", thisx.val));
  77339. state->mode = LIT;
  77340. break;
  77341. }
  77342. if (thisx.op & 32) {
  77343. Tracevv((stderr, "inflate: end of block\n"));
  77344. state->mode = TYPE;
  77345. break;
  77346. }
  77347. if (thisx.op & 64) {
  77348. strm->msg = (char *)"invalid literal/length code";
  77349. state->mode = BAD;
  77350. break;
  77351. }
  77352. state->extra = (unsigned)(thisx.op) & 15;
  77353. state->mode = LENEXT;
  77354. case LENEXT:
  77355. if (state->extra) {
  77356. NEEDBITS(state->extra);
  77357. state->length += BITS(state->extra);
  77358. DROPBITS(state->extra);
  77359. }
  77360. Tracevv((stderr, "inflate: length %u\n", state->length));
  77361. state->mode = DIST;
  77362. case DIST:
  77363. for (;;) {
  77364. thisx = state->distcode[BITS(state->distbits)];
  77365. if ((unsigned)(thisx.bits) <= bits) break;
  77366. PULLBYTE();
  77367. }
  77368. if ((thisx.op & 0xf0) == 0) {
  77369. last = thisx;
  77370. for (;;) {
  77371. thisx = state->distcode[last.val +
  77372. (BITS(last.bits + last.op) >> last.bits)];
  77373. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  77374. PULLBYTE();
  77375. }
  77376. DROPBITS(last.bits);
  77377. }
  77378. DROPBITS(thisx.bits);
  77379. if (thisx.op & 64) {
  77380. strm->msg = (char *)"invalid distance code";
  77381. state->mode = BAD;
  77382. break;
  77383. }
  77384. state->offset = (unsigned)thisx.val;
  77385. state->extra = (unsigned)(thisx.op) & 15;
  77386. state->mode = DISTEXT;
  77387. case DISTEXT:
  77388. if (state->extra) {
  77389. NEEDBITS(state->extra);
  77390. state->offset += BITS(state->extra);
  77391. DROPBITS(state->extra);
  77392. }
  77393. #ifdef INFLATE_STRICT
  77394. if (state->offset > state->dmax) {
  77395. strm->msg = (char *)"invalid distance too far back";
  77396. state->mode = BAD;
  77397. break;
  77398. }
  77399. #endif
  77400. if (state->offset > state->whave + out - left) {
  77401. strm->msg = (char *)"invalid distance too far back";
  77402. state->mode = BAD;
  77403. break;
  77404. }
  77405. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  77406. state->mode = MATCH;
  77407. case MATCH:
  77408. if (left == 0) goto inf_leave;
  77409. copy = out - left;
  77410. if (state->offset > copy) { /* copy from window */
  77411. copy = state->offset - copy;
  77412. if (copy > state->write) {
  77413. copy -= state->write;
  77414. from = state->window + (state->wsize - copy);
  77415. }
  77416. else
  77417. from = state->window + (state->write - copy);
  77418. if (copy > state->length) copy = state->length;
  77419. }
  77420. else { /* copy from output */
  77421. from = put - state->offset;
  77422. copy = state->length;
  77423. }
  77424. if (copy > left) copy = left;
  77425. left -= copy;
  77426. state->length -= copy;
  77427. do {
  77428. *put++ = *from++;
  77429. } while (--copy);
  77430. if (state->length == 0) state->mode = LEN;
  77431. break;
  77432. case LIT:
  77433. if (left == 0) goto inf_leave;
  77434. *put++ = (unsigned char)(state->length);
  77435. left--;
  77436. state->mode = LEN;
  77437. break;
  77438. case CHECK:
  77439. if (state->wrap) {
  77440. NEEDBITS(32);
  77441. out -= left;
  77442. strm->total_out += out;
  77443. state->total += out;
  77444. if (out)
  77445. strm->adler = state->check =
  77446. UPDATE(state->check, put - out, out);
  77447. out = left;
  77448. if ((
  77449. #ifdef GUNZIP
  77450. state->flags ? hold :
  77451. #endif
  77452. REVERSE(hold)) != state->check) {
  77453. strm->msg = (char *)"incorrect data check";
  77454. state->mode = BAD;
  77455. break;
  77456. }
  77457. INITBITS();
  77458. Tracev((stderr, "inflate: check matches trailer\n"));
  77459. }
  77460. #ifdef GUNZIP
  77461. state->mode = LENGTH;
  77462. case LENGTH:
  77463. if (state->wrap && state->flags) {
  77464. NEEDBITS(32);
  77465. if (hold != (state->total & 0xffffffffUL)) {
  77466. strm->msg = (char *)"incorrect length check";
  77467. state->mode = BAD;
  77468. break;
  77469. }
  77470. INITBITS();
  77471. Tracev((stderr, "inflate: length matches trailer\n"));
  77472. }
  77473. #endif
  77474. state->mode = DONE;
  77475. case DONE:
  77476. ret = Z_STREAM_END;
  77477. goto inf_leave;
  77478. case BAD:
  77479. ret = Z_DATA_ERROR;
  77480. goto inf_leave;
  77481. case MEM:
  77482. return Z_MEM_ERROR;
  77483. case SYNC:
  77484. default:
  77485. return Z_STREAM_ERROR;
  77486. }
  77487. /*
  77488. Return from inflate(), updating the total counts and the check value.
  77489. If there was no progress during the inflate() call, return a buffer
  77490. error. Call updatewindow() to create and/or update the window state.
  77491. Note: a memory error from inflate() is non-recoverable.
  77492. */
  77493. inf_leave:
  77494. RESTORE();
  77495. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  77496. if (updatewindow(strm, out)) {
  77497. state->mode = MEM;
  77498. return Z_MEM_ERROR;
  77499. }
  77500. in -= strm->avail_in;
  77501. out -= strm->avail_out;
  77502. strm->total_in += in;
  77503. strm->total_out += out;
  77504. state->total += out;
  77505. if (state->wrap && out)
  77506. strm->adler = state->check =
  77507. UPDATE(state->check, strm->next_out - out, out);
  77508. strm->data_type = state->bits + (state->last ? 64 : 0) +
  77509. (state->mode == TYPE ? 128 : 0);
  77510. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  77511. ret = Z_BUF_ERROR;
  77512. return ret;
  77513. }
  77514. int ZEXPORT inflateEnd (z_streamp strm)
  77515. {
  77516. struct inflate_state FAR *state;
  77517. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  77518. return Z_STREAM_ERROR;
  77519. state = (struct inflate_state FAR *)strm->state;
  77520. if (state->window != Z_NULL) ZFREE(strm, state->window);
  77521. ZFREE(strm, strm->state);
  77522. strm->state = Z_NULL;
  77523. Tracev((stderr, "inflate: end\n"));
  77524. return Z_OK;
  77525. }
  77526. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77527. {
  77528. struct inflate_state FAR *state;
  77529. unsigned long id_;
  77530. /* check state */
  77531. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77532. state = (struct inflate_state FAR *)strm->state;
  77533. if (state->wrap != 0 && state->mode != DICT)
  77534. return Z_STREAM_ERROR;
  77535. /* check for correct dictionary id */
  77536. if (state->mode == DICT) {
  77537. id_ = adler32(0L, Z_NULL, 0);
  77538. id_ = adler32(id_, dictionary, dictLength);
  77539. if (id_ != state->check)
  77540. return Z_DATA_ERROR;
  77541. }
  77542. /* copy dictionary to window */
  77543. if (updatewindow(strm, strm->avail_out)) {
  77544. state->mode = MEM;
  77545. return Z_MEM_ERROR;
  77546. }
  77547. if (dictLength > state->wsize) {
  77548. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  77549. state->wsize);
  77550. state->whave = state->wsize;
  77551. }
  77552. else {
  77553. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  77554. dictLength);
  77555. state->whave = dictLength;
  77556. }
  77557. state->havedict = 1;
  77558. Tracev((stderr, "inflate: dictionary set\n"));
  77559. return Z_OK;
  77560. }
  77561. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  77562. {
  77563. struct inflate_state FAR *state;
  77564. /* check state */
  77565. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77566. state = (struct inflate_state FAR *)strm->state;
  77567. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  77568. /* save header structure */
  77569. state->head = head;
  77570. head->done = 0;
  77571. return Z_OK;
  77572. }
  77573. /*
  77574. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  77575. or when out of input. When called, *have is the number of pattern bytes
  77576. found in order so far, in 0..3. On return *have is updated to the new
  77577. state. If on return *have equals four, then the pattern was found and the
  77578. return value is how many bytes were read including the last byte of the
  77579. pattern. If *have is less than four, then the pattern has not been found
  77580. yet and the return value is len. In the latter case, syncsearch() can be
  77581. called again with more data and the *have state. *have is initialized to
  77582. zero for the first call.
  77583. */
  77584. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  77585. {
  77586. unsigned got;
  77587. unsigned next;
  77588. got = *have;
  77589. next = 0;
  77590. while (next < len && got < 4) {
  77591. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  77592. got++;
  77593. else if (buf[next])
  77594. got = 0;
  77595. else
  77596. got = 4 - got;
  77597. next++;
  77598. }
  77599. *have = got;
  77600. return next;
  77601. }
  77602. int ZEXPORT inflateSync (z_streamp strm)
  77603. {
  77604. unsigned len; /* number of bytes to look at or looked at */
  77605. unsigned long in, out; /* temporary to save total_in and total_out */
  77606. unsigned char buf[4]; /* to restore bit buffer to byte string */
  77607. struct inflate_state FAR *state;
  77608. /* check parameters */
  77609. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77610. state = (struct inflate_state FAR *)strm->state;
  77611. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  77612. /* if first time, start search in bit buffer */
  77613. if (state->mode != SYNC) {
  77614. state->mode = SYNC;
  77615. state->hold <<= state->bits & 7;
  77616. state->bits -= state->bits & 7;
  77617. len = 0;
  77618. while (state->bits >= 8) {
  77619. buf[len++] = (unsigned char)(state->hold);
  77620. state->hold >>= 8;
  77621. state->bits -= 8;
  77622. }
  77623. state->have = 0;
  77624. syncsearch(&(state->have), buf, len);
  77625. }
  77626. /* search available input */
  77627. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  77628. strm->avail_in -= len;
  77629. strm->next_in += len;
  77630. strm->total_in += len;
  77631. /* return no joy or set up to restart inflate() on a new block */
  77632. if (state->have != 4) return Z_DATA_ERROR;
  77633. in = strm->total_in; out = strm->total_out;
  77634. inflateReset(strm);
  77635. strm->total_in = in; strm->total_out = out;
  77636. state->mode = TYPE;
  77637. return Z_OK;
  77638. }
  77639. /*
  77640. Returns true if inflate is currently at the end of a block generated by
  77641. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  77642. implementation to provide an additional safety check. PPP uses
  77643. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  77644. block. When decompressing, PPP checks that at the end of input packet,
  77645. inflate is waiting for these length bytes.
  77646. */
  77647. int ZEXPORT inflateSyncPoint (z_streamp strm)
  77648. {
  77649. struct inflate_state FAR *state;
  77650. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77651. state = (struct inflate_state FAR *)strm->state;
  77652. return state->mode == STORED && state->bits == 0;
  77653. }
  77654. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  77655. {
  77656. struct inflate_state FAR *state;
  77657. struct inflate_state FAR *copy;
  77658. unsigned char FAR *window;
  77659. unsigned wsize;
  77660. /* check input */
  77661. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  77662. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  77663. return Z_STREAM_ERROR;
  77664. state = (struct inflate_state FAR *)source->state;
  77665. /* allocate space */
  77666. copy = (struct inflate_state FAR *)
  77667. ZALLOC(source, 1, sizeof(struct inflate_state));
  77668. if (copy == Z_NULL) return Z_MEM_ERROR;
  77669. window = Z_NULL;
  77670. if (state->window != Z_NULL) {
  77671. window = (unsigned char FAR *)
  77672. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  77673. if (window == Z_NULL) {
  77674. ZFREE(source, copy);
  77675. return Z_MEM_ERROR;
  77676. }
  77677. }
  77678. /* copy state */
  77679. zmemcpy(dest, source, sizeof(z_stream));
  77680. zmemcpy(copy, state, sizeof(struct inflate_state));
  77681. if (state->lencode >= state->codes &&
  77682. state->lencode <= state->codes + ENOUGH - 1) {
  77683. copy->lencode = copy->codes + (state->lencode - state->codes);
  77684. copy->distcode = copy->codes + (state->distcode - state->codes);
  77685. }
  77686. copy->next = copy->codes + (state->next - state->codes);
  77687. if (window != Z_NULL) {
  77688. wsize = 1U << state->wbits;
  77689. zmemcpy(window, state->window, wsize);
  77690. }
  77691. copy->window = window;
  77692. dest->state = (struct internal_state FAR *)copy;
  77693. return Z_OK;
  77694. }
  77695. /********* End of inlined file: inflate.c *********/
  77696. /********* Start of inlined file: inftrees.c *********/
  77697. #define MAXBITS 15
  77698. const char inflate_copyright[] =
  77699. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  77700. /*
  77701. If you use the zlib library in a product, an acknowledgment is welcome
  77702. in the documentation of your product. If for some reason you cannot
  77703. include such an acknowledgment, I would appreciate that you keep this
  77704. copyright string in the executable of your product.
  77705. */
  77706. /*
  77707. Build a set of tables to decode the provided canonical Huffman code.
  77708. The code lengths are lens[0..codes-1]. The result starts at *table,
  77709. whose indices are 0..2^bits-1. work is a writable array of at least
  77710. lens shorts, which is used as a work area. type is the type of code
  77711. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  77712. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  77713. on return points to the next available entry's address. bits is the
  77714. requested root table index bits, and on return it is the actual root
  77715. table index bits. It will differ if the request is greater than the
  77716. longest code or if it is less than the shortest code.
  77717. */
  77718. int inflate_table (codetype type,
  77719. unsigned short FAR *lens,
  77720. unsigned codes,
  77721. code FAR * FAR *table,
  77722. unsigned FAR *bits,
  77723. unsigned short FAR *work)
  77724. {
  77725. unsigned len; /* a code's length in bits */
  77726. unsigned sym; /* index of code symbols */
  77727. unsigned min, max; /* minimum and maximum code lengths */
  77728. unsigned root; /* number of index bits for root table */
  77729. unsigned curr; /* number of index bits for current table */
  77730. unsigned drop; /* code bits to drop for sub-table */
  77731. int left; /* number of prefix codes available */
  77732. unsigned used; /* code entries in table used */
  77733. unsigned huff; /* Huffman code */
  77734. unsigned incr; /* for incrementing code, index */
  77735. unsigned fill; /* index for replicating entries */
  77736. unsigned low; /* low bits for current root entry */
  77737. unsigned mask; /* mask for low root bits */
  77738. code thisx; /* table entry for duplication */
  77739. code FAR *next; /* next available space in table */
  77740. const unsigned short FAR *base; /* base value table to use */
  77741. const unsigned short FAR *extra; /* extra bits table to use */
  77742. int end; /* use base and extra for symbol > end */
  77743. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  77744. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  77745. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  77746. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  77747. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  77748. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  77749. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  77750. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  77751. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  77752. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  77753. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  77754. 8193, 12289, 16385, 24577, 0, 0};
  77755. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  77756. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  77757. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  77758. 28, 28, 29, 29, 64, 64};
  77759. /*
  77760. Process a set of code lengths to create a canonical Huffman code. The
  77761. code lengths are lens[0..codes-1]. Each length corresponds to the
  77762. symbols 0..codes-1. The Huffman code is generated by first sorting the
  77763. symbols by length from short to long, and retaining the symbol order
  77764. for codes with equal lengths. Then the code starts with all zero bits
  77765. for the first code of the shortest length, and the codes are integer
  77766. increments for the same length, and zeros are appended as the length
  77767. increases. For the deflate format, these bits are stored backwards
  77768. from their more natural integer increment ordering, and so when the
  77769. decoding tables are built in the large loop below, the integer codes
  77770. are incremented backwards.
  77771. This routine assumes, but does not check, that all of the entries in
  77772. lens[] are in the range 0..MAXBITS. The caller must assure this.
  77773. 1..MAXBITS is interpreted as that code length. zero means that that
  77774. symbol does not occur in this code.
  77775. The codes are sorted by computing a count of codes for each length,
  77776. creating from that a table of starting indices for each length in the
  77777. sorted table, and then entering the symbols in order in the sorted
  77778. table. The sorted table is work[], with that space being provided by
  77779. the caller.
  77780. The length counts are used for other purposes as well, i.e. finding
  77781. the minimum and maximum length codes, determining if there are any
  77782. codes at all, checking for a valid set of lengths, and looking ahead
  77783. at length counts to determine sub-table sizes when building the
  77784. decoding tables.
  77785. */
  77786. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  77787. for (len = 0; len <= MAXBITS; len++)
  77788. count[len] = 0;
  77789. for (sym = 0; sym < codes; sym++)
  77790. count[lens[sym]]++;
  77791. /* bound code lengths, force root to be within code lengths */
  77792. root = *bits;
  77793. for (max = MAXBITS; max >= 1; max--)
  77794. if (count[max] != 0) break;
  77795. if (root > max) root = max;
  77796. if (max == 0) { /* no symbols to code at all */
  77797. thisx.op = (unsigned char)64; /* invalid code marker */
  77798. thisx.bits = (unsigned char)1;
  77799. thisx.val = (unsigned short)0;
  77800. *(*table)++ = thisx; /* make a table to force an error */
  77801. *(*table)++ = thisx;
  77802. *bits = 1;
  77803. return 0; /* no symbols, but wait for decoding to report error */
  77804. }
  77805. for (min = 1; min <= MAXBITS; min++)
  77806. if (count[min] != 0) break;
  77807. if (root < min) root = min;
  77808. /* check for an over-subscribed or incomplete set of lengths */
  77809. left = 1;
  77810. for (len = 1; len <= MAXBITS; len++) {
  77811. left <<= 1;
  77812. left -= count[len];
  77813. if (left < 0) return -1; /* over-subscribed */
  77814. }
  77815. if (left > 0 && (type == CODES || max != 1))
  77816. return -1; /* incomplete set */
  77817. /* generate offsets into symbol table for each length for sorting */
  77818. offs[1] = 0;
  77819. for (len = 1; len < MAXBITS; len++)
  77820. offs[len + 1] = offs[len] + count[len];
  77821. /* sort symbols by length, by symbol order within each length */
  77822. for (sym = 0; sym < codes; sym++)
  77823. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  77824. /*
  77825. Create and fill in decoding tables. In this loop, the table being
  77826. filled is at next and has curr index bits. The code being used is huff
  77827. with length len. That code is converted to an index by dropping drop
  77828. bits off of the bottom. For codes where len is less than drop + curr,
  77829. those top drop + curr - len bits are incremented through all values to
  77830. fill the table with replicated entries.
  77831. root is the number of index bits for the root table. When len exceeds
  77832. root, sub-tables are created pointed to by the root entry with an index
  77833. of the low root bits of huff. This is saved in low to check for when a
  77834. new sub-table should be started. drop is zero when the root table is
  77835. being filled, and drop is root when sub-tables are being filled.
  77836. When a new sub-table is needed, it is necessary to look ahead in the
  77837. code lengths to determine what size sub-table is needed. The length
  77838. counts are used for this, and so count[] is decremented as codes are
  77839. entered in the tables.
  77840. used keeps track of how many table entries have been allocated from the
  77841. provided *table space. It is checked when a LENS table is being made
  77842. against the space in *table, ENOUGH, minus the maximum space needed by
  77843. the worst case distance code, MAXD. This should never happen, but the
  77844. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  77845. This assumes that when type == LENS, bits == 9.
  77846. sym increments through all symbols, and the loop terminates when
  77847. all codes of length max, i.e. all codes, have been processed. This
  77848. routine permits incomplete codes, so another loop after this one fills
  77849. in the rest of the decoding tables with invalid code markers.
  77850. */
  77851. /* set up for code type */
  77852. switch (type) {
  77853. case CODES:
  77854. base = extra = work; /* dummy value--not used */
  77855. end = 19;
  77856. break;
  77857. case LENS:
  77858. base = lbase;
  77859. base -= 257;
  77860. extra = lext;
  77861. extra -= 257;
  77862. end = 256;
  77863. break;
  77864. default: /* DISTS */
  77865. base = dbase;
  77866. extra = dext;
  77867. end = -1;
  77868. }
  77869. /* initialize state for loop */
  77870. huff = 0; /* starting code */
  77871. sym = 0; /* starting code symbol */
  77872. len = min; /* starting code length */
  77873. next = *table; /* current table to fill in */
  77874. curr = root; /* current table index bits */
  77875. drop = 0; /* current bits to drop from code for index */
  77876. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  77877. used = 1U << root; /* use root table entries */
  77878. mask = used - 1; /* mask for comparing low */
  77879. /* check available table space */
  77880. if (type == LENS && used >= ENOUGH - MAXD)
  77881. return 1;
  77882. /* process all codes and make table entries */
  77883. for (;;) {
  77884. /* create table entry */
  77885. thisx.bits = (unsigned char)(len - drop);
  77886. if ((int)(work[sym]) < end) {
  77887. thisx.op = (unsigned char)0;
  77888. thisx.val = work[sym];
  77889. }
  77890. else if ((int)(work[sym]) > end) {
  77891. thisx.op = (unsigned char)(extra[work[sym]]);
  77892. thisx.val = base[work[sym]];
  77893. }
  77894. else {
  77895. thisx.op = (unsigned char)(32 + 64); /* end of block */
  77896. thisx.val = 0;
  77897. }
  77898. /* replicate for those indices with low len bits equal to huff */
  77899. incr = 1U << (len - drop);
  77900. fill = 1U << curr;
  77901. min = fill; /* save offset to next table */
  77902. do {
  77903. fill -= incr;
  77904. next[(huff >> drop) + fill] = thisx;
  77905. } while (fill != 0);
  77906. /* backwards increment the len-bit code huff */
  77907. incr = 1U << (len - 1);
  77908. while (huff & incr)
  77909. incr >>= 1;
  77910. if (incr != 0) {
  77911. huff &= incr - 1;
  77912. huff += incr;
  77913. }
  77914. else
  77915. huff = 0;
  77916. /* go to next symbol, update count, len */
  77917. sym++;
  77918. if (--(count[len]) == 0) {
  77919. if (len == max) break;
  77920. len = lens[work[sym]];
  77921. }
  77922. /* create new sub-table if needed */
  77923. if (len > root && (huff & mask) != low) {
  77924. /* if first time, transition to sub-tables */
  77925. if (drop == 0)
  77926. drop = root;
  77927. /* increment past last table */
  77928. next += min; /* here min is 1 << curr */
  77929. /* determine length of next table */
  77930. curr = len - drop;
  77931. left = (int)(1 << curr);
  77932. while (curr + drop < max) {
  77933. left -= count[curr + drop];
  77934. if (left <= 0) break;
  77935. curr++;
  77936. left <<= 1;
  77937. }
  77938. /* check for enough space */
  77939. used += 1U << curr;
  77940. if (type == LENS && used >= ENOUGH - MAXD)
  77941. return 1;
  77942. /* point entry in root table to sub-table */
  77943. low = huff & mask;
  77944. (*table)[low].op = (unsigned char)curr;
  77945. (*table)[low].bits = (unsigned char)root;
  77946. (*table)[low].val = (unsigned short)(next - *table);
  77947. }
  77948. }
  77949. /*
  77950. Fill in rest of table for incomplete codes. This loop is similar to the
  77951. loop above in incrementing huff for table indices. It is assumed that
  77952. len is equal to curr + drop, so there is no loop needed to increment
  77953. through high index bits. When the current sub-table is filled, the loop
  77954. drops back to the root table to fill in any remaining entries there.
  77955. */
  77956. thisx.op = (unsigned char)64; /* invalid code marker */
  77957. thisx.bits = (unsigned char)(len - drop);
  77958. thisx.val = (unsigned short)0;
  77959. while (huff != 0) {
  77960. /* when done with sub-table, drop back to root table */
  77961. if (drop != 0 && (huff & mask) != low) {
  77962. drop = 0;
  77963. len = root;
  77964. next = *table;
  77965. thisx.bits = (unsigned char)len;
  77966. }
  77967. /* put invalid code marker in table */
  77968. next[huff >> drop] = thisx;
  77969. /* backwards increment the len-bit code huff */
  77970. incr = 1U << (len - 1);
  77971. while (huff & incr)
  77972. incr >>= 1;
  77973. if (incr != 0) {
  77974. huff &= incr - 1;
  77975. huff += incr;
  77976. }
  77977. else
  77978. huff = 0;
  77979. }
  77980. /* set return parameters */
  77981. *table += used;
  77982. *bits = root;
  77983. return 0;
  77984. }
  77985. /********* End of inlined file: inftrees.c *********/
  77986. /********* Start of inlined file: trees.c *********/
  77987. /*
  77988. * ALGORITHM
  77989. *
  77990. * The "deflation" process uses several Huffman trees. The more
  77991. * common source values are represented by shorter bit sequences.
  77992. *
  77993. * Each code tree is stored in a compressed form which is itself
  77994. * a Huffman encoding of the lengths of all the code strings (in
  77995. * ascending order by source values). The actual code strings are
  77996. * reconstructed from the lengths in the inflate process, as described
  77997. * in the deflate specification.
  77998. *
  77999. * REFERENCES
  78000. *
  78001. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  78002. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  78003. *
  78004. * Storer, James A.
  78005. * Data Compression: Methods and Theory, pp. 49-50.
  78006. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  78007. *
  78008. * Sedgewick, R.
  78009. * Algorithms, p290.
  78010. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78011. */
  78012. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78013. /* #define GEN_TREES_H */
  78014. #ifdef DEBUG
  78015. # include <ctype.h>
  78016. #endif
  78017. /* ===========================================================================
  78018. * Constants
  78019. */
  78020. #define MAX_BL_BITS 7
  78021. /* Bit length codes must not exceed MAX_BL_BITS bits */
  78022. #define END_BLOCK 256
  78023. /* end of block literal code */
  78024. #define REP_3_6 16
  78025. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  78026. #define REPZ_3_10 17
  78027. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  78028. #define REPZ_11_138 18
  78029. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  78030. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  78031. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  78032. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  78033. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  78034. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  78035. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  78036. local const uch bl_order[BL_CODES]
  78037. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  78038. /* The lengths of the bit length codes are sent in order of decreasing
  78039. * probability, to avoid transmitting the lengths for unused bit length codes.
  78040. */
  78041. #define Buf_size (8 * 2*sizeof(char))
  78042. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  78043. * more than 16 bits on some systems.)
  78044. */
  78045. /* ===========================================================================
  78046. * Local data. These are initialized only once.
  78047. */
  78048. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  78049. #if defined(GEN_TREES_H) || !defined(STDC)
  78050. /* non ANSI compilers may not accept trees.h */
  78051. local ct_data static_ltree[L_CODES+2];
  78052. /* The static literal tree. Since the bit lengths are imposed, there is no
  78053. * need for the L_CODES extra codes used during heap construction. However
  78054. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  78055. * below).
  78056. */
  78057. local ct_data static_dtree[D_CODES];
  78058. /* The static distance tree. (Actually a trivial tree since all codes use
  78059. * 5 bits.)
  78060. */
  78061. uch _dist_code[DIST_CODE_LEN];
  78062. /* Distance codes. The first 256 values correspond to the distances
  78063. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  78064. * the 15 bit distances.
  78065. */
  78066. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  78067. /* length code for each normalized match length (0 == MIN_MATCH) */
  78068. local int base_length[LENGTH_CODES];
  78069. /* First normalized length for each code (0 = MIN_MATCH) */
  78070. local int base_dist[D_CODES];
  78071. /* First normalized distance for each code (0 = distance of 1) */
  78072. #else
  78073. /********* Start of inlined file: trees.h *********/
  78074. local const ct_data static_ltree[L_CODES+2] = {
  78075. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  78076. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  78077. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  78078. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  78079. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  78080. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  78081. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  78082. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  78083. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  78084. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  78085. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  78086. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  78087. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  78088. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  78089. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  78090. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  78091. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  78092. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  78093. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  78094. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  78095. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  78096. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  78097. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  78098. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  78099. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  78100. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  78101. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  78102. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  78103. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  78104. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  78105. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  78106. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  78107. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  78108. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  78109. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  78110. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  78111. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  78112. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  78113. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  78114. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  78115. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  78116. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  78117. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  78118. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  78119. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  78120. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  78121. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  78122. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  78123. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  78124. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  78125. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  78126. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  78127. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  78128. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  78129. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  78130. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  78131. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  78132. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  78133. };
  78134. local const ct_data static_dtree[D_CODES] = {
  78135. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  78136. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  78137. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  78138. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  78139. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  78140. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  78141. };
  78142. const uch _dist_code[DIST_CODE_LEN] = {
  78143. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  78144. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  78145. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  78146. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  78147. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  78148. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  78149. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78150. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78151. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78152. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  78153. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78154. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78155. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  78156. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  78157. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78158. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78159. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78160. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  78161. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78162. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78163. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78164. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78165. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78166. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78167. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78168. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  78169. };
  78170. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  78171. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  78172. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  78173. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  78174. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  78175. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  78176. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  78177. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78178. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78179. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78180. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  78181. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78182. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78183. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  78184. };
  78185. local const int base_length[LENGTH_CODES] = {
  78186. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  78187. 64, 80, 96, 112, 128, 160, 192, 224, 0
  78188. };
  78189. local const int base_dist[D_CODES] = {
  78190. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  78191. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  78192. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  78193. };
  78194. /********* End of inlined file: trees.h *********/
  78195. #endif /* GEN_TREES_H */
  78196. struct static_tree_desc_s {
  78197. const ct_data *static_tree; /* static tree or NULL */
  78198. const intf *extra_bits; /* extra bits for each code or NULL */
  78199. int extra_base; /* base index for extra_bits */
  78200. int elems; /* max number of elements in the tree */
  78201. int max_length; /* max bit length for the codes */
  78202. };
  78203. local static_tree_desc static_l_desc =
  78204. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  78205. local static_tree_desc static_d_desc =
  78206. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  78207. local static_tree_desc static_bl_desc =
  78208. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  78209. /* ===========================================================================
  78210. * Local (static) routines in this file.
  78211. */
  78212. local void tr_static_init OF((void));
  78213. local void init_block OF((deflate_state *s));
  78214. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  78215. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  78216. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  78217. local void build_tree OF((deflate_state *s, tree_desc *desc));
  78218. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78219. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78220. local int build_bl_tree OF((deflate_state *s));
  78221. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  78222. int blcodes));
  78223. local void compress_block OF((deflate_state *s, ct_data *ltree,
  78224. ct_data *dtree));
  78225. local void set_data_type OF((deflate_state *s));
  78226. local unsigned bi_reverse OF((unsigned value, int length));
  78227. local void bi_windup OF((deflate_state *s));
  78228. local void bi_flush OF((deflate_state *s));
  78229. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  78230. int header));
  78231. #ifdef GEN_TREES_H
  78232. local void gen_trees_header OF((void));
  78233. #endif
  78234. #ifndef DEBUG
  78235. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  78236. /* Send a code of the given tree. c and tree must not have side effects */
  78237. #else /* DEBUG */
  78238. # define send_code(s, c, tree) \
  78239. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  78240. send_bits(s, tree[c].Code, tree[c].Len); }
  78241. #endif
  78242. /* ===========================================================================
  78243. * Output a short LSB first on the stream.
  78244. * IN assertion: there is enough room in pendingBuf.
  78245. */
  78246. #define put_short(s, w) { \
  78247. put_byte(s, (uch)((w) & 0xff)); \
  78248. put_byte(s, (uch)((ush)(w) >> 8)); \
  78249. }
  78250. /* ===========================================================================
  78251. * Send a value on a given number of bits.
  78252. * IN assertion: length <= 16 and value fits in length bits.
  78253. */
  78254. #ifdef DEBUG
  78255. local void send_bits OF((deflate_state *s, int value, int length));
  78256. local void send_bits (deflate_state *s, int value, int length)
  78257. {
  78258. Tracevv((stderr," l %2d v %4x ", length, value));
  78259. Assert(length > 0 && length <= 15, "invalid length");
  78260. s->bits_sent += (ulg)length;
  78261. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  78262. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  78263. * unused bits in value.
  78264. */
  78265. if (s->bi_valid > (int)Buf_size - length) {
  78266. s->bi_buf |= (value << s->bi_valid);
  78267. put_short(s, s->bi_buf);
  78268. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  78269. s->bi_valid += length - Buf_size;
  78270. } else {
  78271. s->bi_buf |= value << s->bi_valid;
  78272. s->bi_valid += length;
  78273. }
  78274. }
  78275. #else /* !DEBUG */
  78276. #define send_bits(s, value, length) \
  78277. { int len = length;\
  78278. if (s->bi_valid > (int)Buf_size - len) {\
  78279. int val = value;\
  78280. s->bi_buf |= (val << s->bi_valid);\
  78281. put_short(s, s->bi_buf);\
  78282. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  78283. s->bi_valid += len - Buf_size;\
  78284. } else {\
  78285. s->bi_buf |= (value) << s->bi_valid;\
  78286. s->bi_valid += len;\
  78287. }\
  78288. }
  78289. #endif /* DEBUG */
  78290. /* the arguments must not have side effects */
  78291. /* ===========================================================================
  78292. * Initialize the various 'constant' tables.
  78293. */
  78294. local void tr_static_init()
  78295. {
  78296. #if defined(GEN_TREES_H) || !defined(STDC)
  78297. static int static_init_done = 0;
  78298. int n; /* iterates over tree elements */
  78299. int bits; /* bit counter */
  78300. int length; /* length value */
  78301. int code; /* code value */
  78302. int dist; /* distance index */
  78303. ush bl_count[MAX_BITS+1];
  78304. /* number of codes at each bit length for an optimal tree */
  78305. if (static_init_done) return;
  78306. /* For some embedded targets, global variables are not initialized: */
  78307. static_l_desc.static_tree = static_ltree;
  78308. static_l_desc.extra_bits = extra_lbits;
  78309. static_d_desc.static_tree = static_dtree;
  78310. static_d_desc.extra_bits = extra_dbits;
  78311. static_bl_desc.extra_bits = extra_blbits;
  78312. /* Initialize the mapping length (0..255) -> length code (0..28) */
  78313. length = 0;
  78314. for (code = 0; code < LENGTH_CODES-1; code++) {
  78315. base_length[code] = length;
  78316. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  78317. _length_code[length++] = (uch)code;
  78318. }
  78319. }
  78320. Assert (length == 256, "tr_static_init: length != 256");
  78321. /* Note that the length 255 (match length 258) can be represented
  78322. * in two different ways: code 284 + 5 bits or code 285, so we
  78323. * overwrite length_code[255] to use the best encoding:
  78324. */
  78325. _length_code[length-1] = (uch)code;
  78326. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  78327. dist = 0;
  78328. for (code = 0 ; code < 16; code++) {
  78329. base_dist[code] = dist;
  78330. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  78331. _dist_code[dist++] = (uch)code;
  78332. }
  78333. }
  78334. Assert (dist == 256, "tr_static_init: dist != 256");
  78335. dist >>= 7; /* from now on, all distances are divided by 128 */
  78336. for ( ; code < D_CODES; code++) {
  78337. base_dist[code] = dist << 7;
  78338. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  78339. _dist_code[256 + dist++] = (uch)code;
  78340. }
  78341. }
  78342. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  78343. /* Construct the codes of the static literal tree */
  78344. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  78345. n = 0;
  78346. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  78347. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  78348. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  78349. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  78350. /* Codes 286 and 287 do not exist, but we must include them in the
  78351. * tree construction to get a canonical Huffman tree (longest code
  78352. * all ones)
  78353. */
  78354. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  78355. /* The static distance tree is trivial: */
  78356. for (n = 0; n < D_CODES; n++) {
  78357. static_dtree[n].Len = 5;
  78358. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  78359. }
  78360. static_init_done = 1;
  78361. # ifdef GEN_TREES_H
  78362. gen_trees_header();
  78363. # endif
  78364. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  78365. }
  78366. /* ===========================================================================
  78367. * Genererate the file trees.h describing the static trees.
  78368. */
  78369. #ifdef GEN_TREES_H
  78370. # ifndef DEBUG
  78371. # include <stdio.h>
  78372. # endif
  78373. # define SEPARATOR(i, last, width) \
  78374. ((i) == (last)? "\n};\n\n" : \
  78375. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  78376. void gen_trees_header()
  78377. {
  78378. FILE *header = fopen("trees.h", "w");
  78379. int i;
  78380. Assert (header != NULL, "Can't open trees.h");
  78381. fprintf(header,
  78382. "/* header created automatically with -DGEN_TREES_H */\n\n");
  78383. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  78384. for (i = 0; i < L_CODES+2; i++) {
  78385. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  78386. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  78387. }
  78388. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  78389. for (i = 0; i < D_CODES; i++) {
  78390. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  78391. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  78392. }
  78393. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  78394. for (i = 0; i < DIST_CODE_LEN; i++) {
  78395. fprintf(header, "%2u%s", _dist_code[i],
  78396. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  78397. }
  78398. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  78399. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  78400. fprintf(header, "%2u%s", _length_code[i],
  78401. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  78402. }
  78403. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  78404. for (i = 0; i < LENGTH_CODES; i++) {
  78405. fprintf(header, "%1u%s", base_length[i],
  78406. SEPARATOR(i, LENGTH_CODES-1, 20));
  78407. }
  78408. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  78409. for (i = 0; i < D_CODES; i++) {
  78410. fprintf(header, "%5u%s", base_dist[i],
  78411. SEPARATOR(i, D_CODES-1, 10));
  78412. }
  78413. fclose(header);
  78414. }
  78415. #endif /* GEN_TREES_H */
  78416. /* ===========================================================================
  78417. * Initialize the tree data structures for a new zlib stream.
  78418. */
  78419. void _tr_init(deflate_state *s)
  78420. {
  78421. tr_static_init();
  78422. s->l_desc.dyn_tree = s->dyn_ltree;
  78423. s->l_desc.stat_desc = &static_l_desc;
  78424. s->d_desc.dyn_tree = s->dyn_dtree;
  78425. s->d_desc.stat_desc = &static_d_desc;
  78426. s->bl_desc.dyn_tree = s->bl_tree;
  78427. s->bl_desc.stat_desc = &static_bl_desc;
  78428. s->bi_buf = 0;
  78429. s->bi_valid = 0;
  78430. s->last_eob_len = 8; /* enough lookahead for inflate */
  78431. #ifdef DEBUG
  78432. s->compressed_len = 0L;
  78433. s->bits_sent = 0L;
  78434. #endif
  78435. /* Initialize the first block of the first file: */
  78436. init_block(s);
  78437. }
  78438. /* ===========================================================================
  78439. * Initialize a new block.
  78440. */
  78441. local void init_block (deflate_state *s)
  78442. {
  78443. int n; /* iterates over tree elements */
  78444. /* Initialize the trees. */
  78445. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  78446. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  78447. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  78448. s->dyn_ltree[END_BLOCK].Freq = 1;
  78449. s->opt_len = s->static_len = 0L;
  78450. s->last_lit = s->matches = 0;
  78451. }
  78452. #define SMALLEST 1
  78453. /* Index within the heap array of least frequent node in the Huffman tree */
  78454. /* ===========================================================================
  78455. * Remove the smallest element from the heap and recreate the heap with
  78456. * one less element. Updates heap and heap_len.
  78457. */
  78458. #define pqremove(s, tree, top) \
  78459. {\
  78460. top = s->heap[SMALLEST]; \
  78461. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  78462. pqdownheap(s, tree, SMALLEST); \
  78463. }
  78464. /* ===========================================================================
  78465. * Compares to subtrees, using the tree depth as tie breaker when
  78466. * the subtrees have equal frequency. This minimizes the worst case length.
  78467. */
  78468. #define smaller(tree, n, m, depth) \
  78469. (tree[n].Freq < tree[m].Freq || \
  78470. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  78471. /* ===========================================================================
  78472. * Restore the heap property by moving down the tree starting at node k,
  78473. * exchanging a node with the smallest of its two sons if necessary, stopping
  78474. * when the heap property is re-established (each father smaller than its
  78475. * two sons).
  78476. */
  78477. local void pqdownheap (deflate_state *s,
  78478. ct_data *tree, /* the tree to restore */
  78479. int k) /* node to move down */
  78480. {
  78481. int v = s->heap[k];
  78482. int j = k << 1; /* left son of k */
  78483. while (j <= s->heap_len) {
  78484. /* Set j to the smallest of the two sons: */
  78485. if (j < s->heap_len &&
  78486. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  78487. j++;
  78488. }
  78489. /* Exit if v is smaller than both sons */
  78490. if (smaller(tree, v, s->heap[j], s->depth)) break;
  78491. /* Exchange v with the smallest son */
  78492. s->heap[k] = s->heap[j]; k = j;
  78493. /* And continue down the tree, setting j to the left son of k */
  78494. j <<= 1;
  78495. }
  78496. s->heap[k] = v;
  78497. }
  78498. /* ===========================================================================
  78499. * Compute the optimal bit lengths for a tree and update the total bit length
  78500. * for the current block.
  78501. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  78502. * above are the tree nodes sorted by increasing frequency.
  78503. * OUT assertions: the field len is set to the optimal bit length, the
  78504. * array bl_count contains the frequencies for each bit length.
  78505. * The length opt_len is updated; static_len is also updated if stree is
  78506. * not null.
  78507. */
  78508. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  78509. {
  78510. ct_data *tree = desc->dyn_tree;
  78511. int max_code = desc->max_code;
  78512. const ct_data *stree = desc->stat_desc->static_tree;
  78513. const intf *extra = desc->stat_desc->extra_bits;
  78514. int base = desc->stat_desc->extra_base;
  78515. int max_length = desc->stat_desc->max_length;
  78516. int h; /* heap index */
  78517. int n, m; /* iterate over the tree elements */
  78518. int bits; /* bit length */
  78519. int xbits; /* extra bits */
  78520. ush f; /* frequency */
  78521. int overflow = 0; /* number of elements with bit length too large */
  78522. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  78523. /* In a first pass, compute the optimal bit lengths (which may
  78524. * overflow in the case of the bit length tree).
  78525. */
  78526. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  78527. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  78528. n = s->heap[h];
  78529. bits = tree[tree[n].Dad].Len + 1;
  78530. if (bits > max_length) bits = max_length, overflow++;
  78531. tree[n].Len = (ush)bits;
  78532. /* We overwrite tree[n].Dad which is no longer needed */
  78533. if (n > max_code) continue; /* not a leaf node */
  78534. s->bl_count[bits]++;
  78535. xbits = 0;
  78536. if (n >= base) xbits = extra[n-base];
  78537. f = tree[n].Freq;
  78538. s->opt_len += (ulg)f * (bits + xbits);
  78539. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  78540. }
  78541. if (overflow == 0) return;
  78542. Trace((stderr,"\nbit length overflow\n"));
  78543. /* This happens for example on obj2 and pic of the Calgary corpus */
  78544. /* Find the first bit length which could increase: */
  78545. do {
  78546. bits = max_length-1;
  78547. while (s->bl_count[bits] == 0) bits--;
  78548. s->bl_count[bits]--; /* move one leaf down the tree */
  78549. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  78550. s->bl_count[max_length]--;
  78551. /* The brother of the overflow item also moves one step up,
  78552. * but this does not affect bl_count[max_length]
  78553. */
  78554. overflow -= 2;
  78555. } while (overflow > 0);
  78556. /* Now recompute all bit lengths, scanning in increasing frequency.
  78557. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  78558. * lengths instead of fixing only the wrong ones. This idea is taken
  78559. * from 'ar' written by Haruhiko Okumura.)
  78560. */
  78561. for (bits = max_length; bits != 0; bits--) {
  78562. n = s->bl_count[bits];
  78563. while (n != 0) {
  78564. m = s->heap[--h];
  78565. if (m > max_code) continue;
  78566. if ((unsigned) tree[m].Len != (unsigned) bits) {
  78567. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  78568. s->opt_len += ((long)bits - (long)tree[m].Len)
  78569. *(long)tree[m].Freq;
  78570. tree[m].Len = (ush)bits;
  78571. }
  78572. n--;
  78573. }
  78574. }
  78575. }
  78576. /* ===========================================================================
  78577. * Generate the codes for a given tree and bit counts (which need not be
  78578. * optimal).
  78579. * IN assertion: the array bl_count contains the bit length statistics for
  78580. * the given tree and the field len is set for all tree elements.
  78581. * OUT assertion: the field code is set for all tree elements of non
  78582. * zero code length.
  78583. */
  78584. local void gen_codes (ct_data *tree, /* the tree to decorate */
  78585. int max_code, /* largest code with non zero frequency */
  78586. ushf *bl_count) /* number of codes at each bit length */
  78587. {
  78588. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  78589. ush code = 0; /* running code value */
  78590. int bits; /* bit index */
  78591. int n; /* code index */
  78592. /* The distribution counts are first used to generate the code values
  78593. * without bit reversal.
  78594. */
  78595. for (bits = 1; bits <= MAX_BITS; bits++) {
  78596. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  78597. }
  78598. /* Check that the bit counts in bl_count are consistent. The last code
  78599. * must be all ones.
  78600. */
  78601. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  78602. "inconsistent bit counts");
  78603. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  78604. for (n = 0; n <= max_code; n++) {
  78605. int len = tree[n].Len;
  78606. if (len == 0) continue;
  78607. /* Now reverse the bits */
  78608. tree[n].Code = bi_reverse(next_code[len]++, len);
  78609. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  78610. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  78611. }
  78612. }
  78613. /* ===========================================================================
  78614. * Construct one Huffman tree and assigns the code bit strings and lengths.
  78615. * Update the total bit length for the current block.
  78616. * IN assertion: the field freq is set for all tree elements.
  78617. * OUT assertions: the fields len and code are set to the optimal bit length
  78618. * and corresponding code. The length opt_len is updated; static_len is
  78619. * also updated if stree is not null. The field max_code is set.
  78620. */
  78621. local void build_tree (deflate_state *s,
  78622. tree_desc *desc) /* the tree descriptor */
  78623. {
  78624. ct_data *tree = desc->dyn_tree;
  78625. const ct_data *stree = desc->stat_desc->static_tree;
  78626. int elems = desc->stat_desc->elems;
  78627. int n, m; /* iterate over heap elements */
  78628. int max_code = -1; /* largest code with non zero frequency */
  78629. int node; /* new node being created */
  78630. /* Construct the initial heap, with least frequent element in
  78631. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  78632. * heap[0] is not used.
  78633. */
  78634. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  78635. for (n = 0; n < elems; n++) {
  78636. if (tree[n].Freq != 0) {
  78637. s->heap[++(s->heap_len)] = max_code = n;
  78638. s->depth[n] = 0;
  78639. } else {
  78640. tree[n].Len = 0;
  78641. }
  78642. }
  78643. /* The pkzip format requires that at least one distance code exists,
  78644. * and that at least one bit should be sent even if there is only one
  78645. * possible code. So to avoid special checks later on we force at least
  78646. * two codes of non zero frequency.
  78647. */
  78648. while (s->heap_len < 2) {
  78649. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  78650. tree[node].Freq = 1;
  78651. s->depth[node] = 0;
  78652. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  78653. /* node is 0 or 1 so it does not have extra bits */
  78654. }
  78655. desc->max_code = max_code;
  78656. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  78657. * establish sub-heaps of increasing lengths:
  78658. */
  78659. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  78660. /* Construct the Huffman tree by repeatedly combining the least two
  78661. * frequent nodes.
  78662. */
  78663. node = elems; /* next internal node of the tree */
  78664. do {
  78665. pqremove(s, tree, n); /* n = node of least frequency */
  78666. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  78667. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  78668. s->heap[--(s->heap_max)] = m;
  78669. /* Create a new node father of n and m */
  78670. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  78671. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  78672. s->depth[n] : s->depth[m]) + 1);
  78673. tree[n].Dad = tree[m].Dad = (ush)node;
  78674. #ifdef DUMP_BL_TREE
  78675. if (tree == s->bl_tree) {
  78676. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  78677. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  78678. }
  78679. #endif
  78680. /* and insert the new node in the heap */
  78681. s->heap[SMALLEST] = node++;
  78682. pqdownheap(s, tree, SMALLEST);
  78683. } while (s->heap_len >= 2);
  78684. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  78685. /* At this point, the fields freq and dad are set. We can now
  78686. * generate the bit lengths.
  78687. */
  78688. gen_bitlen(s, (tree_desc *)desc);
  78689. /* The field len is now set, we can generate the bit codes */
  78690. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  78691. }
  78692. /* ===========================================================================
  78693. * Scan a literal or distance tree to determine the frequencies of the codes
  78694. * in the bit length tree.
  78695. */
  78696. local void scan_tree (deflate_state *s,
  78697. ct_data *tree, /* the tree to be scanned */
  78698. int max_code) /* and its largest code of non zero frequency */
  78699. {
  78700. int n; /* iterates over all tree elements */
  78701. int prevlen = -1; /* last emitted length */
  78702. int curlen; /* length of current code */
  78703. int nextlen = tree[0].Len; /* length of next code */
  78704. int count = 0; /* repeat count of the current code */
  78705. int max_count = 7; /* max repeat count */
  78706. int min_count = 4; /* min repeat count */
  78707. if (nextlen == 0) max_count = 138, min_count = 3;
  78708. tree[max_code+1].Len = (ush)0xffff; /* guard */
  78709. for (n = 0; n <= max_code; n++) {
  78710. curlen = nextlen; nextlen = tree[n+1].Len;
  78711. if (++count < max_count && curlen == nextlen) {
  78712. continue;
  78713. } else if (count < min_count) {
  78714. s->bl_tree[curlen].Freq += count;
  78715. } else if (curlen != 0) {
  78716. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  78717. s->bl_tree[REP_3_6].Freq++;
  78718. } else if (count <= 10) {
  78719. s->bl_tree[REPZ_3_10].Freq++;
  78720. } else {
  78721. s->bl_tree[REPZ_11_138].Freq++;
  78722. }
  78723. count = 0; prevlen = curlen;
  78724. if (nextlen == 0) {
  78725. max_count = 138, min_count = 3;
  78726. } else if (curlen == nextlen) {
  78727. max_count = 6, min_count = 3;
  78728. } else {
  78729. max_count = 7, min_count = 4;
  78730. }
  78731. }
  78732. }
  78733. /* ===========================================================================
  78734. * Send a literal or distance tree in compressed form, using the codes in
  78735. * bl_tree.
  78736. */
  78737. local void send_tree (deflate_state *s,
  78738. ct_data *tree, /* the tree to be scanned */
  78739. int max_code) /* and its largest code of non zero frequency */
  78740. {
  78741. int n; /* iterates over all tree elements */
  78742. int prevlen = -1; /* last emitted length */
  78743. int curlen; /* length of current code */
  78744. int nextlen = tree[0].Len; /* length of next code */
  78745. int count = 0; /* repeat count of the current code */
  78746. int max_count = 7; /* max repeat count */
  78747. int min_count = 4; /* min repeat count */
  78748. /* tree[max_code+1].Len = -1; */ /* guard already set */
  78749. if (nextlen == 0) max_count = 138, min_count = 3;
  78750. for (n = 0; n <= max_code; n++) {
  78751. curlen = nextlen; nextlen = tree[n+1].Len;
  78752. if (++count < max_count && curlen == nextlen) {
  78753. continue;
  78754. } else if (count < min_count) {
  78755. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  78756. } else if (curlen != 0) {
  78757. if (curlen != prevlen) {
  78758. send_code(s, curlen, s->bl_tree); count--;
  78759. }
  78760. Assert(count >= 3 && count <= 6, " 3_6?");
  78761. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  78762. } else if (count <= 10) {
  78763. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  78764. } else {
  78765. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  78766. }
  78767. count = 0; prevlen = curlen;
  78768. if (nextlen == 0) {
  78769. max_count = 138, min_count = 3;
  78770. } else if (curlen == nextlen) {
  78771. max_count = 6, min_count = 3;
  78772. } else {
  78773. max_count = 7, min_count = 4;
  78774. }
  78775. }
  78776. }
  78777. /* ===========================================================================
  78778. * Construct the Huffman tree for the bit lengths and return the index in
  78779. * bl_order of the last bit length code to send.
  78780. */
  78781. local int build_bl_tree (deflate_state *s)
  78782. {
  78783. int max_blindex; /* index of last bit length code of non zero freq */
  78784. /* Determine the bit length frequencies for literal and distance trees */
  78785. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  78786. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  78787. /* Build the bit length tree: */
  78788. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  78789. /* opt_len now includes the length of the tree representations, except
  78790. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  78791. */
  78792. /* Determine the number of bit length codes to send. The pkzip format
  78793. * requires that at least 4 bit length codes be sent. (appnote.txt says
  78794. * 3 but the actual value used is 4.)
  78795. */
  78796. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  78797. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  78798. }
  78799. /* Update opt_len to include the bit length tree and counts */
  78800. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  78801. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  78802. s->opt_len, s->static_len));
  78803. return max_blindex;
  78804. }
  78805. /* ===========================================================================
  78806. * Send the header for a block using dynamic Huffman trees: the counts, the
  78807. * lengths of the bit length codes, the literal tree and the distance tree.
  78808. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  78809. */
  78810. local void send_all_trees (deflate_state *s,
  78811. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  78812. {
  78813. int rank; /* index in bl_order */
  78814. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  78815. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  78816. "too many codes");
  78817. Tracev((stderr, "\nbl counts: "));
  78818. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  78819. send_bits(s, dcodes-1, 5);
  78820. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  78821. for (rank = 0; rank < blcodes; rank++) {
  78822. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  78823. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  78824. }
  78825. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  78826. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  78827. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  78828. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  78829. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  78830. }
  78831. /* ===========================================================================
  78832. * Send a stored block
  78833. */
  78834. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  78835. {
  78836. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  78837. #ifdef DEBUG
  78838. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  78839. s->compressed_len += (stored_len + 4) << 3;
  78840. #endif
  78841. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  78842. }
  78843. /* ===========================================================================
  78844. * Send one empty static block to give enough lookahead for inflate.
  78845. * This takes 10 bits, of which 7 may remain in the bit buffer.
  78846. * The current inflate code requires 9 bits of lookahead. If the
  78847. * last two codes for the previous block (real code plus EOB) were coded
  78848. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  78849. * the last real code. In this case we send two empty static blocks instead
  78850. * of one. (There are no problems if the previous block is stored or fixed.)
  78851. * To simplify the code, we assume the worst case of last real code encoded
  78852. * on one bit only.
  78853. */
  78854. void _tr_align (deflate_state *s)
  78855. {
  78856. send_bits(s, STATIC_TREES<<1, 3);
  78857. send_code(s, END_BLOCK, static_ltree);
  78858. #ifdef DEBUG
  78859. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  78860. #endif
  78861. bi_flush(s);
  78862. /* Of the 10 bits for the empty block, we have already sent
  78863. * (10 - bi_valid) bits. The lookahead for the last real code (before
  78864. * the EOB of the previous block) was thus at least one plus the length
  78865. * of the EOB plus what we have just sent of the empty static block.
  78866. */
  78867. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  78868. send_bits(s, STATIC_TREES<<1, 3);
  78869. send_code(s, END_BLOCK, static_ltree);
  78870. #ifdef DEBUG
  78871. s->compressed_len += 10L;
  78872. #endif
  78873. bi_flush(s);
  78874. }
  78875. s->last_eob_len = 7;
  78876. }
  78877. /* ===========================================================================
  78878. * Determine the best encoding for the current block: dynamic trees, static
  78879. * trees or store, and output the encoded block to the zip file.
  78880. */
  78881. void _tr_flush_block (deflate_state *s,
  78882. charf *buf, /* input block, or NULL if too old */
  78883. ulg stored_len, /* length of input block */
  78884. int eof) /* true if this is the last block for a file */
  78885. {
  78886. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  78887. int max_blindex = 0; /* index of last bit length code of non zero freq */
  78888. /* Build the Huffman trees unless a stored block is forced */
  78889. if (s->level > 0) {
  78890. /* Check if the file is binary or text */
  78891. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  78892. set_data_type(s);
  78893. /* Construct the literal and distance trees */
  78894. build_tree(s, (tree_desc *)(&(s->l_desc)));
  78895. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  78896. s->static_len));
  78897. build_tree(s, (tree_desc *)(&(s->d_desc)));
  78898. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  78899. s->static_len));
  78900. /* At this point, opt_len and static_len are the total bit lengths of
  78901. * the compressed block data, excluding the tree representations.
  78902. */
  78903. /* Build the bit length tree for the above two trees, and get the index
  78904. * in bl_order of the last bit length code to send.
  78905. */
  78906. max_blindex = build_bl_tree(s);
  78907. /* Determine the best encoding. Compute the block lengths in bytes. */
  78908. opt_lenb = (s->opt_len+3+7)>>3;
  78909. static_lenb = (s->static_len+3+7)>>3;
  78910. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  78911. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  78912. s->last_lit));
  78913. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  78914. } else {
  78915. Assert(buf != (char*)0, "lost buf");
  78916. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  78917. }
  78918. #ifdef FORCE_STORED
  78919. if (buf != (char*)0) { /* force stored block */
  78920. #else
  78921. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  78922. /* 4: two words for the lengths */
  78923. #endif
  78924. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  78925. * Otherwise we can't have processed more than WSIZE input bytes since
  78926. * the last block flush, because compression would have been
  78927. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  78928. * transform a block into a stored block.
  78929. */
  78930. _tr_stored_block(s, buf, stored_len, eof);
  78931. #ifdef FORCE_STATIC
  78932. } else if (static_lenb >= 0) { /* force static trees */
  78933. #else
  78934. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  78935. #endif
  78936. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  78937. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  78938. #ifdef DEBUG
  78939. s->compressed_len += 3 + s->static_len;
  78940. #endif
  78941. } else {
  78942. send_bits(s, (DYN_TREES<<1)+eof, 3);
  78943. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  78944. max_blindex+1);
  78945. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  78946. #ifdef DEBUG
  78947. s->compressed_len += 3 + s->opt_len;
  78948. #endif
  78949. }
  78950. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  78951. /* The above check is made mod 2^32, for files larger than 512 MB
  78952. * and uLong implemented on 32 bits.
  78953. */
  78954. init_block(s);
  78955. if (eof) {
  78956. bi_windup(s);
  78957. #ifdef DEBUG
  78958. s->compressed_len += 7; /* align on byte boundary */
  78959. #endif
  78960. }
  78961. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  78962. s->compressed_len-7*eof));
  78963. }
  78964. /* ===========================================================================
  78965. * Save the match info and tally the frequency counts. Return true if
  78966. * the current block must be flushed.
  78967. */
  78968. int _tr_tally (deflate_state *s,
  78969. unsigned dist, /* distance of matched string */
  78970. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  78971. {
  78972. s->d_buf[s->last_lit] = (ush)dist;
  78973. s->l_buf[s->last_lit++] = (uch)lc;
  78974. if (dist == 0) {
  78975. /* lc is the unmatched char */
  78976. s->dyn_ltree[lc].Freq++;
  78977. } else {
  78978. s->matches++;
  78979. /* Here, lc is the match length - MIN_MATCH */
  78980. dist--; /* dist = match distance - 1 */
  78981. Assert((ush)dist < (ush)MAX_DIST(s) &&
  78982. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  78983. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  78984. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  78985. s->dyn_dtree[d_code(dist)].Freq++;
  78986. }
  78987. #ifdef TRUNCATE_BLOCK
  78988. /* Try to guess if it is profitable to stop the current block here */
  78989. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  78990. /* Compute an upper bound for the compressed length */
  78991. ulg out_length = (ulg)s->last_lit*8L;
  78992. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  78993. int dcode;
  78994. for (dcode = 0; dcode < D_CODES; dcode++) {
  78995. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  78996. (5L+extra_dbits[dcode]);
  78997. }
  78998. out_length >>= 3;
  78999. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  79000. s->last_lit, in_length, out_length,
  79001. 100L - out_length*100L/in_length));
  79002. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  79003. }
  79004. #endif
  79005. return (s->last_lit == s->lit_bufsize-1);
  79006. /* We avoid equality with lit_bufsize because of wraparound at 64K
  79007. * on 16 bit machines and because stored blocks are restricted to
  79008. * 64K-1 bytes.
  79009. */
  79010. }
  79011. /* ===========================================================================
  79012. * Send the block data compressed using the given Huffman trees
  79013. */
  79014. local void compress_block (deflate_state *s,
  79015. ct_data *ltree, /* literal tree */
  79016. ct_data *dtree) /* distance tree */
  79017. {
  79018. unsigned dist; /* distance of matched string */
  79019. int lc; /* match length or unmatched char (if dist == 0) */
  79020. unsigned lx = 0; /* running index in l_buf */
  79021. unsigned code; /* the code to send */
  79022. int extra; /* number of extra bits to send */
  79023. if (s->last_lit != 0) do {
  79024. dist = s->d_buf[lx];
  79025. lc = s->l_buf[lx++];
  79026. if (dist == 0) {
  79027. send_code(s, lc, ltree); /* send a literal byte */
  79028. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  79029. } else {
  79030. /* Here, lc is the match length - MIN_MATCH */
  79031. code = _length_code[lc];
  79032. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  79033. extra = extra_lbits[code];
  79034. if (extra != 0) {
  79035. lc -= base_length[code];
  79036. send_bits(s, lc, extra); /* send the extra length bits */
  79037. }
  79038. dist--; /* dist is now the match distance - 1 */
  79039. code = d_code(dist);
  79040. Assert (code < D_CODES, "bad d_code");
  79041. send_code(s, code, dtree); /* send the distance code */
  79042. extra = extra_dbits[code];
  79043. if (extra != 0) {
  79044. dist -= base_dist[code];
  79045. send_bits(s, dist, extra); /* send the extra distance bits */
  79046. }
  79047. } /* literal or match pair ? */
  79048. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  79049. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  79050. "pendingBuf overflow");
  79051. } while (lx < s->last_lit);
  79052. send_code(s, END_BLOCK, ltree);
  79053. s->last_eob_len = ltree[END_BLOCK].Len;
  79054. }
  79055. /* ===========================================================================
  79056. * Set the data type to BINARY or TEXT, using a crude approximation:
  79057. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  79058. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  79059. * IN assertion: the fields Freq of dyn_ltree are set.
  79060. */
  79061. local void set_data_type (deflate_state *s)
  79062. {
  79063. int n;
  79064. for (n = 0; n < 9; n++)
  79065. if (s->dyn_ltree[n].Freq != 0)
  79066. break;
  79067. if (n == 9)
  79068. for (n = 14; n < 32; n++)
  79069. if (s->dyn_ltree[n].Freq != 0)
  79070. break;
  79071. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  79072. }
  79073. /* ===========================================================================
  79074. * Reverse the first len bits of a code, using straightforward code (a faster
  79075. * method would use a table)
  79076. * IN assertion: 1 <= len <= 15
  79077. */
  79078. local unsigned bi_reverse (unsigned code, int len)
  79079. {
  79080. register unsigned res = 0;
  79081. do {
  79082. res |= code & 1;
  79083. code >>= 1, res <<= 1;
  79084. } while (--len > 0);
  79085. return res >> 1;
  79086. }
  79087. /* ===========================================================================
  79088. * Flush the bit buffer, keeping at most 7 bits in it.
  79089. */
  79090. local void bi_flush (deflate_state *s)
  79091. {
  79092. if (s->bi_valid == 16) {
  79093. put_short(s, s->bi_buf);
  79094. s->bi_buf = 0;
  79095. s->bi_valid = 0;
  79096. } else if (s->bi_valid >= 8) {
  79097. put_byte(s, (Byte)s->bi_buf);
  79098. s->bi_buf >>= 8;
  79099. s->bi_valid -= 8;
  79100. }
  79101. }
  79102. /* ===========================================================================
  79103. * Flush the bit buffer and align the output on a byte boundary
  79104. */
  79105. local void bi_windup (deflate_state *s)
  79106. {
  79107. if (s->bi_valid > 8) {
  79108. put_short(s, s->bi_buf);
  79109. } else if (s->bi_valid > 0) {
  79110. put_byte(s, (Byte)s->bi_buf);
  79111. }
  79112. s->bi_buf = 0;
  79113. s->bi_valid = 0;
  79114. #ifdef DEBUG
  79115. s->bits_sent = (s->bits_sent+7) & ~7;
  79116. #endif
  79117. }
  79118. /* ===========================================================================
  79119. * Copy a stored block, storing first the length and its
  79120. * one's complement if requested.
  79121. */
  79122. local void copy_block(deflate_state *s,
  79123. charf *buf, /* the input data */
  79124. unsigned len, /* its length */
  79125. int header) /* true if block header must be written */
  79126. {
  79127. bi_windup(s); /* align on byte boundary */
  79128. s->last_eob_len = 8; /* enough lookahead for inflate */
  79129. if (header) {
  79130. put_short(s, (ush)len);
  79131. put_short(s, (ush)~len);
  79132. #ifdef DEBUG
  79133. s->bits_sent += 2*16;
  79134. #endif
  79135. }
  79136. #ifdef DEBUG
  79137. s->bits_sent += (ulg)len<<3;
  79138. #endif
  79139. while (len--) {
  79140. put_byte(s, *buf++);
  79141. }
  79142. }
  79143. /********* End of inlined file: trees.c *********/
  79144. /********* Start of inlined file: uncompr.c *********/
  79145. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79146. #define ZLIB_INTERNAL
  79147. /* ===========================================================================
  79148. Decompresses the source buffer into the destination buffer. sourceLen is
  79149. the byte length of the source buffer. Upon entry, destLen is the total
  79150. size of the destination buffer, which must be large enough to hold the
  79151. entire uncompressed data. (The size of the uncompressed data must have
  79152. been saved previously by the compressor and transmitted to the decompressor
  79153. by some mechanism outside the scope of this compression library.)
  79154. Upon exit, destLen is the actual size of the compressed buffer.
  79155. This function can be used to decompress a whole file at once if the
  79156. input file is mmap'ed.
  79157. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79158. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79159. buffer, or Z_DATA_ERROR if the input data was corrupted.
  79160. */
  79161. int ZEXPORT uncompress (Bytef *dest,
  79162. uLongf *destLen,
  79163. const Bytef *source,
  79164. uLong sourceLen)
  79165. {
  79166. z_stream stream;
  79167. int err;
  79168. stream.next_in = (Bytef*)source;
  79169. stream.avail_in = (uInt)sourceLen;
  79170. /* Check for source > 64K on 16-bit machine: */
  79171. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79172. stream.next_out = dest;
  79173. stream.avail_out = (uInt)*destLen;
  79174. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79175. stream.zalloc = (alloc_func)0;
  79176. stream.zfree = (free_func)0;
  79177. err = inflateInit(&stream);
  79178. if (err != Z_OK) return err;
  79179. err = inflate(&stream, Z_FINISH);
  79180. if (err != Z_STREAM_END) {
  79181. inflateEnd(&stream);
  79182. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  79183. return Z_DATA_ERROR;
  79184. return err;
  79185. }
  79186. *destLen = stream.total_out;
  79187. err = inflateEnd(&stream);
  79188. return err;
  79189. }
  79190. /********* End of inlined file: uncompr.c *********/
  79191. /********* Start of inlined file: zutil.c *********/
  79192. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79193. #ifndef NO_DUMMY_DECL
  79194. struct internal_state {int dummy;}; /* for buggy compilers */
  79195. #endif
  79196. const char * const z_errmsg[10] = {
  79197. "need dictionary", /* Z_NEED_DICT 2 */
  79198. "stream end", /* Z_STREAM_END 1 */
  79199. "", /* Z_OK 0 */
  79200. "file error", /* Z_ERRNO (-1) */
  79201. "stream error", /* Z_STREAM_ERROR (-2) */
  79202. "data error", /* Z_DATA_ERROR (-3) */
  79203. "insufficient memory", /* Z_MEM_ERROR (-4) */
  79204. "buffer error", /* Z_BUF_ERROR (-5) */
  79205. "incompatible version",/* Z_VERSION_ERROR (-6) */
  79206. ""};
  79207. /*const char * ZEXPORT zlibVersion()
  79208. {
  79209. return ZLIB_VERSION;
  79210. }
  79211. uLong ZEXPORT zlibCompileFlags()
  79212. {
  79213. uLong flags;
  79214. flags = 0;
  79215. switch (sizeof(uInt)) {
  79216. case 2: break;
  79217. case 4: flags += 1; break;
  79218. case 8: flags += 2; break;
  79219. default: flags += 3;
  79220. }
  79221. switch (sizeof(uLong)) {
  79222. case 2: break;
  79223. case 4: flags += 1 << 2; break;
  79224. case 8: flags += 2 << 2; break;
  79225. default: flags += 3 << 2;
  79226. }
  79227. switch (sizeof(voidpf)) {
  79228. case 2: break;
  79229. case 4: flags += 1 << 4; break;
  79230. case 8: flags += 2 << 4; break;
  79231. default: flags += 3 << 4;
  79232. }
  79233. switch (sizeof(z_off_t)) {
  79234. case 2: break;
  79235. case 4: flags += 1 << 6; break;
  79236. case 8: flags += 2 << 6; break;
  79237. default: flags += 3 << 6;
  79238. }
  79239. #ifdef DEBUG
  79240. flags += 1 << 8;
  79241. #endif
  79242. #if defined(ASMV) || defined(ASMINF)
  79243. flags += 1 << 9;
  79244. #endif
  79245. #ifdef ZLIB_WINAPI
  79246. flags += 1 << 10;
  79247. #endif
  79248. #ifdef BUILDFIXED
  79249. flags += 1 << 12;
  79250. #endif
  79251. #ifdef DYNAMIC_CRC_TABLE
  79252. flags += 1 << 13;
  79253. #endif
  79254. #ifdef NO_GZCOMPRESS
  79255. flags += 1L << 16;
  79256. #endif
  79257. #ifdef NO_GZIP
  79258. flags += 1L << 17;
  79259. #endif
  79260. #ifdef PKZIP_BUG_WORKAROUND
  79261. flags += 1L << 20;
  79262. #endif
  79263. #ifdef FASTEST
  79264. flags += 1L << 21;
  79265. #endif
  79266. #ifdef STDC
  79267. # ifdef NO_vsnprintf
  79268. flags += 1L << 25;
  79269. # ifdef HAS_vsprintf_void
  79270. flags += 1L << 26;
  79271. # endif
  79272. # else
  79273. # ifdef HAS_vsnprintf_void
  79274. flags += 1L << 26;
  79275. # endif
  79276. # endif
  79277. #else
  79278. flags += 1L << 24;
  79279. # ifdef NO_snprintf
  79280. flags += 1L << 25;
  79281. # ifdef HAS_sprintf_void
  79282. flags += 1L << 26;
  79283. # endif
  79284. # else
  79285. # ifdef HAS_snprintf_void
  79286. flags += 1L << 26;
  79287. # endif
  79288. # endif
  79289. #endif
  79290. return flags;
  79291. }*/
  79292. #ifdef DEBUG
  79293. # ifndef verbose
  79294. # define verbose 0
  79295. # endif
  79296. int z_verbose = verbose;
  79297. void z_error (char *m)
  79298. {
  79299. fprintf(stderr, "%s\n", m);
  79300. exit(1);
  79301. }
  79302. #endif
  79303. /* exported to allow conversion of error code to string for compress() and
  79304. * uncompress()
  79305. */
  79306. const char * ZEXPORT zError(int err)
  79307. {
  79308. return ERR_MSG(err);
  79309. }
  79310. #if defined(_WIN32_WCE)
  79311. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79312. * errno. We define it as a global variable to simplify porting.
  79313. * Its value is always 0 and should not be used.
  79314. */
  79315. int errno = 0;
  79316. #endif
  79317. #ifndef HAVE_MEMCPY
  79318. void zmemcpy(dest, source, len)
  79319. Bytef* dest;
  79320. const Bytef* source;
  79321. uInt len;
  79322. {
  79323. if (len == 0) return;
  79324. do {
  79325. *dest++ = *source++; /* ??? to be unrolled */
  79326. } while (--len != 0);
  79327. }
  79328. int zmemcmp(s1, s2, len)
  79329. const Bytef* s1;
  79330. const Bytef* s2;
  79331. uInt len;
  79332. {
  79333. uInt j;
  79334. for (j = 0; j < len; j++) {
  79335. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  79336. }
  79337. return 0;
  79338. }
  79339. void zmemzero(dest, len)
  79340. Bytef* dest;
  79341. uInt len;
  79342. {
  79343. if (len == 0) return;
  79344. do {
  79345. *dest++ = 0; /* ??? to be unrolled */
  79346. } while (--len != 0);
  79347. }
  79348. #endif
  79349. #ifdef SYS16BIT
  79350. #ifdef __TURBOC__
  79351. /* Turbo C in 16-bit mode */
  79352. # define MY_ZCALLOC
  79353. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  79354. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  79355. * must fix the pointer. Warning: the pointer must be put back to its
  79356. * original form in order to free it, use zcfree().
  79357. */
  79358. #define MAX_PTR 10
  79359. /* 10*64K = 640K */
  79360. local int next_ptr = 0;
  79361. typedef struct ptr_table_s {
  79362. voidpf org_ptr;
  79363. voidpf new_ptr;
  79364. } ptr_table;
  79365. local ptr_table table[MAX_PTR];
  79366. /* This table is used to remember the original form of pointers
  79367. * to large buffers (64K). Such pointers are normalized with a zero offset.
  79368. * Since MSDOS is not a preemptive multitasking OS, this table is not
  79369. * protected from concurrent access. This hack doesn't work anyway on
  79370. * a protected system like OS/2. Use Microsoft C instead.
  79371. */
  79372. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79373. {
  79374. voidpf buf = opaque; /* just to make some compilers happy */
  79375. ulg bsize = (ulg)items*size;
  79376. /* If we allocate less than 65520 bytes, we assume that farmalloc
  79377. * will return a usable pointer which doesn't have to be normalized.
  79378. */
  79379. if (bsize < 65520L) {
  79380. buf = farmalloc(bsize);
  79381. if (*(ush*)&buf != 0) return buf;
  79382. } else {
  79383. buf = farmalloc(bsize + 16L);
  79384. }
  79385. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  79386. table[next_ptr].org_ptr = buf;
  79387. /* Normalize the pointer to seg:0 */
  79388. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  79389. *(ush*)&buf = 0;
  79390. table[next_ptr++].new_ptr = buf;
  79391. return buf;
  79392. }
  79393. void zcfree (voidpf opaque, voidpf ptr)
  79394. {
  79395. int n;
  79396. if (*(ush*)&ptr != 0) { /* object < 64K */
  79397. farfree(ptr);
  79398. return;
  79399. }
  79400. /* Find the original pointer */
  79401. for (n = 0; n < next_ptr; n++) {
  79402. if (ptr != table[n].new_ptr) continue;
  79403. farfree(table[n].org_ptr);
  79404. while (++n < next_ptr) {
  79405. table[n-1] = table[n];
  79406. }
  79407. next_ptr--;
  79408. return;
  79409. }
  79410. ptr = opaque; /* just to make some compilers happy */
  79411. Assert(0, "zcfree: ptr not found");
  79412. }
  79413. #endif /* __TURBOC__ */
  79414. #ifdef M_I86
  79415. /* Microsoft C in 16-bit mode */
  79416. # define MY_ZCALLOC
  79417. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  79418. # define _halloc halloc
  79419. # define _hfree hfree
  79420. #endif
  79421. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79422. {
  79423. if (opaque) opaque = 0; /* to make compiler happy */
  79424. return _halloc((long)items, size);
  79425. }
  79426. void zcfree (voidpf opaque, voidpf ptr)
  79427. {
  79428. if (opaque) opaque = 0; /* to make compiler happy */
  79429. _hfree(ptr);
  79430. }
  79431. #endif /* M_I86 */
  79432. #endif /* SYS16BIT */
  79433. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  79434. #ifndef STDC
  79435. extern voidp malloc OF((uInt size));
  79436. extern voidp calloc OF((uInt items, uInt size));
  79437. extern void free OF((voidpf ptr));
  79438. #endif
  79439. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79440. {
  79441. if (opaque) items += size - size; /* make compiler happy */
  79442. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  79443. (voidpf)calloc(items, size);
  79444. }
  79445. void zcfree (voidpf opaque, voidpf ptr)
  79446. {
  79447. free(ptr);
  79448. if (opaque) return; /* make compiler happy */
  79449. }
  79450. #endif /* MY_ZCALLOC */
  79451. /********* End of inlined file: zutil.c *********/
  79452. }
  79453. }
  79454. #if JUCE_MSVC
  79455. #pragma warning (pop)
  79456. #endif
  79457. BEGIN_JUCE_NAMESPACE
  79458. using namespace zlibNamespace;
  79459. // internal helper object that holds the zlib structures so they don't have to be
  79460. // included publicly.
  79461. class GZIPDecompressHelper
  79462. {
  79463. private:
  79464. z_stream* stream;
  79465. uint8* data;
  79466. int dataSize;
  79467. public:
  79468. bool finished, needsDictionary, error;
  79469. GZIPDecompressHelper (const bool noWrap) throw()
  79470. : data (0),
  79471. dataSize (0),
  79472. finished (false),
  79473. needsDictionary (false),
  79474. error (false)
  79475. {
  79476. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  79477. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  79478. : MAX_WBITS) != Z_OK)
  79479. {
  79480. juce_free (stream);
  79481. stream = 0;
  79482. error = true;
  79483. finished = true;
  79484. }
  79485. }
  79486. ~GZIPDecompressHelper() throw()
  79487. {
  79488. if (stream != 0)
  79489. {
  79490. inflateEnd (stream);
  79491. juce_free (stream);
  79492. }
  79493. }
  79494. bool needsInput() const throw() { return dataSize <= 0; }
  79495. int getTotalOut() const throw() { return (stream != 0) ? stream->total_out : 0; }
  79496. void setInput (uint8* const data_, const int size) throw()
  79497. {
  79498. data = data_;
  79499. dataSize = size;
  79500. }
  79501. int doNextBlock (uint8* const dest, const int destSize) throw()
  79502. {
  79503. if (stream != 0 && data != 0 && ! finished)
  79504. {
  79505. stream->next_in = data;
  79506. stream->next_out = dest;
  79507. stream->avail_in = dataSize;
  79508. stream->avail_out = destSize;
  79509. switch (inflate (stream, Z_PARTIAL_FLUSH))
  79510. {
  79511. case Z_STREAM_END:
  79512. finished = true;
  79513. // deliberate fall-through
  79514. case Z_OK:
  79515. data += dataSize - stream->avail_in;
  79516. dataSize = stream->avail_in;
  79517. return destSize - stream->avail_out;
  79518. case Z_NEED_DICT:
  79519. needsDictionary = true;
  79520. data += dataSize - stream->avail_in;
  79521. dataSize = stream->avail_in;
  79522. break;
  79523. case Z_DATA_ERROR:
  79524. case Z_MEM_ERROR:
  79525. error = true;
  79526. default:
  79527. break;
  79528. }
  79529. }
  79530. return 0;
  79531. }
  79532. };
  79533. const int gzipDecompBufferSize = 32768;
  79534. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  79535. const bool deleteSourceWhenDestroyed_,
  79536. const bool noWrap_,
  79537. const int64 uncompressedStreamLength_)
  79538. : sourceStream (sourceStream_),
  79539. uncompressedStreamLength (uncompressedStreamLength_),
  79540. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  79541. noWrap (noWrap_),
  79542. isEof (false),
  79543. activeBufferSize (0),
  79544. originalSourcePos (sourceStream_->getPosition())
  79545. {
  79546. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  79547. helper = new GZIPDecompressHelper (noWrap_);
  79548. }
  79549. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  79550. {
  79551. juce_free (buffer);
  79552. if (deleteSourceWhenDestroyed)
  79553. delete sourceStream;
  79554. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79555. delete h;
  79556. }
  79557. int64 GZIPDecompressorInputStream::getTotalLength()
  79558. {
  79559. return uncompressedStreamLength;
  79560. }
  79561. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  79562. {
  79563. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79564. if ((howMany > 0) && ! isEof)
  79565. {
  79566. jassert (destBuffer != 0);
  79567. if (destBuffer != 0)
  79568. {
  79569. int numRead = 0;
  79570. uint8* d = (uint8*) destBuffer;
  79571. while (! h->error)
  79572. {
  79573. const int n = h->doNextBlock (d, howMany);
  79574. if (n == 0)
  79575. {
  79576. if (h->finished || h->needsDictionary)
  79577. {
  79578. isEof = true;
  79579. return numRead;
  79580. }
  79581. if (h->needsInput())
  79582. {
  79583. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  79584. if (activeBufferSize > 0)
  79585. {
  79586. h->setInput ((uint8*) buffer, activeBufferSize);
  79587. }
  79588. else
  79589. {
  79590. isEof = true;
  79591. return numRead;
  79592. }
  79593. }
  79594. }
  79595. else
  79596. {
  79597. numRead += n;
  79598. howMany -= n;
  79599. d += n;
  79600. if (howMany <= 0)
  79601. return numRead;
  79602. }
  79603. }
  79604. }
  79605. }
  79606. return 0;
  79607. }
  79608. bool GZIPDecompressorInputStream::isExhausted()
  79609. {
  79610. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79611. return h->error || isEof;
  79612. }
  79613. int64 GZIPDecompressorInputStream::getPosition()
  79614. {
  79615. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79616. return h->getTotalOut() + activeBufferSize;
  79617. }
  79618. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  79619. {
  79620. const int64 currentPos = getPosition();
  79621. if (newPos != currentPos)
  79622. {
  79623. // reset the stream and start again..
  79624. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79625. delete h;
  79626. isEof = false;
  79627. activeBufferSize = 0;
  79628. helper = new GZIPDecompressHelper (noWrap);
  79629. sourceStream->setPosition (originalSourcePos);
  79630. skipNextBytes (newPos);
  79631. }
  79632. return true;
  79633. }
  79634. END_JUCE_NAMESPACE
  79635. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  79636. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  79637. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  79638. #ifdef _MSC_VER
  79639. #include <windows.h>
  79640. #endif
  79641. #if JUCE_USE_FLAC
  79642. #ifdef _MSC_VER
  79643. #pragma warning (disable : 4505)
  79644. #pragma warning (push)
  79645. #endif
  79646. namespace FlacNamespace
  79647. {
  79648. #define FLAC__NO_DLL 1
  79649. #if ! defined (SIZE_MAX)
  79650. #define SIZE_MAX 0xffffffff
  79651. #endif
  79652. #define __STDC_LIMIT_MACROS 1
  79653. /********* Start of inlined file: all.h *********/
  79654. #ifndef FLAC__ALL_H
  79655. #define FLAC__ALL_H
  79656. /********* Start of inlined file: export.h *********/
  79657. #ifndef FLAC__EXPORT_H
  79658. #define FLAC__EXPORT_H
  79659. /** \file include/FLAC/export.h
  79660. *
  79661. * \brief
  79662. * This module contains #defines and symbols for exporting function
  79663. * calls, and providing version information and compiled-in features.
  79664. *
  79665. * See the \link flac_export export \endlink module.
  79666. */
  79667. /** \defgroup flac_export FLAC/export.h: export symbols
  79668. * \ingroup flac
  79669. *
  79670. * \brief
  79671. * This module contains #defines and symbols for exporting function
  79672. * calls, and providing version information and compiled-in features.
  79673. *
  79674. * If you are compiling with MSVC and will link to the static library
  79675. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  79676. * make sure the symbols are exported properly.
  79677. *
  79678. * \{
  79679. */
  79680. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  79681. #define FLAC_API
  79682. #else
  79683. #ifdef FLAC_API_EXPORTS
  79684. #define FLAC_API _declspec(dllexport)
  79685. #else
  79686. #define FLAC_API _declspec(dllimport)
  79687. #endif
  79688. #endif
  79689. /** These #defines will mirror the libtool-based library version number, see
  79690. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  79691. */
  79692. #define FLAC_API_VERSION_CURRENT 10
  79693. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  79694. #define FLAC_API_VERSION_AGE 2 /**< see above */
  79695. #ifdef __cplusplus
  79696. extern "C" {
  79697. #endif
  79698. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  79699. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  79700. #ifdef __cplusplus
  79701. }
  79702. #endif
  79703. /* \} */
  79704. #endif
  79705. /********* End of inlined file: export.h *********/
  79706. /********* Start of inlined file: assert.h *********/
  79707. #ifndef FLAC__ASSERT_H
  79708. #define FLAC__ASSERT_H
  79709. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  79710. #ifdef DEBUG
  79711. #include <assert.h>
  79712. #define FLAC__ASSERT(x) assert(x)
  79713. #define FLAC__ASSERT_DECLARATION(x) x
  79714. #else
  79715. #define FLAC__ASSERT(x)
  79716. #define FLAC__ASSERT_DECLARATION(x)
  79717. #endif
  79718. #endif
  79719. /********* End of inlined file: assert.h *********/
  79720. /********* Start of inlined file: callback.h *********/
  79721. #ifndef FLAC__CALLBACK_H
  79722. #define FLAC__CALLBACK_H
  79723. /********* Start of inlined file: ordinals.h *********/
  79724. #ifndef FLAC__ORDINALS_H
  79725. #define FLAC__ORDINALS_H
  79726. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  79727. #include <inttypes.h>
  79728. #endif
  79729. typedef signed char FLAC__int8;
  79730. typedef unsigned char FLAC__uint8;
  79731. #if defined(_MSC_VER) || defined(__BORLANDC__)
  79732. typedef __int16 FLAC__int16;
  79733. typedef __int32 FLAC__int32;
  79734. typedef __int64 FLAC__int64;
  79735. typedef unsigned __int16 FLAC__uint16;
  79736. typedef unsigned __int32 FLAC__uint32;
  79737. typedef unsigned __int64 FLAC__uint64;
  79738. #elif defined(__EMX__)
  79739. typedef short FLAC__int16;
  79740. typedef long FLAC__int32;
  79741. typedef long long FLAC__int64;
  79742. typedef unsigned short FLAC__uint16;
  79743. typedef unsigned long FLAC__uint32;
  79744. typedef unsigned long long FLAC__uint64;
  79745. #else
  79746. typedef int16_t FLAC__int16;
  79747. typedef int32_t FLAC__int32;
  79748. typedef int64_t FLAC__int64;
  79749. typedef uint16_t FLAC__uint16;
  79750. typedef uint32_t FLAC__uint32;
  79751. typedef uint64_t FLAC__uint64;
  79752. #endif
  79753. typedef int FLAC__bool;
  79754. typedef FLAC__uint8 FLAC__byte;
  79755. #ifdef true
  79756. #undef true
  79757. #endif
  79758. #ifdef false
  79759. #undef false
  79760. #endif
  79761. #ifndef __cplusplus
  79762. #define true 1
  79763. #define false 0
  79764. #endif
  79765. #endif
  79766. /********* End of inlined file: ordinals.h *********/
  79767. #include <stdlib.h> /* for size_t */
  79768. /** \file include/FLAC/callback.h
  79769. *
  79770. * \brief
  79771. * This module defines the structures for describing I/O callbacks
  79772. * to the other FLAC interfaces.
  79773. *
  79774. * See the detailed documentation for callbacks in the
  79775. * \link flac_callbacks callbacks \endlink module.
  79776. */
  79777. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  79778. * \ingroup flac
  79779. *
  79780. * \brief
  79781. * This module defines the structures for describing I/O callbacks
  79782. * to the other FLAC interfaces.
  79783. *
  79784. * The purpose of the I/O callback functions is to create a common way
  79785. * for the metadata interfaces to handle I/O.
  79786. *
  79787. * Originally the metadata interfaces required filenames as the way of
  79788. * specifying FLAC files to operate on. This is problematic in some
  79789. * environments so there is an additional option to specify a set of
  79790. * callbacks for doing I/O on the FLAC file, instead of the filename.
  79791. *
  79792. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  79793. * opaque structure for a data source.
  79794. *
  79795. * The callback function prototypes are similar (but not identical) to the
  79796. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  79797. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  79798. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  79799. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  79800. * is required. \warning You generally CANNOT directly use fseek or ftell
  79801. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  79802. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  79803. * large files. You will have to find an equivalent function (e.g. ftello),
  79804. * or write a wrapper. The same is true for feof() since this is usually
  79805. * implemented as a macro, not as a function whose address can be taken.
  79806. *
  79807. * \{
  79808. */
  79809. #ifdef __cplusplus
  79810. extern "C" {
  79811. #endif
  79812. /** This is the opaque handle type used by the callbacks. Typically
  79813. * this is a \c FILE* or address of a file descriptor.
  79814. */
  79815. typedef void* FLAC__IOHandle;
  79816. /** Signature for the read callback.
  79817. * The signature and semantics match POSIX fread() implementations
  79818. * and can generally be used interchangeably.
  79819. *
  79820. * \param ptr The address of the read buffer.
  79821. * \param size The size of the records to be read.
  79822. * \param nmemb The number of records to be read.
  79823. * \param handle The handle to the data source.
  79824. * \retval size_t
  79825. * The number of records read.
  79826. */
  79827. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  79828. /** Signature for the write callback.
  79829. * The signature and semantics match POSIX fwrite() implementations
  79830. * and can generally be used interchangeably.
  79831. *
  79832. * \param ptr The address of the write buffer.
  79833. * \param size The size of the records to be written.
  79834. * \param nmemb The number of records to be written.
  79835. * \param handle The handle to the data source.
  79836. * \retval size_t
  79837. * The number of records written.
  79838. */
  79839. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  79840. /** Signature for the seek callback.
  79841. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  79842. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  79843. * and 32-bits wide.
  79844. *
  79845. * \param handle The handle to the data source.
  79846. * \param offset The new position, relative to \a whence
  79847. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  79848. * \retval int
  79849. * \c 0 on success, \c -1 on error.
  79850. */
  79851. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  79852. /** Signature for the tell callback.
  79853. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  79854. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  79855. * and 32-bits wide.
  79856. *
  79857. * \param handle The handle to the data source.
  79858. * \retval FLAC__int64
  79859. * The current position on success, \c -1 on error.
  79860. */
  79861. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  79862. /** Signature for the EOF callback.
  79863. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  79864. * on many systems, feof() is a macro, so in this case a wrapper function
  79865. * must be provided instead.
  79866. *
  79867. * \param handle The handle to the data source.
  79868. * \retval int
  79869. * \c 0 if not at end of file, nonzero if at end of file.
  79870. */
  79871. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  79872. /** Signature for the close callback.
  79873. * The signature and semantics match POSIX fclose() implementations
  79874. * and can generally be used interchangeably.
  79875. *
  79876. * \param handle The handle to the data source.
  79877. * \retval int
  79878. * \c 0 on success, \c EOF on error.
  79879. */
  79880. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  79881. /** A structure for holding a set of callbacks.
  79882. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  79883. * describe which of the callbacks are required. The ones that are not
  79884. * required may be set to NULL.
  79885. *
  79886. * If the seek requirement for an interface is optional, you can signify that
  79887. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  79888. */
  79889. typedef struct {
  79890. FLAC__IOCallback_Read read;
  79891. FLAC__IOCallback_Write write;
  79892. FLAC__IOCallback_Seek seek;
  79893. FLAC__IOCallback_Tell tell;
  79894. FLAC__IOCallback_Eof eof;
  79895. FLAC__IOCallback_Close close;
  79896. } FLAC__IOCallbacks;
  79897. /* \} */
  79898. #ifdef __cplusplus
  79899. }
  79900. #endif
  79901. #endif
  79902. /********* End of inlined file: callback.h *********/
  79903. /********* Start of inlined file: format.h *********/
  79904. #ifndef FLAC__FORMAT_H
  79905. #define FLAC__FORMAT_H
  79906. #ifdef __cplusplus
  79907. extern "C" {
  79908. #endif
  79909. /** \file include/FLAC/format.h
  79910. *
  79911. * \brief
  79912. * This module contains structure definitions for the representation
  79913. * of FLAC format components in memory. These are the basic
  79914. * structures used by the rest of the interfaces.
  79915. *
  79916. * See the detailed documentation in the
  79917. * \link flac_format format \endlink module.
  79918. */
  79919. /** \defgroup flac_format FLAC/format.h: format components
  79920. * \ingroup flac
  79921. *
  79922. * \brief
  79923. * This module contains structure definitions for the representation
  79924. * of FLAC format components in memory. These are the basic
  79925. * structures used by the rest of the interfaces.
  79926. *
  79927. * First, you should be familiar with the
  79928. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  79929. * follow directly from the specification. As a user of libFLAC, the
  79930. * interesting parts really are the structures that describe the frame
  79931. * header and metadata blocks.
  79932. *
  79933. * The format structures here are very primitive, designed to store
  79934. * information in an efficient way. Reading information from the
  79935. * structures is easy but creating or modifying them directly is
  79936. * more complex. For the most part, as a user of a library, editing
  79937. * is not necessary; however, for metadata blocks it is, so there are
  79938. * convenience functions provided in the \link flac_metadata metadata
  79939. * module \endlink to simplify the manipulation of metadata blocks.
  79940. *
  79941. * \note
  79942. * It's not the best convention, but symbols ending in _LEN are in bits
  79943. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  79944. * global variables because they are usually used when declaring byte
  79945. * arrays and some compilers require compile-time knowledge of array
  79946. * sizes when declared on the stack.
  79947. *
  79948. * \{
  79949. */
  79950. /*
  79951. Most of the values described in this file are defined by the FLAC
  79952. format specification. There is nothing to tune here.
  79953. */
  79954. /** The largest legal metadata type code. */
  79955. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  79956. /** The minimum block size, in samples, permitted by the format. */
  79957. #define FLAC__MIN_BLOCK_SIZE (16u)
  79958. /** The maximum block size, in samples, permitted by the format. */
  79959. #define FLAC__MAX_BLOCK_SIZE (65535u)
  79960. /** The maximum block size, in samples, permitted by the FLAC subset for
  79961. * sample rates up to 48kHz. */
  79962. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  79963. /** The maximum number of channels permitted by the format. */
  79964. #define FLAC__MAX_CHANNELS (8u)
  79965. /** The minimum sample resolution permitted by the format. */
  79966. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  79967. /** The maximum sample resolution permitted by the format. */
  79968. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  79969. /** The maximum sample resolution permitted by libFLAC.
  79970. *
  79971. * \warning
  79972. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  79973. * the reference encoder/decoder is currently limited to 24 bits because
  79974. * of prevalent 32-bit math, so make sure and use this value when
  79975. * appropriate.
  79976. */
  79977. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  79978. /** The maximum sample rate permitted by the format. The value is
  79979. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  79980. * as to why.
  79981. */
  79982. #define FLAC__MAX_SAMPLE_RATE (655350u)
  79983. /** The maximum LPC order permitted by the format. */
  79984. #define FLAC__MAX_LPC_ORDER (32u)
  79985. /** The maximum LPC order permitted by the FLAC subset for sample rates
  79986. * up to 48kHz. */
  79987. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  79988. /** The minimum quantized linear predictor coefficient precision
  79989. * permitted by the format.
  79990. */
  79991. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  79992. /** The maximum quantized linear predictor coefficient precision
  79993. * permitted by the format.
  79994. */
  79995. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  79996. /** The maximum order of the fixed predictors permitted by the format. */
  79997. #define FLAC__MAX_FIXED_ORDER (4u)
  79998. /** The maximum Rice partition order permitted by the format. */
  79999. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  80000. /** The maximum Rice partition order permitted by the FLAC Subset. */
  80001. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  80002. /** The version string of the release, stamped onto the libraries and binaries.
  80003. *
  80004. * \note
  80005. * This does not correspond to the shared library version number, which
  80006. * is used to determine binary compatibility.
  80007. */
  80008. extern FLAC_API const char *FLAC__VERSION_STRING;
  80009. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  80010. * This is a NUL-terminated ASCII string; when inserted into the
  80011. * VORBIS_COMMENT the trailing null is stripped.
  80012. */
  80013. extern FLAC_API const char *FLAC__VENDOR_STRING;
  80014. /** The byte string representation of the beginning of a FLAC stream. */
  80015. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  80016. /** The 32-bit integer big-endian representation of the beginning of
  80017. * a FLAC stream.
  80018. */
  80019. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  80020. /** The length of the FLAC signature in bits. */
  80021. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  80022. /** The length of the FLAC signature in bytes. */
  80023. #define FLAC__STREAM_SYNC_LENGTH (4u)
  80024. /*****************************************************************************
  80025. *
  80026. * Subframe structures
  80027. *
  80028. *****************************************************************************/
  80029. /*****************************************************************************/
  80030. /** An enumeration of the available entropy coding methods. */
  80031. typedef enum {
  80032. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  80033. /**< Residual is coded by partitioning into contexts, each with it's own
  80034. * 4-bit Rice parameter. */
  80035. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  80036. /**< Residual is coded by partitioning into contexts, each with it's own
  80037. * 5-bit Rice parameter. */
  80038. } FLAC__EntropyCodingMethodType;
  80039. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  80040. *
  80041. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  80042. * give the string equivalent. The contents should not be modified.
  80043. */
  80044. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  80045. /** Contents of a Rice partitioned residual
  80046. */
  80047. typedef struct {
  80048. unsigned *parameters;
  80049. /**< The Rice parameters for each context. */
  80050. unsigned *raw_bits;
  80051. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  80052. * partitions and zero for unescaped partitions.
  80053. */
  80054. unsigned capacity_by_order;
  80055. /**< The capacity of the \a parameters and \a raw_bits arrays
  80056. * specified as an order, i.e. the number of array elements
  80057. * allocated is 2 ^ \a capacity_by_order.
  80058. */
  80059. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  80060. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  80061. */
  80062. typedef struct {
  80063. unsigned order;
  80064. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  80065. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  80066. /**< The context's Rice parameters and/or raw bits. */
  80067. } FLAC__EntropyCodingMethod_PartitionedRice;
  80068. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  80069. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  80070. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  80071. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  80072. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  80073. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  80074. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  80075. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  80076. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  80077. */
  80078. typedef struct {
  80079. FLAC__EntropyCodingMethodType type;
  80080. union {
  80081. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  80082. } data;
  80083. } FLAC__EntropyCodingMethod;
  80084. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  80085. /*****************************************************************************/
  80086. /** An enumeration of the available subframe types. */
  80087. typedef enum {
  80088. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  80089. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  80090. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  80091. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  80092. } FLAC__SubframeType;
  80093. /** Maps a FLAC__SubframeType to a C string.
  80094. *
  80095. * Using a FLAC__SubframeType as the index to this array will
  80096. * give the string equivalent. The contents should not be modified.
  80097. */
  80098. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  80099. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  80100. */
  80101. typedef struct {
  80102. FLAC__int32 value; /**< The constant signal value. */
  80103. } FLAC__Subframe_Constant;
  80104. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  80105. */
  80106. typedef struct {
  80107. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  80108. } FLAC__Subframe_Verbatim;
  80109. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  80110. */
  80111. typedef struct {
  80112. FLAC__EntropyCodingMethod entropy_coding_method;
  80113. /**< The residual coding method. */
  80114. unsigned order;
  80115. /**< The polynomial order. */
  80116. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  80117. /**< Warmup samples to prime the predictor, length == order. */
  80118. const FLAC__int32 *residual;
  80119. /**< The residual signal, length == (blocksize minus order) samples. */
  80120. } FLAC__Subframe_Fixed;
  80121. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  80122. */
  80123. typedef struct {
  80124. FLAC__EntropyCodingMethod entropy_coding_method;
  80125. /**< The residual coding method. */
  80126. unsigned order;
  80127. /**< The FIR order. */
  80128. unsigned qlp_coeff_precision;
  80129. /**< Quantized FIR filter coefficient precision in bits. */
  80130. int quantization_level;
  80131. /**< The qlp coeff shift needed. */
  80132. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  80133. /**< FIR filter coefficients. */
  80134. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  80135. /**< Warmup samples to prime the predictor, length == order. */
  80136. const FLAC__int32 *residual;
  80137. /**< The residual signal, length == (blocksize minus order) samples. */
  80138. } FLAC__Subframe_LPC;
  80139. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  80140. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  80141. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  80142. */
  80143. typedef struct {
  80144. FLAC__SubframeType type;
  80145. union {
  80146. FLAC__Subframe_Constant constant;
  80147. FLAC__Subframe_Fixed fixed;
  80148. FLAC__Subframe_LPC lpc;
  80149. FLAC__Subframe_Verbatim verbatim;
  80150. } data;
  80151. unsigned wasted_bits;
  80152. } FLAC__Subframe;
  80153. /** == 1 (bit)
  80154. *
  80155. * This used to be a zero-padding bit (hence the name
  80156. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  80157. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  80158. * to mean something else.
  80159. */
  80160. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  80161. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  80162. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  80163. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  80164. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  80165. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  80166. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  80167. /*****************************************************************************/
  80168. /*****************************************************************************
  80169. *
  80170. * Frame structures
  80171. *
  80172. *****************************************************************************/
  80173. /** An enumeration of the available channel assignments. */
  80174. typedef enum {
  80175. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  80176. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  80177. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  80178. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  80179. } FLAC__ChannelAssignment;
  80180. /** Maps a FLAC__ChannelAssignment to a C string.
  80181. *
  80182. * Using a FLAC__ChannelAssignment as the index to this array will
  80183. * give the string equivalent. The contents should not be modified.
  80184. */
  80185. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  80186. /** An enumeration of the possible frame numbering methods. */
  80187. typedef enum {
  80188. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  80189. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  80190. } FLAC__FrameNumberType;
  80191. /** Maps a FLAC__FrameNumberType to a C string.
  80192. *
  80193. * Using a FLAC__FrameNumberType as the index to this array will
  80194. * give the string equivalent. The contents should not be modified.
  80195. */
  80196. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  80197. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  80198. */
  80199. typedef struct {
  80200. unsigned blocksize;
  80201. /**< The number of samples per subframe. */
  80202. unsigned sample_rate;
  80203. /**< The sample rate in Hz. */
  80204. unsigned channels;
  80205. /**< The number of channels (== number of subframes). */
  80206. FLAC__ChannelAssignment channel_assignment;
  80207. /**< The channel assignment for the frame. */
  80208. unsigned bits_per_sample;
  80209. /**< The sample resolution. */
  80210. FLAC__FrameNumberType number_type;
  80211. /**< The numbering scheme used for the frame. As a convenience, the
  80212. * decoder will always convert a frame number to a sample number because
  80213. * the rules are complex. */
  80214. union {
  80215. FLAC__uint32 frame_number;
  80216. FLAC__uint64 sample_number;
  80217. } number;
  80218. /**< The frame number or sample number of first sample in frame;
  80219. * use the \a number_type value to determine which to use. */
  80220. FLAC__uint8 crc;
  80221. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  80222. * of the raw frame header bytes, meaning everything before the CRC byte
  80223. * including the sync code.
  80224. */
  80225. } FLAC__FrameHeader;
  80226. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  80227. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  80228. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  80229. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  80230. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  80231. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  80232. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  80233. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  80234. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  80235. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  80236. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  80237. */
  80238. typedef struct {
  80239. FLAC__uint16 crc;
  80240. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  80241. * 0) of the bytes before the crc, back to and including the frame header
  80242. * sync code.
  80243. */
  80244. } FLAC__FrameFooter;
  80245. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  80246. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  80247. */
  80248. typedef struct {
  80249. FLAC__FrameHeader header;
  80250. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  80251. FLAC__FrameFooter footer;
  80252. } FLAC__Frame;
  80253. /*****************************************************************************/
  80254. /*****************************************************************************
  80255. *
  80256. * Meta-data structures
  80257. *
  80258. *****************************************************************************/
  80259. /** An enumeration of the available metadata block types. */
  80260. typedef enum {
  80261. FLAC__METADATA_TYPE_STREAMINFO = 0,
  80262. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  80263. FLAC__METADATA_TYPE_PADDING = 1,
  80264. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  80265. FLAC__METADATA_TYPE_APPLICATION = 2,
  80266. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  80267. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  80268. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  80269. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  80270. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  80271. FLAC__METADATA_TYPE_CUESHEET = 5,
  80272. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  80273. FLAC__METADATA_TYPE_PICTURE = 6,
  80274. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  80275. FLAC__METADATA_TYPE_UNDEFINED = 7
  80276. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  80277. } FLAC__MetadataType;
  80278. /** Maps a FLAC__MetadataType to a C string.
  80279. *
  80280. * Using a FLAC__MetadataType as the index to this array will
  80281. * give the string equivalent. The contents should not be modified.
  80282. */
  80283. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  80284. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  80285. */
  80286. typedef struct {
  80287. unsigned min_blocksize, max_blocksize;
  80288. unsigned min_framesize, max_framesize;
  80289. unsigned sample_rate;
  80290. unsigned channels;
  80291. unsigned bits_per_sample;
  80292. FLAC__uint64 total_samples;
  80293. FLAC__byte md5sum[16];
  80294. } FLAC__StreamMetadata_StreamInfo;
  80295. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80296. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80297. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80298. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  80300. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  80301. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  80302. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  80303. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  80304. /** The total stream length of the STREAMINFO block in bytes. */
  80305. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  80306. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  80307. */
  80308. typedef struct {
  80309. int dummy;
  80310. /**< Conceptually this is an empty struct since we don't store the
  80311. * padding bytes. Empty structs are not allowed by some C compilers,
  80312. * hence the dummy.
  80313. */
  80314. } FLAC__StreamMetadata_Padding;
  80315. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  80316. */
  80317. typedef struct {
  80318. FLAC__byte id[4];
  80319. FLAC__byte *data;
  80320. } FLAC__StreamMetadata_Application;
  80321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  80322. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  80323. */
  80324. typedef struct {
  80325. FLAC__uint64 sample_number;
  80326. /**< The sample number of the target frame. */
  80327. FLAC__uint64 stream_offset;
  80328. /**< The offset, in bytes, of the target frame with respect to
  80329. * beginning of the first frame. */
  80330. unsigned frame_samples;
  80331. /**< The number of samples in the target frame. */
  80332. } FLAC__StreamMetadata_SeekPoint;
  80333. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  80334. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  80335. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  80336. /** The total stream length of a seek point in bytes. */
  80337. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  80338. /** The value used in the \a sample_number field of
  80339. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  80340. * point (== 0xffffffffffffffff).
  80341. */
  80342. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  80343. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  80344. *
  80345. * \note From the format specification:
  80346. * - The seek points must be sorted by ascending sample number.
  80347. * - Each seek point's sample number must be the first sample of the
  80348. * target frame.
  80349. * - Each seek point's sample number must be unique within the table.
  80350. * - Existence of a SEEKTABLE block implies a correct setting of
  80351. * total_samples in the stream_info block.
  80352. * - Behavior is undefined when more than one SEEKTABLE block is
  80353. * present in a stream.
  80354. */
  80355. typedef struct {
  80356. unsigned num_points;
  80357. FLAC__StreamMetadata_SeekPoint *points;
  80358. } FLAC__StreamMetadata_SeekTable;
  80359. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  80360. *
  80361. * For convenience, the APIs maintain a trailing NUL character at the end of
  80362. * \a entry which is not counted toward \a length, i.e.
  80363. * \code strlen(entry) == length \endcode
  80364. */
  80365. typedef struct {
  80366. FLAC__uint32 length;
  80367. FLAC__byte *entry;
  80368. } FLAC__StreamMetadata_VorbisComment_Entry;
  80369. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  80370. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  80371. */
  80372. typedef struct {
  80373. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  80374. FLAC__uint32 num_comments;
  80375. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  80376. } FLAC__StreamMetadata_VorbisComment;
  80377. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  80378. /** FLAC CUESHEET track index structure. (See the
  80379. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  80380. * the full description of each field.)
  80381. */
  80382. typedef struct {
  80383. FLAC__uint64 offset;
  80384. /**< Offset in samples, relative to the track offset, of the index
  80385. * point.
  80386. */
  80387. FLAC__byte number;
  80388. /**< The index point number. */
  80389. } FLAC__StreamMetadata_CueSheet_Index;
  80390. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  80391. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  80392. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  80393. /** FLAC CUESHEET track structure. (See the
  80394. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  80395. * the full description of each field.)
  80396. */
  80397. typedef struct {
  80398. FLAC__uint64 offset;
  80399. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  80400. FLAC__byte number;
  80401. /**< The track number. */
  80402. char isrc[13];
  80403. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  80404. unsigned type:1;
  80405. /**< The track type: 0 for audio, 1 for non-audio. */
  80406. unsigned pre_emphasis:1;
  80407. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  80408. FLAC__byte num_indices;
  80409. /**< The number of track index points. */
  80410. FLAC__StreamMetadata_CueSheet_Index *indices;
  80411. /**< NULL if num_indices == 0, else pointer to array of index points. */
  80412. } FLAC__StreamMetadata_CueSheet_Track;
  80413. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  80414. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  80415. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  80416. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  80417. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  80418. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  80419. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  80420. /** FLAC CUESHEET structure. (See the
  80421. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  80422. * for the full description of each field.)
  80423. */
  80424. typedef struct {
  80425. char media_catalog_number[129];
  80426. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  80427. * general, the media catalog number may be 0 to 128 bytes long; any
  80428. * unused characters should be right-padded with NUL characters.
  80429. */
  80430. FLAC__uint64 lead_in;
  80431. /**< The number of lead-in samples. */
  80432. FLAC__bool is_cd;
  80433. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  80434. unsigned num_tracks;
  80435. /**< The number of tracks. */
  80436. FLAC__StreamMetadata_CueSheet_Track *tracks;
  80437. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  80438. } FLAC__StreamMetadata_CueSheet;
  80439. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  80440. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  80441. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  80442. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  80443. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  80444. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  80445. typedef enum {
  80446. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  80447. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  80448. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  80449. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  80450. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  80451. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  80452. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  80453. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  80454. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  80455. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  80456. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  80457. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  80458. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  80459. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  80460. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  80461. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  80462. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  80463. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  80464. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  80465. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  80466. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  80467. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  80468. } FLAC__StreamMetadata_Picture_Type;
  80469. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  80470. *
  80471. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  80472. * will give the string equivalent. The contents should not be
  80473. * modified.
  80474. */
  80475. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  80476. /** FLAC PICTURE structure. (See the
  80477. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  80478. * for the full description of each field.)
  80479. */
  80480. typedef struct {
  80481. FLAC__StreamMetadata_Picture_Type type;
  80482. /**< The kind of picture stored. */
  80483. char *mime_type;
  80484. /**< Picture data's MIME type, in ASCII printable characters
  80485. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  80486. * use picture data of MIME type \c image/jpeg or \c image/png. A
  80487. * MIME type of '-->' is also allowed, in which case the picture
  80488. * data should be a complete URL. In file storage, the MIME type is
  80489. * stored as a 32-bit length followed by the ASCII string with no NUL
  80490. * terminator, but is converted to a plain C string in this structure
  80491. * for convenience.
  80492. */
  80493. FLAC__byte *description;
  80494. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  80495. * the description is stored as a 32-bit length followed by the UTF-8
  80496. * string with no NUL terminator, but is converted to a plain C string
  80497. * in this structure for convenience.
  80498. */
  80499. FLAC__uint32 width;
  80500. /**< Picture's width in pixels. */
  80501. FLAC__uint32 height;
  80502. /**< Picture's height in pixels. */
  80503. FLAC__uint32 depth;
  80504. /**< Picture's color depth in bits-per-pixel. */
  80505. FLAC__uint32 colors;
  80506. /**< For indexed palettes (like GIF), picture's number of colors (the
  80507. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  80508. */
  80509. FLAC__uint32 data_length;
  80510. /**< Length of binary picture data in bytes. */
  80511. FLAC__byte *data;
  80512. /**< Binary picture data. */
  80513. } FLAC__StreamMetadata_Picture;
  80514. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  80515. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  80516. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  80517. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  80518. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  80519. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  80520. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  80521. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  80522. /** Structure that is used when a metadata block of unknown type is loaded.
  80523. * The contents are opaque. The structure is used only internally to
  80524. * correctly handle unknown metadata.
  80525. */
  80526. typedef struct {
  80527. FLAC__byte *data;
  80528. } FLAC__StreamMetadata_Unknown;
  80529. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  80530. */
  80531. typedef struct {
  80532. FLAC__MetadataType type;
  80533. /**< The type of the metadata block; used determine which member of the
  80534. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  80535. * then \a data.unknown must be used. */
  80536. FLAC__bool is_last;
  80537. /**< \c true if this metadata block is the last, else \a false */
  80538. unsigned length;
  80539. /**< Length, in bytes, of the block data as it appears in the stream. */
  80540. union {
  80541. FLAC__StreamMetadata_StreamInfo stream_info;
  80542. FLAC__StreamMetadata_Padding padding;
  80543. FLAC__StreamMetadata_Application application;
  80544. FLAC__StreamMetadata_SeekTable seek_table;
  80545. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  80546. FLAC__StreamMetadata_CueSheet cue_sheet;
  80547. FLAC__StreamMetadata_Picture picture;
  80548. FLAC__StreamMetadata_Unknown unknown;
  80549. } data;
  80550. /**< Polymorphic block data; use the \a type value to determine which
  80551. * to use. */
  80552. } FLAC__StreamMetadata;
  80553. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  80554. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  80555. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  80556. /** The total stream length of a metadata block header in bytes. */
  80557. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  80558. /*****************************************************************************/
  80559. /*****************************************************************************
  80560. *
  80561. * Utility functions
  80562. *
  80563. *****************************************************************************/
  80564. /** Tests that a sample rate is valid for FLAC.
  80565. *
  80566. * \param sample_rate The sample rate to test for compliance.
  80567. * \retval FLAC__bool
  80568. * \c true if the given sample rate conforms to the specification, else
  80569. * \c false.
  80570. */
  80571. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  80572. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  80573. * for valid sample rates are slightly more complex since the rate has to
  80574. * be expressible completely in the frame header.
  80575. *
  80576. * \param sample_rate The sample rate to test for compliance.
  80577. * \retval FLAC__bool
  80578. * \c true if the given sample rate conforms to the specification for the
  80579. * subset, else \c false.
  80580. */
  80581. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  80582. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  80583. * comment specification.
  80584. *
  80585. * Vorbis comment names must be composed only of characters from
  80586. * [0x20-0x3C,0x3E-0x7D].
  80587. *
  80588. * \param name A NUL-terminated string to be checked.
  80589. * \assert
  80590. * \code name != NULL \endcode
  80591. * \retval FLAC__bool
  80592. * \c false if entry name is illegal, else \c true.
  80593. */
  80594. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  80595. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  80596. * comment specification.
  80597. *
  80598. * Vorbis comment values must be valid UTF-8 sequences.
  80599. *
  80600. * \param value A string to be checked.
  80601. * \param length A the length of \a value in bytes. May be
  80602. * \c (unsigned)(-1) to indicate that \a value is a plain
  80603. * UTF-8 NUL-terminated string.
  80604. * \assert
  80605. * \code value != NULL \endcode
  80606. * \retval FLAC__bool
  80607. * \c false if entry name is illegal, else \c true.
  80608. */
  80609. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  80610. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  80611. * comment specification.
  80612. *
  80613. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  80614. * 'value' must be legal according to
  80615. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  80616. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  80617. *
  80618. * \param entry An entry to be checked.
  80619. * \param length The length of \a entry in bytes.
  80620. * \assert
  80621. * \code value != NULL \endcode
  80622. * \retval FLAC__bool
  80623. * \c false if entry name is illegal, else \c true.
  80624. */
  80625. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  80626. /** Check a seek table to see if it conforms to the FLAC specification.
  80627. * See the format specification for limits on the contents of the
  80628. * seek table.
  80629. *
  80630. * \param seek_table A pointer to a seek table to be checked.
  80631. * \assert
  80632. * \code seek_table != NULL \endcode
  80633. * \retval FLAC__bool
  80634. * \c false if seek table is illegal, else \c true.
  80635. */
  80636. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  80637. /** Sort a seek table's seek points according to the format specification.
  80638. * This includes a "unique-ification" step to remove duplicates, i.e.
  80639. * seek points with identical \a sample_number values. Duplicate seek
  80640. * points are converted into placeholder points and sorted to the end of
  80641. * the table.
  80642. *
  80643. * \param seek_table A pointer to a seek table to be sorted.
  80644. * \assert
  80645. * \code seek_table != NULL \endcode
  80646. * \retval unsigned
  80647. * The number of duplicate seek points converted into placeholders.
  80648. */
  80649. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  80650. /** Check a cue sheet to see if it conforms to the FLAC specification.
  80651. * See the format specification for limits on the contents of the
  80652. * cue sheet.
  80653. *
  80654. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  80655. * \param check_cd_da_subset If \c true, check CUESHEET against more
  80656. * stringent requirements for a CD-DA (audio) disc.
  80657. * \param violation Address of a pointer to a string. If there is a
  80658. * violation, a pointer to a string explanation of the
  80659. * violation will be returned here. \a violation may be
  80660. * \c NULL if you don't need the returned string. Do not
  80661. * free the returned string; it will always point to static
  80662. * data.
  80663. * \assert
  80664. * \code cue_sheet != NULL \endcode
  80665. * \retval FLAC__bool
  80666. * \c false if cue sheet is illegal, else \c true.
  80667. */
  80668. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  80669. /** Check picture data to see if it conforms to the FLAC specification.
  80670. * See the format specification for limits on the contents of the
  80671. * PICTURE block.
  80672. *
  80673. * \param picture A pointer to existing picture data to be checked.
  80674. * \param violation Address of a pointer to a string. If there is a
  80675. * violation, a pointer to a string explanation of the
  80676. * violation will be returned here. \a violation may be
  80677. * \c NULL if you don't need the returned string. Do not
  80678. * free the returned string; it will always point to static
  80679. * data.
  80680. * \assert
  80681. * \code picture != NULL \endcode
  80682. * \retval FLAC__bool
  80683. * \c false if picture data is illegal, else \c true.
  80684. */
  80685. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  80686. /* \} */
  80687. #ifdef __cplusplus
  80688. }
  80689. #endif
  80690. #endif
  80691. /********* End of inlined file: format.h *********/
  80692. /********* Start of inlined file: metadata.h *********/
  80693. #ifndef FLAC__METADATA_H
  80694. #define FLAC__METADATA_H
  80695. #include <sys/types.h> /* for off_t */
  80696. /* --------------------------------------------------------------------
  80697. (For an example of how all these routines are used, see the source
  80698. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  80699. metaflac in src/metaflac/)
  80700. ------------------------------------------------------------------*/
  80701. /** \file include/FLAC/metadata.h
  80702. *
  80703. * \brief
  80704. * This module provides functions for creating and manipulating FLAC
  80705. * metadata blocks in memory, and three progressively more powerful
  80706. * interfaces for traversing and editing metadata in FLAC files.
  80707. *
  80708. * See the detailed documentation for each interface in the
  80709. * \link flac_metadata metadata \endlink module.
  80710. */
  80711. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  80712. * \ingroup flac
  80713. *
  80714. * \brief
  80715. * This module provides functions for creating and manipulating FLAC
  80716. * metadata blocks in memory, and three progressively more powerful
  80717. * interfaces for traversing and editing metadata in native FLAC files.
  80718. * Note that currently only the Chain interface (level 2) supports Ogg
  80719. * FLAC files, and it is read-only i.e. no writing back changed
  80720. * metadata to file.
  80721. *
  80722. * There are three metadata interfaces of increasing complexity:
  80723. *
  80724. * Level 0:
  80725. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  80726. * PICTURE blocks.
  80727. *
  80728. * Level 1:
  80729. * Read-write access to all metadata blocks. This level is write-
  80730. * efficient in most cases (more on this below), and uses less memory
  80731. * than level 2.
  80732. *
  80733. * Level 2:
  80734. * Read-write access to all metadata blocks. This level is write-
  80735. * efficient in all cases, but uses more memory since all metadata for
  80736. * the whole file is read into memory and manipulated before writing
  80737. * out again.
  80738. *
  80739. * What do we mean by efficient? Since FLAC metadata appears at the
  80740. * beginning of the file, when writing metadata back to a FLAC file
  80741. * it is possible to grow or shrink the metadata such that the entire
  80742. * file must be rewritten. However, if the size remains the same during
  80743. * changes or PADDING blocks are utilized, only the metadata needs to be
  80744. * overwritten, which is much faster.
  80745. *
  80746. * Efficient means the whole file is rewritten at most one time, and only
  80747. * when necessary. Level 1 is not efficient only in the case that you
  80748. * cause more than one metadata block to grow or shrink beyond what can
  80749. * be accomodated by padding. In this case you should probably use level
  80750. * 2, which allows you to edit all the metadata for a file in memory and
  80751. * write it out all at once.
  80752. *
  80753. * All levels know how to skip over and not disturb an ID3v2 tag at the
  80754. * front of the file.
  80755. *
  80756. * All levels access files via their filenames. In addition, level 2
  80757. * has additional alternative read and write functions that take an I/O
  80758. * handle and callbacks, for situations where access by filename is not
  80759. * possible.
  80760. *
  80761. * In addition to the three interfaces, this module defines functions for
  80762. * creating and manipulating various metadata objects in memory. As we see
  80763. * from the Format module, FLAC metadata blocks in memory are very primitive
  80764. * structures for storing information in an efficient way. Reading
  80765. * information from the structures is easy but creating or modifying them
  80766. * directly is more complex. The metadata object routines here facilitate
  80767. * this by taking care of the consistency and memory management drudgery.
  80768. *
  80769. * Unless you will be using the level 1 or 2 interfaces to modify existing
  80770. * metadata however, you will not probably not need these.
  80771. *
  80772. * From a dependency standpoint, none of the encoders or decoders require
  80773. * the metadata module. This is so that embedded users can strip out the
  80774. * metadata module from libFLAC to reduce the size and complexity.
  80775. */
  80776. #ifdef __cplusplus
  80777. extern "C" {
  80778. #endif
  80779. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  80780. * \ingroup flac_metadata
  80781. *
  80782. * \brief
  80783. * The level 0 interface consists of individual routines to read the
  80784. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  80785. * only a filename.
  80786. *
  80787. * They try to skip any ID3v2 tag at the head of the file.
  80788. *
  80789. * \{
  80790. */
  80791. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  80792. * will try to skip any ID3v2 tag at the head of the file.
  80793. *
  80794. * \param filename The path to the FLAC file to read.
  80795. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  80796. * FLAC__StreamMetadata is a simple structure with no
  80797. * memory allocation involved, you pass the address of
  80798. * an existing structure. It need not be initialized.
  80799. * \assert
  80800. * \code filename != NULL \endcode
  80801. * \code streaminfo != NULL \endcode
  80802. * \retval FLAC__bool
  80803. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  80804. * \c false if there was a memory allocation error, a file decoder error,
  80805. * or the file contained no STREAMINFO block. (A memory allocation error
  80806. * is possible because this function must set up a file decoder.)
  80807. */
  80808. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  80809. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  80810. * function will try to skip any ID3v2 tag at the head of the file.
  80811. *
  80812. * \param filename The path to the FLAC file to read.
  80813. * \param tags The address where the returned pointer will be
  80814. * stored. The \a tags object must be deleted by
  80815. * the caller using FLAC__metadata_object_delete().
  80816. * \assert
  80817. * \code filename != NULL \endcode
  80818. * \code tags != NULL \endcode
  80819. * \retval FLAC__bool
  80820. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  80821. * and \a *tags will be set to the address of the metadata structure.
  80822. * Returns \c false if there was a memory allocation error, a file
  80823. * decoder error, or the file contained no VORBIS_COMMENT block, and
  80824. * \a *tags will be set to \c NULL.
  80825. */
  80826. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  80827. /** Read the CUESHEET metadata block of the given FLAC file. This
  80828. * function will try to skip any ID3v2 tag at the head of the file.
  80829. *
  80830. * \param filename The path to the FLAC file to read.
  80831. * \param cuesheet The address where the returned pointer will be
  80832. * stored. The \a cuesheet object must be deleted by
  80833. * the caller using FLAC__metadata_object_delete().
  80834. * \assert
  80835. * \code filename != NULL \endcode
  80836. * \code cuesheet != NULL \endcode
  80837. * \retval FLAC__bool
  80838. * \c true if a valid CUESHEET block was read from \a filename,
  80839. * and \a *cuesheet will be set to the address of the metadata
  80840. * structure. Returns \c false if there was a memory allocation
  80841. * error, a file decoder error, or the file contained no CUESHEET
  80842. * block, and \a *cuesheet will be set to \c NULL.
  80843. */
  80844. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  80845. /** Read a PICTURE metadata block of the given FLAC file. This
  80846. * function will try to skip any ID3v2 tag at the head of the file.
  80847. * Since there can be more than one PICTURE block in a file, this
  80848. * function takes a number of parameters that act as constraints to
  80849. * the search. The PICTURE block with the largest area matching all
  80850. * the constraints will be returned, or \a *picture will be set to
  80851. * \c NULL if there was no such block.
  80852. *
  80853. * \param filename The path to the FLAC file to read.
  80854. * \param picture The address where the returned pointer will be
  80855. * stored. The \a picture object must be deleted by
  80856. * the caller using FLAC__metadata_object_delete().
  80857. * \param type The desired picture type. Use \c -1 to mean
  80858. * "any type".
  80859. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  80860. * string will be matched exactly. Use \c NULL to
  80861. * mean "any MIME type".
  80862. * \param description The desired description. The string will be
  80863. * matched exactly. Use \c NULL to mean "any
  80864. * description".
  80865. * \param max_width The maximum width in pixels desired. Use
  80866. * \c (unsigned)(-1) to mean "any width".
  80867. * \param max_height The maximum height in pixels desired. Use
  80868. * \c (unsigned)(-1) to mean "any height".
  80869. * \param max_depth The maximum color depth in bits-per-pixel desired.
  80870. * Use \c (unsigned)(-1) to mean "any depth".
  80871. * \param max_colors The maximum number of colors desired. Use
  80872. * \c (unsigned)(-1) to mean "any number of colors".
  80873. * \assert
  80874. * \code filename != NULL \endcode
  80875. * \code picture != NULL \endcode
  80876. * \retval FLAC__bool
  80877. * \c true if a valid PICTURE block was read from \a filename,
  80878. * and \a *picture will be set to the address of the metadata
  80879. * structure. Returns \c false if there was a memory allocation
  80880. * error, a file decoder error, or the file contained no PICTURE
  80881. * block, and \a *picture will be set to \c NULL.
  80882. */
  80883. FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors);
  80884. /* \} */
  80885. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  80886. * \ingroup flac_metadata
  80887. *
  80888. * \brief
  80889. * The level 1 interface provides read-write access to FLAC file metadata and
  80890. * operates directly on the FLAC file.
  80891. *
  80892. * The general usage of this interface is:
  80893. *
  80894. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  80895. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  80896. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  80897. * see if the file is writable, or only read access is allowed.
  80898. * - Use FLAC__metadata_simple_iterator_next() and
  80899. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  80900. * This is does not read the actual blocks themselves.
  80901. * FLAC__metadata_simple_iterator_next() is relatively fast.
  80902. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  80903. * forward from the front of the file.
  80904. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  80905. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  80906. * the current iterator position. The returned object is yours to modify
  80907. * and free.
  80908. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  80909. * back. You must have write permission to the original file. Make sure to
  80910. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  80911. * below.
  80912. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  80913. * Use the object creation functions from
  80914. * \link flac_metadata_object here \endlink to generate new objects.
  80915. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  80916. * currently referred to by the iterator, or replace it with padding.
  80917. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  80918. * finished.
  80919. *
  80920. * \note
  80921. * The FLAC file remains open the whole time between
  80922. * FLAC__metadata_simple_iterator_init() and
  80923. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  80924. * the file during this time.
  80925. *
  80926. * \note
  80927. * Do not modify the \a is_last, \a length, or \a type fields of returned
  80928. * FLAC__StreamMetadata objects. These are managed automatically.
  80929. *
  80930. * \note
  80931. * If any of the modification functions
  80932. * (FLAC__metadata_simple_iterator_set_block(),
  80933. * FLAC__metadata_simple_iterator_delete_block(),
  80934. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  80935. * you should delete the iterator as it may no longer be valid.
  80936. *
  80937. * \{
  80938. */
  80939. struct FLAC__Metadata_SimpleIterator;
  80940. /** The opaque structure definition for the level 1 iterator type.
  80941. * See the
  80942. * \link flac_metadata_level1 metadata level 1 module \endlink
  80943. * for a detailed description.
  80944. */
  80945. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  80946. /** Status type for FLAC__Metadata_SimpleIterator.
  80947. *
  80948. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  80949. */
  80950. typedef enum {
  80951. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  80952. /**< The iterator is in the normal OK state */
  80953. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  80954. /**< The data passed into a function violated the function's usage criteria */
  80955. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  80956. /**< The iterator could not open the target file */
  80957. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  80958. /**< The iterator could not find the FLAC signature at the start of the file */
  80959. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  80960. /**< The iterator tried to write to a file that was not writable */
  80961. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  80962. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  80963. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  80964. /**< The iterator encountered an error while reading the FLAC file */
  80965. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  80966. /**< The iterator encountered an error while seeking in the FLAC file */
  80967. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  80968. /**< The iterator encountered an error while writing the FLAC file */
  80969. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  80970. /**< The iterator encountered an error renaming the FLAC file */
  80971. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  80972. /**< The iterator encountered an error removing the temporary file */
  80973. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  80974. /**< Memory allocation failed */
  80975. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  80976. /**< The caller violated an assertion or an unexpected error occurred */
  80977. } FLAC__Metadata_SimpleIteratorStatus;
  80978. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  80979. *
  80980. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  80981. * will give the string equivalent. The contents should not be modified.
  80982. */
  80983. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  80984. /** Create a new iterator instance.
  80985. *
  80986. * \retval FLAC__Metadata_SimpleIterator*
  80987. * \c NULL if there was an error allocating memory, else the new instance.
  80988. */
  80989. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  80990. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  80991. *
  80992. * \param iterator A pointer to an existing iterator.
  80993. * \assert
  80994. * \code iterator != NULL \endcode
  80995. */
  80996. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  80997. /** Get the current status of the iterator. Call this after a function
  80998. * returns \c false to get the reason for the error. Also resets the status
  80999. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  81000. *
  81001. * \param iterator A pointer to an existing iterator.
  81002. * \assert
  81003. * \code iterator != NULL \endcode
  81004. * \retval FLAC__Metadata_SimpleIteratorStatus
  81005. * The current status of the iterator.
  81006. */
  81007. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  81008. /** Initialize the iterator to point to the first metadata block in the
  81009. * given FLAC file.
  81010. *
  81011. * \param iterator A pointer to an existing iterator.
  81012. * \param filename The path to the FLAC file.
  81013. * \param read_only If \c true, the FLAC file will be opened
  81014. * in read-only mode; if \c false, the FLAC
  81015. * file will be opened for edit even if no
  81016. * edits are performed.
  81017. * \param preserve_file_stats If \c true, the owner and modification
  81018. * time will be preserved even if the FLAC
  81019. * file is written to.
  81020. * \assert
  81021. * \code iterator != NULL \endcode
  81022. * \code filename != NULL \endcode
  81023. * \retval FLAC__bool
  81024. * \c false if a memory allocation error occurs, the file can't be
  81025. * opened, or another error occurs, else \c true.
  81026. */
  81027. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
  81028. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  81029. * FLAC__metadata_simple_iterator_set_block() and
  81030. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  81031. *
  81032. * \param iterator A pointer to an existing iterator.
  81033. * \assert
  81034. * \code iterator != NULL \endcode
  81035. * \retval FLAC__bool
  81036. * See above.
  81037. */
  81038. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  81039. /** Moves the iterator forward one metadata block, returning \c false if
  81040. * already at the end.
  81041. *
  81042. * \param iterator A pointer to an existing initialized iterator.
  81043. * \assert
  81044. * \code iterator != NULL \endcode
  81045. * \a iterator has been successfully initialized with
  81046. * FLAC__metadata_simple_iterator_init()
  81047. * \retval FLAC__bool
  81048. * \c false if already at the last metadata block of the chain, else
  81049. * \c true.
  81050. */
  81051. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  81052. /** Moves the iterator backward one metadata block, returning \c false if
  81053. * already at the beginning.
  81054. *
  81055. * \param iterator A pointer to an existing initialized iterator.
  81056. * \assert
  81057. * \code iterator != NULL \endcode
  81058. * \a iterator has been successfully initialized with
  81059. * FLAC__metadata_simple_iterator_init()
  81060. * \retval FLAC__bool
  81061. * \c false if already at the first metadata block of the chain, else
  81062. * \c true.
  81063. */
  81064. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  81065. /** Returns a flag telling if the current metadata block is the last.
  81066. *
  81067. * \param iterator A pointer to an existing initialized iterator.
  81068. * \assert
  81069. * \code iterator != NULL \endcode
  81070. * \a iterator has been successfully initialized with
  81071. * FLAC__metadata_simple_iterator_init()
  81072. * \retval FLAC__bool
  81073. * \c true if the current metadata block is the last in the file,
  81074. * else \c false.
  81075. */
  81076. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  81077. /** Get the offset of the metadata block at the current position. This
  81078. * avoids reading the actual block data which can save time for large
  81079. * blocks.
  81080. *
  81081. * \param iterator A pointer to an existing initialized iterator.
  81082. * \assert
  81083. * \code iterator != NULL \endcode
  81084. * \a iterator has been successfully initialized with
  81085. * FLAC__metadata_simple_iterator_init()
  81086. * \retval off_t
  81087. * The offset of the metadata block at the current iterator position.
  81088. * This is the byte offset relative to the beginning of the file of
  81089. * the current metadata block's header.
  81090. */
  81091. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  81092. /** Get the type of the metadata block at the current position. This
  81093. * avoids reading the actual block data which can save time for large
  81094. * blocks.
  81095. *
  81096. * \param iterator A pointer to an existing initialized iterator.
  81097. * \assert
  81098. * \code iterator != NULL \endcode
  81099. * \a iterator has been successfully initialized with
  81100. * FLAC__metadata_simple_iterator_init()
  81101. * \retval FLAC__MetadataType
  81102. * The type of the metadata block at the current iterator position.
  81103. */
  81104. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  81105. /** Get the length of the metadata block at the current position. This
  81106. * avoids reading the actual block data which can save time for large
  81107. * blocks.
  81108. *
  81109. * \param iterator A pointer to an existing initialized iterator.
  81110. * \assert
  81111. * \code iterator != NULL \endcode
  81112. * \a iterator has been successfully initialized with
  81113. * FLAC__metadata_simple_iterator_init()
  81114. * \retval unsigned
  81115. * The length of the metadata block at the current iterator position.
  81116. * The is same length as that in the
  81117. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  81118. * i.e. the length of the metadata body that follows the header.
  81119. */
  81120. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  81121. /** Get the application ID of the \c APPLICATION block at the current
  81122. * position. This avoids reading the actual block data which can save
  81123. * time for large blocks.
  81124. *
  81125. * \param iterator A pointer to an existing initialized iterator.
  81126. * \param id A pointer to a buffer of at least \c 4 bytes where
  81127. * the ID will be stored.
  81128. * \assert
  81129. * \code iterator != NULL \endcode
  81130. * \code id != NULL \endcode
  81131. * \a iterator has been successfully initialized with
  81132. * FLAC__metadata_simple_iterator_init()
  81133. * \retval FLAC__bool
  81134. * \c true if the ID was successfully read, else \c false, in which
  81135. * case you should check FLAC__metadata_simple_iterator_status() to
  81136. * find out why. If the status is
  81137. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  81138. * current metadata block is not an \c APPLICATION block. Otherwise
  81139. * if the status is
  81140. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  81141. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  81142. * occurred and the iterator can no longer be used.
  81143. */
  81144. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  81145. /** Get the metadata block at the current position. You can modify the
  81146. * block but must use FLAC__metadata_simple_iterator_set_block() to
  81147. * write it back to the FLAC file.
  81148. *
  81149. * You must call FLAC__metadata_object_delete() on the returned object
  81150. * when you are finished with it.
  81151. *
  81152. * \param iterator A pointer to an existing initialized iterator.
  81153. * \assert
  81154. * \code iterator != NULL \endcode
  81155. * \a iterator has been successfully initialized with
  81156. * FLAC__metadata_simple_iterator_init()
  81157. * \retval FLAC__StreamMetadata*
  81158. * The current metadata block, or \c NULL if there was a memory
  81159. * allocation error.
  81160. */
  81161. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  81162. /** Write a block back to the FLAC file. This function tries to be
  81163. * as efficient as possible; how the block is actually written is
  81164. * shown by the following:
  81165. *
  81166. * Existing block is a STREAMINFO block and the new block is a
  81167. * STREAMINFO block: the new block is written in place. Make sure
  81168. * you know what you're doing when changing the values of a
  81169. * STREAMINFO block.
  81170. *
  81171. * Existing block is a STREAMINFO block and the new block is a
  81172. * not a STREAMINFO block: this is an error since the first block
  81173. * must be a STREAMINFO block. Returns \c false without altering the
  81174. * file.
  81175. *
  81176. * Existing block is not a STREAMINFO block and the new block is a
  81177. * STREAMINFO block: this is an error since there may be only one
  81178. * STREAMINFO block. Returns \c false without altering the file.
  81179. *
  81180. * Existing block and new block are the same length: the existing
  81181. * block will be replaced by the new block, written in place.
  81182. *
  81183. * Existing block is longer than new block: if use_padding is \c true,
  81184. * the existing block will be overwritten in place with the new
  81185. * block followed by a PADDING block, if possible, to make the total
  81186. * size the same as the existing block. Remember that a padding
  81187. * block requires at least four bytes so if the difference in size
  81188. * between the new block and existing block is less than that, the
  81189. * entire file will have to be rewritten, using the new block's
  81190. * exact size. If use_padding is \c false, the entire file will be
  81191. * rewritten, replacing the existing block by the new block.
  81192. *
  81193. * Existing block is shorter than new block: if use_padding is \c true,
  81194. * the function will try and expand the new block into the following
  81195. * PADDING block, if it exists and doing so won't shrink the PADDING
  81196. * block to less than 4 bytes. If there is no following PADDING
  81197. * block, or it will shrink to less than 4 bytes, or use_padding is
  81198. * \c false, the entire file is rewritten, replacing the existing block
  81199. * with the new block. Note that in this case any following PADDING
  81200. * block is preserved as is.
  81201. *
  81202. * After writing the block, the iterator will remain in the same
  81203. * place, i.e. pointing to the new block.
  81204. *
  81205. * \param iterator A pointer to an existing initialized iterator.
  81206. * \param block The block to set.
  81207. * \param use_padding See above.
  81208. * \assert
  81209. * \code iterator != NULL \endcode
  81210. * \a iterator has been successfully initialized with
  81211. * FLAC__metadata_simple_iterator_init()
  81212. * \code block != NULL \endcode
  81213. * \retval FLAC__bool
  81214. * \c true if successful, else \c false.
  81215. */
  81216. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81217. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  81218. * except that instead of writing over an existing block, it appends
  81219. * a block after the existing block. \a use_padding is again used to
  81220. * tell the function to try an expand into following padding in an
  81221. * attempt to avoid rewriting the entire file.
  81222. *
  81223. * This function will fail and return \c false if given a STREAMINFO
  81224. * block.
  81225. *
  81226. * After writing the block, the iterator will be pointing to the
  81227. * new block.
  81228. *
  81229. * \param iterator A pointer to an existing initialized iterator.
  81230. * \param block The block to set.
  81231. * \param use_padding See above.
  81232. * \assert
  81233. * \code iterator != NULL \endcode
  81234. * \a iterator has been successfully initialized with
  81235. * FLAC__metadata_simple_iterator_init()
  81236. * \code block != NULL \endcode
  81237. * \retval FLAC__bool
  81238. * \c true if successful, else \c false.
  81239. */
  81240. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81241. /** Deletes the block at the current position. This will cause the
  81242. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  81243. * in which case the block will be replaced by an equal-sized PADDING
  81244. * block. The iterator will be left pointing to the block before the
  81245. * one just deleted.
  81246. *
  81247. * You may not delete the STREAMINFO block.
  81248. *
  81249. * \param iterator A pointer to an existing initialized iterator.
  81250. * \param use_padding See above.
  81251. * \assert
  81252. * \code iterator != NULL \endcode
  81253. * \a iterator has been successfully initialized with
  81254. * FLAC__metadata_simple_iterator_init()
  81255. * \retval FLAC__bool
  81256. * \c true if successful, else \c false.
  81257. */
  81258. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  81259. /* \} */
  81260. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  81261. * \ingroup flac_metadata
  81262. *
  81263. * \brief
  81264. * The level 2 interface provides read-write access to FLAC file metadata;
  81265. * all metadata is read into memory, operated on in memory, and then written
  81266. * to file, which is more efficient than level 1 when editing multiple blocks.
  81267. *
  81268. * Currently Ogg FLAC is supported for read only, via
  81269. * FLAC__metadata_chain_read_ogg() but a subsequent
  81270. * FLAC__metadata_chain_write() will fail.
  81271. *
  81272. * The general usage of this interface is:
  81273. *
  81274. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  81275. * linked list of FLAC metadata blocks.
  81276. * - Read all metadata into the the chain from a FLAC file using
  81277. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  81278. * check the status.
  81279. * - Optionally, consolidate the padding using
  81280. * FLAC__metadata_chain_merge_padding() or
  81281. * FLAC__metadata_chain_sort_padding().
  81282. * - Create a new iterator using FLAC__metadata_iterator_new()
  81283. * - Initialize the iterator to point to the first element in the chain
  81284. * using FLAC__metadata_iterator_init()
  81285. * - Traverse the chain using FLAC__metadata_iterator_next and
  81286. * FLAC__metadata_iterator_prev().
  81287. * - Get a block for reading or modification using
  81288. * FLAC__metadata_iterator_get_block(). The pointer to the object
  81289. * inside the chain is returned, so the block is yours to modify.
  81290. * Changes will be reflected in the FLAC file when you write the
  81291. * chain. You can also add and delete blocks (see functions below).
  81292. * - When done, write out the chain using FLAC__metadata_chain_write().
  81293. * Make sure to read the whole comment to the function below.
  81294. * - Delete the chain using FLAC__metadata_chain_delete().
  81295. *
  81296. * \note
  81297. * Even though the FLAC file is not open while the chain is being
  81298. * manipulated, you must not alter the file externally during
  81299. * this time. The chain assumes the FLAC file will not change
  81300. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  81301. * and FLAC__metadata_chain_write().
  81302. *
  81303. * \note
  81304. * Do not modify the is_last, length, or type fields of returned
  81305. * FLAC__StreamMetadata objects. These are managed automatically.
  81306. *
  81307. * \note
  81308. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  81309. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  81310. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  81311. * become owned by the chain and they will be deleted when the chain is
  81312. * deleted.
  81313. *
  81314. * \{
  81315. */
  81316. struct FLAC__Metadata_Chain;
  81317. /** The opaque structure definition for the level 2 chain type.
  81318. */
  81319. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  81320. struct FLAC__Metadata_Iterator;
  81321. /** The opaque structure definition for the level 2 iterator type.
  81322. */
  81323. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  81324. typedef enum {
  81325. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  81326. /**< The chain is in the normal OK state */
  81327. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  81328. /**< The data passed into a function violated the function's usage criteria */
  81329. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  81330. /**< The chain could not open the target file */
  81331. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  81332. /**< The chain could not find the FLAC signature at the start of the file */
  81333. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  81334. /**< The chain tried to write to a file that was not writable */
  81335. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  81336. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  81337. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  81338. /**< The chain encountered an error while reading the FLAC file */
  81339. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  81340. /**< The chain encountered an error while seeking in the FLAC file */
  81341. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  81342. /**< The chain encountered an error while writing the FLAC file */
  81343. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  81344. /**< The chain encountered an error renaming the FLAC file */
  81345. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  81346. /**< The chain encountered an error removing the temporary file */
  81347. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  81348. /**< Memory allocation failed */
  81349. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  81350. /**< The caller violated an assertion or an unexpected error occurred */
  81351. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  81352. /**< One or more of the required callbacks was NULL */
  81353. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  81354. /**< FLAC__metadata_chain_write() was called on a chain read by
  81355. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81356. * or
  81357. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  81358. * was called on a chain read by
  81359. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81360. * Matching read/write methods must always be used. */
  81361. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  81362. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  81363. * chain write requires a tempfile; use
  81364. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  81365. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  81366. * called when the chain write does not require a tempfile; use
  81367. * FLAC__metadata_chain_write_with_callbacks() instead.
  81368. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  81369. * before writing via callbacks. */
  81370. } FLAC__Metadata_ChainStatus;
  81371. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  81372. *
  81373. * Using a FLAC__Metadata_ChainStatus as the index to this array
  81374. * will give the string equivalent. The contents should not be modified.
  81375. */
  81376. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  81377. /*********** FLAC__Metadata_Chain ***********/
  81378. /** Create a new chain instance.
  81379. *
  81380. * \retval FLAC__Metadata_Chain*
  81381. * \c NULL if there was an error allocating memory, else the new instance.
  81382. */
  81383. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  81384. /** Free a chain instance. Deletes the object pointed to by \a chain.
  81385. *
  81386. * \param chain A pointer to an existing chain.
  81387. * \assert
  81388. * \code chain != NULL \endcode
  81389. */
  81390. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  81391. /** Get the current status of the chain. Call this after a function
  81392. * returns \c false to get the reason for the error. Also resets the
  81393. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  81394. *
  81395. * \param chain A pointer to an existing chain.
  81396. * \assert
  81397. * \code chain != NULL \endcode
  81398. * \retval FLAC__Metadata_ChainStatus
  81399. * The current status of the chain.
  81400. */
  81401. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  81402. /** Read all metadata from a FLAC file into the chain.
  81403. *
  81404. * \param chain A pointer to an existing chain.
  81405. * \param filename The path to the FLAC file to read.
  81406. * \assert
  81407. * \code chain != NULL \endcode
  81408. * \code filename != NULL \endcode
  81409. * \retval FLAC__bool
  81410. * \c true if a valid list of metadata blocks was read from
  81411. * \a filename, else \c false. On failure, check the status with
  81412. * FLAC__metadata_chain_status().
  81413. */
  81414. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  81415. /** Read all metadata from an Ogg FLAC file into the chain.
  81416. *
  81417. * \note Ogg FLAC metadata data writing is not supported yet and
  81418. * FLAC__metadata_chain_write() will fail.
  81419. *
  81420. * \param chain A pointer to an existing chain.
  81421. * \param filename The path to the Ogg FLAC file to read.
  81422. * \assert
  81423. * \code chain != NULL \endcode
  81424. * \code filename != NULL \endcode
  81425. * \retval FLAC__bool
  81426. * \c true if a valid list of metadata blocks was read from
  81427. * \a filename, else \c false. On failure, check the status with
  81428. * FLAC__metadata_chain_status().
  81429. */
  81430. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  81431. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  81432. *
  81433. * The \a handle need only be open for reading, but must be seekable.
  81434. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81435. * for Windows).
  81436. *
  81437. * \param chain A pointer to an existing chain.
  81438. * \param handle The I/O handle of the FLAC stream to read. The
  81439. * handle will NOT be closed after the metadata is read;
  81440. * that is the duty of the caller.
  81441. * \param callbacks
  81442. * A set of callbacks to use for I/O. The mandatory
  81443. * callbacks are \a read, \a seek, and \a tell.
  81444. * \assert
  81445. * \code chain != NULL \endcode
  81446. * \retval FLAC__bool
  81447. * \c true if a valid list of metadata blocks was read from
  81448. * \a handle, else \c false. On failure, check the status with
  81449. * FLAC__metadata_chain_status().
  81450. */
  81451. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81452. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  81453. *
  81454. * The \a handle need only be open for reading, but must be seekable.
  81455. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81456. * for Windows).
  81457. *
  81458. * \note Ogg FLAC metadata data writing is not supported yet and
  81459. * FLAC__metadata_chain_write() will fail.
  81460. *
  81461. * \param chain A pointer to an existing chain.
  81462. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  81463. * handle will NOT be closed after the metadata is read;
  81464. * that is the duty of the caller.
  81465. * \param callbacks
  81466. * A set of callbacks to use for I/O. The mandatory
  81467. * callbacks are \a read, \a seek, and \a tell.
  81468. * \assert
  81469. * \code chain != NULL \endcode
  81470. * \retval FLAC__bool
  81471. * \c true if a valid list of metadata blocks was read from
  81472. * \a handle, else \c false. On failure, check the status with
  81473. * FLAC__metadata_chain_status().
  81474. */
  81475. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81476. /** Checks if writing the given chain would require the use of a
  81477. * temporary file, or if it could be written in place.
  81478. *
  81479. * Under certain conditions, padding can be utilized so that writing
  81480. * edited metadata back to the FLAC file does not require rewriting the
  81481. * entire file. If rewriting is required, then a temporary workfile is
  81482. * required. When writing metadata using callbacks, you must check
  81483. * this function to know whether to call
  81484. * FLAC__metadata_chain_write_with_callbacks() or
  81485. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  81486. * writing with FLAC__metadata_chain_write(), the temporary file is
  81487. * handled internally.
  81488. *
  81489. * \param chain A pointer to an existing chain.
  81490. * \param use_padding
  81491. * Whether or not padding will be allowed to be used
  81492. * during the write. The value of \a use_padding given
  81493. * here must match the value later passed to
  81494. * FLAC__metadata_chain_write_with_callbacks() or
  81495. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  81496. * \assert
  81497. * \code chain != NULL \endcode
  81498. * \retval FLAC__bool
  81499. * \c true if writing the current chain would require a tempfile, or
  81500. * \c false if metadata can be written in place.
  81501. */
  81502. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  81503. /** Write all metadata out to the FLAC file. This function tries to be as
  81504. * efficient as possible; how the metadata is actually written is shown by
  81505. * the following:
  81506. *
  81507. * If the current chain is the same size as the existing metadata, the new
  81508. * data is written in place.
  81509. *
  81510. * If the current chain is longer than the existing metadata, and
  81511. * \a use_padding is \c true, and the last block is a PADDING block of
  81512. * sufficient length, the function will truncate the final padding block
  81513. * so that the overall size of the metadata is the same as the existing
  81514. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  81515. * the above conditions are met, the entire FLAC file must be rewritten.
  81516. * If you want to use padding this way it is a good idea to call
  81517. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  81518. * amount of padding to work with, unless you need to preserve ordering
  81519. * of the PADDING blocks for some reason.
  81520. *
  81521. * If the current chain is shorter than the existing metadata, and
  81522. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  81523. * is extended to make the overall size the same as the existing data. If
  81524. * \a use_padding is \c true and the last block is not a PADDING block, a new
  81525. * PADDING block is added to the end of the new data to make it the same
  81526. * size as the existing data (if possible, see the note to
  81527. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  81528. * and the new data is written in place. If none of the above apply or
  81529. * \a use_padding is \c false, the entire FLAC file is rewritten.
  81530. *
  81531. * If \a preserve_file_stats is \c true, the owner and modification time will
  81532. * be preserved even if the FLAC file is written.
  81533. *
  81534. * For this write function to be used, the chain must have been read with
  81535. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  81536. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  81537. *
  81538. * \param chain A pointer to an existing chain.
  81539. * \param use_padding See above.
  81540. * \param preserve_file_stats See above.
  81541. * \assert
  81542. * \code chain != NULL \endcode
  81543. * \retval FLAC__bool
  81544. * \c true if the write succeeded, else \c false. On failure,
  81545. * check the status with FLAC__metadata_chain_status().
  81546. */
  81547. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  81548. /** Write all metadata out to a FLAC stream via callbacks.
  81549. *
  81550. * (See FLAC__metadata_chain_write() for the details on how padding is
  81551. * used to write metadata in place if possible.)
  81552. *
  81553. * The \a handle must be open for updating and be seekable. The
  81554. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  81555. * for Windows).
  81556. *
  81557. * For this write function to be used, the chain must have been read with
  81558. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81559. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81560. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  81561. * \c false.
  81562. *
  81563. * \param chain A pointer to an existing chain.
  81564. * \param use_padding See FLAC__metadata_chain_write()
  81565. * \param handle The I/O handle of the FLAC stream to write. The
  81566. * handle will NOT be closed after the metadata is
  81567. * written; that is the duty of the caller.
  81568. * \param callbacks A set of callbacks to use for I/O. The mandatory
  81569. * callbacks are \a write and \a seek.
  81570. * \assert
  81571. * \code chain != NULL \endcode
  81572. * \retval FLAC__bool
  81573. * \c true if the write succeeded, else \c false. On failure,
  81574. * check the status with FLAC__metadata_chain_status().
  81575. */
  81576. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81577. /** Write all metadata out to a FLAC stream via callbacks.
  81578. *
  81579. * (See FLAC__metadata_chain_write() for the details on how padding is
  81580. * used to write metadata in place if possible.)
  81581. *
  81582. * This version of the write-with-callbacks function must be used when
  81583. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  81584. * this function, you must supply an I/O handle corresponding to the
  81585. * FLAC file to edit, and a temporary handle to which the new FLAC
  81586. * file will be written. It is the caller's job to move this temporary
  81587. * FLAC file on top of the original FLAC file to complete the metadata
  81588. * edit.
  81589. *
  81590. * The \a handle must be open for reading and be seekable. The
  81591. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81592. * for Windows).
  81593. *
  81594. * The \a temp_handle must be open for writing. The
  81595. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  81596. * for Windows). It should be an empty stream, or at least positioned
  81597. * at the start-of-file (in which case it is the caller's duty to
  81598. * truncate it on return).
  81599. *
  81600. * For this write function to be used, the chain must have been read with
  81601. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81602. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81603. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  81604. * \c true.
  81605. *
  81606. * \param chain A pointer to an existing chain.
  81607. * \param use_padding See FLAC__metadata_chain_write()
  81608. * \param handle The I/O handle of the original FLAC stream to read.
  81609. * The handle will NOT be closed after the metadata is
  81610. * written; that is the duty of the caller.
  81611. * \param callbacks A set of callbacks to use for I/O on \a handle.
  81612. * The mandatory callbacks are \a read, \a seek, and
  81613. * \a eof.
  81614. * \param temp_handle The I/O handle of the FLAC stream to write. The
  81615. * handle will NOT be closed after the metadata is
  81616. * written; that is the duty of the caller.
  81617. * \param temp_callbacks
  81618. * A set of callbacks to use for I/O on temp_handle.
  81619. * The only mandatory callback is \a write.
  81620. * \assert
  81621. * \code chain != NULL \endcode
  81622. * \retval FLAC__bool
  81623. * \c true if the write succeeded, else \c false. On failure,
  81624. * check the status with FLAC__metadata_chain_status().
  81625. */
  81626. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks);
  81627. /** Merge adjacent PADDING blocks into a single block.
  81628. *
  81629. * \note This function does not write to the FLAC file, it only
  81630. * modifies the chain.
  81631. *
  81632. * \warning Any iterator on the current chain will become invalid after this
  81633. * call. You should delete the iterator and get a new one.
  81634. *
  81635. * \param chain A pointer to an existing chain.
  81636. * \assert
  81637. * \code chain != NULL \endcode
  81638. */
  81639. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  81640. /** This function will move all PADDING blocks to the end on the metadata,
  81641. * then merge them into a single block.
  81642. *
  81643. * \note This function does not write to the FLAC file, it only
  81644. * modifies the chain.
  81645. *
  81646. * \warning Any iterator on the current chain will become invalid after this
  81647. * call. You should delete the iterator and get a new one.
  81648. *
  81649. * \param chain A pointer to an existing chain.
  81650. * \assert
  81651. * \code chain != NULL \endcode
  81652. */
  81653. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  81654. /*********** FLAC__Metadata_Iterator ***********/
  81655. /** Create a new iterator instance.
  81656. *
  81657. * \retval FLAC__Metadata_Iterator*
  81658. * \c NULL if there was an error allocating memory, else the new instance.
  81659. */
  81660. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  81661. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81662. *
  81663. * \param iterator A pointer to an existing iterator.
  81664. * \assert
  81665. * \code iterator != NULL \endcode
  81666. */
  81667. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  81668. /** Initialize the iterator to point to the first metadata block in the
  81669. * given chain.
  81670. *
  81671. * \param iterator A pointer to an existing iterator.
  81672. * \param chain A pointer to an existing and initialized (read) chain.
  81673. * \assert
  81674. * \code iterator != NULL \endcode
  81675. * \code chain != NULL \endcode
  81676. */
  81677. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  81678. /** Moves the iterator forward one metadata block, returning \c false if
  81679. * already at the end.
  81680. *
  81681. * \param iterator A pointer to an existing initialized iterator.
  81682. * \assert
  81683. * \code iterator != NULL \endcode
  81684. * \a iterator has been successfully initialized with
  81685. * FLAC__metadata_iterator_init()
  81686. * \retval FLAC__bool
  81687. * \c false if already at the last metadata block of the chain, else
  81688. * \c true.
  81689. */
  81690. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  81691. /** Moves the iterator backward one metadata block, returning \c false if
  81692. * already at the beginning.
  81693. *
  81694. * \param iterator A pointer to an existing initialized iterator.
  81695. * \assert
  81696. * \code iterator != NULL \endcode
  81697. * \a iterator has been successfully initialized with
  81698. * FLAC__metadata_iterator_init()
  81699. * \retval FLAC__bool
  81700. * \c false if already at the first metadata block of the chain, else
  81701. * \c true.
  81702. */
  81703. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  81704. /** Get the type of the metadata block at the current position.
  81705. *
  81706. * \param iterator A pointer to an existing initialized iterator.
  81707. * \assert
  81708. * \code iterator != NULL \endcode
  81709. * \a iterator has been successfully initialized with
  81710. * FLAC__metadata_iterator_init()
  81711. * \retval FLAC__MetadataType
  81712. * The type of the metadata block at the current iterator position.
  81713. */
  81714. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  81715. /** Get the metadata block at the current position. You can modify
  81716. * the block in place but must write the chain before the changes
  81717. * are reflected to the FLAC file. You do not need to call
  81718. * FLAC__metadata_iterator_set_block() to reflect the changes;
  81719. * the pointer returned by FLAC__metadata_iterator_get_block()
  81720. * points directly into the chain.
  81721. *
  81722. * \warning
  81723. * Do not call FLAC__metadata_object_delete() on the returned object;
  81724. * to delete a block use FLAC__metadata_iterator_delete_block().
  81725. *
  81726. * \param iterator A pointer to an existing initialized iterator.
  81727. * \assert
  81728. * \code iterator != NULL \endcode
  81729. * \a iterator has been successfully initialized with
  81730. * FLAC__metadata_iterator_init()
  81731. * \retval FLAC__StreamMetadata*
  81732. * The current metadata block.
  81733. */
  81734. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  81735. /** Set the metadata block at the current position, replacing the existing
  81736. * block. The new block passed in becomes owned by the chain and it will be
  81737. * deleted when the chain is deleted.
  81738. *
  81739. * \param iterator A pointer to an existing initialized iterator.
  81740. * \param block A pointer to a metadata block.
  81741. * \assert
  81742. * \code iterator != NULL \endcode
  81743. * \a iterator has been successfully initialized with
  81744. * FLAC__metadata_iterator_init()
  81745. * \code block != NULL \endcode
  81746. * \retval FLAC__bool
  81747. * \c false if the conditions in the above description are not met, or
  81748. * a memory allocation error occurs, otherwise \c true.
  81749. */
  81750. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81751. /** Removes the current block from the chain. If \a replace_with_padding is
  81752. * \c true, the block will instead be replaced with a padding block of equal
  81753. * size. You can not delete the STREAMINFO block. The iterator will be
  81754. * left pointing to the block before the one just "deleted", even if
  81755. * \a replace_with_padding is \c true.
  81756. *
  81757. * \param iterator A pointer to an existing initialized iterator.
  81758. * \param replace_with_padding See above.
  81759. * \assert
  81760. * \code iterator != NULL \endcode
  81761. * \a iterator has been successfully initialized with
  81762. * FLAC__metadata_iterator_init()
  81763. * \retval FLAC__bool
  81764. * \c false if the conditions in the above description are not met,
  81765. * otherwise \c true.
  81766. */
  81767. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  81768. /** Insert a new block before the current block. You cannot insert a block
  81769. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  81770. * as there can be only one, the one that already exists at the head when you
  81771. * read in a chain. The chain takes ownership of the new block and it will be
  81772. * deleted when the chain is deleted. The iterator will be left pointing to
  81773. * the new block.
  81774. *
  81775. * \param iterator A pointer to an existing initialized iterator.
  81776. * \param block A pointer to a metadata block to insert.
  81777. * \assert
  81778. * \code iterator != NULL \endcode
  81779. * \a iterator has been successfully initialized with
  81780. * FLAC__metadata_iterator_init()
  81781. * \retval FLAC__bool
  81782. * \c false if the conditions in the above description are not met, or
  81783. * a memory allocation error occurs, otherwise \c true.
  81784. */
  81785. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81786. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  81787. * block as there can be only one, the one that already exists at the head when
  81788. * you read in a chain. The chain takes ownership of the new block and it will
  81789. * be deleted when the chain is deleted. The iterator will be left pointing to
  81790. * the new block.
  81791. *
  81792. * \param iterator A pointer to an existing initialized iterator.
  81793. * \param block A pointer to a metadata block to insert.
  81794. * \assert
  81795. * \code iterator != NULL \endcode
  81796. * \a iterator has been successfully initialized with
  81797. * FLAC__metadata_iterator_init()
  81798. * \retval FLAC__bool
  81799. * \c false if the conditions in the above description are not met, or
  81800. * a memory allocation error occurs, otherwise \c true.
  81801. */
  81802. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81803. /* \} */
  81804. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  81805. * \ingroup flac_metadata
  81806. *
  81807. * \brief
  81808. * This module contains methods for manipulating FLAC metadata objects.
  81809. *
  81810. * Since many are variable length we have to be careful about the memory
  81811. * management. We decree that all pointers to data in the object are
  81812. * owned by the object and memory-managed by the object.
  81813. *
  81814. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  81815. * functions to create all instances. When using the
  81816. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  81817. * \a copy to \c true to have the function make it's own copy of the data, or
  81818. * to \c false to give the object ownership of your data. In the latter case
  81819. * your pointer must be freeable by free() and will be free()d when the object
  81820. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  81821. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  81822. * the length argument is 0 and the \a copy argument is \c false.
  81823. *
  81824. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  81825. * will return \c NULL in the case of a memory allocation error, otherwise a new
  81826. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  81827. * case of a memory allocation error.
  81828. *
  81829. * We don't have the convenience of C++ here, so note that the library relies
  81830. * on you to keep the types straight. In other words, if you pass, for
  81831. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  81832. * FLAC__metadata_object_application_set_data(), you will get an assertion
  81833. * failure.
  81834. *
  81835. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  81836. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  81837. * toward the length or stored in the stream, but it can make working with plain
  81838. * comments (those that don't contain embedded-NULs in the value) easier.
  81839. * Entries passed into these functions have trailing NULs added if missing, and
  81840. * returned entries are guaranteed to have a trailing NUL.
  81841. *
  81842. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  81843. * comment entry/name/value will first validate that it complies with the Vorbis
  81844. * comment specification and return false if it does not.
  81845. *
  81846. * There is no need to recalculate the length field on metadata blocks you
  81847. * have modified. They will be calculated automatically before they are
  81848. * written back to a file.
  81849. *
  81850. * \{
  81851. */
  81852. /** Create a new metadata object instance of the given type.
  81853. *
  81854. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  81855. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  81856. * the vendor string set (but zero comments).
  81857. *
  81858. * Do not pass in a value greater than or equal to
  81859. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  81860. * doing.
  81861. *
  81862. * \param type Type of object to create
  81863. * \retval FLAC__StreamMetadata*
  81864. * \c NULL if there was an error allocating memory or the type code is
  81865. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  81866. */
  81867. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  81868. /** Create a copy of an existing metadata object.
  81869. *
  81870. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  81871. * object is also copied. The caller takes ownership of the new block and
  81872. * is responsible for freeing it with FLAC__metadata_object_delete().
  81873. *
  81874. * \param object Pointer to object to copy.
  81875. * \assert
  81876. * \code object != NULL \endcode
  81877. * \retval FLAC__StreamMetadata*
  81878. * \c NULL if there was an error allocating memory, else the new instance.
  81879. */
  81880. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  81881. /** Free a metadata object. Deletes the object pointed to by \a object.
  81882. *
  81883. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  81884. * object is also deleted.
  81885. *
  81886. * \param object A pointer to an existing object.
  81887. * \assert
  81888. * \code object != NULL \endcode
  81889. */
  81890. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  81891. /** Compares two metadata objects.
  81892. *
  81893. * The compare is "deep", i.e. dynamically allocated data within the
  81894. * object is also compared.
  81895. *
  81896. * \param block1 A pointer to an existing object.
  81897. * \param block2 A pointer to an existing object.
  81898. * \assert
  81899. * \code block1 != NULL \endcode
  81900. * \code block2 != NULL \endcode
  81901. * \retval FLAC__bool
  81902. * \c true if objects are identical, else \c false.
  81903. */
  81904. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  81905. /** Sets the application data of an APPLICATION block.
  81906. *
  81907. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  81908. * takes ownership of the pointer. The existing data will be freed if this
  81909. * function is successful, otherwise the original data will remain if \a copy
  81910. * is \c true and malloc() fails.
  81911. *
  81912. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  81913. *
  81914. * \param object A pointer to an existing APPLICATION object.
  81915. * \param data A pointer to the data to set.
  81916. * \param length The length of \a data in bytes.
  81917. * \param copy See above.
  81918. * \assert
  81919. * \code object != NULL \endcode
  81920. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  81921. * \code (data != NULL && length > 0) ||
  81922. * (data == NULL && length == 0 && copy == false) \endcode
  81923. * \retval FLAC__bool
  81924. * \c false if \a copy is \c true and malloc() fails, else \c true.
  81925. */
  81926. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  81927. /** Resize the seekpoint array.
  81928. *
  81929. * If the size shrinks, elements will truncated; if it grows, new placeholder
  81930. * points will be added to the end.
  81931. *
  81932. * \param object A pointer to an existing SEEKTABLE object.
  81933. * \param new_num_points The desired length of the array; may be \c 0.
  81934. * \assert
  81935. * \code object != NULL \endcode
  81936. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81937. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  81938. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  81939. * \retval FLAC__bool
  81940. * \c false if memory allocation error, else \c true.
  81941. */
  81942. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  81943. /** Set a seekpoint in a seektable.
  81944. *
  81945. * \param object A pointer to an existing SEEKTABLE object.
  81946. * \param point_num Index into seekpoint array to set.
  81947. * \param point The point to set.
  81948. * \assert
  81949. * \code object != NULL \endcode
  81950. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81951. * \code object->data.seek_table.num_points > point_num \endcode
  81952. */
  81953. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  81954. /** Insert a seekpoint into a seektable.
  81955. *
  81956. * \param object A pointer to an existing SEEKTABLE object.
  81957. * \param point_num Index into seekpoint array to set.
  81958. * \param point The point to set.
  81959. * \assert
  81960. * \code object != NULL \endcode
  81961. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81962. * \code object->data.seek_table.num_points >= point_num \endcode
  81963. * \retval FLAC__bool
  81964. * \c false if memory allocation error, else \c true.
  81965. */
  81966. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  81967. /** Delete a seekpoint from a seektable.
  81968. *
  81969. * \param object A pointer to an existing SEEKTABLE object.
  81970. * \param point_num Index into seekpoint array to set.
  81971. * \assert
  81972. * \code object != NULL \endcode
  81973. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81974. * \code object->data.seek_table.num_points > point_num \endcode
  81975. * \retval FLAC__bool
  81976. * \c false if memory allocation error, else \c true.
  81977. */
  81978. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  81979. /** Check a seektable to see if it conforms to the FLAC specification.
  81980. * See the format specification for limits on the contents of the
  81981. * seektable.
  81982. *
  81983. * \param object A pointer to an existing SEEKTABLE object.
  81984. * \assert
  81985. * \code object != NULL \endcode
  81986. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81987. * \retval FLAC__bool
  81988. * \c false if seek table is illegal, else \c true.
  81989. */
  81990. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  81991. /** Append a number of placeholder points to the end of a seek table.
  81992. *
  81993. * \note
  81994. * As with the other ..._seektable_template_... functions, you should
  81995. * call FLAC__metadata_object_seektable_template_sort() when finished
  81996. * to make the seek table legal.
  81997. *
  81998. * \param object A pointer to an existing SEEKTABLE object.
  81999. * \param num The number of placeholder points to append.
  82000. * \assert
  82001. * \code object != NULL \endcode
  82002. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82003. * \retval FLAC__bool
  82004. * \c false if memory allocation fails, else \c true.
  82005. */
  82006. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  82007. /** Append a specific seek point template to the end of a seek table.
  82008. *
  82009. * \note
  82010. * As with the other ..._seektable_template_... functions, you should
  82011. * call FLAC__metadata_object_seektable_template_sort() when finished
  82012. * to make the seek table legal.
  82013. *
  82014. * \param object A pointer to an existing SEEKTABLE object.
  82015. * \param sample_number The sample number of the seek point template.
  82016. * \assert
  82017. * \code object != NULL \endcode
  82018. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82019. * \retval FLAC__bool
  82020. * \c false if memory allocation fails, else \c true.
  82021. */
  82022. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  82023. /** Append specific seek point templates to the end of a seek table.
  82024. *
  82025. * \note
  82026. * As with the other ..._seektable_template_... functions, you should
  82027. * call FLAC__metadata_object_seektable_template_sort() when finished
  82028. * to make the seek table legal.
  82029. *
  82030. * \param object A pointer to an existing SEEKTABLE object.
  82031. * \param sample_numbers An array of sample numbers for the seek points.
  82032. * \param num The number of seek point templates to append.
  82033. * \assert
  82034. * \code object != NULL \endcode
  82035. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82036. * \retval FLAC__bool
  82037. * \c false if memory allocation fails, else \c true.
  82038. */
  82039. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  82040. /** Append a set of evenly-spaced seek point templates to the end of a
  82041. * seek table.
  82042. *
  82043. * \note
  82044. * As with the other ..._seektable_template_... functions, you should
  82045. * call FLAC__metadata_object_seektable_template_sort() when finished
  82046. * to make the seek table legal.
  82047. *
  82048. * \param object A pointer to an existing SEEKTABLE object.
  82049. * \param num The number of placeholder points to append.
  82050. * \param total_samples The total number of samples to be encoded;
  82051. * the seekpoints will be spaced approximately
  82052. * \a total_samples / \a num samples apart.
  82053. * \assert
  82054. * \code object != NULL \endcode
  82055. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82056. * \code total_samples > 0 \endcode
  82057. * \retval FLAC__bool
  82058. * \c false if memory allocation fails, else \c true.
  82059. */
  82060. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  82061. /** Append a set of evenly-spaced seek point templates to the end of a
  82062. * seek table.
  82063. *
  82064. * \note
  82065. * As with the other ..._seektable_template_... functions, you should
  82066. * call FLAC__metadata_object_seektable_template_sort() when finished
  82067. * to make the seek table legal.
  82068. *
  82069. * \param object A pointer to an existing SEEKTABLE object.
  82070. * \param samples The number of samples apart to space the placeholder
  82071. * points. The first point will be at sample \c 0, the
  82072. * second at sample \a samples, then 2*\a samples, and
  82073. * so on. As long as \a samples and \a total_samples
  82074. * are greater than \c 0, there will always be at least
  82075. * one seekpoint at sample \c 0.
  82076. * \param total_samples The total number of samples to be encoded;
  82077. * the seekpoints will be spaced
  82078. * \a samples samples apart.
  82079. * \assert
  82080. * \code object != NULL \endcode
  82081. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82082. * \code samples > 0 \endcode
  82083. * \code total_samples > 0 \endcode
  82084. * \retval FLAC__bool
  82085. * \c false if memory allocation fails, else \c true.
  82086. */
  82087. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  82088. /** Sort a seek table's seek points according to the format specification,
  82089. * removing duplicates.
  82090. *
  82091. * \param object A pointer to a seek table to be sorted.
  82092. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  82093. * If \c true, duplicates are deleted and the seek table is
  82094. * shrunk appropriately; the number of placeholder points
  82095. * present in the seek table will be the same after the call
  82096. * as before.
  82097. * \assert
  82098. * \code object != NULL \endcode
  82099. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82100. * \retval FLAC__bool
  82101. * \c false if realloc() fails, else \c true.
  82102. */
  82103. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  82104. /** Sets the vendor string in a VORBIS_COMMENT block.
  82105. *
  82106. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82107. * one already.
  82108. *
  82109. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82110. * takes ownership of the \c entry.entry pointer.
  82111. *
  82112. * \note If this function returns \c false, the caller still owns the
  82113. * pointer.
  82114. *
  82115. * \param object A pointer to an existing VORBIS_COMMENT object.
  82116. * \param entry The entry to set the vendor string to.
  82117. * \param copy See above.
  82118. * \assert
  82119. * \code object != NULL \endcode
  82120. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82121. * \code (entry.entry != NULL && entry.length > 0) ||
  82122. * (entry.entry == NULL && entry.length == 0) \endcode
  82123. * \retval FLAC__bool
  82124. * \c false if memory allocation fails or \a entry does not comply with the
  82125. * Vorbis comment specification, else \c true.
  82126. */
  82127. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82128. /** Resize the comment array.
  82129. *
  82130. * If the size shrinks, elements will truncated; if it grows, new empty
  82131. * fields will be added to the end.
  82132. *
  82133. * \param object A pointer to an existing VORBIS_COMMENT object.
  82134. * \param new_num_comments The desired length of the array; may be \c 0.
  82135. * \assert
  82136. * \code object != NULL \endcode
  82137. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82138. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  82139. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  82140. * \retval FLAC__bool
  82141. * \c false if memory allocation fails, else \c true.
  82142. */
  82143. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  82144. /** Sets a comment in a VORBIS_COMMENT block.
  82145. *
  82146. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82147. * one already.
  82148. *
  82149. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82150. * takes ownership of the \c entry.entry pointer.
  82151. *
  82152. * \note If this function returns \c false, the caller still owns the
  82153. * pointer.
  82154. *
  82155. * \param object A pointer to an existing VORBIS_COMMENT object.
  82156. * \param comment_num Index into comment array to set.
  82157. * \param entry The entry to set the comment to.
  82158. * \param copy See above.
  82159. * \assert
  82160. * \code object != NULL \endcode
  82161. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82162. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  82163. * \code (entry.entry != NULL && entry.length > 0) ||
  82164. * (entry.entry == NULL && entry.length == 0) \endcode
  82165. * \retval FLAC__bool
  82166. * \c false if memory allocation fails or \a entry does not comply with the
  82167. * Vorbis comment specification, else \c true.
  82168. */
  82169. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82170. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  82171. *
  82172. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82173. * one already.
  82174. *
  82175. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82176. * takes ownership of the \c entry.entry pointer.
  82177. *
  82178. * \note If this function returns \c false, the caller still owns the
  82179. * pointer.
  82180. *
  82181. * \param object A pointer to an existing VORBIS_COMMENT object.
  82182. * \param comment_num The index at which to insert the comment. The comments
  82183. * at and after \a comment_num move right one position.
  82184. * To append a comment to the end, set \a comment_num to
  82185. * \c object->data.vorbis_comment.num_comments .
  82186. * \param entry The comment to insert.
  82187. * \param copy See above.
  82188. * \assert
  82189. * \code object != NULL \endcode
  82190. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82191. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  82192. * \code (entry.entry != NULL && entry.length > 0) ||
  82193. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82194. * \retval FLAC__bool
  82195. * \c false if memory allocation fails or \a entry does not comply with the
  82196. * Vorbis comment specification, else \c true.
  82197. */
  82198. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82199. /** Appends a comment to a VORBIS_COMMENT block.
  82200. *
  82201. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82202. * one already.
  82203. *
  82204. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82205. * takes ownership of the \c entry.entry pointer.
  82206. *
  82207. * \note If this function returns \c false, the caller still owns the
  82208. * pointer.
  82209. *
  82210. * \param object A pointer to an existing VORBIS_COMMENT object.
  82211. * \param entry The comment to insert.
  82212. * \param copy See above.
  82213. * \assert
  82214. * \code object != NULL \endcode
  82215. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82216. * \code (entry.entry != NULL && entry.length > 0) ||
  82217. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82218. * \retval FLAC__bool
  82219. * \c false if memory allocation fails or \a entry does not comply with the
  82220. * Vorbis comment specification, else \c true.
  82221. */
  82222. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82223. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  82224. *
  82225. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82226. * one already.
  82227. *
  82228. * Depending on the the value of \a all, either all or just the first comment
  82229. * whose field name(s) match the given entry's name will be replaced by the
  82230. * given entry. If no comments match, \a entry will simply be appended.
  82231. *
  82232. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82233. * takes ownership of the \c entry.entry pointer.
  82234. *
  82235. * \note If this function returns \c false, the caller still owns the
  82236. * pointer.
  82237. *
  82238. * \param object A pointer to an existing VORBIS_COMMENT object.
  82239. * \param entry The comment to insert.
  82240. * \param all If \c true, all comments whose field name matches
  82241. * \a entry's field name will be removed, and \a entry will
  82242. * be inserted at the position of the first matching
  82243. * comment. If \c false, only the first comment whose
  82244. * field name matches \a entry's field name will be
  82245. * replaced with \a entry.
  82246. * \param copy See above.
  82247. * \assert
  82248. * \code object != NULL \endcode
  82249. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82250. * \code (entry.entry != NULL && entry.length > 0) ||
  82251. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82252. * \retval FLAC__bool
  82253. * \c false if memory allocation fails or \a entry does not comply with the
  82254. * Vorbis comment specification, else \c true.
  82255. */
  82256. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  82257. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  82258. *
  82259. * \param object A pointer to an existing VORBIS_COMMENT object.
  82260. * \param comment_num The index of the comment to delete.
  82261. * \assert
  82262. * \code object != NULL \endcode
  82263. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82264. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  82265. * \retval FLAC__bool
  82266. * \c false if realloc() fails, else \c true.
  82267. */
  82268. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  82269. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  82270. *
  82271. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  82272. * memory and shall be owned by the caller. For convenience the entry will
  82273. * have a terminating NUL.
  82274. *
  82275. * \param entry A pointer to a Vorbis comment entry. The entry's
  82276. * \c entry pointer should not point to allocated
  82277. * memory as it will be overwritten.
  82278. * \param field_name The field name in ASCII, \c NUL terminated.
  82279. * \param field_value The field value in UTF-8, \c NUL terminated.
  82280. * \assert
  82281. * \code entry != NULL \endcode
  82282. * \code field_name != NULL \endcode
  82283. * \code field_value != NULL \endcode
  82284. * \retval FLAC__bool
  82285. * \c false if malloc() fails, or if \a field_name or \a field_value does
  82286. * not comply with the Vorbis comment specification, else \c true.
  82287. */
  82288. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value);
  82289. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  82290. *
  82291. * The returned pointers to name and value will be allocated by malloc()
  82292. * and shall be owned by the caller.
  82293. *
  82294. * \param entry An existing Vorbis comment entry.
  82295. * \param field_name The address of where the returned pointer to the
  82296. * field name will be stored.
  82297. * \param field_value The address of where the returned pointer to the
  82298. * field value will be stored.
  82299. * \assert
  82300. * \code (entry.entry != NULL && entry.length > 0) \endcode
  82301. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  82302. * \code field_name != NULL \endcode
  82303. * \code field_value != NULL \endcode
  82304. * \retval FLAC__bool
  82305. * \c false if memory allocation fails or \a entry does not comply with the
  82306. * Vorbis comment specification, else \c true.
  82307. */
  82308. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  82309. /** Check if the given Vorbis comment entry's field name matches the given
  82310. * field name.
  82311. *
  82312. * \param entry An existing Vorbis comment entry.
  82313. * \param field_name The field name to check.
  82314. * \param field_name_length The length of \a field_name, not including the
  82315. * terminating \c NUL.
  82316. * \assert
  82317. * \code (entry.entry != NULL && entry.length > 0) \endcode
  82318. * \retval FLAC__bool
  82319. * \c true if the field names match, else \c false
  82320. */
  82321. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  82322. /** Find a Vorbis comment with the given field name.
  82323. *
  82324. * The search begins at entry number \a offset; use an offset of 0 to
  82325. * search from the beginning of the comment array.
  82326. *
  82327. * \param object A pointer to an existing VORBIS_COMMENT object.
  82328. * \param offset The offset into the comment array from where to start
  82329. * the search.
  82330. * \param field_name The field name of the comment to find.
  82331. * \assert
  82332. * \code object != NULL \endcode
  82333. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82334. * \code field_name != NULL \endcode
  82335. * \retval int
  82336. * The offset in the comment array of the first comment whose field
  82337. * name matches \a field_name, or \c -1 if no match was found.
  82338. */
  82339. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  82340. /** Remove first Vorbis comment matching the given field name.
  82341. *
  82342. * \param object A pointer to an existing VORBIS_COMMENT object.
  82343. * \param field_name The field name of comment to delete.
  82344. * \assert
  82345. * \code object != NULL \endcode
  82346. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82347. * \retval int
  82348. * \c -1 for memory allocation error, \c 0 for no matching entries,
  82349. * \c 1 for one matching entry deleted.
  82350. */
  82351. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  82352. /** Remove all Vorbis comments matching the given field name.
  82353. *
  82354. * \param object A pointer to an existing VORBIS_COMMENT object.
  82355. * \param field_name The field name of comments to delete.
  82356. * \assert
  82357. * \code object != NULL \endcode
  82358. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82359. * \retval int
  82360. * \c -1 for memory allocation error, \c 0 for no matching entries,
  82361. * else the number of matching entries deleted.
  82362. */
  82363. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  82364. /** Create a new CUESHEET track instance.
  82365. *
  82366. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  82367. *
  82368. * \retval FLAC__StreamMetadata_CueSheet_Track*
  82369. * \c NULL if there was an error allocating memory, else the new instance.
  82370. */
  82371. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  82372. /** Create a copy of an existing CUESHEET track object.
  82373. *
  82374. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  82375. * object is also copied. The caller takes ownership of the new object and
  82376. * is responsible for freeing it with
  82377. * FLAC__metadata_object_cuesheet_track_delete().
  82378. *
  82379. * \param object Pointer to object to copy.
  82380. * \assert
  82381. * \code object != NULL \endcode
  82382. * \retval FLAC__StreamMetadata_CueSheet_Track*
  82383. * \c NULL if there was an error allocating memory, else the new instance.
  82384. */
  82385. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  82386. /** Delete a CUESHEET track object
  82387. *
  82388. * \param object A pointer to an existing CUESHEET track object.
  82389. * \assert
  82390. * \code object != NULL \endcode
  82391. */
  82392. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  82393. /** Resize a track's index point array.
  82394. *
  82395. * If the size shrinks, elements will truncated; if it grows, new blank
  82396. * indices will be added to the end.
  82397. *
  82398. * \param object A pointer to an existing CUESHEET object.
  82399. * \param track_num The index of the track to modify. NOTE: this is not
  82400. * necessarily the same as the track's \a number field.
  82401. * \param new_num_indices The desired length of the array; may be \c 0.
  82402. * \assert
  82403. * \code object != NULL \endcode
  82404. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82405. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82406. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  82407. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  82408. * \retval FLAC__bool
  82409. * \c false if memory allocation error, else \c true.
  82410. */
  82411. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  82412. /** Insert an index point in a CUESHEET track at the given index.
  82413. *
  82414. * \param object A pointer to an existing CUESHEET object.
  82415. * \param track_num The index of the track to modify. NOTE: this is not
  82416. * necessarily the same as the track's \a number field.
  82417. * \param index_num The index into the track's index array at which to
  82418. * insert the index point. NOTE: this is not necessarily
  82419. * the same as the index point's \a number field. The
  82420. * indices at and after \a index_num move right one
  82421. * position. To append an index point to the end, set
  82422. * \a index_num to
  82423. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  82424. * \param index The index point to insert.
  82425. * \assert
  82426. * \code object != NULL \endcode
  82427. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82428. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82429. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  82430. * \retval FLAC__bool
  82431. * \c false if realloc() fails, else \c true.
  82432. */
  82433. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  82434. /** Insert a blank index point in a CUESHEET track at the given index.
  82435. *
  82436. * A blank index point is one in which all field values are zero.
  82437. *
  82438. * \param object A pointer to an existing CUESHEET object.
  82439. * \param track_num The index of the track to modify. NOTE: this is not
  82440. * necessarily the same as the track's \a number field.
  82441. * \param index_num The index into the track's index array at which to
  82442. * insert the index point. NOTE: this is not necessarily
  82443. * the same as the index point's \a number field. The
  82444. * indices at and after \a index_num move right one
  82445. * position. To append an index point to the end, set
  82446. * \a index_num to
  82447. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  82448. * \assert
  82449. * \code object != NULL \endcode
  82450. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82451. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82452. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  82453. * \retval FLAC__bool
  82454. * \c false if realloc() fails, else \c true.
  82455. */
  82456. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  82457. /** Delete an index point in a CUESHEET track at the given index.
  82458. *
  82459. * \param object A pointer to an existing CUESHEET object.
  82460. * \param track_num The index into the track array of the track to
  82461. * modify. NOTE: this is not necessarily the same
  82462. * as the track's \a number field.
  82463. * \param index_num The index into the track's index array of the index
  82464. * to delete. NOTE: this is not necessarily the same
  82465. * as the index's \a number field.
  82466. * \assert
  82467. * \code object != NULL \endcode
  82468. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82469. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82470. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  82471. * \retval FLAC__bool
  82472. * \c false if realloc() fails, else \c true.
  82473. */
  82474. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  82475. /** Resize the track array.
  82476. *
  82477. * If the size shrinks, elements will truncated; if it grows, new blank
  82478. * tracks will be added to the end.
  82479. *
  82480. * \param object A pointer to an existing CUESHEET object.
  82481. * \param new_num_tracks The desired length of the array; may be \c 0.
  82482. * \assert
  82483. * \code object != NULL \endcode
  82484. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82485. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  82486. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  82487. * \retval FLAC__bool
  82488. * \c false if memory allocation error, else \c true.
  82489. */
  82490. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  82491. /** Sets a track in a CUESHEET block.
  82492. *
  82493. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  82494. * takes ownership of the \a track pointer.
  82495. *
  82496. * \param object A pointer to an existing CUESHEET object.
  82497. * \param track_num Index into track array to set. NOTE: this is not
  82498. * necessarily the same as the track's \a number field.
  82499. * \param track The track to set the track to. You may safely pass in
  82500. * a const pointer if \a copy is \c true.
  82501. * \param copy See above.
  82502. * \assert
  82503. * \code object != NULL \endcode
  82504. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82505. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  82506. * \code (track->indices != NULL && track->num_indices > 0) ||
  82507. * (track->indices == NULL && track->num_indices == 0)
  82508. * \retval FLAC__bool
  82509. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82510. */
  82511. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  82512. /** Insert a track in a CUESHEET block at the given index.
  82513. *
  82514. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  82515. * takes ownership of the \a track pointer.
  82516. *
  82517. * \param object A pointer to an existing CUESHEET object.
  82518. * \param track_num The index at which to insert the track. NOTE: this
  82519. * is not necessarily the same as the track's \a number
  82520. * field. The tracks at and after \a track_num move right
  82521. * one position. To append a track to the end, set
  82522. * \a track_num to \c object->data.cue_sheet.num_tracks .
  82523. * \param track The track to insert. You may safely pass in a const
  82524. * pointer if \a copy is \c true.
  82525. * \param copy See above.
  82526. * \assert
  82527. * \code object != NULL \endcode
  82528. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82529. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  82530. * \retval FLAC__bool
  82531. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82532. */
  82533. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  82534. /** Insert a blank track in a CUESHEET block at the given index.
  82535. *
  82536. * A blank track is one in which all field values are zero.
  82537. *
  82538. * \param object A pointer to an existing CUESHEET object.
  82539. * \param track_num The index at which to insert the track. NOTE: this
  82540. * is not necessarily the same as the track's \a number
  82541. * field. The tracks at and after \a track_num move right
  82542. * one position. To append a track to the end, set
  82543. * \a track_num to \c object->data.cue_sheet.num_tracks .
  82544. * \assert
  82545. * \code object != NULL \endcode
  82546. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82547. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  82548. * \retval FLAC__bool
  82549. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82550. */
  82551. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  82552. /** Delete a track in a CUESHEET block at the given index.
  82553. *
  82554. * \param object A pointer to an existing CUESHEET object.
  82555. * \param track_num The index into the track array of the track to
  82556. * delete. NOTE: this is not necessarily the same
  82557. * as the track's \a number field.
  82558. * \assert
  82559. * \code object != NULL \endcode
  82560. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82561. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82562. * \retval FLAC__bool
  82563. * \c false if realloc() fails, else \c true.
  82564. */
  82565. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  82566. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82567. * See the format specification for limits on the contents of the
  82568. * cue sheet.
  82569. *
  82570. * \param object A pointer to an existing CUESHEET object.
  82571. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82572. * stringent requirements for a CD-DA (audio) disc.
  82573. * \param violation Address of a pointer to a string. If there is a
  82574. * violation, a pointer to a string explanation of the
  82575. * violation will be returned here. \a violation may be
  82576. * \c NULL if you don't need the returned string. Do not
  82577. * free the returned string; it will always point to static
  82578. * data.
  82579. * \assert
  82580. * \code object != NULL \endcode
  82581. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82582. * \retval FLAC__bool
  82583. * \c false if cue sheet is illegal, else \c true.
  82584. */
  82585. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  82586. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  82587. * assumes the cue sheet corresponds to a CD; the result is undefined
  82588. * if the cuesheet's is_cd bit is not set.
  82589. *
  82590. * \param object A pointer to an existing CUESHEET object.
  82591. * \assert
  82592. * \code object != NULL \endcode
  82593. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82594. * \retval FLAC__uint32
  82595. * The unsigned integer representation of the CDDB/freedb ID
  82596. */
  82597. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  82598. /** Sets the MIME type of a PICTURE block.
  82599. *
  82600. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  82601. * takes ownership of the pointer. The existing string will be freed if this
  82602. * function is successful, otherwise the original string will remain if \a copy
  82603. * is \c true and malloc() fails.
  82604. *
  82605. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  82606. *
  82607. * \param object A pointer to an existing PICTURE object.
  82608. * \param mime_type A pointer to the MIME type string. The string must be
  82609. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  82610. * is done.
  82611. * \param copy See above.
  82612. * \assert
  82613. * \code object != NULL \endcode
  82614. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82615. * \code (mime_type != NULL) \endcode
  82616. * \retval FLAC__bool
  82617. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82618. */
  82619. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  82620. /** Sets the description of a PICTURE block.
  82621. *
  82622. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  82623. * takes ownership of the pointer. The existing string will be freed if this
  82624. * function is successful, otherwise the original string will remain if \a copy
  82625. * is \c true and malloc() fails.
  82626. *
  82627. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  82628. *
  82629. * \param object A pointer to an existing PICTURE object.
  82630. * \param description A pointer to the description string. The string must be
  82631. * valid UTF-8, NUL-terminated. No validation is done.
  82632. * \param copy See above.
  82633. * \assert
  82634. * \code object != NULL \endcode
  82635. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82636. * \code (description != NULL) \endcode
  82637. * \retval FLAC__bool
  82638. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82639. */
  82640. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  82641. /** Sets the picture data of a PICTURE block.
  82642. *
  82643. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  82644. * takes ownership of the pointer. Also sets the \a data_length field of the
  82645. * metadata object to what is passed in as the \a length parameter. The
  82646. * existing data will be freed if this function is successful, otherwise the
  82647. * original data and data_length will remain if \a copy is \c true and
  82648. * malloc() fails.
  82649. *
  82650. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  82651. *
  82652. * \param object A pointer to an existing PICTURE object.
  82653. * \param data A pointer to the data to set.
  82654. * \param length The length of \a data in bytes.
  82655. * \param copy See above.
  82656. * \assert
  82657. * \code object != NULL \endcode
  82658. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82659. * \code (data != NULL && length > 0) ||
  82660. * (data == NULL && length == 0 && copy == false) \endcode
  82661. * \retval FLAC__bool
  82662. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82663. */
  82664. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  82665. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  82666. * See the format specification for limits on the contents of the
  82667. * PICTURE block.
  82668. *
  82669. * \param object A pointer to existing PICTURE block to be checked.
  82670. * \param violation Address of a pointer to a string. If there is a
  82671. * violation, a pointer to a string explanation of the
  82672. * violation will be returned here. \a violation may be
  82673. * \c NULL if you don't need the returned string. Do not
  82674. * free the returned string; it will always point to static
  82675. * data.
  82676. * \assert
  82677. * \code object != NULL \endcode
  82678. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82679. * \retval FLAC__bool
  82680. * \c false if PICTURE block is illegal, else \c true.
  82681. */
  82682. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  82683. /* \} */
  82684. #ifdef __cplusplus
  82685. }
  82686. #endif
  82687. #endif
  82688. /********* End of inlined file: metadata.h *********/
  82689. /********* Start of inlined file: stream_decoder.h *********/
  82690. #ifndef FLAC__STREAM_DECODER_H
  82691. #define FLAC__STREAM_DECODER_H
  82692. #include <stdio.h> /* for FILE */
  82693. #ifdef __cplusplus
  82694. extern "C" {
  82695. #endif
  82696. /** \file include/FLAC/stream_decoder.h
  82697. *
  82698. * \brief
  82699. * This module contains the functions which implement the stream
  82700. * decoder.
  82701. *
  82702. * See the detailed documentation in the
  82703. * \link flac_stream_decoder stream decoder \endlink module.
  82704. */
  82705. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  82706. * \ingroup flac
  82707. *
  82708. * \brief
  82709. * This module describes the decoder layers provided by libFLAC.
  82710. *
  82711. * The stream decoder can be used to decode complete streams either from
  82712. * the client via callbacks, or directly from a file, depending on how
  82713. * it is initialized. When decoding via callbacks, the client provides
  82714. * callbacks for reading FLAC data and writing decoded samples, and
  82715. * handling metadata and errors. If the client also supplies seek-related
  82716. * callback, the decoder function for sample-accurate seeking within the
  82717. * FLAC input is also available. When decoding from a file, the client
  82718. * needs only supply a filename or open \c FILE* and write/metadata/error
  82719. * callbacks; the rest of the callbacks are supplied internally. For more
  82720. * info see the \link flac_stream_decoder stream decoder \endlink module.
  82721. */
  82722. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  82723. * \ingroup flac_decoder
  82724. *
  82725. * \brief
  82726. * This module contains the functions which implement the stream
  82727. * decoder.
  82728. *
  82729. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  82730. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  82731. *
  82732. * The basic usage of this decoder is as follows:
  82733. * - The program creates an instance of a decoder using
  82734. * FLAC__stream_decoder_new().
  82735. * - The program overrides the default settings using
  82736. * FLAC__stream_decoder_set_*() functions.
  82737. * - The program initializes the instance to validate the settings and
  82738. * prepare for decoding using
  82739. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  82740. * or FLAC__stream_decoder_init_file() for native FLAC,
  82741. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  82742. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  82743. * - The program calls the FLAC__stream_decoder_process_*() functions
  82744. * to decode data, which subsequently calls the callbacks.
  82745. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  82746. * which flushes the input and output and resets the decoder to the
  82747. * uninitialized state.
  82748. * - The instance may be used again or deleted with
  82749. * FLAC__stream_decoder_delete().
  82750. *
  82751. * In more detail, the program will create a new instance by calling
  82752. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  82753. * functions to override the default decoder options, and call
  82754. * one of the FLAC__stream_decoder_init_*() functions.
  82755. *
  82756. * There are three initialization functions for native FLAC, one for
  82757. * setting up the decoder to decode FLAC data from the client via
  82758. * callbacks, and two for decoding directly from a FLAC file.
  82759. *
  82760. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  82761. * You must also supply several callbacks for handling I/O. Some (like
  82762. * seeking) are optional, depending on the capabilities of the input.
  82763. *
  82764. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  82765. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  82766. * \c FILE* or filename and fewer callbacks; the decoder will handle
  82767. * the other callbacks internally.
  82768. *
  82769. * There are three similarly-named init functions for decoding from Ogg
  82770. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  82771. * library has been built with Ogg support.
  82772. *
  82773. * Once the decoder is initialized, your program will call one of several
  82774. * functions to start the decoding process:
  82775. *
  82776. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  82777. * most one metadata block or audio frame and return, calling either the
  82778. * metadata callback or write callback, respectively, once. If the decoder
  82779. * loses sync it will return with only the error callback being called.
  82780. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  82781. * to process the stream from the current location and stop upon reaching
  82782. * the first audio frame. The client will get one metadata, write, or error
  82783. * callback per metadata block, audio frame, or sync error, respectively.
  82784. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  82785. * to process the stream from the current location until the read callback
  82786. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  82787. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  82788. * write, or error callback per metadata block, audio frame, or sync error,
  82789. * respectively.
  82790. *
  82791. * When the decoder has finished decoding (normally or through an abort),
  82792. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  82793. * ensures the decoder is in the correct state and frees memory. Then the
  82794. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  82795. * again to decode another stream.
  82796. *
  82797. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  82798. * At any point after the stream decoder has been initialized, the client can
  82799. * call this function to seek to an exact sample within the stream.
  82800. * Subsequently, the first time the write callback is called it will be
  82801. * passed a (possibly partial) block starting at that sample.
  82802. *
  82803. * If the client cannot seek via the callback interface provided, but still
  82804. * has another way of seeking, it can flush the decoder using
  82805. * FLAC__stream_decoder_flush() and start feeding data from the new position
  82806. * through the read callback.
  82807. *
  82808. * The stream decoder also provides MD5 signature checking. If this is
  82809. * turned on before initialization, FLAC__stream_decoder_finish() will
  82810. * report when the decoded MD5 signature does not match the one stored
  82811. * in the STREAMINFO block. MD5 checking is automatically turned off
  82812. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  82813. * in the STREAMINFO block or when a seek is attempted.
  82814. *
  82815. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  82816. * attention. By default, the decoder only calls the metadata_callback for
  82817. * the STREAMINFO block. These functions allow you to tell the decoder
  82818. * explicitly which blocks to parse and return via the metadata_callback
  82819. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  82820. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  82821. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  82822. * which blocks to return. Remember that metadata blocks can potentially
  82823. * be big (for example, cover art) so filtering out the ones you don't
  82824. * use can reduce the memory requirements of the decoder. Also note the
  82825. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  82826. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  82827. * filtering APPLICATION blocks based on the application ID.
  82828. *
  82829. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  82830. * they still can legally be filtered from the metadata_callback.
  82831. *
  82832. * \note
  82833. * The "set" functions may only be called when the decoder is in the
  82834. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  82835. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  82836. * before FLAC__stream_decoder_init_*(). If this is the case they will
  82837. * return \c true, otherwise \c false.
  82838. *
  82839. * \note
  82840. * FLAC__stream_decoder_finish() resets all settings to the constructor
  82841. * defaults, including the callbacks.
  82842. *
  82843. * \{
  82844. */
  82845. /** State values for a FLAC__StreamDecoder
  82846. *
  82847. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  82848. */
  82849. typedef enum {
  82850. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  82851. /**< The decoder is ready to search for metadata. */
  82852. FLAC__STREAM_DECODER_READ_METADATA,
  82853. /**< The decoder is ready to or is in the process of reading metadata. */
  82854. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  82855. /**< The decoder is ready to or is in the process of searching for the
  82856. * frame sync code.
  82857. */
  82858. FLAC__STREAM_DECODER_READ_FRAME,
  82859. /**< The decoder is ready to or is in the process of reading a frame. */
  82860. FLAC__STREAM_DECODER_END_OF_STREAM,
  82861. /**< The decoder has reached the end of the stream. */
  82862. FLAC__STREAM_DECODER_OGG_ERROR,
  82863. /**< An error occurred in the underlying Ogg layer. */
  82864. FLAC__STREAM_DECODER_SEEK_ERROR,
  82865. /**< An error occurred while seeking. The decoder must be flushed
  82866. * with FLAC__stream_decoder_flush() or reset with
  82867. * FLAC__stream_decoder_reset() before decoding can continue.
  82868. */
  82869. FLAC__STREAM_DECODER_ABORTED,
  82870. /**< The decoder was aborted by the read callback. */
  82871. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  82872. /**< An error occurred allocating memory. The decoder is in an invalid
  82873. * state and can no longer be used.
  82874. */
  82875. FLAC__STREAM_DECODER_UNINITIALIZED
  82876. /**< The decoder is in the uninitialized state; one of the
  82877. * FLAC__stream_decoder_init_*() functions must be called before samples
  82878. * can be processed.
  82879. */
  82880. } FLAC__StreamDecoderState;
  82881. /** Maps a FLAC__StreamDecoderState to a C string.
  82882. *
  82883. * Using a FLAC__StreamDecoderState as the index to this array
  82884. * will give the string equivalent. The contents should not be modified.
  82885. */
  82886. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  82887. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  82888. */
  82889. typedef enum {
  82890. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  82891. /**< Initialization was successful. */
  82892. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  82893. /**< The library was not compiled with support for the given container
  82894. * format.
  82895. */
  82896. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  82897. /**< A required callback was not supplied. */
  82898. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  82899. /**< An error occurred allocating memory. */
  82900. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  82901. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  82902. * FLAC__stream_decoder_init_ogg_file(). */
  82903. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  82904. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  82905. * already initialized, usually because
  82906. * FLAC__stream_decoder_finish() was not called.
  82907. */
  82908. } FLAC__StreamDecoderInitStatus;
  82909. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  82910. *
  82911. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  82912. * will give the string equivalent. The contents should not be modified.
  82913. */
  82914. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  82915. /** Return values for the FLAC__StreamDecoder read callback.
  82916. */
  82917. typedef enum {
  82918. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  82919. /**< The read was OK and decoding can continue. */
  82920. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  82921. /**< The read was attempted while at the end of the stream. Note that
  82922. * the client must only return this value when the read callback was
  82923. * called when already at the end of the stream. Otherwise, if the read
  82924. * itself moves to the end of the stream, the client should still return
  82925. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  82926. * the next read callback it should return
  82927. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  82928. * of \c 0.
  82929. */
  82930. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  82931. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82932. } FLAC__StreamDecoderReadStatus;
  82933. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  82934. *
  82935. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  82936. * will give the string equivalent. The contents should not be modified.
  82937. */
  82938. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  82939. /** Return values for the FLAC__StreamDecoder seek callback.
  82940. */
  82941. typedef enum {
  82942. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  82943. /**< The seek was OK and decoding can continue. */
  82944. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  82945. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82946. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  82947. /**< Client does not support seeking. */
  82948. } FLAC__StreamDecoderSeekStatus;
  82949. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  82950. *
  82951. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  82952. * will give the string equivalent. The contents should not be modified.
  82953. */
  82954. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  82955. /** Return values for the FLAC__StreamDecoder tell callback.
  82956. */
  82957. typedef enum {
  82958. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  82959. /**< The tell was OK and decoding can continue. */
  82960. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  82961. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82962. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  82963. /**< Client does not support telling the position. */
  82964. } FLAC__StreamDecoderTellStatus;
  82965. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  82966. *
  82967. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  82968. * will give the string equivalent. The contents should not be modified.
  82969. */
  82970. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  82971. /** Return values for the FLAC__StreamDecoder length callback.
  82972. */
  82973. typedef enum {
  82974. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  82975. /**< The length call was OK and decoding can continue. */
  82976. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  82977. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82978. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  82979. /**< Client does not support reporting the length. */
  82980. } FLAC__StreamDecoderLengthStatus;
  82981. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  82982. *
  82983. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  82984. * will give the string equivalent. The contents should not be modified.
  82985. */
  82986. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  82987. /** Return values for the FLAC__StreamDecoder write callback.
  82988. */
  82989. typedef enum {
  82990. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  82991. /**< The write was OK and decoding can continue. */
  82992. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  82993. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82994. } FLAC__StreamDecoderWriteStatus;
  82995. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  82996. *
  82997. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  82998. * will give the string equivalent. The contents should not be modified.
  82999. */
  83000. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  83001. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  83002. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  83003. * all. The rest could be caused by bad sync (false synchronization on
  83004. * data that is not the start of a frame) or corrupted data. The error
  83005. * itself is the decoder's best guess at what happened assuming a correct
  83006. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  83007. * could be caused by a correct sync on the start of a frame, but some
  83008. * data in the frame header was corrupted. Or it could be the result of
  83009. * syncing on a point the stream that looked like the starting of a frame
  83010. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83011. * could be because the decoder encountered a valid frame made by a future
  83012. * version of the encoder which it cannot parse, or because of a false
  83013. * sync making it appear as though an encountered frame was generated by
  83014. * a future encoder.
  83015. */
  83016. typedef enum {
  83017. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  83018. /**< An error in the stream caused the decoder to lose synchronization. */
  83019. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  83020. /**< The decoder encountered a corrupted frame header. */
  83021. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  83022. /**< The frame's data did not match the CRC in the footer. */
  83023. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83024. /**< The decoder encountered reserved fields in use in the stream. */
  83025. } FLAC__StreamDecoderErrorStatus;
  83026. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  83027. *
  83028. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  83029. * will give the string equivalent. The contents should not be modified.
  83030. */
  83031. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  83032. /***********************************************************************
  83033. *
  83034. * class FLAC__StreamDecoder
  83035. *
  83036. ***********************************************************************/
  83037. struct FLAC__StreamDecoderProtected;
  83038. struct FLAC__StreamDecoderPrivate;
  83039. /** The opaque structure definition for the stream decoder type.
  83040. * See the \link flac_stream_decoder stream decoder module \endlink
  83041. * for a detailed description.
  83042. */
  83043. typedef struct {
  83044. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  83045. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  83046. } FLAC__StreamDecoder;
  83047. /** Signature for the read callback.
  83048. *
  83049. * A function pointer matching this signature must be passed to
  83050. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83051. * called when the decoder needs more input data. The address of the
  83052. * buffer to be filled is supplied, along with the number of bytes the
  83053. * buffer can hold. The callback may choose to supply less data and
  83054. * modify the byte count but must be careful not to overflow the buffer.
  83055. * The callback then returns a status code chosen from
  83056. * FLAC__StreamDecoderReadStatus.
  83057. *
  83058. * Here is an example of a read callback for stdio streams:
  83059. * \code
  83060. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  83061. * {
  83062. * FILE *file = ((MyClientData*)client_data)->file;
  83063. * if(*bytes > 0) {
  83064. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  83065. * if(ferror(file))
  83066. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83067. * else if(*bytes == 0)
  83068. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  83069. * else
  83070. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  83071. * }
  83072. * else
  83073. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83074. * }
  83075. * \endcode
  83076. *
  83077. * \note In general, FLAC__StreamDecoder functions which change the
  83078. * state should not be called on the \a decoder while in the callback.
  83079. *
  83080. * \param decoder The decoder instance calling the callback.
  83081. * \param buffer A pointer to a location for the callee to store
  83082. * data to be decoded.
  83083. * \param bytes A pointer to the size of the buffer. On entry
  83084. * to the callback, it contains the maximum number
  83085. * of bytes that may be stored in \a buffer. The
  83086. * callee must set it to the actual number of bytes
  83087. * stored (0 in case of error or end-of-stream) before
  83088. * returning.
  83089. * \param client_data The callee's client data set through
  83090. * FLAC__stream_decoder_init_*().
  83091. * \retval FLAC__StreamDecoderReadStatus
  83092. * The callee's return status. Note that the callback should return
  83093. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  83094. * zero bytes were read and there is no more data to be read.
  83095. */
  83096. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  83097. /** Signature for the seek callback.
  83098. *
  83099. * A function pointer matching this signature may be passed to
  83100. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83101. * called when the decoder needs to seek the input stream. The decoder
  83102. * will pass the absolute byte offset to seek to, 0 meaning the
  83103. * beginning of the stream.
  83104. *
  83105. * Here is an example of a seek callback for stdio streams:
  83106. * \code
  83107. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  83108. * {
  83109. * FILE *file = ((MyClientData*)client_data)->file;
  83110. * if(file == stdin)
  83111. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  83112. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  83113. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  83114. * else
  83115. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  83116. * }
  83117. * \endcode
  83118. *
  83119. * \note In general, FLAC__StreamDecoder functions which change the
  83120. * state should not be called on the \a decoder while in the callback.
  83121. *
  83122. * \param decoder The decoder instance calling the callback.
  83123. * \param absolute_byte_offset The offset from the beginning of the stream
  83124. * to seek to.
  83125. * \param client_data The callee's client data set through
  83126. * FLAC__stream_decoder_init_*().
  83127. * \retval FLAC__StreamDecoderSeekStatus
  83128. * The callee's return status.
  83129. */
  83130. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  83131. /** Signature for the tell callback.
  83132. *
  83133. * A function pointer matching this signature may be passed to
  83134. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83135. * called when the decoder wants to know the current position of the
  83136. * stream. The callback should return the byte offset from the
  83137. * beginning of the stream.
  83138. *
  83139. * Here is an example of a tell callback for stdio streams:
  83140. * \code
  83141. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  83142. * {
  83143. * FILE *file = ((MyClientData*)client_data)->file;
  83144. * off_t pos;
  83145. * if(file == stdin)
  83146. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  83147. * else if((pos = ftello(file)) < 0)
  83148. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  83149. * else {
  83150. * *absolute_byte_offset = (FLAC__uint64)pos;
  83151. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  83152. * }
  83153. * }
  83154. * \endcode
  83155. *
  83156. * \note In general, FLAC__StreamDecoder functions which change the
  83157. * state should not be called on the \a decoder while in the callback.
  83158. *
  83159. * \param decoder The decoder instance calling the callback.
  83160. * \param absolute_byte_offset A pointer to storage for the current offset
  83161. * from the beginning of the stream.
  83162. * \param client_data The callee's client data set through
  83163. * FLAC__stream_decoder_init_*().
  83164. * \retval FLAC__StreamDecoderTellStatus
  83165. * The callee's return status.
  83166. */
  83167. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  83168. /** Signature for the length callback.
  83169. *
  83170. * A function pointer matching this signature may be passed to
  83171. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83172. * called when the decoder wants to know the total length of the stream
  83173. * in bytes.
  83174. *
  83175. * Here is an example of a length callback for stdio streams:
  83176. * \code
  83177. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  83178. * {
  83179. * FILE *file = ((MyClientData*)client_data)->file;
  83180. * struct stat filestats;
  83181. *
  83182. * if(file == stdin)
  83183. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  83184. * else if(fstat(fileno(file), &filestats) != 0)
  83185. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  83186. * else {
  83187. * *stream_length = (FLAC__uint64)filestats.st_size;
  83188. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  83189. * }
  83190. * }
  83191. * \endcode
  83192. *
  83193. * \note In general, FLAC__StreamDecoder functions which change the
  83194. * state should not be called on the \a decoder while in the callback.
  83195. *
  83196. * \param decoder The decoder instance calling the callback.
  83197. * \param stream_length A pointer to storage for the length of the stream
  83198. * in bytes.
  83199. * \param client_data The callee's client data set through
  83200. * FLAC__stream_decoder_init_*().
  83201. * \retval FLAC__StreamDecoderLengthStatus
  83202. * The callee's return status.
  83203. */
  83204. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  83205. /** Signature for the EOF callback.
  83206. *
  83207. * A function pointer matching this signature may be passed to
  83208. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83209. * called when the decoder needs to know if the end of the stream has
  83210. * been reached.
  83211. *
  83212. * Here is an example of a EOF callback for stdio streams:
  83213. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  83214. * \code
  83215. * {
  83216. * FILE *file = ((MyClientData*)client_data)->file;
  83217. * return feof(file)? true : false;
  83218. * }
  83219. * \endcode
  83220. *
  83221. * \note In general, FLAC__StreamDecoder functions which change the
  83222. * state should not be called on the \a decoder while in the callback.
  83223. *
  83224. * \param decoder The decoder instance calling the callback.
  83225. * \param client_data The callee's client data set through
  83226. * FLAC__stream_decoder_init_*().
  83227. * \retval FLAC__bool
  83228. * \c true if the currently at the end of the stream, else \c false.
  83229. */
  83230. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  83231. /** Signature for the write callback.
  83232. *
  83233. * A function pointer matching this signature must be passed to one of
  83234. * the FLAC__stream_decoder_init_*() functions.
  83235. * The supplied function will be called when the decoder has decoded a
  83236. * single audio frame. The decoder will pass the frame metadata as well
  83237. * as an array of pointers (one for each channel) pointing to the
  83238. * decoded audio.
  83239. *
  83240. * \note In general, FLAC__StreamDecoder functions which change the
  83241. * state should not be called on the \a decoder while in the callback.
  83242. *
  83243. * \param decoder The decoder instance calling the callback.
  83244. * \param frame The description of the decoded frame. See
  83245. * FLAC__Frame.
  83246. * \param buffer An array of pointers to decoded channels of data.
  83247. * Each pointer will point to an array of signed
  83248. * samples of length \a frame->header.blocksize.
  83249. * Channels will be ordered according to the FLAC
  83250. * specification; see the documentation for the
  83251. * <A HREF="../format.html#frame_header">frame header</A>.
  83252. * \param client_data The callee's client data set through
  83253. * FLAC__stream_decoder_init_*().
  83254. * \retval FLAC__StreamDecoderWriteStatus
  83255. * The callee's return status.
  83256. */
  83257. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  83258. /** Signature for the metadata callback.
  83259. *
  83260. * A function pointer matching this signature must be passed to one of
  83261. * the FLAC__stream_decoder_init_*() functions.
  83262. * The supplied function will be called when the decoder has decoded a
  83263. * metadata block. In a valid FLAC file there will always be one
  83264. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  83265. * These will be supplied by the decoder in the same order as they
  83266. * appear in the stream and always before the first audio frame (i.e.
  83267. * write callback). The metadata block that is passed in must not be
  83268. * modified, and it doesn't live beyond the callback, so you should make
  83269. * a copy of it with FLAC__metadata_object_clone() if you will need it
  83270. * elsewhere. Since metadata blocks can potentially be large, by
  83271. * default the decoder only calls the metadata callback for the
  83272. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  83273. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  83274. *
  83275. * \note In general, FLAC__StreamDecoder functions which change the
  83276. * state should not be called on the \a decoder while in the callback.
  83277. *
  83278. * \param decoder The decoder instance calling the callback.
  83279. * \param metadata The decoded metadata block.
  83280. * \param client_data The callee's client data set through
  83281. * FLAC__stream_decoder_init_*().
  83282. */
  83283. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  83284. /** Signature for the error callback.
  83285. *
  83286. * A function pointer matching this signature must be passed to one of
  83287. * the FLAC__stream_decoder_init_*() functions.
  83288. * The supplied function will be called whenever an error occurs during
  83289. * decoding.
  83290. *
  83291. * \note In general, FLAC__StreamDecoder functions which change the
  83292. * state should not be called on the \a decoder while in the callback.
  83293. *
  83294. * \param decoder The decoder instance calling the callback.
  83295. * \param status The error encountered by the decoder.
  83296. * \param client_data The callee's client data set through
  83297. * FLAC__stream_decoder_init_*().
  83298. */
  83299. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  83300. /***********************************************************************
  83301. *
  83302. * Class constructor/destructor
  83303. *
  83304. ***********************************************************************/
  83305. /** Create a new stream decoder instance. The instance is created with
  83306. * default settings; see the individual FLAC__stream_decoder_set_*()
  83307. * functions for each setting's default.
  83308. *
  83309. * \retval FLAC__StreamDecoder*
  83310. * \c NULL if there was an error allocating memory, else the new instance.
  83311. */
  83312. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  83313. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  83314. *
  83315. * \param decoder A pointer to an existing decoder.
  83316. * \assert
  83317. * \code decoder != NULL \endcode
  83318. */
  83319. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  83320. /***********************************************************************
  83321. *
  83322. * Public class method prototypes
  83323. *
  83324. ***********************************************************************/
  83325. /** Set the serial number for the FLAC stream within the Ogg container.
  83326. * The default behavior is to use the serial number of the first Ogg
  83327. * page. Setting a serial number here will explicitly specify which
  83328. * stream is to be decoded.
  83329. *
  83330. * \note
  83331. * This does not need to be set for native FLAC decoding.
  83332. *
  83333. * \default \c use serial number of first page
  83334. * \param decoder A decoder instance to set.
  83335. * \param serial_number See above.
  83336. * \assert
  83337. * \code decoder != NULL \endcode
  83338. * \retval FLAC__bool
  83339. * \c false if the decoder is already initialized, else \c true.
  83340. */
  83341. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  83342. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  83343. * compute the MD5 signature of the unencoded audio data while decoding
  83344. * and compare it to the signature from the STREAMINFO block, if it
  83345. * exists, during FLAC__stream_decoder_finish().
  83346. *
  83347. * MD5 signature checking will be turned off (until the next
  83348. * FLAC__stream_decoder_reset()) if there is no signature in the
  83349. * STREAMINFO block or when a seek is attempted.
  83350. *
  83351. * Clients that do not use the MD5 check should leave this off to speed
  83352. * up decoding.
  83353. *
  83354. * \default \c false
  83355. * \param decoder A decoder instance to set.
  83356. * \param value Flag value (see above).
  83357. * \assert
  83358. * \code decoder != NULL \endcode
  83359. * \retval FLAC__bool
  83360. * \c false if the decoder is already initialized, else \c true.
  83361. */
  83362. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  83363. /** Direct the decoder to pass on all metadata blocks of type \a type.
  83364. *
  83365. * \default By default, only the \c STREAMINFO block is returned via the
  83366. * metadata callback.
  83367. * \param decoder A decoder instance to set.
  83368. * \param type See above.
  83369. * \assert
  83370. * \code decoder != NULL \endcode
  83371. * \a type is valid
  83372. * \retval FLAC__bool
  83373. * \c false if the decoder is already initialized, else \c true.
  83374. */
  83375. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  83376. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  83377. * given \a id.
  83378. *
  83379. * \default By default, only the \c STREAMINFO block is returned via the
  83380. * metadata callback.
  83381. * \param decoder A decoder instance to set.
  83382. * \param id See above.
  83383. * \assert
  83384. * \code decoder != NULL \endcode
  83385. * \code id != NULL \endcode
  83386. * \retval FLAC__bool
  83387. * \c false if the decoder is already initialized, else \c true.
  83388. */
  83389. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  83390. /** Direct the decoder to pass on all metadata blocks of any type.
  83391. *
  83392. * \default By default, only the \c STREAMINFO block is returned via the
  83393. * metadata callback.
  83394. * \param decoder A decoder instance to set.
  83395. * \assert
  83396. * \code decoder != NULL \endcode
  83397. * \retval FLAC__bool
  83398. * \c false if the decoder is already initialized, else \c true.
  83399. */
  83400. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  83401. /** Direct the decoder to filter out all metadata blocks of type \a type.
  83402. *
  83403. * \default By default, only the \c STREAMINFO block is returned via the
  83404. * metadata callback.
  83405. * \param decoder A decoder instance to set.
  83406. * \param type See above.
  83407. * \assert
  83408. * \code decoder != NULL \endcode
  83409. * \a type is valid
  83410. * \retval FLAC__bool
  83411. * \c false if the decoder is already initialized, else \c true.
  83412. */
  83413. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  83414. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  83415. * the given \a id.
  83416. *
  83417. * \default By default, only the \c STREAMINFO block is returned via the
  83418. * metadata callback.
  83419. * \param decoder A decoder instance to set.
  83420. * \param id See above.
  83421. * \assert
  83422. * \code decoder != NULL \endcode
  83423. * \code id != NULL \endcode
  83424. * \retval FLAC__bool
  83425. * \c false if the decoder is already initialized, else \c true.
  83426. */
  83427. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  83428. /** Direct the decoder to filter out all metadata blocks of any type.
  83429. *
  83430. * \default By default, only the \c STREAMINFO block is returned via the
  83431. * metadata callback.
  83432. * \param decoder A decoder instance to set.
  83433. * \assert
  83434. * \code decoder != NULL \endcode
  83435. * \retval FLAC__bool
  83436. * \c false if the decoder is already initialized, else \c true.
  83437. */
  83438. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  83439. /** Get the current decoder state.
  83440. *
  83441. * \param decoder A decoder instance to query.
  83442. * \assert
  83443. * \code decoder != NULL \endcode
  83444. * \retval FLAC__StreamDecoderState
  83445. * The current decoder state.
  83446. */
  83447. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  83448. /** Get the current decoder state as a C string.
  83449. *
  83450. * \param decoder A decoder instance to query.
  83451. * \assert
  83452. * \code decoder != NULL \endcode
  83453. * \retval const char *
  83454. * The decoder state as a C string. Do not modify the contents.
  83455. */
  83456. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  83457. /** Get the "MD5 signature checking" flag.
  83458. * This is the value of the setting, not whether or not the decoder is
  83459. * currently checking the MD5 (remember, it can be turned off automatically
  83460. * by a seek). When the decoder is reset the flag will be restored to the
  83461. * value returned by this function.
  83462. *
  83463. * \param decoder A decoder instance to query.
  83464. * \assert
  83465. * \code decoder != NULL \endcode
  83466. * \retval FLAC__bool
  83467. * See above.
  83468. */
  83469. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  83470. /** Get the total number of samples in the stream being decoded.
  83471. * Will only be valid after decoding has started and will contain the
  83472. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  83473. *
  83474. * \param decoder A decoder instance to query.
  83475. * \assert
  83476. * \code decoder != NULL \endcode
  83477. * \retval unsigned
  83478. * See above.
  83479. */
  83480. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  83481. /** Get the current number of channels in the stream being decoded.
  83482. * Will only be valid after decoding has started and will contain the
  83483. * value from the most recently decoded frame header.
  83484. *
  83485. * \param decoder A decoder instance to query.
  83486. * \assert
  83487. * \code decoder != NULL \endcode
  83488. * \retval unsigned
  83489. * See above.
  83490. */
  83491. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  83492. /** Get the current channel assignment in the stream being decoded.
  83493. * Will only be valid after decoding has started and will contain the
  83494. * value from the most recently decoded frame header.
  83495. *
  83496. * \param decoder A decoder instance to query.
  83497. * \assert
  83498. * \code decoder != NULL \endcode
  83499. * \retval FLAC__ChannelAssignment
  83500. * See above.
  83501. */
  83502. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  83503. /** Get the current sample resolution in the stream being decoded.
  83504. * Will only be valid after decoding has started and will contain the
  83505. * value from the most recently decoded frame header.
  83506. *
  83507. * \param decoder A decoder instance to query.
  83508. * \assert
  83509. * \code decoder != NULL \endcode
  83510. * \retval unsigned
  83511. * See above.
  83512. */
  83513. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  83514. /** Get the current sample rate in Hz of the stream being decoded.
  83515. * Will only be valid after decoding has started and will contain the
  83516. * value from the most recently decoded frame header.
  83517. *
  83518. * \param decoder A decoder instance to query.
  83519. * \assert
  83520. * \code decoder != NULL \endcode
  83521. * \retval unsigned
  83522. * See above.
  83523. */
  83524. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  83525. /** Get the current blocksize of the stream being decoded.
  83526. * Will only be valid after decoding has started and will contain the
  83527. * value from the most recently decoded frame header.
  83528. *
  83529. * \param decoder A decoder instance to query.
  83530. * \assert
  83531. * \code decoder != NULL \endcode
  83532. * \retval unsigned
  83533. * See above.
  83534. */
  83535. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  83536. /** Returns the decoder's current read position within the stream.
  83537. * The position is the byte offset from the start of the stream.
  83538. * Bytes before this position have been fully decoded. Note that
  83539. * there may still be undecoded bytes in the decoder's read FIFO.
  83540. * The returned position is correct even after a seek.
  83541. *
  83542. * \warning This function currently only works for native FLAC,
  83543. * not Ogg FLAC streams.
  83544. *
  83545. * \param decoder A decoder instance to query.
  83546. * \param position Address at which to return the desired position.
  83547. * \assert
  83548. * \code decoder != NULL \endcode
  83549. * \code position != NULL \endcode
  83550. * \retval FLAC__bool
  83551. * \c true if successful, \c false if the stream is not native FLAC,
  83552. * or there was an error from the 'tell' callback or it returned
  83553. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  83554. */
  83555. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  83556. /** Initialize the decoder instance to decode native FLAC streams.
  83557. *
  83558. * This flavor of initialization sets up the decoder to decode from a
  83559. * native FLAC stream. I/O is performed via callbacks to the client.
  83560. * For decoding from a plain file via filename or open FILE*,
  83561. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  83562. * provide a simpler interface.
  83563. *
  83564. * This function should be called after FLAC__stream_decoder_new() and
  83565. * FLAC__stream_decoder_set_*() but before any of the
  83566. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83567. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83568. * if initialization succeeded.
  83569. *
  83570. * \param decoder An uninitialized decoder instance.
  83571. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  83572. * pointer must not be \c NULL.
  83573. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  83574. * pointer may be \c NULL if seeking is not
  83575. * supported. If \a seek_callback is not \c NULL then a
  83576. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  83577. * Alternatively, a dummy seek callback that just
  83578. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83579. * may also be supplied, all though this is slightly
  83580. * less efficient for the decoder.
  83581. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  83582. * pointer may be \c NULL if not supported by the client. If
  83583. * \a seek_callback is not \c NULL then a
  83584. * \a tell_callback must also be supplied.
  83585. * Alternatively, a dummy tell callback that just
  83586. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83587. * may also be supplied, all though this is slightly
  83588. * less efficient for the decoder.
  83589. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  83590. * pointer may be \c NULL if not supported by the client. If
  83591. * \a seek_callback is not \c NULL then a
  83592. * \a length_callback must also be supplied.
  83593. * Alternatively, a dummy length callback that just
  83594. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83595. * may also be supplied, all though this is slightly
  83596. * less efficient for the decoder.
  83597. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  83598. * pointer may be \c NULL if not supported by the client. If
  83599. * \a seek_callback is not \c NULL then a
  83600. * \a eof_callback must also be supplied.
  83601. * Alternatively, a dummy length callback that just
  83602. * returns \c false
  83603. * may also be supplied, all though this is slightly
  83604. * less efficient for the decoder.
  83605. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83606. * pointer must not be \c NULL.
  83607. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83608. * pointer may be \c NULL if the callback is not
  83609. * desired.
  83610. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83611. * pointer must not be \c NULL.
  83612. * \param client_data This value will be supplied to callbacks in their
  83613. * \a client_data argument.
  83614. * \assert
  83615. * \code decoder != NULL \endcode
  83616. * \retval FLAC__StreamDecoderInitStatus
  83617. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83618. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83619. */
  83620. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  83621. FLAC__StreamDecoder *decoder,
  83622. FLAC__StreamDecoderReadCallback read_callback,
  83623. FLAC__StreamDecoderSeekCallback seek_callback,
  83624. FLAC__StreamDecoderTellCallback tell_callback,
  83625. FLAC__StreamDecoderLengthCallback length_callback,
  83626. FLAC__StreamDecoderEofCallback eof_callback,
  83627. FLAC__StreamDecoderWriteCallback write_callback,
  83628. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83629. FLAC__StreamDecoderErrorCallback error_callback,
  83630. void *client_data
  83631. );
  83632. /** Initialize the decoder instance to decode Ogg FLAC streams.
  83633. *
  83634. * This flavor of initialization sets up the decoder to decode from a
  83635. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  83636. * client. For decoding from a plain file via filename or open FILE*,
  83637. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  83638. * provide a simpler interface.
  83639. *
  83640. * This function should be called after FLAC__stream_decoder_new() and
  83641. * FLAC__stream_decoder_set_*() but before any of the
  83642. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83643. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83644. * if initialization succeeded.
  83645. *
  83646. * \note Support for Ogg FLAC in the library is optional. If this
  83647. * library has been built without support for Ogg FLAC, this function
  83648. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83649. *
  83650. * \param decoder An uninitialized decoder instance.
  83651. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  83652. * pointer must not be \c NULL.
  83653. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  83654. * pointer may be \c NULL if seeking is not
  83655. * supported. If \a seek_callback is not \c NULL then a
  83656. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  83657. * Alternatively, a dummy seek callback that just
  83658. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83659. * may also be supplied, all though this is slightly
  83660. * less efficient for the decoder.
  83661. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  83662. * pointer may be \c NULL if not supported by the client. If
  83663. * \a seek_callback is not \c NULL then a
  83664. * \a tell_callback must also be supplied.
  83665. * Alternatively, a dummy tell callback that just
  83666. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83667. * may also be supplied, all though this is slightly
  83668. * less efficient for the decoder.
  83669. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  83670. * pointer may be \c NULL if not supported by the client. If
  83671. * \a seek_callback is not \c NULL then a
  83672. * \a length_callback must also be supplied.
  83673. * Alternatively, a dummy length callback that just
  83674. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83675. * may also be supplied, all though this is slightly
  83676. * less efficient for the decoder.
  83677. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  83678. * pointer may be \c NULL if not supported by the client. If
  83679. * \a seek_callback is not \c NULL then a
  83680. * \a eof_callback must also be supplied.
  83681. * Alternatively, a dummy length callback that just
  83682. * returns \c false
  83683. * may also be supplied, all though this is slightly
  83684. * less efficient for the decoder.
  83685. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83686. * pointer must not be \c NULL.
  83687. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83688. * pointer may be \c NULL if the callback is not
  83689. * desired.
  83690. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83691. * pointer must not be \c NULL.
  83692. * \param client_data This value will be supplied to callbacks in their
  83693. * \a client_data argument.
  83694. * \assert
  83695. * \code decoder != NULL \endcode
  83696. * \retval FLAC__StreamDecoderInitStatus
  83697. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83698. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83699. */
  83700. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  83701. FLAC__StreamDecoder *decoder,
  83702. FLAC__StreamDecoderReadCallback read_callback,
  83703. FLAC__StreamDecoderSeekCallback seek_callback,
  83704. FLAC__StreamDecoderTellCallback tell_callback,
  83705. FLAC__StreamDecoderLengthCallback length_callback,
  83706. FLAC__StreamDecoderEofCallback eof_callback,
  83707. FLAC__StreamDecoderWriteCallback write_callback,
  83708. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83709. FLAC__StreamDecoderErrorCallback error_callback,
  83710. void *client_data
  83711. );
  83712. /** Initialize the decoder instance to decode native FLAC files.
  83713. *
  83714. * This flavor of initialization sets up the decoder to decode from a
  83715. * plain native FLAC file. For non-stdio streams, you must use
  83716. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  83717. *
  83718. * This function should be called after FLAC__stream_decoder_new() and
  83719. * FLAC__stream_decoder_set_*() but before any of the
  83720. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83721. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83722. * if initialization succeeded.
  83723. *
  83724. * \param decoder An uninitialized decoder instance.
  83725. * \param file An open FLAC file. The file should have been
  83726. * opened with mode \c "rb" and rewound. The file
  83727. * becomes owned by the decoder and should not be
  83728. * manipulated by the client while decoding.
  83729. * Unless \a file is \c stdin, it will be closed
  83730. * when FLAC__stream_decoder_finish() is called.
  83731. * Note however that seeking will not work when
  83732. * decoding from \c stdout since it is not seekable.
  83733. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83734. * pointer must not be \c NULL.
  83735. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83736. * pointer may be \c NULL if the callback is not
  83737. * desired.
  83738. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83739. * pointer must not be \c NULL.
  83740. * \param client_data This value will be supplied to callbacks in their
  83741. * \a client_data argument.
  83742. * \assert
  83743. * \code decoder != NULL \endcode
  83744. * \code file != NULL \endcode
  83745. * \retval FLAC__StreamDecoderInitStatus
  83746. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83747. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83748. */
  83749. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  83750. FLAC__StreamDecoder *decoder,
  83751. FILE *file,
  83752. FLAC__StreamDecoderWriteCallback write_callback,
  83753. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83754. FLAC__StreamDecoderErrorCallback error_callback,
  83755. void *client_data
  83756. );
  83757. /** Initialize the decoder instance to decode Ogg FLAC files.
  83758. *
  83759. * This flavor of initialization sets up the decoder to decode from a
  83760. * plain Ogg FLAC file. For non-stdio streams, you must use
  83761. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  83762. *
  83763. * This function should be called after FLAC__stream_decoder_new() and
  83764. * FLAC__stream_decoder_set_*() but before any of the
  83765. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83766. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83767. * if initialization succeeded.
  83768. *
  83769. * \note Support for Ogg FLAC in the library is optional. If this
  83770. * library has been built without support for Ogg FLAC, this function
  83771. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83772. *
  83773. * \param decoder An uninitialized decoder instance.
  83774. * \param file An open FLAC file. The file should have been
  83775. * opened with mode \c "rb" and rewound. The file
  83776. * becomes owned by the decoder and should not be
  83777. * manipulated by the client while decoding.
  83778. * Unless \a file is \c stdin, it will be closed
  83779. * when FLAC__stream_decoder_finish() is called.
  83780. * Note however that seeking will not work when
  83781. * decoding from \c stdout since it is not seekable.
  83782. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83783. * pointer must not be \c NULL.
  83784. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83785. * pointer may be \c NULL if the callback is not
  83786. * desired.
  83787. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83788. * pointer must not be \c NULL.
  83789. * \param client_data This value will be supplied to callbacks in their
  83790. * \a client_data argument.
  83791. * \assert
  83792. * \code decoder != NULL \endcode
  83793. * \code file != NULL \endcode
  83794. * \retval FLAC__StreamDecoderInitStatus
  83795. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83796. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83797. */
  83798. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  83799. FLAC__StreamDecoder *decoder,
  83800. FILE *file,
  83801. FLAC__StreamDecoderWriteCallback write_callback,
  83802. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83803. FLAC__StreamDecoderErrorCallback error_callback,
  83804. void *client_data
  83805. );
  83806. /** Initialize the decoder instance to decode native FLAC files.
  83807. *
  83808. * This flavor of initialization sets up the decoder to decode from a plain
  83809. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  83810. * example, with Unicode filenames on Windows), you must use
  83811. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  83812. * and provide callbacks for the I/O.
  83813. *
  83814. * This function should be called after FLAC__stream_decoder_new() and
  83815. * FLAC__stream_decoder_set_*() but before any of the
  83816. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83817. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83818. * if initialization succeeded.
  83819. *
  83820. * \param decoder An uninitialized decoder instance.
  83821. * \param filename The name of the file to decode from. The file will
  83822. * be opened with fopen(). Use \c NULL to decode from
  83823. * \c stdin. Note that \c stdin is not seekable.
  83824. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83825. * pointer must not be \c NULL.
  83826. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83827. * pointer may be \c NULL if the callback is not
  83828. * desired.
  83829. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83830. * pointer must not be \c NULL.
  83831. * \param client_data This value will be supplied to callbacks in their
  83832. * \a client_data argument.
  83833. * \assert
  83834. * \code decoder != NULL \endcode
  83835. * \retval FLAC__StreamDecoderInitStatus
  83836. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83837. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83838. */
  83839. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  83840. FLAC__StreamDecoder *decoder,
  83841. const char *filename,
  83842. FLAC__StreamDecoderWriteCallback write_callback,
  83843. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83844. FLAC__StreamDecoderErrorCallback error_callback,
  83845. void *client_data
  83846. );
  83847. /** Initialize the decoder instance to decode Ogg FLAC files.
  83848. *
  83849. * This flavor of initialization sets up the decoder to decode from a plain
  83850. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  83851. * example, with Unicode filenames on Windows), you must use
  83852. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  83853. * and provide callbacks for the I/O.
  83854. *
  83855. * This function should be called after FLAC__stream_decoder_new() and
  83856. * FLAC__stream_decoder_set_*() but before any of the
  83857. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83858. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83859. * if initialization succeeded.
  83860. *
  83861. * \note Support for Ogg FLAC in the library is optional. If this
  83862. * library has been built without support for Ogg FLAC, this function
  83863. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83864. *
  83865. * \param decoder An uninitialized decoder instance.
  83866. * \param filename The name of the file to decode from. The file will
  83867. * be opened with fopen(). Use \c NULL to decode from
  83868. * \c stdin. Note that \c stdin is not seekable.
  83869. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83870. * pointer must not be \c NULL.
  83871. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83872. * pointer may be \c NULL if the callback is not
  83873. * desired.
  83874. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83875. * pointer must not be \c NULL.
  83876. * \param client_data This value will be supplied to callbacks in their
  83877. * \a client_data argument.
  83878. * \assert
  83879. * \code decoder != NULL \endcode
  83880. * \retval FLAC__StreamDecoderInitStatus
  83881. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83882. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83883. */
  83884. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  83885. FLAC__StreamDecoder *decoder,
  83886. const char *filename,
  83887. FLAC__StreamDecoderWriteCallback write_callback,
  83888. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83889. FLAC__StreamDecoderErrorCallback error_callback,
  83890. void *client_data
  83891. );
  83892. /** Finish the decoding process.
  83893. * Flushes the decoding buffer, releases resources, resets the decoder
  83894. * settings to their defaults, and returns the decoder state to
  83895. * FLAC__STREAM_DECODER_UNINITIALIZED.
  83896. *
  83897. * In the event of a prematurely-terminated decode, it is not strictly
  83898. * necessary to call this immediately before FLAC__stream_decoder_delete()
  83899. * but it is good practice to match every FLAC__stream_decoder_init_*()
  83900. * with a FLAC__stream_decoder_finish().
  83901. *
  83902. * \param decoder An uninitialized decoder instance.
  83903. * \assert
  83904. * \code decoder != NULL \endcode
  83905. * \retval FLAC__bool
  83906. * \c false if MD5 checking is on AND a STREAMINFO block was available
  83907. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  83908. * signature does not match the one computed by the decoder; else
  83909. * \c true.
  83910. */
  83911. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  83912. /** Flush the stream input.
  83913. * The decoder's input buffer will be cleared and the state set to
  83914. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  83915. * off MD5 checking.
  83916. *
  83917. * \param decoder A decoder instance.
  83918. * \assert
  83919. * \code decoder != NULL \endcode
  83920. * \retval FLAC__bool
  83921. * \c true if successful, else \c false if a memory allocation
  83922. * error occurs (in which case the state will be set to
  83923. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  83924. */
  83925. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  83926. /** Reset the decoding process.
  83927. * The decoder's input buffer will be cleared and the state set to
  83928. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  83929. * FLAC__stream_decoder_finish() except that the settings are
  83930. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  83931. * before decoding again. MD5 checking will be restored to its original
  83932. * setting.
  83933. *
  83934. * If the decoder is seekable, or was initialized with
  83935. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  83936. * the decoder will also attempt to seek to the beginning of the file.
  83937. * If this rewind fails, this function will return \c false. It follows
  83938. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  83939. * \c stdin.
  83940. *
  83941. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  83942. * and is not seekable (i.e. no seek callback was provided or the seek
  83943. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  83944. * is the duty of the client to start feeding data from the beginning of
  83945. * the stream on the next FLAC__stream_decoder_process() or
  83946. * FLAC__stream_decoder_process_interleaved() call.
  83947. *
  83948. * \param decoder A decoder instance.
  83949. * \assert
  83950. * \code decoder != NULL \endcode
  83951. * \retval FLAC__bool
  83952. * \c true if successful, else \c false if a memory allocation occurs
  83953. * (in which case the state will be set to
  83954. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  83955. * occurs (the state will be unchanged).
  83956. */
  83957. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  83958. /** Decode one metadata block or audio frame.
  83959. * This version instructs the decoder to decode a either a single metadata
  83960. * block or a single frame and stop, unless the callbacks return a fatal
  83961. * error or the read callback returns
  83962. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  83963. *
  83964. * As the decoder needs more input it will call the read callback.
  83965. * Depending on what was decoded, the metadata or write callback will be
  83966. * called with the decoded metadata block or audio frame.
  83967. *
  83968. * Unless there is a fatal read error or end of stream, this function
  83969. * will return once one whole frame is decoded. In other words, if the
  83970. * stream is not synchronized or points to a corrupt frame header, the
  83971. * decoder will continue to try and resync until it gets to a valid
  83972. * frame, then decode one frame, then return. If the decoder points to
  83973. * a frame whose frame CRC in the frame footer does not match the
  83974. * computed frame CRC, this function will issue a
  83975. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  83976. * error callback, and return, having decoded one complete, although
  83977. * corrupt, frame. (Such corrupted frames are sent as silence of the
  83978. * correct length to the write callback.)
  83979. *
  83980. * \param decoder An initialized decoder instance.
  83981. * \assert
  83982. * \code decoder != NULL \endcode
  83983. * \retval FLAC__bool
  83984. * \c false if any fatal read, write, or memory allocation error
  83985. * occurred (meaning decoding must stop), else \c true; for more
  83986. * information about the decoder, check the decoder state with
  83987. * FLAC__stream_decoder_get_state().
  83988. */
  83989. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  83990. /** Decode until the end of the metadata.
  83991. * This version instructs the decoder to decode from the current position
  83992. * and continue until all the metadata has been read, or until the
  83993. * callbacks return a fatal error or the read callback returns
  83994. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  83995. *
  83996. * As the decoder needs more input it will call the read callback.
  83997. * As each metadata block is decoded, the metadata callback will be called
  83998. * with the decoded metadata.
  83999. *
  84000. * \param decoder An initialized decoder instance.
  84001. * \assert
  84002. * \code decoder != NULL \endcode
  84003. * \retval FLAC__bool
  84004. * \c false if any fatal read, write, or memory allocation error
  84005. * occurred (meaning decoding must stop), else \c true; for more
  84006. * information about the decoder, check the decoder state with
  84007. * FLAC__stream_decoder_get_state().
  84008. */
  84009. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  84010. /** Decode until the end of the stream.
  84011. * This version instructs the decoder to decode from the current position
  84012. * and continue until the end of stream (the read callback returns
  84013. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  84014. * callbacks return a fatal error.
  84015. *
  84016. * As the decoder needs more input it will call the read callback.
  84017. * As each metadata block and frame is decoded, the metadata or write
  84018. * callback will be called with the decoded metadata or frame.
  84019. *
  84020. * \param decoder An initialized decoder instance.
  84021. * \assert
  84022. * \code decoder != NULL \endcode
  84023. * \retval FLAC__bool
  84024. * \c false if any fatal read, write, or memory allocation error
  84025. * occurred (meaning decoding must stop), else \c true; for more
  84026. * information about the decoder, check the decoder state with
  84027. * FLAC__stream_decoder_get_state().
  84028. */
  84029. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  84030. /** Skip one audio frame.
  84031. * This version instructs the decoder to 'skip' a single frame and stop,
  84032. * unless the callbacks return a fatal error or the read callback returns
  84033. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84034. *
  84035. * The decoding flow is the same as what occurs when
  84036. * FLAC__stream_decoder_process_single() is called to process an audio
  84037. * frame, except that this function does not decode the parsed data into
  84038. * PCM or call the write callback. The integrity of the frame is still
  84039. * checked the same way as in the other process functions.
  84040. *
  84041. * This function will return once one whole frame is skipped, in the
  84042. * same way that FLAC__stream_decoder_process_single() will return once
  84043. * one whole frame is decoded.
  84044. *
  84045. * This function can be used in more quickly determining FLAC frame
  84046. * boundaries when decoding of the actual data is not needed, for
  84047. * example when an application is separating a FLAC stream into frames
  84048. * for editing or storing in a container. To do this, the application
  84049. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  84050. * to the next frame, then use
  84051. * FLAC__stream_decoder_get_decode_position() to find the new frame
  84052. * boundary.
  84053. *
  84054. * This function should only be called when the stream has advanced
  84055. * past all the metadata, otherwise it will return \c false.
  84056. *
  84057. * \param decoder An initialized decoder instance not in a metadata
  84058. * state.
  84059. * \assert
  84060. * \code decoder != NULL \endcode
  84061. * \retval FLAC__bool
  84062. * \c false if any fatal read, write, or memory allocation error
  84063. * occurred (meaning decoding must stop), or if the decoder
  84064. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  84065. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  84066. * information about the decoder, check the decoder state with
  84067. * FLAC__stream_decoder_get_state().
  84068. */
  84069. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  84070. /** Flush the input and seek to an absolute sample.
  84071. * Decoding will resume at the given sample. Note that because of
  84072. * this, the next write callback may contain a partial block. The
  84073. * client must support seeking the input or this function will fail
  84074. * and return \c false. Furthermore, if the decoder state is
  84075. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  84076. * with FLAC__stream_decoder_flush() or reset with
  84077. * FLAC__stream_decoder_reset() before decoding can continue.
  84078. *
  84079. * \param decoder A decoder instance.
  84080. * \param sample The target sample number to seek to.
  84081. * \assert
  84082. * \code decoder != NULL \endcode
  84083. * \retval FLAC__bool
  84084. * \c true if successful, else \c false.
  84085. */
  84086. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  84087. /* \} */
  84088. #ifdef __cplusplus
  84089. }
  84090. #endif
  84091. #endif
  84092. /********* End of inlined file: stream_decoder.h *********/
  84093. /********* Start of inlined file: stream_encoder.h *********/
  84094. #ifndef FLAC__STREAM_ENCODER_H
  84095. #define FLAC__STREAM_ENCODER_H
  84096. #include <stdio.h> /* for FILE */
  84097. #ifdef __cplusplus
  84098. extern "C" {
  84099. #endif
  84100. /** \file include/FLAC/stream_encoder.h
  84101. *
  84102. * \brief
  84103. * This module contains the functions which implement the stream
  84104. * encoder.
  84105. *
  84106. * See the detailed documentation in the
  84107. * \link flac_stream_encoder stream encoder \endlink module.
  84108. */
  84109. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  84110. * \ingroup flac
  84111. *
  84112. * \brief
  84113. * This module describes the encoder layers provided by libFLAC.
  84114. *
  84115. * The stream encoder can be used to encode complete streams either to the
  84116. * client via callbacks, or directly to a file, depending on how it is
  84117. * initialized. When encoding via callbacks, the client provides a write
  84118. * callback which will be called whenever FLAC data is ready to be written.
  84119. * If the client also supplies a seek callback, the encoder will also
  84120. * automatically handle the writing back of metadata discovered while
  84121. * encoding, like stream info, seek points offsets, etc. When encoding to
  84122. * a file, the client needs only supply a filename or open \c FILE* and an
  84123. * optional progress callback for periodic notification of progress; the
  84124. * write and seek callbacks are supplied internally. For more info see the
  84125. * \link flac_stream_encoder stream encoder \endlink module.
  84126. */
  84127. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  84128. * \ingroup flac_encoder
  84129. *
  84130. * \brief
  84131. * This module contains the functions which implement the stream
  84132. * encoder.
  84133. *
  84134. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  84135. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84136. *
  84137. * The basic usage of this encoder is as follows:
  84138. * - The program creates an instance of an encoder using
  84139. * FLAC__stream_encoder_new().
  84140. * - The program overrides the default settings using
  84141. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  84142. * functions should be called:
  84143. * - FLAC__stream_encoder_set_channels()
  84144. * - FLAC__stream_encoder_set_bits_per_sample()
  84145. * - FLAC__stream_encoder_set_sample_rate()
  84146. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  84147. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  84148. * - If the application wants to control the compression level or set its own
  84149. * metadata, then the following should also be called:
  84150. * - FLAC__stream_encoder_set_compression_level()
  84151. * - FLAC__stream_encoder_set_verify()
  84152. * - FLAC__stream_encoder_set_metadata()
  84153. * - The rest of the set functions should only be called if the client needs
  84154. * exact control over how the audio is compressed; thorough understanding
  84155. * of the FLAC format is necessary to achieve good results.
  84156. * - The program initializes the instance to validate the settings and
  84157. * prepare for encoding using
  84158. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  84159. * or FLAC__stream_encoder_init_file() for native FLAC
  84160. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  84161. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  84162. * - The program calls FLAC__stream_encoder_process() or
  84163. * FLAC__stream_encoder_process_interleaved() to encode data, which
  84164. * subsequently calls the callbacks when there is encoder data ready
  84165. * to be written.
  84166. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  84167. * which causes the encoder to encode any data still in its input pipe,
  84168. * update the metadata with the final encoding statistics if output
  84169. * seeking is possible, and finally reset the encoder to the
  84170. * uninitialized state.
  84171. * - The instance may be used again or deleted with
  84172. * FLAC__stream_encoder_delete().
  84173. *
  84174. * In more detail, the stream encoder functions similarly to the
  84175. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  84176. * callbacks and more options. Typically the client will create a new
  84177. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  84178. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  84179. * calling one of the FLAC__stream_encoder_init_*() functions.
  84180. *
  84181. * Unlike the decoders, the stream encoder has many options that can
  84182. * affect the speed and compression ratio. When setting these parameters
  84183. * you should have some basic knowledge of the format (see the
  84184. * <A HREF="../documentation.html#format">user-level documentation</A>
  84185. * or the <A HREF="../format.html">formal description</A>). The
  84186. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  84187. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  84188. * functions will do this, so make sure to pay attention to the state
  84189. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  84190. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  84191. * before FLAC__stream_encoder_init_*() will take on the defaults from
  84192. * the constructor.
  84193. *
  84194. * There are three initialization functions for native FLAC, one for
  84195. * setting up the encoder to encode FLAC data to the client via
  84196. * callbacks, and two for encoding directly to a file.
  84197. *
  84198. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  84199. * You must also supply a write callback which will be called anytime
  84200. * there is raw encoded data to write. If the client can seek the output
  84201. * it is best to also supply seek and tell callbacks, as this allows the
  84202. * encoder to go back after encoding is finished to write back
  84203. * information that was collected while encoding, like seek point offsets,
  84204. * frame sizes, etc.
  84205. *
  84206. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  84207. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  84208. * filename or open \c FILE*; the encoder will handle all the callbacks
  84209. * internally. You may also supply a progress callback for periodic
  84210. * notification of the encoding progress.
  84211. *
  84212. * There are three similarly-named init functions for encoding to Ogg
  84213. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84214. * library has been built with Ogg support.
  84215. *
  84216. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  84217. * call the write callback several times, once with the \c fLaC signature,
  84218. * and once for each encoded metadata block. Note that for Ogg FLAC
  84219. * encoding you will usually get at least twice the number of callbacks than
  84220. * with native FLAC, one for the Ogg page header and one for the page body.
  84221. *
  84222. * After initializing the instance, the client may feed audio data to the
  84223. * encoder in one of two ways:
  84224. *
  84225. * - Channel separate, through FLAC__stream_encoder_process() - The client
  84226. * will pass an array of pointers to buffers, one for each channel, to
  84227. * the encoder, each of the same length. The samples need not be
  84228. * block-aligned, but each channel should have the same number of samples.
  84229. * - Channel interleaved, through
  84230. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  84231. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  84232. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  84233. * Again, the samples need not be block-aligned but they must be
  84234. * sample-aligned, i.e. the first value should be channel0_sample0 and
  84235. * the last value channelN_sampleM.
  84236. *
  84237. * Note that for either process call, each sample in the buffers should be a
  84238. * signed integer, right-justified to the resolution set by
  84239. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  84240. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  84241. *
  84242. * When the client is finished encoding data, it calls
  84243. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  84244. * data still in its input pipe, and call the metadata callback with the
  84245. * final encoding statistics. Then the instance may be deleted with
  84246. * FLAC__stream_encoder_delete() or initialized again to encode another
  84247. * stream.
  84248. *
  84249. * For programs that write their own metadata, but that do not know the
  84250. * actual metadata until after encoding, it is advantageous to instruct
  84251. * the encoder to write a PADDING block of the correct size, so that
  84252. * instead of rewriting the whole stream after encoding, the program can
  84253. * just overwrite the PADDING block. If only the maximum size of the
  84254. * metadata is known, the program can write a slightly larger padding
  84255. * block, then split it after encoding.
  84256. *
  84257. * Make sure you understand how lengths are calculated. All FLAC metadata
  84258. * blocks have a 4 byte header which contains the type and length. This
  84259. * length does not include the 4 bytes of the header. See the format page
  84260. * for the specification of metadata blocks and their lengths.
  84261. *
  84262. * \note
  84263. * If you are writing the FLAC data to a file via callbacks, make sure it
  84264. * is open for update (e.g. mode "w+" for stdio streams). This is because
  84265. * after the first encoding pass, the encoder will try to seek back to the
  84266. * beginning of the stream, to the STREAMINFO block, to write some data
  84267. * there. (If using FLAC__stream_encoder_init*_file() or
  84268. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  84269. *
  84270. * \note
  84271. * The "set" functions may only be called when the encoder is in the
  84272. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  84273. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  84274. * before FLAC__stream_encoder_init_*(). If this is the case they will
  84275. * return \c true, otherwise \c false.
  84276. *
  84277. * \note
  84278. * FLAC__stream_encoder_finish() resets all settings to the constructor
  84279. * defaults.
  84280. *
  84281. * \{
  84282. */
  84283. /** State values for a FLAC__StreamEncoder.
  84284. *
  84285. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  84286. *
  84287. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  84288. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  84289. * must be deleted with FLAC__stream_encoder_delete().
  84290. */
  84291. typedef enum {
  84292. FLAC__STREAM_ENCODER_OK = 0,
  84293. /**< The encoder is in the normal OK state and samples can be processed. */
  84294. FLAC__STREAM_ENCODER_UNINITIALIZED,
  84295. /**< The encoder is in the uninitialized state; one of the
  84296. * FLAC__stream_encoder_init_*() functions must be called before samples
  84297. * can be processed.
  84298. */
  84299. FLAC__STREAM_ENCODER_OGG_ERROR,
  84300. /**< An error occurred in the underlying Ogg layer. */
  84301. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  84302. /**< An error occurred in the underlying verify stream decoder;
  84303. * check FLAC__stream_encoder_get_verify_decoder_state().
  84304. */
  84305. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  84306. /**< The verify decoder detected a mismatch between the original
  84307. * audio signal and the decoded audio signal.
  84308. */
  84309. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  84310. /**< One of the callbacks returned a fatal error. */
  84311. FLAC__STREAM_ENCODER_IO_ERROR,
  84312. /**< An I/O error occurred while opening/reading/writing a file.
  84313. * Check \c errno.
  84314. */
  84315. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  84316. /**< An error occurred while writing the stream; usually, the
  84317. * write_callback returned an error.
  84318. */
  84319. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  84320. /**< Memory allocation failed. */
  84321. } FLAC__StreamEncoderState;
  84322. /** Maps a FLAC__StreamEncoderState to a C string.
  84323. *
  84324. * Using a FLAC__StreamEncoderState as the index to this array
  84325. * will give the string equivalent. The contents should not be modified.
  84326. */
  84327. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  84328. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  84329. */
  84330. typedef enum {
  84331. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  84332. /**< Initialization was successful. */
  84333. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  84334. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  84335. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  84336. /**< The library was not compiled with support for the given container
  84337. * format.
  84338. */
  84339. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  84340. /**< A required callback was not supplied. */
  84341. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  84342. /**< The encoder has an invalid setting for number of channels. */
  84343. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  84344. /**< The encoder has an invalid setting for bits-per-sample.
  84345. * FLAC supports 4-32 bps but the reference encoder currently supports
  84346. * only up to 24 bps.
  84347. */
  84348. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  84349. /**< The encoder has an invalid setting for the input sample rate. */
  84350. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  84351. /**< The encoder has an invalid setting for the block size. */
  84352. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  84353. /**< The encoder has an invalid setting for the maximum LPC order. */
  84354. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  84355. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  84356. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  84357. /**< The specified block size is less than the maximum LPC order. */
  84358. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  84359. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  84360. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  84361. /**< The metadata input to the encoder is invalid, in one of the following ways:
  84362. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  84363. * - One of the metadata blocks contains an undefined type
  84364. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  84365. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  84366. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  84367. */
  84368. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  84369. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  84370. * already initialized, usually because
  84371. * FLAC__stream_encoder_finish() was not called.
  84372. */
  84373. } FLAC__StreamEncoderInitStatus;
  84374. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  84375. *
  84376. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  84377. * will give the string equivalent. The contents should not be modified.
  84378. */
  84379. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  84380. /** Return values for the FLAC__StreamEncoder read callback.
  84381. */
  84382. typedef enum {
  84383. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  84384. /**< The read was OK and decoding can continue. */
  84385. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  84386. /**< The read was attempted at the end of the stream. */
  84387. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  84388. /**< An unrecoverable error occurred. */
  84389. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  84390. /**< Client does not support reading back from the output. */
  84391. } FLAC__StreamEncoderReadStatus;
  84392. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  84393. *
  84394. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  84395. * will give the string equivalent. The contents should not be modified.
  84396. */
  84397. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  84398. /** Return values for the FLAC__StreamEncoder write callback.
  84399. */
  84400. typedef enum {
  84401. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  84402. /**< The write was OK and encoding can continue. */
  84403. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  84404. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  84405. } FLAC__StreamEncoderWriteStatus;
  84406. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  84407. *
  84408. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  84409. * will give the string equivalent. The contents should not be modified.
  84410. */
  84411. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  84412. /** Return values for the FLAC__StreamEncoder seek callback.
  84413. */
  84414. typedef enum {
  84415. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  84416. /**< The seek was OK and encoding can continue. */
  84417. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  84418. /**< An unrecoverable error occurred. */
  84419. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  84420. /**< Client does not support seeking. */
  84421. } FLAC__StreamEncoderSeekStatus;
  84422. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  84423. *
  84424. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  84425. * will give the string equivalent. The contents should not be modified.
  84426. */
  84427. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  84428. /** Return values for the FLAC__StreamEncoder tell callback.
  84429. */
  84430. typedef enum {
  84431. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  84432. /**< The tell was OK and encoding can continue. */
  84433. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  84434. /**< An unrecoverable error occurred. */
  84435. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  84436. /**< Client does not support seeking. */
  84437. } FLAC__StreamEncoderTellStatus;
  84438. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  84439. *
  84440. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  84441. * will give the string equivalent. The contents should not be modified.
  84442. */
  84443. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  84444. /***********************************************************************
  84445. *
  84446. * class FLAC__StreamEncoder
  84447. *
  84448. ***********************************************************************/
  84449. struct FLAC__StreamEncoderProtected;
  84450. struct FLAC__StreamEncoderPrivate;
  84451. /** The opaque structure definition for the stream encoder type.
  84452. * See the \link flac_stream_encoder stream encoder module \endlink
  84453. * for a detailed description.
  84454. */
  84455. typedef struct {
  84456. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  84457. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  84458. } FLAC__StreamEncoder;
  84459. /** Signature for the read callback.
  84460. *
  84461. * A function pointer matching this signature must be passed to
  84462. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  84463. * The supplied function will be called when the encoder needs to read back
  84464. * encoded data. This happens during the metadata callback, when the encoder
  84465. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  84466. * while encoding. The address of the buffer to be filled is supplied, along
  84467. * with the number of bytes the buffer can hold. The callback may choose to
  84468. * supply less data and modify the byte count but must be careful not to
  84469. * overflow the buffer. The callback then returns a status code chosen from
  84470. * FLAC__StreamEncoderReadStatus.
  84471. *
  84472. * Here is an example of a read callback for stdio streams:
  84473. * \code
  84474. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  84475. * {
  84476. * FILE *file = ((MyClientData*)client_data)->file;
  84477. * if(*bytes > 0) {
  84478. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  84479. * if(ferror(file))
  84480. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  84481. * else if(*bytes == 0)
  84482. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  84483. * else
  84484. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  84485. * }
  84486. * else
  84487. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  84488. * }
  84489. * \endcode
  84490. *
  84491. * \note In general, FLAC__StreamEncoder functions which change the
  84492. * state should not be called on the \a encoder while in the callback.
  84493. *
  84494. * \param encoder The encoder instance calling the callback.
  84495. * \param buffer A pointer to a location for the callee to store
  84496. * data to be encoded.
  84497. * \param bytes A pointer to the size of the buffer. On entry
  84498. * to the callback, it contains the maximum number
  84499. * of bytes that may be stored in \a buffer. The
  84500. * callee must set it to the actual number of bytes
  84501. * stored (0 in case of error or end-of-stream) before
  84502. * returning.
  84503. * \param client_data The callee's client data set through
  84504. * FLAC__stream_encoder_set_client_data().
  84505. * \retval FLAC__StreamEncoderReadStatus
  84506. * The callee's return status.
  84507. */
  84508. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  84509. /** Signature for the write callback.
  84510. *
  84511. * A function pointer matching this signature must be passed to
  84512. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84513. * by the encoder anytime there is raw encoded data ready to write. It may
  84514. * include metadata mixed with encoded audio frames and the data is not
  84515. * guaranteed to be aligned on frame or metadata block boundaries.
  84516. *
  84517. * The only duty of the callback is to write out the \a bytes worth of data
  84518. * in \a buffer to the current position in the output stream. The arguments
  84519. * \a samples and \a current_frame are purely informational. If \a samples
  84520. * is greater than \c 0, then \a current_frame will hold the current frame
  84521. * number that is being written; otherwise it indicates that the write
  84522. * callback is being called to write metadata.
  84523. *
  84524. * \note
  84525. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  84526. * write callback will be called twice when writing each audio
  84527. * frame; once for the page header, and once for the page body.
  84528. * When writing the page header, the \a samples argument to the
  84529. * write callback will be \c 0.
  84530. *
  84531. * \note In general, FLAC__StreamEncoder functions which change the
  84532. * state should not be called on the \a encoder while in the callback.
  84533. *
  84534. * \param encoder The encoder instance calling the callback.
  84535. * \param buffer An array of encoded data of length \a bytes.
  84536. * \param bytes The byte length of \a buffer.
  84537. * \param samples The number of samples encoded by \a buffer.
  84538. * \c 0 has a special meaning; see above.
  84539. * \param current_frame The number of the current frame being encoded.
  84540. * \param client_data The callee's client data set through
  84541. * FLAC__stream_encoder_init_*().
  84542. * \retval FLAC__StreamEncoderWriteStatus
  84543. * The callee's return status.
  84544. */
  84545. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  84546. /** Signature for the seek callback.
  84547. *
  84548. * A function pointer matching this signature may be passed to
  84549. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84550. * when the encoder needs to seek the output stream. The encoder will pass
  84551. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  84552. *
  84553. * Here is an example of a seek callback for stdio streams:
  84554. * \code
  84555. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  84556. * {
  84557. * FILE *file = ((MyClientData*)client_data)->file;
  84558. * if(file == stdin)
  84559. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  84560. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  84561. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  84562. * else
  84563. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  84564. * }
  84565. * \endcode
  84566. *
  84567. * \note In general, FLAC__StreamEncoder functions which change the
  84568. * state should not be called on the \a encoder while in the callback.
  84569. *
  84570. * \param encoder The encoder instance calling the callback.
  84571. * \param absolute_byte_offset The offset from the beginning of the stream
  84572. * to seek to.
  84573. * \param client_data The callee's client data set through
  84574. * FLAC__stream_encoder_init_*().
  84575. * \retval FLAC__StreamEncoderSeekStatus
  84576. * The callee's return status.
  84577. */
  84578. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  84579. /** Signature for the tell callback.
  84580. *
  84581. * A function pointer matching this signature may be passed to
  84582. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84583. * when the encoder needs to know the current position of the output stream.
  84584. *
  84585. * \warning
  84586. * The callback must return the true current byte offset of the output to
  84587. * which the encoder is writing. If you are buffering the output, make
  84588. * sure and take this into account. If you are writing directly to a
  84589. * FILE* from your write callback, ftell() is sufficient. If you are
  84590. * writing directly to a file descriptor from your write callback, you
  84591. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  84592. * these points to rewrite metadata after encoding.
  84593. *
  84594. * Here is an example of a tell callback for stdio streams:
  84595. * \code
  84596. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  84597. * {
  84598. * FILE *file = ((MyClientData*)client_data)->file;
  84599. * off_t pos;
  84600. * if(file == stdin)
  84601. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  84602. * else if((pos = ftello(file)) < 0)
  84603. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  84604. * else {
  84605. * *absolute_byte_offset = (FLAC__uint64)pos;
  84606. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  84607. * }
  84608. * }
  84609. * \endcode
  84610. *
  84611. * \note In general, FLAC__StreamEncoder functions which change the
  84612. * state should not be called on the \a encoder while in the callback.
  84613. *
  84614. * \param encoder The encoder instance calling the callback.
  84615. * \param absolute_byte_offset The address at which to store the current
  84616. * position of the output.
  84617. * \param client_data The callee's client data set through
  84618. * FLAC__stream_encoder_init_*().
  84619. * \retval FLAC__StreamEncoderTellStatus
  84620. * The callee's return status.
  84621. */
  84622. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  84623. /** Signature for the metadata callback.
  84624. *
  84625. * A function pointer matching this signature may be passed to
  84626. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84627. * once at the end of encoding with the populated STREAMINFO structure. This
  84628. * is so the client can seek back to the beginning of the file and write the
  84629. * STREAMINFO block with the correct statistics after encoding (like
  84630. * minimum/maximum frame size and total samples).
  84631. *
  84632. * \note In general, FLAC__StreamEncoder functions which change the
  84633. * state should not be called on the \a encoder while in the callback.
  84634. *
  84635. * \param encoder The encoder instance calling the callback.
  84636. * \param metadata The final populated STREAMINFO block.
  84637. * \param client_data The callee's client data set through
  84638. * FLAC__stream_encoder_init_*().
  84639. */
  84640. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  84641. /** Signature for the progress callback.
  84642. *
  84643. * A function pointer matching this signature may be passed to
  84644. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  84645. * The supplied function will be called when the encoder has finished
  84646. * writing a frame. The \c total_frames_estimate argument to the
  84647. * callback will be based on the value from
  84648. * FLAC__stream_encoder_set_total_samples_estimate().
  84649. *
  84650. * \note In general, FLAC__StreamEncoder functions which change the
  84651. * state should not be called on the \a encoder while in the callback.
  84652. *
  84653. * \param encoder The encoder instance calling the callback.
  84654. * \param bytes_written Bytes written so far.
  84655. * \param samples_written Samples written so far.
  84656. * \param frames_written Frames written so far.
  84657. * \param total_frames_estimate The estimate of the total number of
  84658. * frames to be written.
  84659. * \param client_data The callee's client data set through
  84660. * FLAC__stream_encoder_init_*().
  84661. */
  84662. typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
  84663. /***********************************************************************
  84664. *
  84665. * Class constructor/destructor
  84666. *
  84667. ***********************************************************************/
  84668. /** Create a new stream encoder instance. The instance is created with
  84669. * default settings; see the individual FLAC__stream_encoder_set_*()
  84670. * functions for each setting's default.
  84671. *
  84672. * \retval FLAC__StreamEncoder*
  84673. * \c NULL if there was an error allocating memory, else the new instance.
  84674. */
  84675. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  84676. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  84677. *
  84678. * \param encoder A pointer to an existing encoder.
  84679. * \assert
  84680. * \code encoder != NULL \endcode
  84681. */
  84682. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  84683. /***********************************************************************
  84684. *
  84685. * Public class method prototypes
  84686. *
  84687. ***********************************************************************/
  84688. /** Set the serial number for the FLAC stream to use in the Ogg container.
  84689. *
  84690. * \note
  84691. * This does not need to be set for native FLAC encoding.
  84692. *
  84693. * \note
  84694. * It is recommended to set a serial number explicitly as the default of '0'
  84695. * may collide with other streams.
  84696. *
  84697. * \default \c 0
  84698. * \param encoder An encoder instance to set.
  84699. * \param serial_number See above.
  84700. * \assert
  84701. * \code encoder != NULL \endcode
  84702. * \retval FLAC__bool
  84703. * \c false if the encoder is already initialized, else \c true.
  84704. */
  84705. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  84706. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  84707. * encoded output by feeding it through an internal decoder and comparing
  84708. * the original signal against the decoded signal. If a mismatch occurs,
  84709. * the process call will return \c false. Note that this will slow the
  84710. * encoding process by the extra time required for decoding and comparison.
  84711. *
  84712. * \default \c false
  84713. * \param encoder An encoder instance to set.
  84714. * \param value Flag value (see above).
  84715. * \assert
  84716. * \code encoder != NULL \endcode
  84717. * \retval FLAC__bool
  84718. * \c false if the encoder is already initialized, else \c true.
  84719. */
  84720. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84721. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  84722. * the encoder will comply with the Subset and will check the
  84723. * settings during FLAC__stream_encoder_init_*() to see if all settings
  84724. * comply. If \c false, the settings may take advantage of the full
  84725. * range that the format allows.
  84726. *
  84727. * Make sure you know what it entails before setting this to \c false.
  84728. *
  84729. * \default \c true
  84730. * \param encoder An encoder instance to set.
  84731. * \param value Flag value (see above).
  84732. * \assert
  84733. * \code encoder != NULL \endcode
  84734. * \retval FLAC__bool
  84735. * \c false if the encoder is already initialized, else \c true.
  84736. */
  84737. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84738. /** Set the number of channels to be encoded.
  84739. *
  84740. * \default \c 2
  84741. * \param encoder An encoder instance to set.
  84742. * \param value See above.
  84743. * \assert
  84744. * \code encoder != NULL \endcode
  84745. * \retval FLAC__bool
  84746. * \c false if the encoder is already initialized, else \c true.
  84747. */
  84748. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  84749. /** Set the sample resolution of the input to be encoded.
  84750. *
  84751. * \warning
  84752. * Do not feed the encoder data that is wider than the value you
  84753. * set here or you will generate an invalid stream.
  84754. *
  84755. * \default \c 16
  84756. * \param encoder An encoder instance to set.
  84757. * \param value See above.
  84758. * \assert
  84759. * \code encoder != NULL \endcode
  84760. * \retval FLAC__bool
  84761. * \c false if the encoder is already initialized, else \c true.
  84762. */
  84763. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  84764. /** Set the sample rate (in Hz) of the input to be encoded.
  84765. *
  84766. * \default \c 44100
  84767. * \param encoder An encoder instance to set.
  84768. * \param value See above.
  84769. * \assert
  84770. * \code encoder != NULL \endcode
  84771. * \retval FLAC__bool
  84772. * \c false if the encoder is already initialized, else \c true.
  84773. */
  84774. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  84775. /** Set the compression level
  84776. *
  84777. * The compression level is roughly proportional to the amount of effort
  84778. * the encoder expends to compress the file. A higher level usually
  84779. * means more computation but higher compression. The default level is
  84780. * suitable for most applications.
  84781. *
  84782. * Currently the levels range from \c 0 (fastest, least compression) to
  84783. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  84784. * treated as \c 8.
  84785. *
  84786. * This function automatically calls the following other \c _set_
  84787. * functions with appropriate values, so the client does not need to
  84788. * unless it specifically wants to override them:
  84789. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  84790. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  84791. * - FLAC__stream_encoder_set_apodization()
  84792. * - FLAC__stream_encoder_set_max_lpc_order()
  84793. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  84794. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  84795. * - FLAC__stream_encoder_set_do_escape_coding()
  84796. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  84797. * - FLAC__stream_encoder_set_min_residual_partition_order()
  84798. * - FLAC__stream_encoder_set_max_residual_partition_order()
  84799. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  84800. *
  84801. * The actual values set for each level are:
  84802. * <table>
  84803. * <tr>
  84804. * <td><b>level</b><td>
  84805. * <td>do mid-side stereo<td>
  84806. * <td>loose mid-side stereo<td>
  84807. * <td>apodization<td>
  84808. * <td>max lpc order<td>
  84809. * <td>qlp coeff precision<td>
  84810. * <td>qlp coeff prec search<td>
  84811. * <td>escape coding<td>
  84812. * <td>exhaustive model search<td>
  84813. * <td>min residual partition order<td>
  84814. * <td>max residual partition order<td>
  84815. * <td>rice parameter search dist<td>
  84816. * </tr>
  84817. * <tr> <td><b>0</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  84818. * <tr> <td><b>1</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  84819. * <tr> <td><b>2</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  84820. * <tr> <td><b>3</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>6<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  84821. * <tr> <td><b>4</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  84822. * <tr> <td><b>5</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>5<td> <td>0<td> </tr>
  84823. * <tr> <td><b>6</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  84824. * <tr> <td><b>7</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  84825. * <tr> <td><b>8</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>12<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  84826. * </table>
  84827. *
  84828. * \default \c 5
  84829. * \param encoder An encoder instance to set.
  84830. * \param value See above.
  84831. * \assert
  84832. * \code encoder != NULL \endcode
  84833. * \retval FLAC__bool
  84834. * \c false if the encoder is already initialized, else \c true.
  84835. */
  84836. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  84837. /** Set the blocksize to use while encoding.
  84838. *
  84839. * The number of samples to use per frame. Use \c 0 to let the encoder
  84840. * estimate a blocksize; this is usually best.
  84841. *
  84842. * \default \c 0
  84843. * \param encoder An encoder instance to set.
  84844. * \param value See above.
  84845. * \assert
  84846. * \code encoder != NULL \endcode
  84847. * \retval FLAC__bool
  84848. * \c false if the encoder is already initialized, else \c true.
  84849. */
  84850. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  84851. /** Set to \c true to enable mid-side encoding on stereo input. The
  84852. * number of channels must be 2 for this to have any effect. Set to
  84853. * \c false to use only independent channel coding.
  84854. *
  84855. * \default \c false
  84856. * \param encoder An encoder instance to set.
  84857. * \param value Flag value (see above).
  84858. * \assert
  84859. * \code encoder != NULL \endcode
  84860. * \retval FLAC__bool
  84861. * \c false if the encoder is already initialized, else \c true.
  84862. */
  84863. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84864. /** Set to \c true to enable adaptive switching between mid-side and
  84865. * left-right encoding on stereo input. Set to \c false to use
  84866. * exhaustive searching. Setting this to \c true requires
  84867. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  84868. * \c true in order to have any effect.
  84869. *
  84870. * \default \c false
  84871. * \param encoder An encoder instance to set.
  84872. * \param value Flag value (see above).
  84873. * \assert
  84874. * \code encoder != NULL \endcode
  84875. * \retval FLAC__bool
  84876. * \c false if the encoder is already initialized, else \c true.
  84877. */
  84878. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84879. /** Sets the apodization function(s) the encoder will use when windowing
  84880. * audio data for LPC analysis.
  84881. *
  84882. * The \a specification is a plain ASCII string which specifies exactly
  84883. * which functions to use. There may be more than one (up to 32),
  84884. * separated by \c ';' characters. Some functions take one or more
  84885. * comma-separated arguments in parentheses.
  84886. *
  84887. * The available functions are \c bartlett, \c bartlett_hann,
  84888. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  84889. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  84890. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  84891. *
  84892. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  84893. * (0<STDDEV<=0.5).
  84894. *
  84895. * For \c tukey(P), P specifies the fraction of the window that is
  84896. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  84897. * corresponds to \c hann.
  84898. *
  84899. * Example specifications are \c "blackman" or
  84900. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  84901. *
  84902. * Any function that is specified erroneously is silently dropped. Up
  84903. * to 32 functions are kept, the rest are dropped. If the specification
  84904. * is empty the encoder defaults to \c "tukey(0.5)".
  84905. *
  84906. * When more than one function is specified, then for every subframe the
  84907. * encoder will try each of them separately and choose the window that
  84908. * results in the smallest compressed subframe.
  84909. *
  84910. * Note that each function specified causes the encoder to occupy a
  84911. * floating point array in which to store the window.
  84912. *
  84913. * \default \c "tukey(0.5)"
  84914. * \param encoder An encoder instance to set.
  84915. * \param specification See above.
  84916. * \assert
  84917. * \code encoder != NULL \endcode
  84918. * \code specification != NULL \endcode
  84919. * \retval FLAC__bool
  84920. * \c false if the encoder is already initialized, else \c true.
  84921. */
  84922. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  84923. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  84924. *
  84925. * \default \c 0
  84926. * \param encoder An encoder instance to set.
  84927. * \param value See above.
  84928. * \assert
  84929. * \code encoder != NULL \endcode
  84930. * \retval FLAC__bool
  84931. * \c false if the encoder is already initialized, else \c true.
  84932. */
  84933. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  84934. /** Set the precision, in bits, of the quantized linear predictor
  84935. * coefficients, or \c 0 to let the encoder select it based on the
  84936. * blocksize.
  84937. *
  84938. * \note
  84939. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  84940. * be less than 32.
  84941. *
  84942. * \default \c 0
  84943. * \param encoder An encoder instance to set.
  84944. * \param value See above.
  84945. * \assert
  84946. * \code encoder != NULL \endcode
  84947. * \retval FLAC__bool
  84948. * \c false if the encoder is already initialized, else \c true.
  84949. */
  84950. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  84951. /** Set to \c false to use only the specified quantized linear predictor
  84952. * coefficient precision, or \c true to search neighboring precision
  84953. * values and use the best one.
  84954. *
  84955. * \default \c false
  84956. * \param encoder An encoder instance to set.
  84957. * \param value See above.
  84958. * \assert
  84959. * \code encoder != NULL \endcode
  84960. * \retval FLAC__bool
  84961. * \c false if the encoder is already initialized, else \c true.
  84962. */
  84963. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84964. /** Deprecated. Setting this value has no effect.
  84965. *
  84966. * \default \c false
  84967. * \param encoder An encoder instance to set.
  84968. * \param value See above.
  84969. * \assert
  84970. * \code encoder != NULL \endcode
  84971. * \retval FLAC__bool
  84972. * \c false if the encoder is already initialized, else \c true.
  84973. */
  84974. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84975. /** Set to \c false to let the encoder estimate the best model order
  84976. * based on the residual signal energy, or \c true to force the
  84977. * encoder to evaluate all order models and select the best.
  84978. *
  84979. * \default \c false
  84980. * \param encoder An encoder instance to set.
  84981. * \param value See above.
  84982. * \assert
  84983. * \code encoder != NULL \endcode
  84984. * \retval FLAC__bool
  84985. * \c false if the encoder is already initialized, else \c true.
  84986. */
  84987. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84988. /** Set the minimum partition order to search when coding the residual.
  84989. * This is used in tandem with
  84990. * FLAC__stream_encoder_set_max_residual_partition_order().
  84991. *
  84992. * The partition order determines the context size in the residual.
  84993. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  84994. *
  84995. * Set both min and max values to \c 0 to force a single context,
  84996. * whose Rice parameter is based on the residual signal variance.
  84997. * Otherwise, set a min and max order, and the encoder will search
  84998. * all orders, using the mean of each context for its Rice parameter,
  84999. * and use the best.
  85000. *
  85001. * \default \c 0
  85002. * \param encoder An encoder instance to set.
  85003. * \param value See above.
  85004. * \assert
  85005. * \code encoder != NULL \endcode
  85006. * \retval FLAC__bool
  85007. * \c false if the encoder is already initialized, else \c true.
  85008. */
  85009. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85010. /** Set the maximum partition order to search when coding the residual.
  85011. * This is used in tandem with
  85012. * FLAC__stream_encoder_set_min_residual_partition_order().
  85013. *
  85014. * The partition order determines the context size in the residual.
  85015. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85016. *
  85017. * Set both min and max values to \c 0 to force a single context,
  85018. * whose Rice parameter is based on the residual signal variance.
  85019. * Otherwise, set a min and max order, and the encoder will search
  85020. * all orders, using the mean of each context for its Rice parameter,
  85021. * and use the best.
  85022. *
  85023. * \default \c 0
  85024. * \param encoder An encoder instance to set.
  85025. * \param value See above.
  85026. * \assert
  85027. * \code encoder != NULL \endcode
  85028. * \retval FLAC__bool
  85029. * \c false if the encoder is already initialized, else \c true.
  85030. */
  85031. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85032. /** Deprecated. Setting this value has no effect.
  85033. *
  85034. * \default \c 0
  85035. * \param encoder An encoder instance to set.
  85036. * \param value See above.
  85037. * \assert
  85038. * \code encoder != NULL \endcode
  85039. * \retval FLAC__bool
  85040. * \c false if the encoder is already initialized, else \c true.
  85041. */
  85042. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  85043. /** Set an estimate of the total samples that will be encoded.
  85044. * This is merely an estimate and may be set to \c 0 if unknown.
  85045. * This value will be written to the STREAMINFO block before encoding,
  85046. * and can remove the need for the caller to rewrite the value later
  85047. * if the value is known before encoding.
  85048. *
  85049. * \default \c 0
  85050. * \param encoder An encoder instance to set.
  85051. * \param value See above.
  85052. * \assert
  85053. * \code encoder != NULL \endcode
  85054. * \retval FLAC__bool
  85055. * \c false if the encoder is already initialized, else \c true.
  85056. */
  85057. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  85058. /** Set the metadata blocks to be emitted to the stream before encoding.
  85059. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  85060. * array of pointers to metadata blocks. The array is non-const since
  85061. * the encoder may need to change the \a is_last flag inside them, and
  85062. * in some cases update seek point offsets. Otherwise, the encoder will
  85063. * not modify or free the blocks. It is up to the caller to free the
  85064. * metadata blocks after encoding finishes.
  85065. *
  85066. * \note
  85067. * The encoder stores only copies of the pointers in the \a metadata array;
  85068. * the metadata blocks themselves must survive at least until after
  85069. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  85070. *
  85071. * \note
  85072. * The STREAMINFO block is always written and no STREAMINFO block may
  85073. * occur in the supplied array.
  85074. *
  85075. * \note
  85076. * By default the encoder does not create a SEEKTABLE. If one is supplied
  85077. * in the \a metadata array, but the client has specified that it does not
  85078. * support seeking, then the SEEKTABLE will be written verbatim. However
  85079. * by itself this is not very useful as the client will not know the stream
  85080. * offsets for the seekpoints ahead of time. In order to get a proper
  85081. * seektable the client must support seeking. See next note.
  85082. *
  85083. * \note
  85084. * SEEKTABLE blocks are handled specially. Since you will not know
  85085. * the values for the seek point stream offsets, you should pass in
  85086. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  85087. * required sample numbers (or placeholder points), with \c 0 for the
  85088. * \a frame_samples and \a stream_offset fields for each point. If the
  85089. * client has specified that it supports seeking by providing a seek
  85090. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  85091. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  85092. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  85093. * then while it is encoding the encoder will fill the stream offsets in
  85094. * for you and when encoding is finished, it will seek back and write the
  85095. * real values into the SEEKTABLE block in the stream. There are helper
  85096. * routines for manipulating seektable template blocks; see metadata.h:
  85097. * FLAC__metadata_object_seektable_template_*(). If the client does
  85098. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  85099. * will slow down or remove the ability to seek in the FLAC stream.
  85100. *
  85101. * \note
  85102. * The encoder instance \b will modify the first \c SEEKTABLE block
  85103. * as it transforms the template to a valid seektable while encoding,
  85104. * but it is still up to the caller to free all metadata blocks after
  85105. * encoding.
  85106. *
  85107. * \note
  85108. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  85109. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  85110. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  85111. * will simply write it's own into the stream. If no VORBIS_COMMENT
  85112. * block is present in the \a metadata array, libFLAC will write an
  85113. * empty one, containing only the vendor string.
  85114. *
  85115. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  85116. * the second metadata block of the stream. The encoder already supplies
  85117. * the STREAMINFO block automatically. If \a metadata does not contain a
  85118. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  85119. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  85120. * first, the init function will reorder \a metadata by moving the
  85121. * VORBIS_COMMENT block to the front; the relative ordering of the other
  85122. * blocks will remain as they were.
  85123. *
  85124. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  85125. * stream to \c 65535. If \a num_blocks exceeds this the function will
  85126. * return \c false.
  85127. *
  85128. * \default \c NULL, 0
  85129. * \param encoder An encoder instance to set.
  85130. * \param metadata See above.
  85131. * \param num_blocks See above.
  85132. * \assert
  85133. * \code encoder != NULL \endcode
  85134. * \retval FLAC__bool
  85135. * \c false if the encoder is already initialized, else \c true.
  85136. * \c false if the encoder is already initialized, or if
  85137. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  85138. */
  85139. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  85140. /** Get the current encoder state.
  85141. *
  85142. * \param encoder An encoder instance to query.
  85143. * \assert
  85144. * \code encoder != NULL \endcode
  85145. * \retval FLAC__StreamEncoderState
  85146. * The current encoder state.
  85147. */
  85148. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  85149. /** Get the state of the verify stream decoder.
  85150. * Useful when the stream encoder state is
  85151. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  85152. *
  85153. * \param encoder An encoder instance to query.
  85154. * \assert
  85155. * \code encoder != NULL \endcode
  85156. * \retval FLAC__StreamDecoderState
  85157. * The verify stream decoder state.
  85158. */
  85159. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  85160. /** Get the current encoder state as a C string.
  85161. * This version automatically resolves
  85162. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  85163. * verify decoder's state.
  85164. *
  85165. * \param encoder A encoder instance to query.
  85166. * \assert
  85167. * \code encoder != NULL \endcode
  85168. * \retval const char *
  85169. * The encoder state as a C string. Do not modify the contents.
  85170. */
  85171. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  85172. /** Get relevant values about the nature of a verify decoder error.
  85173. * Useful when the stream encoder state is
  85174. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  85175. * be addresses in which the stats will be returned, or NULL if value
  85176. * is not desired.
  85177. *
  85178. * \param encoder An encoder instance to query.
  85179. * \param absolute_sample The absolute sample number of the mismatch.
  85180. * \param frame_number The number of the frame in which the mismatch occurred.
  85181. * \param channel The channel in which the mismatch occurred.
  85182. * \param sample The number of the sample (relative to the frame) in
  85183. * which the mismatch occurred.
  85184. * \param expected The expected value for the sample in question.
  85185. * \param got The actual value returned by the decoder.
  85186. * \assert
  85187. * \code encoder != NULL \endcode
  85188. */
  85189. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
  85190. /** Get the "verify" flag.
  85191. *
  85192. * \param encoder An encoder instance to query.
  85193. * \assert
  85194. * \code encoder != NULL \endcode
  85195. * \retval FLAC__bool
  85196. * See FLAC__stream_encoder_set_verify().
  85197. */
  85198. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  85199. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  85200. *
  85201. * \param encoder An encoder instance to query.
  85202. * \assert
  85203. * \code encoder != NULL \endcode
  85204. * \retval FLAC__bool
  85205. * See FLAC__stream_encoder_set_streamable_subset().
  85206. */
  85207. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  85208. /** Get the number of input channels being processed.
  85209. *
  85210. * \param encoder An encoder instance to query.
  85211. * \assert
  85212. * \code encoder != NULL \endcode
  85213. * \retval unsigned
  85214. * See FLAC__stream_encoder_set_channels().
  85215. */
  85216. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  85217. /** Get the input sample resolution setting.
  85218. *
  85219. * \param encoder An encoder instance to query.
  85220. * \assert
  85221. * \code encoder != NULL \endcode
  85222. * \retval unsigned
  85223. * See FLAC__stream_encoder_set_bits_per_sample().
  85224. */
  85225. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  85226. /** Get the input sample rate setting.
  85227. *
  85228. * \param encoder An encoder instance to query.
  85229. * \assert
  85230. * \code encoder != NULL \endcode
  85231. * \retval unsigned
  85232. * See FLAC__stream_encoder_set_sample_rate().
  85233. */
  85234. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  85235. /** Get the blocksize setting.
  85236. *
  85237. * \param encoder An encoder instance to query.
  85238. * \assert
  85239. * \code encoder != NULL \endcode
  85240. * \retval unsigned
  85241. * See FLAC__stream_encoder_set_blocksize().
  85242. */
  85243. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  85244. /** Get the "mid/side stereo coding" flag.
  85245. *
  85246. * \param encoder An encoder instance to query.
  85247. * \assert
  85248. * \code encoder != NULL \endcode
  85249. * \retval FLAC__bool
  85250. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  85251. */
  85252. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85253. /** Get the "adaptive mid/side switching" flag.
  85254. *
  85255. * \param encoder An encoder instance to query.
  85256. * \assert
  85257. * \code encoder != NULL \endcode
  85258. * \retval FLAC__bool
  85259. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  85260. */
  85261. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85262. /** Get the maximum LPC order setting.
  85263. *
  85264. * \param encoder An encoder instance to query.
  85265. * \assert
  85266. * \code encoder != NULL \endcode
  85267. * \retval unsigned
  85268. * See FLAC__stream_encoder_set_max_lpc_order().
  85269. */
  85270. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  85271. /** Get the quantized linear predictor coefficient precision setting.
  85272. *
  85273. * \param encoder An encoder instance to query.
  85274. * \assert
  85275. * \code encoder != NULL \endcode
  85276. * \retval unsigned
  85277. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  85278. */
  85279. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  85280. /** Get the qlp coefficient precision search flag.
  85281. *
  85282. * \param encoder An encoder instance to query.
  85283. * \assert
  85284. * \code encoder != NULL \endcode
  85285. * \retval FLAC__bool
  85286. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  85287. */
  85288. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  85289. /** Get the "escape coding" flag.
  85290. *
  85291. * \param encoder An encoder instance to query.
  85292. * \assert
  85293. * \code encoder != NULL \endcode
  85294. * \retval FLAC__bool
  85295. * See FLAC__stream_encoder_set_do_escape_coding().
  85296. */
  85297. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  85298. /** Get the exhaustive model search flag.
  85299. *
  85300. * \param encoder An encoder instance to query.
  85301. * \assert
  85302. * \code encoder != NULL \endcode
  85303. * \retval FLAC__bool
  85304. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  85305. */
  85306. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  85307. /** Get the minimum residual partition order setting.
  85308. *
  85309. * \param encoder An encoder instance to query.
  85310. * \assert
  85311. * \code encoder != NULL \endcode
  85312. * \retval unsigned
  85313. * See FLAC__stream_encoder_set_min_residual_partition_order().
  85314. */
  85315. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  85316. /** Get maximum residual partition order setting.
  85317. *
  85318. * \param encoder An encoder instance to query.
  85319. * \assert
  85320. * \code encoder != NULL \endcode
  85321. * \retval unsigned
  85322. * See FLAC__stream_encoder_set_max_residual_partition_order().
  85323. */
  85324. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  85325. /** Get the Rice parameter search distance setting.
  85326. *
  85327. * \param encoder An encoder instance to query.
  85328. * \assert
  85329. * \code encoder != NULL \endcode
  85330. * \retval unsigned
  85331. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  85332. */
  85333. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  85334. /** Get the previously set estimate of the total samples to be encoded.
  85335. * The encoder merely mimics back the value given to
  85336. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  85337. * other way of knowing how many samples the client will encode.
  85338. *
  85339. * \param encoder An encoder instance to set.
  85340. * \assert
  85341. * \code encoder != NULL \endcode
  85342. * \retval FLAC__uint64
  85343. * See FLAC__stream_encoder_get_total_samples_estimate().
  85344. */
  85345. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  85346. /** Initialize the encoder instance to encode native FLAC streams.
  85347. *
  85348. * This flavor of initialization sets up the encoder to encode to a
  85349. * native FLAC stream. I/O is performed via callbacks to the client.
  85350. * For encoding to a plain file via filename or open \c FILE*,
  85351. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  85352. * provide a simpler interface.
  85353. *
  85354. * This function should be called after FLAC__stream_encoder_new() and
  85355. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85356. * or FLAC__stream_encoder_process_interleaved().
  85357. * initialization succeeded.
  85358. *
  85359. * The call to FLAC__stream_encoder_init_stream() currently will also
  85360. * immediately call the write callback several times, once with the \c fLaC
  85361. * signature, and once for each encoded metadata block.
  85362. *
  85363. * \param encoder An uninitialized encoder instance.
  85364. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  85365. * pointer must not be \c NULL.
  85366. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  85367. * pointer may be \c NULL if seeking is not
  85368. * supported. The encoder uses seeking to go back
  85369. * and write some some stream statistics to the
  85370. * STREAMINFO block; this is recommended but not
  85371. * necessary to create a valid FLAC stream. If
  85372. * \a seek_callback is not \c NULL then a
  85373. * \a tell_callback must also be supplied.
  85374. * Alternatively, a dummy seek callback that just
  85375. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85376. * may also be supplied, all though this is slightly
  85377. * less efficient for the encoder.
  85378. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  85379. * pointer may be \c NULL if seeking is not
  85380. * supported. If \a seek_callback is \c NULL then
  85381. * this argument will be ignored. If
  85382. * \a seek_callback is not \c NULL then a
  85383. * \a tell_callback must also be supplied.
  85384. * Alternatively, a dummy tell callback that just
  85385. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85386. * may also be supplied, all though this is slightly
  85387. * less efficient for the encoder.
  85388. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  85389. * pointer may be \c NULL if the callback is not
  85390. * desired. If the client provides a seek callback,
  85391. * this function is not necessary as the encoder
  85392. * will automatically seek back and update the
  85393. * STREAMINFO block. It may also be \c NULL if the
  85394. * client does not support seeking, since it will
  85395. * have no way of going back to update the
  85396. * STREAMINFO. However the client can still supply
  85397. * a callback if it would like to know the details
  85398. * from the STREAMINFO.
  85399. * \param client_data This value will be supplied to callbacks in their
  85400. * \a client_data argument.
  85401. * \assert
  85402. * \code encoder != NULL \endcode
  85403. * \retval FLAC__StreamEncoderInitStatus
  85404. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85405. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85406. */
  85407. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  85408. /** Initialize the encoder instance to encode Ogg FLAC streams.
  85409. *
  85410. * This flavor of initialization sets up the encoder to encode to a FLAC
  85411. * stream in an Ogg container. I/O is performed via callbacks to the
  85412. * client. For encoding to a plain file via filename or open \c FILE*,
  85413. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  85414. * provide a simpler interface.
  85415. *
  85416. * This function should be called after FLAC__stream_encoder_new() and
  85417. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85418. * or FLAC__stream_encoder_process_interleaved().
  85419. * initialization succeeded.
  85420. *
  85421. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  85422. * immediately call the write callback several times to write the metadata
  85423. * packets.
  85424. *
  85425. * \param encoder An uninitialized encoder instance.
  85426. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  85427. * pointer must not be \c NULL if \a seek_callback
  85428. * is non-NULL since they are both needed to be
  85429. * able to write data back to the Ogg FLAC stream
  85430. * in the post-encode phase.
  85431. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  85432. * pointer must not be \c NULL.
  85433. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  85434. * pointer may be \c NULL if seeking is not
  85435. * supported. The encoder uses seeking to go back
  85436. * and write some some stream statistics to the
  85437. * STREAMINFO block; this is recommended but not
  85438. * necessary to create a valid FLAC stream. If
  85439. * \a seek_callback is not \c NULL then a
  85440. * \a tell_callback must also be supplied.
  85441. * Alternatively, a dummy seek callback that just
  85442. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85443. * may also be supplied, all though this is slightly
  85444. * less efficient for the encoder.
  85445. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  85446. * pointer may be \c NULL if seeking is not
  85447. * supported. If \a seek_callback is \c NULL then
  85448. * this argument will be ignored. If
  85449. * \a seek_callback is not \c NULL then a
  85450. * \a tell_callback must also be supplied.
  85451. * Alternatively, a dummy tell callback that just
  85452. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85453. * may also be supplied, all though this is slightly
  85454. * less efficient for the encoder.
  85455. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  85456. * pointer may be \c NULL if the callback is not
  85457. * desired. If the client provides a seek callback,
  85458. * this function is not necessary as the encoder
  85459. * will automatically seek back and update the
  85460. * STREAMINFO block. It may also be \c NULL if the
  85461. * client does not support seeking, since it will
  85462. * have no way of going back to update the
  85463. * STREAMINFO. However the client can still supply
  85464. * a callback if it would like to know the details
  85465. * from the STREAMINFO.
  85466. * \param client_data This value will be supplied to callbacks in their
  85467. * \a client_data argument.
  85468. * \assert
  85469. * \code encoder != NULL \endcode
  85470. * \retval FLAC__StreamEncoderInitStatus
  85471. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85472. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85473. */
  85474. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderReadCallback read_callback, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  85475. /** Initialize the encoder instance to encode native FLAC files.
  85476. *
  85477. * This flavor of initialization sets up the encoder to encode to a
  85478. * plain native FLAC file. For non-stdio streams, you must use
  85479. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  85480. *
  85481. * This function should be called after FLAC__stream_encoder_new() and
  85482. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85483. * or FLAC__stream_encoder_process_interleaved().
  85484. * initialization succeeded.
  85485. *
  85486. * \param encoder An uninitialized encoder instance.
  85487. * \param file An open file. The file should have been opened
  85488. * with mode \c "w+b" and rewound. The file
  85489. * becomes owned by the encoder and should not be
  85490. * manipulated by the client while encoding.
  85491. * Unless \a file is \c stdout, it will be closed
  85492. * when FLAC__stream_encoder_finish() is called.
  85493. * Note however that a proper SEEKTABLE cannot be
  85494. * created when encoding to \c stdout since it is
  85495. * not seekable.
  85496. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85497. * pointer may be \c NULL if the callback is not
  85498. * desired.
  85499. * \param client_data This value will be supplied to callbacks in their
  85500. * \a client_data argument.
  85501. * \assert
  85502. * \code encoder != NULL \endcode
  85503. * \code file != NULL \endcode
  85504. * \retval FLAC__StreamEncoderInitStatus
  85505. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85506. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85507. */
  85508. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85509. /** Initialize the encoder instance to encode Ogg FLAC files.
  85510. *
  85511. * This flavor of initialization sets up the encoder to encode to a
  85512. * plain Ogg FLAC file. For non-stdio streams, you must use
  85513. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  85514. *
  85515. * This function should be called after FLAC__stream_encoder_new() and
  85516. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85517. * or FLAC__stream_encoder_process_interleaved().
  85518. * initialization succeeded.
  85519. *
  85520. * \param encoder An uninitialized encoder instance.
  85521. * \param file An open file. The file should have been opened
  85522. * with mode \c "w+b" and rewound. The file
  85523. * becomes owned by the encoder and should not be
  85524. * manipulated by the client while encoding.
  85525. * Unless \a file is \c stdout, it will be closed
  85526. * when FLAC__stream_encoder_finish() is called.
  85527. * Note however that a proper SEEKTABLE cannot be
  85528. * created when encoding to \c stdout since it is
  85529. * not seekable.
  85530. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85531. * pointer may be \c NULL if the callback is not
  85532. * desired.
  85533. * \param client_data This value will be supplied to callbacks in their
  85534. * \a client_data argument.
  85535. * \assert
  85536. * \code encoder != NULL \endcode
  85537. * \code file != NULL \endcode
  85538. * \retval FLAC__StreamEncoderInitStatus
  85539. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85540. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85541. */
  85542. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85543. /** Initialize the encoder instance to encode native FLAC files.
  85544. *
  85545. * This flavor of initialization sets up the encoder to encode to a plain
  85546. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  85547. * with Unicode filenames on Windows), you must use
  85548. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  85549. * and provide callbacks for the I/O.
  85550. *
  85551. * This function should be called after FLAC__stream_encoder_new() and
  85552. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85553. * or FLAC__stream_encoder_process_interleaved().
  85554. * initialization succeeded.
  85555. *
  85556. * \param encoder An uninitialized encoder instance.
  85557. * \param filename The name of the file to encode to. The file will
  85558. * be opened with fopen(). Use \c NULL to encode to
  85559. * \c stdout. Note however that a proper SEEKTABLE
  85560. * cannot be created when encoding to \c stdout since
  85561. * it is not seekable.
  85562. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85563. * pointer may be \c NULL if the callback is not
  85564. * desired.
  85565. * \param client_data This value will be supplied to callbacks in their
  85566. * \a client_data argument.
  85567. * \assert
  85568. * \code encoder != NULL \endcode
  85569. * \retval FLAC__StreamEncoderInitStatus
  85570. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85571. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85572. */
  85573. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85574. /** Initialize the encoder instance to encode Ogg FLAC files.
  85575. *
  85576. * This flavor of initialization sets up the encoder to encode to a plain
  85577. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  85578. * with Unicode filenames on Windows), you must use
  85579. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  85580. * and provide callbacks for the I/O.
  85581. *
  85582. * This function should be called after FLAC__stream_encoder_new() and
  85583. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85584. * or FLAC__stream_encoder_process_interleaved().
  85585. * initialization succeeded.
  85586. *
  85587. * \param encoder An uninitialized encoder instance.
  85588. * \param filename The name of the file to encode to. The file will
  85589. * be opened with fopen(). Use \c NULL to encode to
  85590. * \c stdout. Note however that a proper SEEKTABLE
  85591. * cannot be created when encoding to \c stdout since
  85592. * it is not seekable.
  85593. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85594. * pointer may be \c NULL if the callback is not
  85595. * desired.
  85596. * \param client_data This value will be supplied to callbacks in their
  85597. * \a client_data argument.
  85598. * \assert
  85599. * \code encoder != NULL \endcode
  85600. * \retval FLAC__StreamEncoderInitStatus
  85601. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85602. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85603. */
  85604. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85605. /** Finish the encoding process.
  85606. * Flushes the encoding buffer, releases resources, resets the encoder
  85607. * settings to their defaults, and returns the encoder state to
  85608. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  85609. * one or more write callbacks before returning, and will generate
  85610. * a metadata callback.
  85611. *
  85612. * Note that in the course of processing the last frame, errors can
  85613. * occur, so the caller should be sure to check the return value to
  85614. * ensure the file was encoded properly.
  85615. *
  85616. * In the event of a prematurely-terminated encode, it is not strictly
  85617. * necessary to call this immediately before FLAC__stream_encoder_delete()
  85618. * but it is good practice to match every FLAC__stream_encoder_init_*()
  85619. * with a FLAC__stream_encoder_finish().
  85620. *
  85621. * \param encoder An uninitialized encoder instance.
  85622. * \assert
  85623. * \code encoder != NULL \endcode
  85624. * \retval FLAC__bool
  85625. * \c false if an error occurred processing the last frame; or if verify
  85626. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  85627. * verify mismatch; else \c true. If \c false, caller should check the
  85628. * state with FLAC__stream_encoder_get_state() for more information
  85629. * about the error.
  85630. */
  85631. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  85632. /** Submit data for encoding.
  85633. * This version allows you to supply the input data via an array of
  85634. * pointers, each pointer pointing to an array of \a samples samples
  85635. * representing one channel. The samples need not be block-aligned,
  85636. * but each channel should have the same number of samples. Each sample
  85637. * should be a signed integer, right-justified to the resolution set by
  85638. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  85639. * resolution is 16 bits per sample, the samples should all be in the
  85640. * range [-32768,32767].
  85641. *
  85642. * For applications where channel order is important, channels must
  85643. * follow the order as described in the
  85644. * <A HREF="../format.html#frame_header">frame header</A>.
  85645. *
  85646. * \param encoder An initialized encoder instance in the OK state.
  85647. * \param buffer An array of pointers to each channel's signal.
  85648. * \param samples The number of samples in one channel.
  85649. * \assert
  85650. * \code encoder != NULL \endcode
  85651. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  85652. * \retval FLAC__bool
  85653. * \c true if successful, else \c false; in this case, check the
  85654. * encoder state with FLAC__stream_encoder_get_state() to see what
  85655. * went wrong.
  85656. */
  85657. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  85658. /** Submit data for encoding.
  85659. * This version allows you to supply the input data where the channels
  85660. * are interleaved into a single array (i.e. channel0_sample0,
  85661. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85662. * The samples need not be block-aligned but they must be
  85663. * sample-aligned, i.e. the first value should be channel0_sample0
  85664. * and the last value channelN_sampleM. Each sample should be a signed
  85665. * integer, right-justified to the resolution set by
  85666. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  85667. * resolution is 16 bits per sample, the samples should all be in the
  85668. * range [-32768,32767].
  85669. *
  85670. * For applications where channel order is important, channels must
  85671. * follow the order as described in the
  85672. * <A HREF="../format.html#frame_header">frame header</A>.
  85673. *
  85674. * \param encoder An initialized encoder instance in the OK state.
  85675. * \param buffer An array of channel-interleaved data (see above).
  85676. * \param samples The number of samples in one channel, the same as for
  85677. * FLAC__stream_encoder_process(). For example, if
  85678. * encoding two channels, \c 1000 \a samples corresponds
  85679. * to a \a buffer of 2000 values.
  85680. * \assert
  85681. * \code encoder != NULL \endcode
  85682. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  85683. * \retval FLAC__bool
  85684. * \c true if successful, else \c false; in this case, check the
  85685. * encoder state with FLAC__stream_encoder_get_state() to see what
  85686. * went wrong.
  85687. */
  85688. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  85689. /* \} */
  85690. #ifdef __cplusplus
  85691. }
  85692. #endif
  85693. #endif
  85694. /********* End of inlined file: stream_encoder.h *********/
  85695. #ifdef _MSC_VER
  85696. /* OPT: an MSVC built-in would be better */
  85697. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  85698. {
  85699. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  85700. return (x>>16) | (x<<16);
  85701. }
  85702. #endif
  85703. #if defined(_MSC_VER) && defined(_X86_)
  85704. /* OPT: an MSVC built-in would be better */
  85705. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  85706. {
  85707. __asm {
  85708. mov edx, start
  85709. mov ecx, len
  85710. test ecx, ecx
  85711. loop1:
  85712. jz done1
  85713. mov eax, [edx]
  85714. bswap eax
  85715. mov [edx], eax
  85716. add edx, 4
  85717. dec ecx
  85718. jmp short loop1
  85719. done1:
  85720. }
  85721. }
  85722. #endif
  85723. /** \mainpage
  85724. *
  85725. * \section intro Introduction
  85726. *
  85727. * This is the documentation for the FLAC C and C++ APIs. It is
  85728. * highly interconnected; this introduction should give you a top
  85729. * level idea of the structure and how to find the information you
  85730. * need. As a prerequisite you should have at least a basic
  85731. * knowledge of the FLAC format, documented
  85732. * <A HREF="../format.html">here</A>.
  85733. *
  85734. * \section c_api FLAC C API
  85735. *
  85736. * The FLAC C API is the interface to libFLAC, a set of structures
  85737. * describing the components of FLAC streams, and functions for
  85738. * encoding and decoding streams, as well as manipulating FLAC
  85739. * metadata in files. The public include files will be installed
  85740. * in your include area (for example /usr/include/FLAC/...).
  85741. *
  85742. * By writing a little code and linking against libFLAC, it is
  85743. * relatively easy to add FLAC support to another program. The
  85744. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  85745. * Complete source code of libFLAC as well as the command-line
  85746. * encoder and plugins is available and is a useful source of
  85747. * examples.
  85748. *
  85749. * Aside from encoders and decoders, libFLAC provides a powerful
  85750. * metadata interface for manipulating metadata in FLAC files. It
  85751. * allows the user to add, delete, and modify FLAC metadata blocks
  85752. * and it can automatically take advantage of PADDING blocks to avoid
  85753. * rewriting the entire FLAC file when changing the size of the
  85754. * metadata.
  85755. *
  85756. * libFLAC usually only requires the standard C library and C math
  85757. * library. In particular, threading is not used so there is no
  85758. * dependency on a thread library. However, libFLAC does not use
  85759. * global variables and should be thread-safe.
  85760. *
  85761. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  85762. * However the metadata editing interfaces currently have limited
  85763. * read-only support for Ogg FLAC files.
  85764. *
  85765. * \section cpp_api FLAC C++ API
  85766. *
  85767. * The FLAC C++ API is a set of classes that encapsulate the
  85768. * structures and functions in libFLAC. They provide slightly more
  85769. * functionality with respect to metadata but are otherwise
  85770. * equivalent. For the most part, they share the same usage as
  85771. * their counterparts in libFLAC, and the FLAC C API documentation
  85772. * can be used as a supplement. The public include files
  85773. * for the C++ API will be installed in your include area (for
  85774. * example /usr/include/FLAC++/...).
  85775. *
  85776. * libFLAC++ is also licensed under
  85777. * <A HREF="../license.html">Xiph's BSD license</A>.
  85778. *
  85779. * \section getting_started Getting Started
  85780. *
  85781. * A good starting point for learning the API is to browse through
  85782. * the <A HREF="modules.html">modules</A>. Modules are logical
  85783. * groupings of related functions or classes, which correspond roughly
  85784. * to header files or sections of header files. Each module includes a
  85785. * detailed description of the general usage of its functions or
  85786. * classes.
  85787. *
  85788. * From there you can go on to look at the documentation of
  85789. * individual functions. You can see different views of the individual
  85790. * functions through the links in top bar across this page.
  85791. *
  85792. * If you prefer a more hands-on approach, you can jump right to some
  85793. * <A HREF="../documentation_example_code.html">example code</A>.
  85794. *
  85795. * \section porting_guide Porting Guide
  85796. *
  85797. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  85798. * has been introduced which gives detailed instructions on how to
  85799. * port your code to newer versions of FLAC.
  85800. *
  85801. * \section embedded_developers Embedded Developers
  85802. *
  85803. * libFLAC has grown larger over time as more functionality has been
  85804. * included, but much of it may be unnecessary for a particular embedded
  85805. * implementation. Unused parts may be pruned by some simple editing of
  85806. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  85807. * metadata interface are all independent from each other.
  85808. *
  85809. * It is easiest to just describe the dependencies:
  85810. *
  85811. * - All modules depend on the \link flac_format Format \endlink module.
  85812. * - The decoders and encoders depend on the bitbuffer.
  85813. * - The decoder is independent of the encoder. The encoder uses the
  85814. * decoder because of the verify feature, but this can be removed if
  85815. * not needed.
  85816. * - Parts of the metadata interface require the stream decoder (but not
  85817. * the encoder).
  85818. * - Ogg support is selectable through the compile time macro
  85819. * \c FLAC__HAS_OGG.
  85820. *
  85821. * For example, if your application only requires the stream decoder, no
  85822. * encoder, and no metadata interface, you can remove the stream encoder
  85823. * and the metadata interface, which will greatly reduce the size of the
  85824. * library.
  85825. *
  85826. * Also, there are several places in the libFLAC code with comments marked
  85827. * with "OPT:" where a #define can be changed to enable code that might be
  85828. * faster on a specific platform. Experimenting with these can yield faster
  85829. * binaries.
  85830. */
  85831. /** \defgroup porting Porting Guide for New Versions
  85832. *
  85833. * This module describes differences in the library interfaces from
  85834. * version to version. It assists in the porting of code that uses
  85835. * the libraries to newer versions of FLAC.
  85836. *
  85837. * One simple facility for making porting easier that has been added
  85838. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  85839. * library's includes (e.g. \c include/FLAC/export.h). The
  85840. * \c #defines mirror the libraries'
  85841. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  85842. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  85843. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  85844. * These can be used to support multiple versions of an API during the
  85845. * transition phase, e.g.
  85846. *
  85847. * \code
  85848. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  85849. * legacy code
  85850. * #else
  85851. * new code
  85852. * #endif
  85853. * \endcode
  85854. *
  85855. * The the source will work for multiple versions and the legacy code can
  85856. * easily be removed when the transition is complete.
  85857. *
  85858. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  85859. * include/FLAC/export.h), which can be used to determine whether or not
  85860. * the library has been compiled with support for Ogg FLAC. This is
  85861. * simpler than trying to call an Ogg init function and catching the
  85862. * error.
  85863. */
  85864. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  85865. * \ingroup porting
  85866. *
  85867. * \brief
  85868. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  85869. *
  85870. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  85871. * been simplified. First, libOggFLAC has been merged into libFLAC and
  85872. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  85873. * decoding layers and three encoding layers have been merged into a
  85874. * single stream decoder and stream encoder. That is, the functionality
  85875. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  85876. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  85877. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  85878. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  85879. * is there is now a single API that can be used to encode or decode
  85880. * streams to/from native FLAC or Ogg FLAC and the single API can work
  85881. * on both seekable and non-seekable streams.
  85882. *
  85883. * Instead of creating an encoder or decoder of a certain layer, now the
  85884. * client will always create a FLAC__StreamEncoder or
  85885. * FLAC__StreamDecoder. The old layers are now differentiated by the
  85886. * initialization function. For example, for the decoder,
  85887. * FLAC__stream_decoder_init() has been replaced by
  85888. * FLAC__stream_decoder_init_stream(). This init function takes
  85889. * callbacks for the I/O, and the seeking callbacks are optional. This
  85890. * allows the client to use the same object for seekable and
  85891. * non-seekable streams. For decoding a FLAC file directly, the client
  85892. * can use FLAC__stream_decoder_init_file() and pass just a filename
  85893. * and fewer callbacks; most of the other callbacks are supplied
  85894. * internally. For situations where fopen()ing by filename is not
  85895. * possible (e.g. Unicode filenames on Windows) the client can instead
  85896. * open the file itself and supply the FILE* to
  85897. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  85898. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  85899. * Since the callbacks and client data are now passed to the init
  85900. * function, the FLAC__stream_decoder_set_*_callback() functions and
  85901. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  85902. * rest of the calls to the decoder are the same as before.
  85903. *
  85904. * There are counterpart init functions for Ogg FLAC, e.g.
  85905. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  85906. * and callbacks are the same as for native FLAC.
  85907. *
  85908. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  85909. * been set up like so:
  85910. *
  85911. * \code
  85912. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  85913. * if(decoder == NULL) do_something;
  85914. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  85915. * [... other settings ...]
  85916. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  85917. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  85918. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  85919. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  85920. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  85921. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  85922. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  85923. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  85924. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  85925. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  85926. * \endcode
  85927. *
  85928. * In FLAC 1.1.3 it is like this:
  85929. *
  85930. * \code
  85931. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  85932. * if(decoder == NULL) do_something;
  85933. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  85934. * [... other settings ...]
  85935. * if(FLAC__stream_decoder_init_stream(
  85936. * decoder,
  85937. * my_read_callback,
  85938. * my_seek_callback, // or NULL
  85939. * my_tell_callback, // or NULL
  85940. * my_length_callback, // or NULL
  85941. * my_eof_callback, // or NULL
  85942. * my_write_callback,
  85943. * my_metadata_callback, // or NULL
  85944. * my_error_callback,
  85945. * my_client_data
  85946. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  85947. * \endcode
  85948. *
  85949. * or you could do;
  85950. *
  85951. * \code
  85952. * [...]
  85953. * FILE *file = fopen("somefile.flac","rb");
  85954. * if(file == NULL) do_somthing;
  85955. * if(FLAC__stream_decoder_init_FILE(
  85956. * decoder,
  85957. * file,
  85958. * my_write_callback,
  85959. * my_metadata_callback, // or NULL
  85960. * my_error_callback,
  85961. * my_client_data
  85962. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  85963. * \endcode
  85964. *
  85965. * or just:
  85966. *
  85967. * \code
  85968. * [...]
  85969. * if(FLAC__stream_decoder_init_file(
  85970. * decoder,
  85971. * "somefile.flac",
  85972. * my_write_callback,
  85973. * my_metadata_callback, // or NULL
  85974. * my_error_callback,
  85975. * my_client_data
  85976. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  85977. * \endcode
  85978. *
  85979. * Another small change to the decoder is in how it handles unparseable
  85980. * streams. Before, when the decoder found an unparseable stream
  85981. * (reserved for when the decoder encounters a stream from a future
  85982. * encoder that it can't parse), it changed the state to
  85983. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  85984. * drops sync and calls the error callback with a new error code
  85985. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  85986. * more robust. If your error callback does not discriminate on the the
  85987. * error state, your code does not need to be changed.
  85988. *
  85989. * The encoder now has a new setting:
  85990. * FLAC__stream_encoder_set_apodization(). This is for setting the
  85991. * method used to window the data before LPC analysis. You only need to
  85992. * add a call to this function if the default is not suitable. There
  85993. * are also two new convenience functions that may be useful:
  85994. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  85995. * FLAC__metadata_get_cuesheet().
  85996. *
  85997. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  85998. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  85999. * is now \c size_t instead of \c unsigned.
  86000. */
  86001. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  86002. * \ingroup porting
  86003. *
  86004. * \brief
  86005. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  86006. *
  86007. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  86008. * There was a slight change in the implementation of
  86009. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  86010. * of the \a metadata array of pointers so the client no longer needs
  86011. * to maintain it after the call. The objects themselves that are
  86012. * pointed to by the array are still not copied though and must be
  86013. * maintained until the call to FLAC__stream_encoder_finish().
  86014. */
  86015. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  86016. * \ingroup porting
  86017. *
  86018. * \brief
  86019. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  86020. *
  86021. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  86022. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  86023. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  86024. *
  86025. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  86026. * has changed to reflect the conversion of one of the reserved bits
  86027. * into active use. It used to be \c 2 and now is \c 1. However the
  86028. * FLAC frame header length has not changed, so to skip the proper
  86029. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  86030. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  86031. */
  86032. /** \defgroup flac FLAC C API
  86033. *
  86034. * The FLAC C API is the interface to libFLAC, a set of structures
  86035. * describing the components of FLAC streams, and functions for
  86036. * encoding and decoding streams, as well as manipulating FLAC
  86037. * metadata in files.
  86038. *
  86039. * You should start with the format components as all other modules
  86040. * are dependent on it.
  86041. */
  86042. #endif
  86043. /********* End of inlined file: all.h *********/
  86044. /********* Start of inlined file: bitmath.c *********/
  86045. /********* Start of inlined file: juce_FlacHeader.h *********/
  86046. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86047. // tasks..
  86048. #define VERSION "1.2.1"
  86049. #define FLAC__NO_DLL 1
  86050. #ifdef _MSC_VER
  86051. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86052. #endif
  86053. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86054. #define FLAC__SYS_DARWIN 1
  86055. #endif
  86056. /********* End of inlined file: juce_FlacHeader.h *********/
  86057. #if JUCE_USE_FLAC
  86058. #if HAVE_CONFIG_H
  86059. # include <config.h>
  86060. #endif
  86061. /********* Start of inlined file: bitmath.h *********/
  86062. #ifndef FLAC__PRIVATE__BITMATH_H
  86063. #define FLAC__PRIVATE__BITMATH_H
  86064. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  86065. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  86066. unsigned FLAC__bitmath_silog2(int v);
  86067. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  86068. #endif
  86069. /********* End of inlined file: bitmath.h *********/
  86070. /* An example of what FLAC__bitmath_ilog2() computes:
  86071. *
  86072. * ilog2( 0) = assertion failure
  86073. * ilog2( 1) = 0
  86074. * ilog2( 2) = 1
  86075. * ilog2( 3) = 1
  86076. * ilog2( 4) = 2
  86077. * ilog2( 5) = 2
  86078. * ilog2( 6) = 2
  86079. * ilog2( 7) = 2
  86080. * ilog2( 8) = 3
  86081. * ilog2( 9) = 3
  86082. * ilog2(10) = 3
  86083. * ilog2(11) = 3
  86084. * ilog2(12) = 3
  86085. * ilog2(13) = 3
  86086. * ilog2(14) = 3
  86087. * ilog2(15) = 3
  86088. * ilog2(16) = 4
  86089. * ilog2(17) = 4
  86090. * ilog2(18) = 4
  86091. */
  86092. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  86093. {
  86094. unsigned l = 0;
  86095. FLAC__ASSERT(v > 0);
  86096. while(v >>= 1)
  86097. l++;
  86098. return l;
  86099. }
  86100. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  86101. {
  86102. unsigned l = 0;
  86103. FLAC__ASSERT(v > 0);
  86104. while(v >>= 1)
  86105. l++;
  86106. return l;
  86107. }
  86108. /* An example of what FLAC__bitmath_silog2() computes:
  86109. *
  86110. * silog2(-10) = 5
  86111. * silog2(- 9) = 5
  86112. * silog2(- 8) = 4
  86113. * silog2(- 7) = 4
  86114. * silog2(- 6) = 4
  86115. * silog2(- 5) = 4
  86116. * silog2(- 4) = 3
  86117. * silog2(- 3) = 3
  86118. * silog2(- 2) = 2
  86119. * silog2(- 1) = 2
  86120. * silog2( 0) = 0
  86121. * silog2( 1) = 2
  86122. * silog2( 2) = 3
  86123. * silog2( 3) = 3
  86124. * silog2( 4) = 4
  86125. * silog2( 5) = 4
  86126. * silog2( 6) = 4
  86127. * silog2( 7) = 4
  86128. * silog2( 8) = 5
  86129. * silog2( 9) = 5
  86130. * silog2( 10) = 5
  86131. */
  86132. unsigned FLAC__bitmath_silog2(int v)
  86133. {
  86134. while(1) {
  86135. if(v == 0) {
  86136. return 0;
  86137. }
  86138. else if(v > 0) {
  86139. unsigned l = 0;
  86140. while(v) {
  86141. l++;
  86142. v >>= 1;
  86143. }
  86144. return l+1;
  86145. }
  86146. else if(v == -1) {
  86147. return 2;
  86148. }
  86149. else {
  86150. v++;
  86151. v = -v;
  86152. }
  86153. }
  86154. }
  86155. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  86156. {
  86157. while(1) {
  86158. if(v == 0) {
  86159. return 0;
  86160. }
  86161. else if(v > 0) {
  86162. unsigned l = 0;
  86163. while(v) {
  86164. l++;
  86165. v >>= 1;
  86166. }
  86167. return l+1;
  86168. }
  86169. else if(v == -1) {
  86170. return 2;
  86171. }
  86172. else {
  86173. v++;
  86174. v = -v;
  86175. }
  86176. }
  86177. }
  86178. #endif
  86179. /********* End of inlined file: bitmath.c *********/
  86180. /********* Start of inlined file: bitreader.c *********/
  86181. /********* Start of inlined file: juce_FlacHeader.h *********/
  86182. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86183. // tasks..
  86184. #define VERSION "1.2.1"
  86185. #define FLAC__NO_DLL 1
  86186. #ifdef _MSC_VER
  86187. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86188. #endif
  86189. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86190. #define FLAC__SYS_DARWIN 1
  86191. #endif
  86192. /********* End of inlined file: juce_FlacHeader.h *********/
  86193. #if JUCE_USE_FLAC
  86194. #if HAVE_CONFIG_H
  86195. # include <config.h>
  86196. #endif
  86197. #include <stdlib.h> /* for malloc() */
  86198. #include <string.h> /* for memcpy(), memset() */
  86199. #ifdef _MSC_VER
  86200. #include <winsock.h> /* for ntohl() */
  86201. #elif defined FLAC__SYS_DARWIN
  86202. #include <machine/endian.h> /* for ntohl() */
  86203. #elif defined __MINGW32__
  86204. #include <winsock.h> /* for ntohl() */
  86205. #else
  86206. #include <netinet/in.h> /* for ntohl() */
  86207. #endif
  86208. /********* Start of inlined file: bitreader.h *********/
  86209. #ifndef FLAC__PRIVATE__BITREADER_H
  86210. #define FLAC__PRIVATE__BITREADER_H
  86211. #include <stdio.h> /* for FILE */
  86212. /********* Start of inlined file: cpu.h *********/
  86213. #ifndef FLAC__PRIVATE__CPU_H
  86214. #define FLAC__PRIVATE__CPU_H
  86215. #ifdef HAVE_CONFIG_H
  86216. #include <config.h>
  86217. #endif
  86218. typedef enum {
  86219. FLAC__CPUINFO_TYPE_IA32,
  86220. FLAC__CPUINFO_TYPE_PPC,
  86221. FLAC__CPUINFO_TYPE_UNKNOWN
  86222. } FLAC__CPUInfo_Type;
  86223. typedef struct {
  86224. FLAC__bool cpuid;
  86225. FLAC__bool bswap;
  86226. FLAC__bool cmov;
  86227. FLAC__bool mmx;
  86228. FLAC__bool fxsr;
  86229. FLAC__bool sse;
  86230. FLAC__bool sse2;
  86231. FLAC__bool sse3;
  86232. FLAC__bool ssse3;
  86233. FLAC__bool _3dnow;
  86234. FLAC__bool ext3dnow;
  86235. FLAC__bool extmmx;
  86236. } FLAC__CPUInfo_IA32;
  86237. typedef struct {
  86238. FLAC__bool altivec;
  86239. FLAC__bool ppc64;
  86240. } FLAC__CPUInfo_PPC;
  86241. typedef struct {
  86242. FLAC__bool use_asm;
  86243. FLAC__CPUInfo_Type type;
  86244. union {
  86245. FLAC__CPUInfo_IA32 ia32;
  86246. FLAC__CPUInfo_PPC ppc;
  86247. } data;
  86248. } FLAC__CPUInfo;
  86249. void FLAC__cpu_info(FLAC__CPUInfo *info);
  86250. #ifndef FLAC__NO_ASM
  86251. #ifdef FLAC__CPU_IA32
  86252. #ifdef FLAC__HAS_NASM
  86253. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  86254. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  86255. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  86256. #endif
  86257. #endif
  86258. #endif
  86259. #endif
  86260. /********* End of inlined file: cpu.h *********/
  86261. /*
  86262. * opaque structure definition
  86263. */
  86264. struct FLAC__BitReader;
  86265. typedef struct FLAC__BitReader FLAC__BitReader;
  86266. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  86267. /*
  86268. * construction, deletion, initialization, etc functions
  86269. */
  86270. FLAC__BitReader *FLAC__bitreader_new(void);
  86271. void FLAC__bitreader_delete(FLAC__BitReader *br);
  86272. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  86273. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  86274. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  86275. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  86276. /*
  86277. * CRC functions
  86278. */
  86279. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  86280. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  86281. /*
  86282. * info functions
  86283. */
  86284. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  86285. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  86286. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  86287. /*
  86288. * read functions
  86289. */
  86290. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  86291. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  86292. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  86293. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  86294. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  86295. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  86296. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  86297. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  86298. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  86299. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86300. #ifndef FLAC__NO_ASM
  86301. # ifdef FLAC__CPU_IA32
  86302. # ifdef FLAC__HAS_NASM
  86303. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86304. # endif
  86305. # endif
  86306. #endif
  86307. #if 0 /* UNUSED */
  86308. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  86309. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  86310. #endif
  86311. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  86312. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  86313. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  86314. #endif
  86315. /********* End of inlined file: bitreader.h *********/
  86316. /********* Start of inlined file: crc.h *********/
  86317. #ifndef FLAC__PRIVATE__CRC_H
  86318. #define FLAC__PRIVATE__CRC_H
  86319. /* 8 bit CRC generator, MSB shifted first
  86320. ** polynomial = x^8 + x^2 + x^1 + x^0
  86321. ** init = 0
  86322. */
  86323. extern FLAC__byte const FLAC__crc8_table[256];
  86324. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  86325. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  86326. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  86327. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  86328. /* 16 bit CRC generator, MSB shifted first
  86329. ** polynomial = x^16 + x^15 + x^2 + x^0
  86330. ** init = 0
  86331. */
  86332. extern unsigned FLAC__crc16_table[256];
  86333. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  86334. /* this alternate may be faster on some systems/compilers */
  86335. #if 0
  86336. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  86337. #endif
  86338. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  86339. #endif
  86340. /********* End of inlined file: crc.h *********/
  86341. /* Things should be fastest when this matches the machine word size */
  86342. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  86343. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  86344. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  86345. typedef FLAC__uint32 brword;
  86346. #define FLAC__BYTES_PER_WORD 4
  86347. #define FLAC__BITS_PER_WORD 32
  86348. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  86349. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  86350. #if WORDS_BIGENDIAN
  86351. #define SWAP_BE_WORD_TO_HOST(x) (x)
  86352. #else
  86353. #if defined (_MSC_VER) && defined (_X86_)
  86354. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  86355. #else
  86356. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  86357. #endif
  86358. #endif
  86359. /* counts the # of zero MSBs in a word */
  86360. #define COUNT_ZERO_MSBS(word) ( \
  86361. (word) <= 0xffff ? \
  86362. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  86363. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  86364. )
  86365. /* this alternate might be slightly faster on some systems/compilers: */
  86366. #define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) )
  86367. /*
  86368. * This should be at least twice as large as the largest number of words
  86369. * required to represent any 'number' (in any encoding) you are going to
  86370. * read. With FLAC this is on the order of maybe a few hundred bits.
  86371. * If the buffer is smaller than that, the decoder won't be able to read
  86372. * in a whole number that is in a variable length encoding (e.g. Rice).
  86373. * But to be practical it should be at least 1K bytes.
  86374. *
  86375. * Increase this number to decrease the number of read callbacks, at the
  86376. * expense of using more memory. Or decrease for the reverse effect,
  86377. * keeping in mind the limit from the first paragraph. The optimal size
  86378. * also depends on the CPU cache size and other factors; some twiddling
  86379. * may be necessary to squeeze out the best performance.
  86380. */
  86381. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  86382. static const unsigned char byte_to_unary_table[] = {
  86383. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  86384. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  86385. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  86386. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  86387. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86388. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86389. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86390. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  86399. };
  86400. #ifdef min
  86401. #undef min
  86402. #endif
  86403. #define min(x,y) ((x)<(y)?(x):(y))
  86404. #ifdef max
  86405. #undef max
  86406. #endif
  86407. #define max(x,y) ((x)>(y)?(x):(y))
  86408. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  86409. #ifdef _MSC_VER
  86410. #define FLAC__U64L(x) x
  86411. #else
  86412. #define FLAC__U64L(x) x##LLU
  86413. #endif
  86414. #ifndef FLaC__INLINE
  86415. #define FLaC__INLINE
  86416. #endif
  86417. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  86418. struct FLAC__BitReader {
  86419. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  86420. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  86421. brword *buffer;
  86422. unsigned capacity; /* in words */
  86423. unsigned words; /* # of completed words in buffer */
  86424. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  86425. unsigned consumed_words; /* #words ... */
  86426. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  86427. unsigned read_crc16; /* the running frame CRC */
  86428. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  86429. FLAC__BitReaderReadCallback read_callback;
  86430. void *client_data;
  86431. FLAC__CPUInfo cpu_info;
  86432. };
  86433. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  86434. {
  86435. register unsigned crc = br->read_crc16;
  86436. #if FLAC__BYTES_PER_WORD == 4
  86437. switch(br->crc16_align) {
  86438. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  86439. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  86440. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  86441. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  86442. }
  86443. #elif FLAC__BYTES_PER_WORD == 8
  86444. switch(br->crc16_align) {
  86445. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  86446. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  86447. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  86448. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  86449. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  86450. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  86451. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  86452. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  86453. }
  86454. #else
  86455. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  86456. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  86457. br->read_crc16 = crc;
  86458. #endif
  86459. br->crc16_align = 0;
  86460. }
  86461. /* would be static except it needs to be called by asm routines */
  86462. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  86463. {
  86464. unsigned start, end;
  86465. size_t bytes;
  86466. FLAC__byte *target;
  86467. /* first shift the unconsumed buffer data toward the front as much as possible */
  86468. if(br->consumed_words > 0) {
  86469. start = br->consumed_words;
  86470. end = br->words + (br->bytes? 1:0);
  86471. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  86472. br->words -= start;
  86473. br->consumed_words = 0;
  86474. }
  86475. /*
  86476. * set the target for reading, taking into account word alignment and endianness
  86477. */
  86478. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  86479. if(bytes == 0)
  86480. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  86481. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  86482. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  86483. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  86484. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  86485. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  86486. * ^^-------target, bytes=3
  86487. * on LE machines, have to byteswap the odd tail word so nothing is
  86488. * overwritten:
  86489. */
  86490. #if WORDS_BIGENDIAN
  86491. #else
  86492. if(br->bytes)
  86493. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  86494. #endif
  86495. /* now it looks like:
  86496. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  86497. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  86498. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  86499. * ^^-------target, bytes=3
  86500. */
  86501. /* read in the data; note that the callback may return a smaller number of bytes */
  86502. if(!br->read_callback(target, &bytes, br->client_data))
  86503. return false;
  86504. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  86505. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  86506. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  86507. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  86508. * now have to byteswap on LE machines:
  86509. */
  86510. #if WORDS_BIGENDIAN
  86511. #else
  86512. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  86513. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  86514. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  86515. start = br->words;
  86516. local_swap32_block_(br->buffer + start, end - start);
  86517. }
  86518. else
  86519. # endif
  86520. for(start = br->words; start < end; start++)
  86521. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  86522. #endif
  86523. /* now it looks like:
  86524. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  86525. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  86526. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  86527. * finally we'll update the reader values:
  86528. */
  86529. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  86530. br->words = end / FLAC__BYTES_PER_WORD;
  86531. br->bytes = end % FLAC__BYTES_PER_WORD;
  86532. return true;
  86533. }
  86534. /***********************************************************************
  86535. *
  86536. * Class constructor/destructor
  86537. *
  86538. ***********************************************************************/
  86539. FLAC__BitReader *FLAC__bitreader_new(void)
  86540. {
  86541. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  86542. /* calloc() implies:
  86543. memset(br, 0, sizeof(FLAC__BitReader));
  86544. br->buffer = 0;
  86545. br->capacity = 0;
  86546. br->words = br->bytes = 0;
  86547. br->consumed_words = br->consumed_bits = 0;
  86548. br->read_callback = 0;
  86549. br->client_data = 0;
  86550. */
  86551. return br;
  86552. }
  86553. void FLAC__bitreader_delete(FLAC__BitReader *br)
  86554. {
  86555. FLAC__ASSERT(0 != br);
  86556. FLAC__bitreader_free(br);
  86557. free(br);
  86558. }
  86559. /***********************************************************************
  86560. *
  86561. * Public class methods
  86562. *
  86563. ***********************************************************************/
  86564. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  86565. {
  86566. FLAC__ASSERT(0 != br);
  86567. br->words = br->bytes = 0;
  86568. br->consumed_words = br->consumed_bits = 0;
  86569. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  86570. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  86571. if(br->buffer == 0)
  86572. return false;
  86573. br->read_callback = rcb;
  86574. br->client_data = cd;
  86575. br->cpu_info = cpu;
  86576. return true;
  86577. }
  86578. void FLAC__bitreader_free(FLAC__BitReader *br)
  86579. {
  86580. FLAC__ASSERT(0 != br);
  86581. if(0 != br->buffer)
  86582. free(br->buffer);
  86583. br->buffer = 0;
  86584. br->capacity = 0;
  86585. br->words = br->bytes = 0;
  86586. br->consumed_words = br->consumed_bits = 0;
  86587. br->read_callback = 0;
  86588. br->client_data = 0;
  86589. }
  86590. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  86591. {
  86592. br->words = br->bytes = 0;
  86593. br->consumed_words = br->consumed_bits = 0;
  86594. return true;
  86595. }
  86596. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  86597. {
  86598. unsigned i, j;
  86599. if(br == 0) {
  86600. fprintf(out, "bitreader is NULL\n");
  86601. }
  86602. else {
  86603. fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
  86604. for(i = 0; i < br->words; i++) {
  86605. fprintf(out, "%08X: ", i);
  86606. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  86607. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  86608. fprintf(out, ".");
  86609. else
  86610. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  86611. fprintf(out, "\n");
  86612. }
  86613. if(br->bytes > 0) {
  86614. fprintf(out, "%08X: ", i);
  86615. for(j = 0; j < br->bytes*8; j++)
  86616. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  86617. fprintf(out, ".");
  86618. else
  86619. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  86620. fprintf(out, "\n");
  86621. }
  86622. }
  86623. }
  86624. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  86625. {
  86626. FLAC__ASSERT(0 != br);
  86627. FLAC__ASSERT(0 != br->buffer);
  86628. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  86629. br->read_crc16 = (unsigned)seed;
  86630. br->crc16_align = br->consumed_bits;
  86631. }
  86632. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  86633. {
  86634. FLAC__ASSERT(0 != br);
  86635. FLAC__ASSERT(0 != br->buffer);
  86636. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  86637. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  86638. /* CRC any tail bytes in a partially-consumed word */
  86639. if(br->consumed_bits) {
  86640. const brword tail = br->buffer[br->consumed_words];
  86641. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  86642. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  86643. }
  86644. return br->read_crc16;
  86645. }
  86646. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  86647. {
  86648. return ((br->consumed_bits & 7) == 0);
  86649. }
  86650. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  86651. {
  86652. return 8 - (br->consumed_bits & 7);
  86653. }
  86654. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  86655. {
  86656. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  86657. }
  86658. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  86659. {
  86660. FLAC__ASSERT(0 != br);
  86661. FLAC__ASSERT(0 != br->buffer);
  86662. FLAC__ASSERT(bits <= 32);
  86663. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  86664. FLAC__ASSERT(br->consumed_words <= br->words);
  86665. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  86666. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  86667. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  86668. *val = 0;
  86669. return true;
  86670. }
  86671. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  86672. if(!bitreader_read_from_client_(br))
  86673. return false;
  86674. }
  86675. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  86676. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  86677. if(br->consumed_bits) {
  86678. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  86679. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  86680. const brword word = br->buffer[br->consumed_words];
  86681. if(bits < n) {
  86682. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  86683. br->consumed_bits += bits;
  86684. return true;
  86685. }
  86686. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  86687. bits -= n;
  86688. crc16_update_word_(br, word);
  86689. br->consumed_words++;
  86690. br->consumed_bits = 0;
  86691. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  86692. *val <<= bits;
  86693. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  86694. br->consumed_bits = bits;
  86695. }
  86696. return true;
  86697. }
  86698. else {
  86699. const brword word = br->buffer[br->consumed_words];
  86700. if(bits < FLAC__BITS_PER_WORD) {
  86701. *val = word >> (FLAC__BITS_PER_WORD-bits);
  86702. br->consumed_bits = bits;
  86703. return true;
  86704. }
  86705. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  86706. *val = word;
  86707. crc16_update_word_(br, word);
  86708. br->consumed_words++;
  86709. return true;
  86710. }
  86711. }
  86712. else {
  86713. /* in this case we're starting our read at a partial tail word;
  86714. * the reader has guaranteed that we have at least 'bits' bits
  86715. * available to read, which makes this case simpler.
  86716. */
  86717. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  86718. if(br->consumed_bits) {
  86719. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  86720. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  86721. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  86722. br->consumed_bits += bits;
  86723. return true;
  86724. }
  86725. else {
  86726. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  86727. br->consumed_bits += bits;
  86728. return true;
  86729. }
  86730. }
  86731. }
  86732. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  86733. {
  86734. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  86735. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  86736. return false;
  86737. /* sign-extend: */
  86738. *val <<= (32-bits);
  86739. *val >>= (32-bits);
  86740. return true;
  86741. }
  86742. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  86743. {
  86744. FLAC__uint32 hi, lo;
  86745. if(bits > 32) {
  86746. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  86747. return false;
  86748. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  86749. return false;
  86750. *val = hi;
  86751. *val <<= 32;
  86752. *val |= lo;
  86753. }
  86754. else {
  86755. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  86756. return false;
  86757. *val = lo;
  86758. }
  86759. return true;
  86760. }
  86761. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  86762. {
  86763. FLAC__uint32 x8, x32 = 0;
  86764. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  86765. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  86766. return false;
  86767. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86768. return false;
  86769. x32 |= (x8 << 8);
  86770. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86771. return false;
  86772. x32 |= (x8 << 16);
  86773. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86774. return false;
  86775. x32 |= (x8 << 24);
  86776. *val = x32;
  86777. return true;
  86778. }
  86779. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  86780. {
  86781. /*
  86782. * OPT: a faster implementation is possible but probably not that useful
  86783. * since this is only called a couple of times in the metadata readers.
  86784. */
  86785. FLAC__ASSERT(0 != br);
  86786. FLAC__ASSERT(0 != br->buffer);
  86787. if(bits > 0) {
  86788. const unsigned n = br->consumed_bits & 7;
  86789. unsigned m;
  86790. FLAC__uint32 x;
  86791. if(n != 0) {
  86792. m = min(8-n, bits);
  86793. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  86794. return false;
  86795. bits -= m;
  86796. }
  86797. m = bits / 8;
  86798. if(m > 0) {
  86799. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  86800. return false;
  86801. bits %= 8;
  86802. }
  86803. if(bits > 0) {
  86804. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  86805. return false;
  86806. }
  86807. }
  86808. return true;
  86809. }
  86810. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  86811. {
  86812. FLAC__uint32 x;
  86813. FLAC__ASSERT(0 != br);
  86814. FLAC__ASSERT(0 != br->buffer);
  86815. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  86816. /* step 1: skip over partial head word to get word aligned */
  86817. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  86818. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86819. return false;
  86820. nvals--;
  86821. }
  86822. if(0 == nvals)
  86823. return true;
  86824. /* step 2: skip whole words in chunks */
  86825. while(nvals >= FLAC__BYTES_PER_WORD) {
  86826. if(br->consumed_words < br->words) {
  86827. br->consumed_words++;
  86828. nvals -= FLAC__BYTES_PER_WORD;
  86829. }
  86830. else if(!bitreader_read_from_client_(br))
  86831. return false;
  86832. }
  86833. /* step 3: skip any remainder from partial tail bytes */
  86834. while(nvals) {
  86835. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86836. return false;
  86837. nvals--;
  86838. }
  86839. return true;
  86840. }
  86841. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  86842. {
  86843. FLAC__uint32 x;
  86844. FLAC__ASSERT(0 != br);
  86845. FLAC__ASSERT(0 != br->buffer);
  86846. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  86847. /* step 1: read from partial head word to get word aligned */
  86848. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  86849. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86850. return false;
  86851. *val++ = (FLAC__byte)x;
  86852. nvals--;
  86853. }
  86854. if(0 == nvals)
  86855. return true;
  86856. /* step 2: read whole words in chunks */
  86857. while(nvals >= FLAC__BYTES_PER_WORD) {
  86858. if(br->consumed_words < br->words) {
  86859. const brword word = br->buffer[br->consumed_words++];
  86860. #if FLAC__BYTES_PER_WORD == 4
  86861. val[0] = (FLAC__byte)(word >> 24);
  86862. val[1] = (FLAC__byte)(word >> 16);
  86863. val[2] = (FLAC__byte)(word >> 8);
  86864. val[3] = (FLAC__byte)word;
  86865. #elif FLAC__BYTES_PER_WORD == 8
  86866. val[0] = (FLAC__byte)(word >> 56);
  86867. val[1] = (FLAC__byte)(word >> 48);
  86868. val[2] = (FLAC__byte)(word >> 40);
  86869. val[3] = (FLAC__byte)(word >> 32);
  86870. val[4] = (FLAC__byte)(word >> 24);
  86871. val[5] = (FLAC__byte)(word >> 16);
  86872. val[6] = (FLAC__byte)(word >> 8);
  86873. val[7] = (FLAC__byte)word;
  86874. #else
  86875. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  86876. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  86877. #endif
  86878. val += FLAC__BYTES_PER_WORD;
  86879. nvals -= FLAC__BYTES_PER_WORD;
  86880. }
  86881. else if(!bitreader_read_from_client_(br))
  86882. return false;
  86883. }
  86884. /* step 3: read any remainder from partial tail bytes */
  86885. while(nvals) {
  86886. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86887. return false;
  86888. *val++ = (FLAC__byte)x;
  86889. nvals--;
  86890. }
  86891. return true;
  86892. }
  86893. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  86894. #if 0 /* slow but readable version */
  86895. {
  86896. unsigned bit;
  86897. FLAC__ASSERT(0 != br);
  86898. FLAC__ASSERT(0 != br->buffer);
  86899. *val = 0;
  86900. while(1) {
  86901. if(!FLAC__bitreader_read_bit(br, &bit))
  86902. return false;
  86903. if(bit)
  86904. break;
  86905. else
  86906. *val++;
  86907. }
  86908. return true;
  86909. }
  86910. #else
  86911. {
  86912. unsigned i;
  86913. FLAC__ASSERT(0 != br);
  86914. FLAC__ASSERT(0 != br->buffer);
  86915. *val = 0;
  86916. while(1) {
  86917. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  86918. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  86919. if(b) {
  86920. i = COUNT_ZERO_MSBS(b);
  86921. *val += i;
  86922. i++;
  86923. br->consumed_bits += i;
  86924. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  86925. crc16_update_word_(br, br->buffer[br->consumed_words]);
  86926. br->consumed_words++;
  86927. br->consumed_bits = 0;
  86928. }
  86929. return true;
  86930. }
  86931. else {
  86932. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  86933. crc16_update_word_(br, br->buffer[br->consumed_words]);
  86934. br->consumed_words++;
  86935. br->consumed_bits = 0;
  86936. /* didn't find stop bit yet, have to keep going... */
  86937. }
  86938. }
  86939. /* at this point we've eaten up all the whole words; have to try
  86940. * reading through any tail bytes before calling the read callback.
  86941. * this is a repeat of the above logic adjusted for the fact we
  86942. * don't have a whole word. note though if the client is feeding
  86943. * us data a byte at a time (unlikely), br->consumed_bits may not
  86944. * be zero.
  86945. */
  86946. if(br->bytes) {
  86947. const unsigned end = br->bytes * 8;
  86948. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  86949. if(b) {
  86950. i = COUNT_ZERO_MSBS(b);
  86951. *val += i;
  86952. i++;
  86953. br->consumed_bits += i;
  86954. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  86955. return true;
  86956. }
  86957. else {
  86958. *val += end - br->consumed_bits;
  86959. br->consumed_bits += end;
  86960. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  86961. /* didn't find stop bit yet, have to keep going... */
  86962. }
  86963. }
  86964. if(!bitreader_read_from_client_(br))
  86965. return false;
  86966. }
  86967. }
  86968. #endif
  86969. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  86970. {
  86971. FLAC__uint32 lsbs = 0, msbs = 0;
  86972. unsigned uval;
  86973. FLAC__ASSERT(0 != br);
  86974. FLAC__ASSERT(0 != br->buffer);
  86975. FLAC__ASSERT(parameter <= 31);
  86976. /* read the unary MSBs and end bit */
  86977. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  86978. return false;
  86979. /* read the binary LSBs */
  86980. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  86981. return false;
  86982. /* compose the value */
  86983. uval = (msbs << parameter) | lsbs;
  86984. if(uval & 1)
  86985. *val = -((int)(uval >> 1)) - 1;
  86986. else
  86987. *val = (int)(uval >> 1);
  86988. return true;
  86989. }
  86990. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  86991. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  86992. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  86993. /* OPT: possibly faster version for use with MSVC */
  86994. #ifdef _MSC_VER
  86995. {
  86996. unsigned i;
  86997. unsigned uval = 0;
  86998. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  86999. /* try and get br->consumed_words and br->consumed_bits into register;
  87000. * must remember to flush them back to *br before calling other
  87001. * bitwriter functions that use them, and before returning */
  87002. register unsigned cwords;
  87003. register unsigned cbits;
  87004. FLAC__ASSERT(0 != br);
  87005. FLAC__ASSERT(0 != br->buffer);
  87006. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87007. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87008. FLAC__ASSERT(parameter < 32);
  87009. /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */
  87010. if(nvals == 0)
  87011. return true;
  87012. cbits = br->consumed_bits;
  87013. cwords = br->consumed_words;
  87014. while(1) {
  87015. /* read unary part */
  87016. while(1) {
  87017. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87018. brword b = br->buffer[cwords] << cbits;
  87019. if(b) {
  87020. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  87021. __asm {
  87022. bsr eax, b
  87023. not eax
  87024. and eax, 31
  87025. mov i, eax
  87026. }
  87027. #else
  87028. i = COUNT_ZERO_MSBS(b);
  87029. #endif
  87030. uval += i;
  87031. bits = parameter;
  87032. i++;
  87033. cbits += i;
  87034. if(cbits == FLAC__BITS_PER_WORD) {
  87035. crc16_update_word_(br, br->buffer[cwords]);
  87036. cwords++;
  87037. cbits = 0;
  87038. }
  87039. goto break1;
  87040. }
  87041. else {
  87042. uval += FLAC__BITS_PER_WORD - cbits;
  87043. crc16_update_word_(br, br->buffer[cwords]);
  87044. cwords++;
  87045. cbits = 0;
  87046. /* didn't find stop bit yet, have to keep going... */
  87047. }
  87048. }
  87049. /* at this point we've eaten up all the whole words; have to try
  87050. * reading through any tail bytes before calling the read callback.
  87051. * this is a repeat of the above logic adjusted for the fact we
  87052. * don't have a whole word. note though if the client is feeding
  87053. * us data a byte at a time (unlikely), br->consumed_bits may not
  87054. * be zero.
  87055. */
  87056. if(br->bytes) {
  87057. const unsigned end = br->bytes * 8;
  87058. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  87059. if(b) {
  87060. i = COUNT_ZERO_MSBS(b);
  87061. uval += i;
  87062. bits = parameter;
  87063. i++;
  87064. cbits += i;
  87065. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87066. goto break1;
  87067. }
  87068. else {
  87069. uval += end - cbits;
  87070. cbits += end;
  87071. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87072. /* didn't find stop bit yet, have to keep going... */
  87073. }
  87074. }
  87075. /* flush registers and read; bitreader_read_from_client_() does
  87076. * not touch br->consumed_bits at all but we still need to set
  87077. * it in case it fails and we have to return false.
  87078. */
  87079. br->consumed_bits = cbits;
  87080. br->consumed_words = cwords;
  87081. if(!bitreader_read_from_client_(br))
  87082. return false;
  87083. cwords = br->consumed_words;
  87084. }
  87085. break1:
  87086. /* read binary part */
  87087. FLAC__ASSERT(cwords <= br->words);
  87088. if(bits) {
  87089. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  87090. /* flush registers and read; bitreader_read_from_client_() does
  87091. * not touch br->consumed_bits at all but we still need to set
  87092. * it in case it fails and we have to return false.
  87093. */
  87094. br->consumed_bits = cbits;
  87095. br->consumed_words = cwords;
  87096. if(!bitreader_read_from_client_(br))
  87097. return false;
  87098. cwords = br->consumed_words;
  87099. }
  87100. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87101. if(cbits) {
  87102. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87103. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87104. const brword word = br->buffer[cwords];
  87105. if(bits < n) {
  87106. uval <<= bits;
  87107. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  87108. cbits += bits;
  87109. goto break2;
  87110. }
  87111. uval <<= n;
  87112. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87113. bits -= n;
  87114. crc16_update_word_(br, word);
  87115. cwords++;
  87116. cbits = 0;
  87117. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  87118. uval <<= bits;
  87119. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  87120. cbits = bits;
  87121. }
  87122. goto break2;
  87123. }
  87124. else {
  87125. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  87126. uval <<= bits;
  87127. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87128. cbits = bits;
  87129. goto break2;
  87130. }
  87131. }
  87132. else {
  87133. /* in this case we're starting our read at a partial tail word;
  87134. * the reader has guaranteed that we have at least 'bits' bits
  87135. * available to read, which makes this case simpler.
  87136. */
  87137. uval <<= bits;
  87138. if(cbits) {
  87139. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87140. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  87141. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  87142. cbits += bits;
  87143. goto break2;
  87144. }
  87145. else {
  87146. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87147. cbits += bits;
  87148. goto break2;
  87149. }
  87150. }
  87151. }
  87152. break2:
  87153. /* compose the value */
  87154. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87155. /* are we done? */
  87156. --nvals;
  87157. if(nvals == 0) {
  87158. br->consumed_bits = cbits;
  87159. br->consumed_words = cwords;
  87160. return true;
  87161. }
  87162. uval = 0;
  87163. ++vals;
  87164. }
  87165. }
  87166. #else
  87167. {
  87168. unsigned i;
  87169. unsigned uval = 0;
  87170. /* try and get br->consumed_words and br->consumed_bits into register;
  87171. * must remember to flush them back to *br before calling other
  87172. * bitwriter functions that use them, and before returning */
  87173. register unsigned cwords;
  87174. register unsigned cbits;
  87175. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  87176. FLAC__ASSERT(0 != br);
  87177. FLAC__ASSERT(0 != br->buffer);
  87178. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87179. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87180. FLAC__ASSERT(parameter < 32);
  87181. /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
  87182. if(nvals == 0)
  87183. return true;
  87184. cbits = br->consumed_bits;
  87185. cwords = br->consumed_words;
  87186. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87187. while(1) {
  87188. /* read unary part */
  87189. while(1) {
  87190. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87191. brword b = br->buffer[cwords] << cbits;
  87192. if(b) {
  87193. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  87194. asm volatile (
  87195. "bsrl %1, %0;"
  87196. "notl %0;"
  87197. "andl $31, %0;"
  87198. : "=r"(i)
  87199. : "r"(b)
  87200. );
  87201. #else
  87202. i = COUNT_ZERO_MSBS(b);
  87203. #endif
  87204. uval += i;
  87205. cbits += i;
  87206. cbits++; /* skip over stop bit */
  87207. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  87208. crc16_update_word_(br, br->buffer[cwords]);
  87209. cwords++;
  87210. cbits = 0;
  87211. }
  87212. goto break1;
  87213. }
  87214. else {
  87215. uval += FLAC__BITS_PER_WORD - cbits;
  87216. crc16_update_word_(br, br->buffer[cwords]);
  87217. cwords++;
  87218. cbits = 0;
  87219. /* didn't find stop bit yet, have to keep going... */
  87220. }
  87221. }
  87222. /* at this point we've eaten up all the whole words; have to try
  87223. * reading through any tail bytes before calling the read callback.
  87224. * this is a repeat of the above logic adjusted for the fact we
  87225. * don't have a whole word. note though if the client is feeding
  87226. * us data a byte at a time (unlikely), br->consumed_bits may not
  87227. * be zero.
  87228. */
  87229. if(br->bytes) {
  87230. const unsigned end = br->bytes * 8;
  87231. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  87232. if(b) {
  87233. i = COUNT_ZERO_MSBS(b);
  87234. uval += i;
  87235. cbits += i;
  87236. cbits++; /* skip over stop bit */
  87237. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87238. goto break1;
  87239. }
  87240. else {
  87241. uval += end - cbits;
  87242. cbits += end;
  87243. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87244. /* didn't find stop bit yet, have to keep going... */
  87245. }
  87246. }
  87247. /* flush registers and read; bitreader_read_from_client_() does
  87248. * not touch br->consumed_bits at all but we still need to set
  87249. * it in case it fails and we have to return false.
  87250. */
  87251. br->consumed_bits = cbits;
  87252. br->consumed_words = cwords;
  87253. if(!bitreader_read_from_client_(br))
  87254. return false;
  87255. cwords = br->consumed_words;
  87256. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  87257. /* + uval to offset our count by the # of unary bits already
  87258. * consumed before the read, because we will add these back
  87259. * in all at once at break1
  87260. */
  87261. }
  87262. break1:
  87263. ucbits -= uval;
  87264. ucbits--; /* account for stop bit */
  87265. /* read binary part */
  87266. FLAC__ASSERT(cwords <= br->words);
  87267. if(parameter) {
  87268. while(ucbits < parameter) {
  87269. /* flush registers and read; bitreader_read_from_client_() does
  87270. * not touch br->consumed_bits at all but we still need to set
  87271. * it in case it fails and we have to return false.
  87272. */
  87273. br->consumed_bits = cbits;
  87274. br->consumed_words = cwords;
  87275. if(!bitreader_read_from_client_(br))
  87276. return false;
  87277. cwords = br->consumed_words;
  87278. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87279. }
  87280. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87281. if(cbits) {
  87282. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  87283. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87284. const brword word = br->buffer[cwords];
  87285. if(parameter < n) {
  87286. uval <<= parameter;
  87287. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  87288. cbits += parameter;
  87289. }
  87290. else {
  87291. uval <<= n;
  87292. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87293. crc16_update_word_(br, word);
  87294. cwords++;
  87295. cbits = parameter - n;
  87296. if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  87297. uval <<= cbits;
  87298. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  87299. }
  87300. }
  87301. }
  87302. else {
  87303. cbits = parameter;
  87304. uval <<= parameter;
  87305. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  87306. }
  87307. }
  87308. else {
  87309. /* in this case we're starting our read at a partial tail word;
  87310. * the reader has guaranteed that we have at least 'parameter'
  87311. * bits available to read, which makes this case simpler.
  87312. */
  87313. uval <<= parameter;
  87314. if(cbits) {
  87315. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87316. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  87317. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  87318. cbits += parameter;
  87319. }
  87320. else {
  87321. cbits = parameter;
  87322. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  87323. }
  87324. }
  87325. }
  87326. ucbits -= parameter;
  87327. /* compose the value */
  87328. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87329. /* are we done? */
  87330. --nvals;
  87331. if(nvals == 0) {
  87332. br->consumed_bits = cbits;
  87333. br->consumed_words = cwords;
  87334. return true;
  87335. }
  87336. uval = 0;
  87337. ++vals;
  87338. }
  87339. }
  87340. #endif
  87341. #if 0 /* UNUSED */
  87342. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  87343. {
  87344. FLAC__uint32 lsbs = 0, msbs = 0;
  87345. unsigned bit, uval, k;
  87346. FLAC__ASSERT(0 != br);
  87347. FLAC__ASSERT(0 != br->buffer);
  87348. k = FLAC__bitmath_ilog2(parameter);
  87349. /* read the unary MSBs and end bit */
  87350. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  87351. return false;
  87352. /* read the binary LSBs */
  87353. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  87354. return false;
  87355. if(parameter == 1u<<k) {
  87356. /* compose the value */
  87357. uval = (msbs << k) | lsbs;
  87358. }
  87359. else {
  87360. unsigned d = (1 << (k+1)) - parameter;
  87361. if(lsbs >= d) {
  87362. if(!FLAC__bitreader_read_bit(br, &bit))
  87363. return false;
  87364. lsbs <<= 1;
  87365. lsbs |= bit;
  87366. lsbs -= d;
  87367. }
  87368. /* compose the value */
  87369. uval = msbs * parameter + lsbs;
  87370. }
  87371. /* unfold unsigned to signed */
  87372. if(uval & 1)
  87373. *val = -((int)(uval >> 1)) - 1;
  87374. else
  87375. *val = (int)(uval >> 1);
  87376. return true;
  87377. }
  87378. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  87379. {
  87380. FLAC__uint32 lsbs, msbs = 0;
  87381. unsigned bit, k;
  87382. FLAC__ASSERT(0 != br);
  87383. FLAC__ASSERT(0 != br->buffer);
  87384. k = FLAC__bitmath_ilog2(parameter);
  87385. /* read the unary MSBs and end bit */
  87386. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  87387. return false;
  87388. /* read the binary LSBs */
  87389. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  87390. return false;
  87391. if(parameter == 1u<<k) {
  87392. /* compose the value */
  87393. *val = (msbs << k) | lsbs;
  87394. }
  87395. else {
  87396. unsigned d = (1 << (k+1)) - parameter;
  87397. if(lsbs >= d) {
  87398. if(!FLAC__bitreader_read_bit(br, &bit))
  87399. return false;
  87400. lsbs <<= 1;
  87401. lsbs |= bit;
  87402. lsbs -= d;
  87403. }
  87404. /* compose the value */
  87405. *val = msbs * parameter + lsbs;
  87406. }
  87407. return true;
  87408. }
  87409. #endif /* UNUSED */
  87410. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  87411. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  87412. {
  87413. FLAC__uint32 v = 0;
  87414. FLAC__uint32 x;
  87415. unsigned i;
  87416. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87417. return false;
  87418. if(raw)
  87419. raw[(*rawlen)++] = (FLAC__byte)x;
  87420. if(!(x & 0x80)) { /* 0xxxxxxx */
  87421. v = x;
  87422. i = 0;
  87423. }
  87424. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  87425. v = x & 0x1F;
  87426. i = 1;
  87427. }
  87428. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  87429. v = x & 0x0F;
  87430. i = 2;
  87431. }
  87432. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  87433. v = x & 0x07;
  87434. i = 3;
  87435. }
  87436. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  87437. v = x & 0x03;
  87438. i = 4;
  87439. }
  87440. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  87441. v = x & 0x01;
  87442. i = 5;
  87443. }
  87444. else {
  87445. *val = 0xffffffff;
  87446. return true;
  87447. }
  87448. for( ; i; i--) {
  87449. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87450. return false;
  87451. if(raw)
  87452. raw[(*rawlen)++] = (FLAC__byte)x;
  87453. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  87454. *val = 0xffffffff;
  87455. return true;
  87456. }
  87457. v <<= 6;
  87458. v |= (x & 0x3F);
  87459. }
  87460. *val = v;
  87461. return true;
  87462. }
  87463. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  87464. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  87465. {
  87466. FLAC__uint64 v = 0;
  87467. FLAC__uint32 x;
  87468. unsigned i;
  87469. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87470. return false;
  87471. if(raw)
  87472. raw[(*rawlen)++] = (FLAC__byte)x;
  87473. if(!(x & 0x80)) { /* 0xxxxxxx */
  87474. v = x;
  87475. i = 0;
  87476. }
  87477. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  87478. v = x & 0x1F;
  87479. i = 1;
  87480. }
  87481. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  87482. v = x & 0x0F;
  87483. i = 2;
  87484. }
  87485. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  87486. v = x & 0x07;
  87487. i = 3;
  87488. }
  87489. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  87490. v = x & 0x03;
  87491. i = 4;
  87492. }
  87493. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  87494. v = x & 0x01;
  87495. i = 5;
  87496. }
  87497. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  87498. v = 0;
  87499. i = 6;
  87500. }
  87501. else {
  87502. *val = FLAC__U64L(0xffffffffffffffff);
  87503. return true;
  87504. }
  87505. for( ; i; i--) {
  87506. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87507. return false;
  87508. if(raw)
  87509. raw[(*rawlen)++] = (FLAC__byte)x;
  87510. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  87511. *val = FLAC__U64L(0xffffffffffffffff);
  87512. return true;
  87513. }
  87514. v <<= 6;
  87515. v |= (x & 0x3F);
  87516. }
  87517. *val = v;
  87518. return true;
  87519. }
  87520. #endif
  87521. /********* End of inlined file: bitreader.c *********/
  87522. /********* Start of inlined file: bitwriter.c *********/
  87523. /********* Start of inlined file: juce_FlacHeader.h *********/
  87524. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87525. // tasks..
  87526. #define VERSION "1.2.1"
  87527. #define FLAC__NO_DLL 1
  87528. #ifdef _MSC_VER
  87529. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87530. #endif
  87531. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87532. #define FLAC__SYS_DARWIN 1
  87533. #endif
  87534. /********* End of inlined file: juce_FlacHeader.h *********/
  87535. #if JUCE_USE_FLAC
  87536. #if HAVE_CONFIG_H
  87537. # include <config.h>
  87538. #endif
  87539. #include <stdlib.h> /* for malloc() */
  87540. #include <string.h> /* for memcpy(), memset() */
  87541. #ifdef _MSC_VER
  87542. #include <winsock.h> /* for ntohl() */
  87543. #elif defined FLAC__SYS_DARWIN
  87544. #include <machine/endian.h> /* for ntohl() */
  87545. #elif defined __MINGW32__
  87546. #include <winsock.h> /* for ntohl() */
  87547. #else
  87548. #include <netinet/in.h> /* for ntohl() */
  87549. #endif
  87550. #if 0 /* UNUSED */
  87551. #endif
  87552. /********* Start of inlined file: bitwriter.h *********/
  87553. #ifndef FLAC__PRIVATE__BITWRITER_H
  87554. #define FLAC__PRIVATE__BITWRITER_H
  87555. #include <stdio.h> /* for FILE */
  87556. /*
  87557. * opaque structure definition
  87558. */
  87559. struct FLAC__BitWriter;
  87560. typedef struct FLAC__BitWriter FLAC__BitWriter;
  87561. /*
  87562. * construction, deletion, initialization, etc functions
  87563. */
  87564. FLAC__BitWriter *FLAC__bitwriter_new(void);
  87565. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  87566. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  87567. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  87568. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  87569. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  87570. /*
  87571. * CRC functions
  87572. *
  87573. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  87574. */
  87575. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  87576. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  87577. /*
  87578. * info functions
  87579. */
  87580. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  87581. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  87582. /*
  87583. * direct buffer access
  87584. *
  87585. * there may be no calls on the bitwriter between get and release.
  87586. * the bitwriter continues to own the returned buffer.
  87587. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  87588. */
  87589. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  87590. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  87591. /*
  87592. * write functions
  87593. */
  87594. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  87595. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  87596. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  87597. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  87598. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  87599. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  87600. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  87601. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  87602. #if 0 /* UNUSED */
  87603. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  87604. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  87605. #endif
  87606. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  87607. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  87608. #if 0 /* UNUSED */
  87609. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  87610. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  87611. #endif
  87612. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  87613. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  87614. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  87615. #endif
  87616. /********* End of inlined file: bitwriter.h *********/
  87617. /********* Start of inlined file: alloc.h *********/
  87618. #ifndef FLAC__SHARE__ALLOC_H
  87619. #define FLAC__SHARE__ALLOC_H
  87620. #if HAVE_CONFIG_H
  87621. # include <config.h>
  87622. #endif
  87623. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  87624. * before #including this file, otherwise SIZE_MAX might not be defined
  87625. */
  87626. #include <limits.h> /* for SIZE_MAX */
  87627. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  87628. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  87629. #endif
  87630. #include <stdlib.h> /* for size_t, malloc(), etc */
  87631. #ifndef SIZE_MAX
  87632. # ifndef SIZE_T_MAX
  87633. # ifdef _MSC_VER
  87634. # define SIZE_T_MAX UINT_MAX
  87635. # else
  87636. # error
  87637. # endif
  87638. # endif
  87639. # define SIZE_MAX SIZE_T_MAX
  87640. #endif
  87641. #ifndef FLaC__INLINE
  87642. #define FLaC__INLINE
  87643. #endif
  87644. /* avoid malloc()ing 0 bytes, see:
  87645. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  87646. */
  87647. static FLaC__INLINE void *safe_malloc_(size_t size)
  87648. {
  87649. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87650. if(!size)
  87651. size++;
  87652. return malloc(size);
  87653. }
  87654. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  87655. {
  87656. if(!nmemb || !size)
  87657. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87658. return calloc(nmemb, size);
  87659. }
  87660. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  87661. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  87662. {
  87663. size2 += size1;
  87664. if(size2 < size1)
  87665. return 0;
  87666. return safe_malloc_(size2);
  87667. }
  87668. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  87669. {
  87670. size2 += size1;
  87671. if(size2 < size1)
  87672. return 0;
  87673. size3 += size2;
  87674. if(size3 < size2)
  87675. return 0;
  87676. return safe_malloc_(size3);
  87677. }
  87678. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  87679. {
  87680. size2 += size1;
  87681. if(size2 < size1)
  87682. return 0;
  87683. size3 += size2;
  87684. if(size3 < size2)
  87685. return 0;
  87686. size4 += size3;
  87687. if(size4 < size3)
  87688. return 0;
  87689. return safe_malloc_(size4);
  87690. }
  87691. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  87692. #if 0
  87693. needs support for cases where sizeof(size_t) != 4
  87694. {
  87695. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  87696. if(sizeof(size_t) == 4) {
  87697. if ((double)size1 * (double)size2 < 4294967296.0)
  87698. return malloc(size1*size2);
  87699. }
  87700. return 0;
  87701. }
  87702. #else
  87703. /* better? */
  87704. {
  87705. if(!size1 || !size2)
  87706. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87707. if(size1 > SIZE_MAX / size2)
  87708. return 0;
  87709. return malloc(size1*size2);
  87710. }
  87711. #endif
  87712. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  87713. {
  87714. if(!size1 || !size2 || !size3)
  87715. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87716. if(size1 > SIZE_MAX / size2)
  87717. return 0;
  87718. size1 *= size2;
  87719. if(size1 > SIZE_MAX / size3)
  87720. return 0;
  87721. return malloc(size1*size3);
  87722. }
  87723. /* size1*size2 + size3 */
  87724. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  87725. {
  87726. if(!size1 || !size2)
  87727. return safe_malloc_(size3);
  87728. if(size1 > SIZE_MAX / size2)
  87729. return 0;
  87730. return safe_malloc_add_2op_(size1*size2, size3);
  87731. }
  87732. /* size1 * (size2 + size3) */
  87733. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  87734. {
  87735. if(!size1 || (!size2 && !size3))
  87736. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87737. size2 += size3;
  87738. if(size2 < size3)
  87739. return 0;
  87740. return safe_malloc_mul_2op_(size1, size2);
  87741. }
  87742. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  87743. {
  87744. size2 += size1;
  87745. if(size2 < size1)
  87746. return 0;
  87747. return realloc(ptr, size2);
  87748. }
  87749. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  87750. {
  87751. size2 += size1;
  87752. if(size2 < size1)
  87753. return 0;
  87754. size3 += size2;
  87755. if(size3 < size2)
  87756. return 0;
  87757. return realloc(ptr, size3);
  87758. }
  87759. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  87760. {
  87761. size2 += size1;
  87762. if(size2 < size1)
  87763. return 0;
  87764. size3 += size2;
  87765. if(size3 < size2)
  87766. return 0;
  87767. size4 += size3;
  87768. if(size4 < size3)
  87769. return 0;
  87770. return realloc(ptr, size4);
  87771. }
  87772. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  87773. {
  87774. if(!size1 || !size2)
  87775. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  87776. if(size1 > SIZE_MAX / size2)
  87777. return 0;
  87778. return realloc(ptr, size1*size2);
  87779. }
  87780. /* size1 * (size2 + size3) */
  87781. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  87782. {
  87783. if(!size1 || (!size2 && !size3))
  87784. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  87785. size2 += size3;
  87786. if(size2 < size3)
  87787. return 0;
  87788. return safe_realloc_mul_2op_(ptr, size1, size2);
  87789. }
  87790. #endif
  87791. /********* End of inlined file: alloc.h *********/
  87792. /* Things should be fastest when this matches the machine word size */
  87793. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  87794. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  87795. typedef FLAC__uint32 bwword;
  87796. #define FLAC__BYTES_PER_WORD 4
  87797. #define FLAC__BITS_PER_WORD 32
  87798. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87799. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  87800. #if WORDS_BIGENDIAN
  87801. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87802. #else
  87803. #ifdef _MSC_VER
  87804. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87805. #else
  87806. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87807. #endif
  87808. #endif
  87809. /*
  87810. * The default capacity here doesn't matter too much. The buffer always grows
  87811. * to hold whatever is written to it. Usually the encoder will stop adding at
  87812. * a frame or metadata block, then write that out and clear the buffer for the
  87813. * next one.
  87814. */
  87815. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  87816. /* When growing, increment 4K at a time */
  87817. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  87818. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  87819. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  87820. #ifdef min
  87821. #undef min
  87822. #endif
  87823. #define min(x,y) ((x)<(y)?(x):(y))
  87824. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87825. #ifdef _MSC_VER
  87826. #define FLAC__U64L(x) x
  87827. #else
  87828. #define FLAC__U64L(x) x##LLU
  87829. #endif
  87830. #ifndef FLaC__INLINE
  87831. #define FLaC__INLINE
  87832. #endif
  87833. struct FLAC__BitWriter {
  87834. bwword *buffer;
  87835. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  87836. unsigned capacity; /* capacity of buffer in words */
  87837. unsigned words; /* # of complete words in buffer */
  87838. unsigned bits; /* # of used bits in accum */
  87839. };
  87840. /* * WATCHOUT: The current implementation only grows the buffer. */
  87841. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  87842. {
  87843. unsigned new_capacity;
  87844. bwword *new_buffer;
  87845. FLAC__ASSERT(0 != bw);
  87846. FLAC__ASSERT(0 != bw->buffer);
  87847. /* calculate total words needed to store 'bits_to_add' additional bits */
  87848. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  87849. /* it's possible (due to pessimism in the growth estimation that
  87850. * leads to this call) that we don't actually need to grow
  87851. */
  87852. if(bw->capacity >= new_capacity)
  87853. return true;
  87854. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  87855. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  87856. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  87857. /* make sure we got everything right */
  87858. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  87859. FLAC__ASSERT(new_capacity > bw->capacity);
  87860. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  87861. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  87862. if(new_buffer == 0)
  87863. return false;
  87864. bw->buffer = new_buffer;
  87865. bw->capacity = new_capacity;
  87866. return true;
  87867. }
  87868. /***********************************************************************
  87869. *
  87870. * Class constructor/destructor
  87871. *
  87872. ***********************************************************************/
  87873. FLAC__BitWriter *FLAC__bitwriter_new(void)
  87874. {
  87875. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  87876. /* note that calloc() sets all members to 0 for us */
  87877. return bw;
  87878. }
  87879. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  87880. {
  87881. FLAC__ASSERT(0 != bw);
  87882. FLAC__bitwriter_free(bw);
  87883. free(bw);
  87884. }
  87885. /***********************************************************************
  87886. *
  87887. * Public class methods
  87888. *
  87889. ***********************************************************************/
  87890. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  87891. {
  87892. FLAC__ASSERT(0 != bw);
  87893. bw->words = bw->bits = 0;
  87894. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  87895. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  87896. if(bw->buffer == 0)
  87897. return false;
  87898. return true;
  87899. }
  87900. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  87901. {
  87902. FLAC__ASSERT(0 != bw);
  87903. if(0 != bw->buffer)
  87904. free(bw->buffer);
  87905. bw->buffer = 0;
  87906. bw->capacity = 0;
  87907. bw->words = bw->bits = 0;
  87908. }
  87909. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  87910. {
  87911. bw->words = bw->bits = 0;
  87912. }
  87913. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  87914. {
  87915. unsigned i, j;
  87916. if(bw == 0) {
  87917. fprintf(out, "bitwriter is NULL\n");
  87918. }
  87919. else {
  87920. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  87921. for(i = 0; i < bw->words; i++) {
  87922. fprintf(out, "%08X: ", i);
  87923. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  87924. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  87925. fprintf(out, "\n");
  87926. }
  87927. if(bw->bits > 0) {
  87928. fprintf(out, "%08X: ", i);
  87929. for(j = 0; j < bw->bits; j++)
  87930. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  87931. fprintf(out, "\n");
  87932. }
  87933. }
  87934. }
  87935. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  87936. {
  87937. const FLAC__byte *buffer;
  87938. size_t bytes;
  87939. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  87940. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  87941. return false;
  87942. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  87943. FLAC__bitwriter_release_buffer(bw);
  87944. return true;
  87945. }
  87946. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  87947. {
  87948. const FLAC__byte *buffer;
  87949. size_t bytes;
  87950. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  87951. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  87952. return false;
  87953. *crc = FLAC__crc8(buffer, bytes);
  87954. FLAC__bitwriter_release_buffer(bw);
  87955. return true;
  87956. }
  87957. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  87958. {
  87959. return ((bw->bits & 7) == 0);
  87960. }
  87961. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  87962. {
  87963. return FLAC__TOTAL_BITS(bw);
  87964. }
  87965. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  87966. {
  87967. FLAC__ASSERT((bw->bits & 7) == 0);
  87968. /* double protection */
  87969. if(bw->bits & 7)
  87970. return false;
  87971. /* if we have bits in the accumulator we have to flush those to the buffer first */
  87972. if(bw->bits) {
  87973. FLAC__ASSERT(bw->words <= bw->capacity);
  87974. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  87975. return false;
  87976. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  87977. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  87978. }
  87979. /* now we can just return what we have */
  87980. *buffer = (FLAC__byte*)bw->buffer;
  87981. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  87982. return true;
  87983. }
  87984. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  87985. {
  87986. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  87987. * get-mode' flag could be added everywhere and then cleared here
  87988. */
  87989. (void)bw;
  87990. }
  87991. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  87992. {
  87993. unsigned n;
  87994. FLAC__ASSERT(0 != bw);
  87995. FLAC__ASSERT(0 != bw->buffer);
  87996. if(bits == 0)
  87997. return true;
  87998. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  87999. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88000. return false;
  88001. /* first part gets to word alignment */
  88002. if(bw->bits) {
  88003. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  88004. bw->accum <<= n;
  88005. bits -= n;
  88006. bw->bits += n;
  88007. if(bw->bits == FLAC__BITS_PER_WORD) {
  88008. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88009. bw->bits = 0;
  88010. }
  88011. else
  88012. return true;
  88013. }
  88014. /* do whole words */
  88015. while(bits >= FLAC__BITS_PER_WORD) {
  88016. bw->buffer[bw->words++] = 0;
  88017. bits -= FLAC__BITS_PER_WORD;
  88018. }
  88019. /* do any leftovers */
  88020. if(bits > 0) {
  88021. bw->accum = 0;
  88022. bw->bits = bits;
  88023. }
  88024. return true;
  88025. }
  88026. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  88027. {
  88028. register unsigned left;
  88029. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88030. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88031. FLAC__ASSERT(0 != bw);
  88032. FLAC__ASSERT(0 != bw->buffer);
  88033. FLAC__ASSERT(bits <= 32);
  88034. if(bits == 0)
  88035. return true;
  88036. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88037. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88038. return false;
  88039. left = FLAC__BITS_PER_WORD - bw->bits;
  88040. if(bits < left) {
  88041. bw->accum <<= bits;
  88042. bw->accum |= val;
  88043. bw->bits += bits;
  88044. }
  88045. else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
  88046. bw->accum <<= left;
  88047. bw->accum |= val >> (bw->bits = bits - left);
  88048. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88049. bw->accum = val;
  88050. }
  88051. else {
  88052. bw->accum = val;
  88053. bw->bits = 0;
  88054. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  88055. }
  88056. return true;
  88057. }
  88058. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  88059. {
  88060. /* zero-out unused bits */
  88061. if(bits < 32)
  88062. val &= (~(0xffffffff << bits));
  88063. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88064. }
  88065. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  88066. {
  88067. /* this could be a little faster but it's not used for much */
  88068. if(bits > 32) {
  88069. return
  88070. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  88071. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  88072. }
  88073. else
  88074. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88075. }
  88076. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  88077. {
  88078. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88079. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  88080. return false;
  88081. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  88082. return false;
  88083. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  88084. return false;
  88085. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  88086. return false;
  88087. return true;
  88088. }
  88089. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  88090. {
  88091. unsigned i;
  88092. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  88093. for(i = 0; i < nvals; i++) {
  88094. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  88095. return false;
  88096. }
  88097. return true;
  88098. }
  88099. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  88100. {
  88101. if(val < 32)
  88102. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  88103. else
  88104. return
  88105. FLAC__bitwriter_write_zeroes(bw, val) &&
  88106. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  88107. }
  88108. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  88109. {
  88110. FLAC__uint32 uval;
  88111. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  88112. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88113. uval = (val<<1) ^ (val>>31);
  88114. return 1 + parameter + (uval >> parameter);
  88115. }
  88116. #if 0 /* UNUSED */
  88117. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  88118. {
  88119. unsigned bits, msbs, uval;
  88120. unsigned k;
  88121. FLAC__ASSERT(parameter > 0);
  88122. /* fold signed to unsigned */
  88123. if(val < 0)
  88124. uval = (unsigned)(((-(++val)) << 1) + 1);
  88125. else
  88126. uval = (unsigned)(val << 1);
  88127. k = FLAC__bitmath_ilog2(parameter);
  88128. if(parameter == 1u<<k) {
  88129. FLAC__ASSERT(k <= 30);
  88130. msbs = uval >> k;
  88131. bits = 1 + k + msbs;
  88132. }
  88133. else {
  88134. unsigned q, r, d;
  88135. d = (1 << (k+1)) - parameter;
  88136. q = uval / parameter;
  88137. r = uval - (q * parameter);
  88138. bits = 1 + q + k;
  88139. if(r >= d)
  88140. bits++;
  88141. }
  88142. return bits;
  88143. }
  88144. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  88145. {
  88146. unsigned bits, msbs;
  88147. unsigned k;
  88148. FLAC__ASSERT(parameter > 0);
  88149. k = FLAC__bitmath_ilog2(parameter);
  88150. if(parameter == 1u<<k) {
  88151. FLAC__ASSERT(k <= 30);
  88152. msbs = uval >> k;
  88153. bits = 1 + k + msbs;
  88154. }
  88155. else {
  88156. unsigned q, r, d;
  88157. d = (1 << (k+1)) - parameter;
  88158. q = uval / parameter;
  88159. r = uval - (q * parameter);
  88160. bits = 1 + q + k;
  88161. if(r >= d)
  88162. bits++;
  88163. }
  88164. return bits;
  88165. }
  88166. #endif /* UNUSED */
  88167. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  88168. {
  88169. unsigned total_bits, interesting_bits, msbs;
  88170. FLAC__uint32 uval, pattern;
  88171. FLAC__ASSERT(0 != bw);
  88172. FLAC__ASSERT(0 != bw->buffer);
  88173. FLAC__ASSERT(parameter < 8*sizeof(uval));
  88174. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88175. uval = (val<<1) ^ (val>>31);
  88176. msbs = uval >> parameter;
  88177. interesting_bits = 1 + parameter;
  88178. total_bits = interesting_bits + msbs;
  88179. pattern = 1 << parameter; /* the unary end bit */
  88180. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  88181. if(total_bits <= 32)
  88182. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  88183. else
  88184. return
  88185. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  88186. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  88187. }
  88188. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  88189. {
  88190. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  88191. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  88192. FLAC__uint32 uval;
  88193. unsigned left;
  88194. const unsigned lsbits = 1 + parameter;
  88195. unsigned msbits;
  88196. FLAC__ASSERT(0 != bw);
  88197. FLAC__ASSERT(0 != bw->buffer);
  88198. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  88199. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88200. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88201. while(nvals) {
  88202. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88203. uval = (*vals<<1) ^ (*vals>>31);
  88204. msbits = uval >> parameter;
  88205. #if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */
  88206. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88207. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88208. bw->bits = bw->bits + msbits + lsbits;
  88209. uval |= mask1; /* set stop bit */
  88210. uval &= mask2; /* mask off unused top bits */
  88211. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  88212. bw->accum <<= msbits;
  88213. bw->accum <<= lsbits;
  88214. bw->accum |= uval;
  88215. if(bw->bits == FLAC__BITS_PER_WORD) {
  88216. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88217. bw->bits = 0;
  88218. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  88219. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  88220. FLAC__ASSERT(bw->capacity == bw->words);
  88221. return false;
  88222. }
  88223. }
  88224. }
  88225. else {
  88226. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  88227. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88228. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88229. bw->bits = bw->bits + msbits + lsbits;
  88230. uval |= mask1; /* set stop bit */
  88231. uval &= mask2; /* mask off unused top bits */
  88232. bw->accum <<= msbits + lsbits;
  88233. bw->accum |= uval;
  88234. }
  88235. else {
  88236. #endif
  88237. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88238. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  88239. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  88240. return false;
  88241. if(msbits) {
  88242. /* first part gets to word alignment */
  88243. if(bw->bits) {
  88244. left = FLAC__BITS_PER_WORD - bw->bits;
  88245. if(msbits < left) {
  88246. bw->accum <<= msbits;
  88247. bw->bits += msbits;
  88248. goto break1;
  88249. }
  88250. else {
  88251. bw->accum <<= left;
  88252. msbits -= left;
  88253. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88254. bw->bits = 0;
  88255. }
  88256. }
  88257. /* do whole words */
  88258. while(msbits >= FLAC__BITS_PER_WORD) {
  88259. bw->buffer[bw->words++] = 0;
  88260. msbits -= FLAC__BITS_PER_WORD;
  88261. }
  88262. /* do any leftovers */
  88263. if(msbits > 0) {
  88264. bw->accum = 0;
  88265. bw->bits = msbits;
  88266. }
  88267. }
  88268. break1:
  88269. uval |= mask1; /* set stop bit */
  88270. uval &= mask2; /* mask off unused top bits */
  88271. left = FLAC__BITS_PER_WORD - bw->bits;
  88272. if(lsbits < left) {
  88273. bw->accum <<= lsbits;
  88274. bw->accum |= uval;
  88275. bw->bits += lsbits;
  88276. }
  88277. else {
  88278. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  88279. * be > lsbits (because of previous assertions) so it would have
  88280. * triggered the (lsbits<left) case above.
  88281. */
  88282. FLAC__ASSERT(bw->bits);
  88283. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  88284. bw->accum <<= left;
  88285. bw->accum |= uval >> (bw->bits = lsbits - left);
  88286. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88287. bw->accum = uval;
  88288. }
  88289. #if 1
  88290. }
  88291. #endif
  88292. vals++;
  88293. nvals--;
  88294. }
  88295. return true;
  88296. }
  88297. #if 0 /* UNUSED */
  88298. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  88299. {
  88300. unsigned total_bits, msbs, uval;
  88301. unsigned k;
  88302. FLAC__ASSERT(0 != bw);
  88303. FLAC__ASSERT(0 != bw->buffer);
  88304. FLAC__ASSERT(parameter > 0);
  88305. /* fold signed to unsigned */
  88306. if(val < 0)
  88307. uval = (unsigned)(((-(++val)) << 1) + 1);
  88308. else
  88309. uval = (unsigned)(val << 1);
  88310. k = FLAC__bitmath_ilog2(parameter);
  88311. if(parameter == 1u<<k) {
  88312. unsigned pattern;
  88313. FLAC__ASSERT(k <= 30);
  88314. msbs = uval >> k;
  88315. total_bits = 1 + k + msbs;
  88316. pattern = 1 << k; /* the unary end bit */
  88317. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  88318. if(total_bits <= 32) {
  88319. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  88320. return false;
  88321. }
  88322. else {
  88323. /* write the unary MSBs */
  88324. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  88325. return false;
  88326. /* write the unary end bit and binary LSBs */
  88327. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  88328. return false;
  88329. }
  88330. }
  88331. else {
  88332. unsigned q, r, d;
  88333. d = (1 << (k+1)) - parameter;
  88334. q = uval / parameter;
  88335. r = uval - (q * parameter);
  88336. /* write the unary MSBs */
  88337. if(!FLAC__bitwriter_write_zeroes(bw, q))
  88338. return false;
  88339. /* write the unary end bit */
  88340. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  88341. return false;
  88342. /* write the binary LSBs */
  88343. if(r >= d) {
  88344. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  88345. return false;
  88346. }
  88347. else {
  88348. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  88349. return false;
  88350. }
  88351. }
  88352. return true;
  88353. }
  88354. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  88355. {
  88356. unsigned total_bits, msbs;
  88357. unsigned k;
  88358. FLAC__ASSERT(0 != bw);
  88359. FLAC__ASSERT(0 != bw->buffer);
  88360. FLAC__ASSERT(parameter > 0);
  88361. k = FLAC__bitmath_ilog2(parameter);
  88362. if(parameter == 1u<<k) {
  88363. unsigned pattern;
  88364. FLAC__ASSERT(k <= 30);
  88365. msbs = uval >> k;
  88366. total_bits = 1 + k + msbs;
  88367. pattern = 1 << k; /* the unary end bit */
  88368. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  88369. if(total_bits <= 32) {
  88370. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  88371. return false;
  88372. }
  88373. else {
  88374. /* write the unary MSBs */
  88375. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  88376. return false;
  88377. /* write the unary end bit and binary LSBs */
  88378. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  88379. return false;
  88380. }
  88381. }
  88382. else {
  88383. unsigned q, r, d;
  88384. d = (1 << (k+1)) - parameter;
  88385. q = uval / parameter;
  88386. r = uval - (q * parameter);
  88387. /* write the unary MSBs */
  88388. if(!FLAC__bitwriter_write_zeroes(bw, q))
  88389. return false;
  88390. /* write the unary end bit */
  88391. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  88392. return false;
  88393. /* write the binary LSBs */
  88394. if(r >= d) {
  88395. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  88396. return false;
  88397. }
  88398. else {
  88399. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  88400. return false;
  88401. }
  88402. }
  88403. return true;
  88404. }
  88405. #endif /* UNUSED */
  88406. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  88407. {
  88408. FLAC__bool ok = 1;
  88409. FLAC__ASSERT(0 != bw);
  88410. FLAC__ASSERT(0 != bw->buffer);
  88411. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  88412. if(val < 0x80) {
  88413. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  88414. }
  88415. else if(val < 0x800) {
  88416. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  88417. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88418. }
  88419. else if(val < 0x10000) {
  88420. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  88421. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88422. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88423. }
  88424. else if(val < 0x200000) {
  88425. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  88426. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88427. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88428. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88429. }
  88430. else if(val < 0x4000000) {
  88431. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  88432. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  88433. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88434. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88435. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88436. }
  88437. else {
  88438. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  88439. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  88440. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  88441. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88442. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88443. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88444. }
  88445. return ok;
  88446. }
  88447. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  88448. {
  88449. FLAC__bool ok = 1;
  88450. FLAC__ASSERT(0 != bw);
  88451. FLAC__ASSERT(0 != bw->buffer);
  88452. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  88453. if(val < 0x80) {
  88454. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  88455. }
  88456. else if(val < 0x800) {
  88457. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  88458. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88459. }
  88460. else if(val < 0x10000) {
  88461. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  88462. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88463. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88464. }
  88465. else if(val < 0x200000) {
  88466. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  88467. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88468. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88469. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88470. }
  88471. else if(val < 0x4000000) {
  88472. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  88473. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88474. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88475. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88476. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88477. }
  88478. else if(val < 0x80000000) {
  88479. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  88480. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  88481. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88482. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88483. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88484. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88485. }
  88486. else {
  88487. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  88488. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  88489. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  88490. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88491. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88492. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88493. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88494. }
  88495. return ok;
  88496. }
  88497. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  88498. {
  88499. /* 0-pad to byte boundary */
  88500. if(bw->bits & 7u)
  88501. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  88502. else
  88503. return true;
  88504. }
  88505. #endif
  88506. /********* End of inlined file: bitwriter.c *********/
  88507. /********* Start of inlined file: cpu.c *********/
  88508. /********* Start of inlined file: juce_FlacHeader.h *********/
  88509. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88510. // tasks..
  88511. #define VERSION "1.2.1"
  88512. #define FLAC__NO_DLL 1
  88513. #ifdef _MSC_VER
  88514. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88515. #endif
  88516. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88517. #define FLAC__SYS_DARWIN 1
  88518. #endif
  88519. /********* End of inlined file: juce_FlacHeader.h *********/
  88520. #if JUCE_USE_FLAC
  88521. #if HAVE_CONFIG_H
  88522. # include <config.h>
  88523. #endif
  88524. #include <stdlib.h>
  88525. #include <stdio.h>
  88526. #if defined FLAC__CPU_IA32
  88527. # include <signal.h>
  88528. #elif defined FLAC__CPU_PPC
  88529. # if !defined FLAC__NO_ASM
  88530. # if defined FLAC__SYS_DARWIN
  88531. # include <sys/sysctl.h>
  88532. # include <mach/mach.h>
  88533. # include <mach/mach_host.h>
  88534. # include <mach/host_info.h>
  88535. # include <mach/machine.h>
  88536. # ifndef CPU_SUBTYPE_POWERPC_970
  88537. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  88538. # endif
  88539. # else /* FLAC__SYS_DARWIN */
  88540. # include <signal.h>
  88541. # include <setjmp.h>
  88542. static sigjmp_buf jmpbuf;
  88543. static volatile sig_atomic_t canjump = 0;
  88544. static void sigill_handler (int sig)
  88545. {
  88546. if (!canjump) {
  88547. signal (sig, SIG_DFL);
  88548. raise (sig);
  88549. }
  88550. canjump = 0;
  88551. siglongjmp (jmpbuf, 1);
  88552. }
  88553. # endif /* FLAC__SYS_DARWIN */
  88554. # endif /* FLAC__NO_ASM */
  88555. #endif /* FLAC__CPU_PPC */
  88556. #if defined (__NetBSD__) || defined(__OpenBSD__)
  88557. #include <sys/param.h>
  88558. #include <sys/sysctl.h>
  88559. #include <machine/cpu.h>
  88560. #endif
  88561. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  88562. #include <sys/types.h>
  88563. #include <sys/sysctl.h>
  88564. #endif
  88565. #if defined(__APPLE__)
  88566. /* how to get sysctlbyname()? */
  88567. #endif
  88568. /* these are flags in EDX of CPUID AX=00000001 */
  88569. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  88570. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  88571. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  88572. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  88573. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  88574. /* these are flags in ECX of CPUID AX=00000001 */
  88575. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  88576. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  88577. /* these are flags in EDX of CPUID AX=80000001 */
  88578. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  88579. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  88580. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  88581. /*
  88582. * Extra stuff needed for detection of OS support for SSE on IA-32
  88583. */
  88584. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  88585. # if defined(__linux__)
  88586. /*
  88587. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  88588. * modify the return address to jump over the offending SSE instruction
  88589. * and also the operation following it that indicates the instruction
  88590. * executed successfully. In this way we use no global variables and
  88591. * stay thread-safe.
  88592. *
  88593. * 3 + 3 + 6:
  88594. * 3 bytes for "xorps xmm0,xmm0"
  88595. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  88596. * 6 bytes extra in case our estimate is wrong
  88597. * 12 bytes puts us in the NOP "landing zone"
  88598. */
  88599. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  88600. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  88601. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  88602. {
  88603. (void)signal;
  88604. sc.eip += 3 + 3 + 6;
  88605. }
  88606. # else
  88607. # include <sys/ucontext.h>
  88608. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  88609. {
  88610. (void)signal, (void)si;
  88611. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  88612. }
  88613. # endif
  88614. # elif defined(_MSC_VER)
  88615. # include <windows.h>
  88616. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  88617. # ifdef USE_TRY_CATCH_FLAVOR
  88618. # else
  88619. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  88620. {
  88621. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  88622. ep->ContextRecord->Eip += 3 + 3 + 6;
  88623. return EXCEPTION_CONTINUE_EXECUTION;
  88624. }
  88625. return EXCEPTION_CONTINUE_SEARCH;
  88626. }
  88627. # endif
  88628. # endif
  88629. #endif
  88630. void FLAC__cpu_info(FLAC__CPUInfo *info)
  88631. {
  88632. /*
  88633. * IA32-specific
  88634. */
  88635. #ifdef FLAC__CPU_IA32
  88636. info->type = FLAC__CPUINFO_TYPE_IA32;
  88637. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  88638. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  88639. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  88640. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  88641. info->data.ia32.cmov = false;
  88642. info->data.ia32.mmx = false;
  88643. info->data.ia32.fxsr = false;
  88644. info->data.ia32.sse = false;
  88645. info->data.ia32.sse2 = false;
  88646. info->data.ia32.sse3 = false;
  88647. info->data.ia32.ssse3 = false;
  88648. info->data.ia32._3dnow = false;
  88649. info->data.ia32.ext3dnow = false;
  88650. info->data.ia32.extmmx = false;
  88651. if(info->data.ia32.cpuid) {
  88652. /* http://www.sandpile.org/ia32/cpuid.htm */
  88653. FLAC__uint32 flags_edx, flags_ecx;
  88654. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  88655. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  88656. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  88657. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  88658. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  88659. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  88660. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  88661. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  88662. #ifdef FLAC__USE_3DNOW
  88663. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  88664. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  88665. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  88666. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  88667. #else
  88668. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  88669. #endif
  88670. #ifdef DEBUG
  88671. fprintf(stderr, "CPU info (IA-32):\n");
  88672. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  88673. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  88674. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  88675. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  88676. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  88677. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  88678. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  88679. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  88680. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  88681. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  88682. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  88683. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  88684. #endif
  88685. /*
  88686. * now have to check for OS support of SSE/SSE2
  88687. */
  88688. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  88689. #if defined FLAC__NO_SSE_OS
  88690. /* assume user knows better than us; turn it off */
  88691. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88692. #elif defined FLAC__SSE_OS
  88693. /* assume user knows better than us; leave as detected above */
  88694. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  88695. int sse = 0;
  88696. size_t len;
  88697. /* at least one of these must work: */
  88698. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  88699. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  88700. if(!sse)
  88701. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88702. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  88703. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  88704. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  88705. size_t len = sizeof(val);
  88706. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  88707. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88708. else { /* double-check SSE2 */
  88709. mib[1] = CPU_SSE2;
  88710. len = sizeof(val);
  88711. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  88712. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88713. }
  88714. # else
  88715. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88716. # endif
  88717. #elif defined(__linux__)
  88718. int sse = 0;
  88719. struct sigaction sigill_save;
  88720. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  88721. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  88722. #else
  88723. struct sigaction sigill_sse;
  88724. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  88725. __sigemptyset(&sigill_sse.sa_mask);
  88726. sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
  88727. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  88728. #endif
  88729. {
  88730. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  88731. /* see sigill_handler_sse_os() for an explanation of the following: */
  88732. asm volatile (
  88733. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  88734. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  88735. "incl %0\n\t" /* SIGILL handler will jump over this */
  88736. /* landing zone */
  88737. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  88738. "nop\n\t"
  88739. "nop\n\t"
  88740. "nop\n\t"
  88741. "nop\n\t"
  88742. "nop\n\t"
  88743. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  88744. "nop\n\t"
  88745. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  88746. : "=r"(sse)
  88747. : "r"(sse)
  88748. );
  88749. sigaction(SIGILL, &sigill_save, NULL);
  88750. }
  88751. if(!sse)
  88752. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88753. #elif defined(_MSC_VER)
  88754. # ifdef USE_TRY_CATCH_FLAVOR
  88755. _try {
  88756. __asm {
  88757. # if _MSC_VER <= 1200
  88758. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  88759. _emit 0x0F
  88760. _emit 0x57
  88761. _emit 0xC0
  88762. # else
  88763. xorps xmm0,xmm0
  88764. # endif
  88765. }
  88766. }
  88767. _except(EXCEPTION_EXECUTE_HANDLER) {
  88768. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  88769. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88770. }
  88771. # else
  88772. int sse = 0;
  88773. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  88774. /* see GCC version above for explanation */
  88775. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  88776. /* http://www.codeproject.com/cpp/gccasm.asp */
  88777. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  88778. __asm {
  88779. # if _MSC_VER <= 1200
  88780. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  88781. _emit 0x0F
  88782. _emit 0x57
  88783. _emit 0xC0
  88784. # else
  88785. xorps xmm0,xmm0
  88786. # endif
  88787. inc sse
  88788. nop
  88789. nop
  88790. nop
  88791. nop
  88792. nop
  88793. nop
  88794. nop
  88795. nop
  88796. nop
  88797. }
  88798. SetUnhandledExceptionFilter(save);
  88799. if(!sse)
  88800. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88801. # endif
  88802. #else
  88803. /* no way to test, disable to be safe */
  88804. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88805. #endif
  88806. #ifdef DEBUG
  88807. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  88808. #endif
  88809. }
  88810. }
  88811. #else
  88812. info->use_asm = false;
  88813. #endif
  88814. /*
  88815. * PPC-specific
  88816. */
  88817. #elif defined FLAC__CPU_PPC
  88818. info->type = FLAC__CPUINFO_TYPE_PPC;
  88819. # if !defined FLAC__NO_ASM
  88820. info->use_asm = true;
  88821. # ifdef FLAC__USE_ALTIVEC
  88822. # if defined FLAC__SYS_DARWIN
  88823. {
  88824. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  88825. size_t len = sizeof(val);
  88826. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  88827. }
  88828. {
  88829. host_basic_info_data_t hostInfo;
  88830. mach_msg_type_number_t infoCount;
  88831. infoCount = HOST_BASIC_INFO_COUNT;
  88832. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  88833. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  88834. }
  88835. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  88836. {
  88837. /* no Darwin, do it the brute-force way */
  88838. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  88839. info->data.ppc.altivec = 0;
  88840. info->data.ppc.ppc64 = 0;
  88841. signal (SIGILL, sigill_handler);
  88842. canjump = 0;
  88843. if (!sigsetjmp (jmpbuf, 1)) {
  88844. canjump = 1;
  88845. asm volatile (
  88846. "mtspr 256, %0\n\t"
  88847. "vand %%v0, %%v0, %%v0"
  88848. :
  88849. : "r" (-1)
  88850. );
  88851. info->data.ppc.altivec = 1;
  88852. }
  88853. canjump = 0;
  88854. if (!sigsetjmp (jmpbuf, 1)) {
  88855. int x = 0;
  88856. canjump = 1;
  88857. /* PPC64 hardware implements the cntlzd instruction */
  88858. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  88859. info->data.ppc.ppc64 = 1;
  88860. }
  88861. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  88862. }
  88863. # endif
  88864. # else /* !FLAC__USE_ALTIVEC */
  88865. info->data.ppc.altivec = 0;
  88866. info->data.ppc.ppc64 = 0;
  88867. # endif
  88868. # else
  88869. info->use_asm = false;
  88870. # endif
  88871. /*
  88872. * unknown CPI
  88873. */
  88874. #else
  88875. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  88876. info->use_asm = false;
  88877. #endif
  88878. }
  88879. #endif
  88880. /********* End of inlined file: cpu.c *********/
  88881. /********* Start of inlined file: crc.c *********/
  88882. /********* Start of inlined file: juce_FlacHeader.h *********/
  88883. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88884. // tasks..
  88885. #define VERSION "1.2.1"
  88886. #define FLAC__NO_DLL 1
  88887. #ifdef _MSC_VER
  88888. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88889. #endif
  88890. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88891. #define FLAC__SYS_DARWIN 1
  88892. #endif
  88893. /********* End of inlined file: juce_FlacHeader.h *********/
  88894. #if JUCE_USE_FLAC
  88895. #if HAVE_CONFIG_H
  88896. # include <config.h>
  88897. #endif
  88898. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  88899. FLAC__byte const FLAC__crc8_table[256] = {
  88900. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  88901. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  88902. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  88903. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  88904. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  88905. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  88906. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  88907. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  88908. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  88909. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  88910. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  88911. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  88912. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  88913. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  88914. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  88915. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  88916. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  88917. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  88918. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  88919. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  88920. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  88921. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  88922. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  88923. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  88924. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  88925. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  88926. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  88927. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  88928. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  88929. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  88930. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  88931. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  88932. };
  88933. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  88934. unsigned FLAC__crc16_table[256] = {
  88935. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  88936. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  88937. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  88938. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  88939. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  88940. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  88941. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  88942. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  88943. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  88944. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  88945. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  88946. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  88947. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  88948. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  88949. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  88950. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  88951. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  88952. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  88953. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  88954. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  88955. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  88956. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  88957. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  88958. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  88959. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  88960. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  88961. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  88962. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  88963. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  88964. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  88965. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  88966. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  88967. };
  88968. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  88969. {
  88970. *crc = FLAC__crc8_table[*crc ^ data];
  88971. }
  88972. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  88973. {
  88974. while(len--)
  88975. *crc = FLAC__crc8_table[*crc ^ *data++];
  88976. }
  88977. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  88978. {
  88979. FLAC__uint8 crc = 0;
  88980. while(len--)
  88981. crc = FLAC__crc8_table[crc ^ *data++];
  88982. return crc;
  88983. }
  88984. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  88985. {
  88986. unsigned crc = 0;
  88987. while(len--)
  88988. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  88989. return crc;
  88990. }
  88991. #endif
  88992. /********* End of inlined file: crc.c *********/
  88993. /********* Start of inlined file: fixed.c *********/
  88994. /********* Start of inlined file: juce_FlacHeader.h *********/
  88995. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88996. // tasks..
  88997. #define VERSION "1.2.1"
  88998. #define FLAC__NO_DLL 1
  88999. #ifdef _MSC_VER
  89000. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89001. #endif
  89002. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89003. #define FLAC__SYS_DARWIN 1
  89004. #endif
  89005. /********* End of inlined file: juce_FlacHeader.h *********/
  89006. #if JUCE_USE_FLAC
  89007. #if HAVE_CONFIG_H
  89008. # include <config.h>
  89009. #endif
  89010. #include <math.h>
  89011. #include <string.h>
  89012. /********* Start of inlined file: fixed.h *********/
  89013. #ifndef FLAC__PRIVATE__FIXED_H
  89014. #define FLAC__PRIVATE__FIXED_H
  89015. #ifdef HAVE_CONFIG_H
  89016. #include <config.h>
  89017. #endif
  89018. /********* Start of inlined file: float.h *********/
  89019. #ifndef FLAC__PRIVATE__FLOAT_H
  89020. #define FLAC__PRIVATE__FLOAT_H
  89021. #ifdef HAVE_CONFIG_H
  89022. #include <config.h>
  89023. #endif
  89024. /*
  89025. * These typedefs make it easier to ensure that integer versions of
  89026. * the library really only contain integer operations. All the code
  89027. * in libFLAC should use FLAC__float and FLAC__double in place of
  89028. * float and double, and be protected by checks of the macro
  89029. * FLAC__INTEGER_ONLY_LIBRARY.
  89030. *
  89031. * FLAC__real is the basic floating point type used in LPC analysis.
  89032. */
  89033. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89034. typedef double FLAC__double;
  89035. typedef float FLAC__float;
  89036. /*
  89037. * WATCHOUT: changing FLAC__real will change the signatures of many
  89038. * functions that have assembly language equivalents and break them.
  89039. */
  89040. typedef float FLAC__real;
  89041. #else
  89042. /*
  89043. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  89044. * for the integer part and lower 16 bits for the fractional part.
  89045. */
  89046. typedef FLAC__int32 FLAC__fixedpoint;
  89047. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  89048. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  89049. extern const FLAC__fixedpoint FLAC__FP_ONE;
  89050. extern const FLAC__fixedpoint FLAC__FP_LN2;
  89051. extern const FLAC__fixedpoint FLAC__FP_E;
  89052. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  89053. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  89054. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  89055. /*
  89056. * FLAC__fixedpoint_log2()
  89057. * --------------------------------------------------------------------
  89058. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  89059. * algorithm by Knuth for x >= 1.0
  89060. *
  89061. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  89062. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  89063. *
  89064. * 'precision' roughly limits the number of iterations that are done;
  89065. * use (unsigned)(-1) for maximum precision.
  89066. *
  89067. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  89068. * function will punt and return 0.
  89069. *
  89070. * The return value will also have 'fracbits' fractional bits.
  89071. */
  89072. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  89073. #endif
  89074. #endif
  89075. /********* End of inlined file: float.h *********/
  89076. /********* Start of inlined file: format.h *********/
  89077. #ifndef FLAC__PRIVATE__FORMAT_H
  89078. #define FLAC__PRIVATE__FORMAT_H
  89079. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  89080. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  89081. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  89082. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89083. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89084. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  89085. #endif
  89086. /********* End of inlined file: format.h *********/
  89087. /*
  89088. * FLAC__fixed_compute_best_predictor()
  89089. * --------------------------------------------------------------------
  89090. * Compute the best fixed predictor and the expected bits-per-sample
  89091. * of the residual signal for each order. The _wide() version uses
  89092. * 64-bit integers which is statistically necessary when bits-per-
  89093. * sample + log2(blocksize) > 30
  89094. *
  89095. * IN data[0,data_len-1]
  89096. * IN data_len
  89097. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  89098. */
  89099. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89100. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89101. # ifndef FLAC__NO_ASM
  89102. # ifdef FLAC__CPU_IA32
  89103. # ifdef FLAC__HAS_NASM
  89104. unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89105. # endif
  89106. # endif
  89107. # endif
  89108. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89109. #else
  89110. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89111. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89112. #endif
  89113. /*
  89114. * FLAC__fixed_compute_residual()
  89115. * --------------------------------------------------------------------
  89116. * Compute the residual signal obtained from sutracting the predicted
  89117. * signal from the original.
  89118. *
  89119. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  89120. * IN data_len length of original signal
  89121. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89122. * OUT residual[0,data_len-1] residual signal
  89123. */
  89124. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  89125. /*
  89126. * FLAC__fixed_restore_signal()
  89127. * --------------------------------------------------------------------
  89128. * Restore the original signal by summing the residual and the
  89129. * predictor.
  89130. *
  89131. * IN residual[0,data_len-1] residual signal
  89132. * IN data_len length of original signal
  89133. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89134. * *** IMPORTANT: the caller must pass in the historical samples:
  89135. * IN data[-order,-1] previously-reconstructed historical samples
  89136. * OUT data[0,data_len-1] original signal
  89137. */
  89138. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  89139. #endif
  89140. /********* End of inlined file: fixed.h *********/
  89141. #ifndef M_LN2
  89142. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  89143. #define M_LN2 0.69314718055994530942
  89144. #endif
  89145. #ifdef min
  89146. #undef min
  89147. #endif
  89148. #define min(x,y) ((x) < (y)? (x) : (y))
  89149. #ifdef local_abs
  89150. #undef local_abs
  89151. #endif
  89152. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  89153. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89154. /* rbps stands for residual bits per sample
  89155. *
  89156. * (ln(2) * err)
  89157. * rbps = log (-----------)
  89158. * 2 ( n )
  89159. */
  89160. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  89161. {
  89162. FLAC__uint32 rbps;
  89163. unsigned bits; /* the number of bits required to represent a number */
  89164. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89165. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89166. FLAC__ASSERT(err > 0);
  89167. FLAC__ASSERT(n > 0);
  89168. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89169. if(err <= n)
  89170. return 0;
  89171. /*
  89172. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89173. * These allow us later to know we won't lose too much precision in the
  89174. * fixed-point division (err<<fracbits)/n.
  89175. */
  89176. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  89177. err <<= fracbits;
  89178. err /= n;
  89179. /* err now holds err/n with fracbits fractional bits */
  89180. /*
  89181. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89182. * our purposes.
  89183. */
  89184. FLAC__ASSERT(err > 0);
  89185. bits = FLAC__bitmath_ilog2(err)+1;
  89186. if(bits > 16) {
  89187. err >>= (bits-16);
  89188. fracbits -= (bits-16);
  89189. }
  89190. rbps = (FLAC__uint32)err;
  89191. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89192. rbps *= FLAC__FP_LN2;
  89193. fracbits += 16;
  89194. FLAC__ASSERT(fracbits >= 0);
  89195. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89196. {
  89197. const int f = fracbits & 3;
  89198. if(f) {
  89199. rbps >>= f;
  89200. fracbits -= f;
  89201. }
  89202. }
  89203. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89204. if(rbps == 0)
  89205. return 0;
  89206. /*
  89207. * The return value must have 16 fractional bits. Since the whole part
  89208. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89209. * must be >= -3, these assertion allows us to be able to shift rbps
  89210. * left if necessary to get 16 fracbits without losing any bits of the
  89211. * whole part of rbps.
  89212. *
  89213. * There is a slight chance due to accumulated error that the whole part
  89214. * will require 6 bits, so we use 6 in the assertion. Really though as
  89215. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89216. */
  89217. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89218. FLAC__ASSERT(fracbits >= -3);
  89219. /* now shift the decimal point into place */
  89220. if(fracbits < 16)
  89221. return rbps << (16-fracbits);
  89222. else if(fracbits > 16)
  89223. return rbps >> (fracbits-16);
  89224. else
  89225. return rbps;
  89226. }
  89227. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  89228. {
  89229. FLAC__uint32 rbps;
  89230. unsigned bits; /* the number of bits required to represent a number */
  89231. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89232. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89233. FLAC__ASSERT(err > 0);
  89234. FLAC__ASSERT(n > 0);
  89235. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89236. if(err <= n)
  89237. return 0;
  89238. /*
  89239. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89240. * These allow us later to know we won't lose too much precision in the
  89241. * fixed-point division (err<<fracbits)/n.
  89242. */
  89243. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  89244. err <<= fracbits;
  89245. err /= n;
  89246. /* err now holds err/n with fracbits fractional bits */
  89247. /*
  89248. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89249. * our purposes.
  89250. */
  89251. FLAC__ASSERT(err > 0);
  89252. bits = FLAC__bitmath_ilog2_wide(err)+1;
  89253. if(bits > 16) {
  89254. err >>= (bits-16);
  89255. fracbits -= (bits-16);
  89256. }
  89257. rbps = (FLAC__uint32)err;
  89258. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89259. rbps *= FLAC__FP_LN2;
  89260. fracbits += 16;
  89261. FLAC__ASSERT(fracbits >= 0);
  89262. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89263. {
  89264. const int f = fracbits & 3;
  89265. if(f) {
  89266. rbps >>= f;
  89267. fracbits -= f;
  89268. }
  89269. }
  89270. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89271. if(rbps == 0)
  89272. return 0;
  89273. /*
  89274. * The return value must have 16 fractional bits. Since the whole part
  89275. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89276. * must be >= -3, these assertion allows us to be able to shift rbps
  89277. * left if necessary to get 16 fracbits without losing any bits of the
  89278. * whole part of rbps.
  89279. *
  89280. * There is a slight chance due to accumulated error that the whole part
  89281. * will require 6 bits, so we use 6 in the assertion. Really though as
  89282. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89283. */
  89284. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89285. FLAC__ASSERT(fracbits >= -3);
  89286. /* now shift the decimal point into place */
  89287. if(fracbits < 16)
  89288. return rbps << (16-fracbits);
  89289. else if(fracbits > 16)
  89290. return rbps >> (fracbits-16);
  89291. else
  89292. return rbps;
  89293. }
  89294. #endif
  89295. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89296. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89297. #else
  89298. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89299. #endif
  89300. {
  89301. FLAC__int32 last_error_0 = data[-1];
  89302. FLAC__int32 last_error_1 = data[-1] - data[-2];
  89303. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  89304. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  89305. FLAC__int32 error, save;
  89306. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  89307. unsigned i, order;
  89308. for(i = 0; i < data_len; i++) {
  89309. error = data[i] ; total_error_0 += local_abs(error); save = error;
  89310. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  89311. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  89312. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  89313. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  89314. }
  89315. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  89316. order = 0;
  89317. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  89318. order = 1;
  89319. else if(total_error_2 < min(total_error_3, total_error_4))
  89320. order = 2;
  89321. else if(total_error_3 < total_error_4)
  89322. order = 3;
  89323. else
  89324. order = 4;
  89325. /* Estimate the expected number of bits per residual signal sample. */
  89326. /* 'total_error*' is linearly related to the variance of the residual */
  89327. /* signal, so we use it directly to compute E(|x|) */
  89328. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  89329. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  89330. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  89331. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  89332. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  89333. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89334. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89335. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89336. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89337. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89338. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89339. #else
  89340. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  89341. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  89342. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  89343. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  89344. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  89345. #endif
  89346. return order;
  89347. }
  89348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89349. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89350. #else
  89351. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89352. #endif
  89353. {
  89354. FLAC__int32 last_error_0 = data[-1];
  89355. FLAC__int32 last_error_1 = data[-1] - data[-2];
  89356. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  89357. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  89358. FLAC__int32 error, save;
  89359. /* total_error_* are 64-bits to avoid overflow when encoding
  89360. * erratic signals when the bits-per-sample and blocksize are
  89361. * large.
  89362. */
  89363. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  89364. unsigned i, order;
  89365. for(i = 0; i < data_len; i++) {
  89366. error = data[i] ; total_error_0 += local_abs(error); save = error;
  89367. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  89368. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  89369. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  89370. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  89371. }
  89372. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  89373. order = 0;
  89374. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  89375. order = 1;
  89376. else if(total_error_2 < min(total_error_3, total_error_4))
  89377. order = 2;
  89378. else if(total_error_3 < total_error_4)
  89379. order = 3;
  89380. else
  89381. order = 4;
  89382. /* Estimate the expected number of bits per residual signal sample. */
  89383. /* 'total_error*' is linearly related to the variance of the residual */
  89384. /* signal, so we use it directly to compute E(|x|) */
  89385. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  89386. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  89387. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  89388. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  89389. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  89390. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89391. #if defined _MSC_VER || defined __MINGW32__
  89392. /* with MSVC you have to spoon feed it the casting */
  89393. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89394. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89395. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89396. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89397. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89398. #else
  89399. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89400. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89401. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89402. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89403. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  89404. #endif
  89405. #else
  89406. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  89407. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  89408. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  89409. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  89410. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  89411. #endif
  89412. return order;
  89413. }
  89414. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  89415. {
  89416. const int idata_len = (int)data_len;
  89417. int i;
  89418. switch(order) {
  89419. case 0:
  89420. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  89421. memcpy(residual, data, sizeof(residual[0])*data_len);
  89422. break;
  89423. case 1:
  89424. for(i = 0; i < idata_len; i++)
  89425. residual[i] = data[i] - data[i-1];
  89426. break;
  89427. case 2:
  89428. for(i = 0; i < idata_len; i++)
  89429. #if 1 /* OPT: may be faster with some compilers on some systems */
  89430. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  89431. #else
  89432. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  89433. #endif
  89434. break;
  89435. case 3:
  89436. for(i = 0; i < idata_len; i++)
  89437. #if 1 /* OPT: may be faster with some compilers on some systems */
  89438. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  89439. #else
  89440. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  89441. #endif
  89442. break;
  89443. case 4:
  89444. for(i = 0; i < idata_len; i++)
  89445. #if 1 /* OPT: may be faster with some compilers on some systems */
  89446. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  89447. #else
  89448. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  89449. #endif
  89450. break;
  89451. default:
  89452. FLAC__ASSERT(0);
  89453. }
  89454. }
  89455. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  89456. {
  89457. int i, idata_len = (int)data_len;
  89458. switch(order) {
  89459. case 0:
  89460. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  89461. memcpy(data, residual, sizeof(residual[0])*data_len);
  89462. break;
  89463. case 1:
  89464. for(i = 0; i < idata_len; i++)
  89465. data[i] = residual[i] + data[i-1];
  89466. break;
  89467. case 2:
  89468. for(i = 0; i < idata_len; i++)
  89469. #if 1 /* OPT: may be faster with some compilers on some systems */
  89470. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  89471. #else
  89472. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  89473. #endif
  89474. break;
  89475. case 3:
  89476. for(i = 0; i < idata_len; i++)
  89477. #if 1 /* OPT: may be faster with some compilers on some systems */
  89478. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  89479. #else
  89480. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  89481. #endif
  89482. break;
  89483. case 4:
  89484. for(i = 0; i < idata_len; i++)
  89485. #if 1 /* OPT: may be faster with some compilers on some systems */
  89486. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  89487. #else
  89488. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  89489. #endif
  89490. break;
  89491. default:
  89492. FLAC__ASSERT(0);
  89493. }
  89494. }
  89495. #endif
  89496. /********* End of inlined file: fixed.c *********/
  89497. /********* Start of inlined file: float.c *********/
  89498. /********* Start of inlined file: juce_FlacHeader.h *********/
  89499. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89500. // tasks..
  89501. #define VERSION "1.2.1"
  89502. #define FLAC__NO_DLL 1
  89503. #ifdef _MSC_VER
  89504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89505. #endif
  89506. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89507. #define FLAC__SYS_DARWIN 1
  89508. #endif
  89509. /********* End of inlined file: juce_FlacHeader.h *********/
  89510. #if JUCE_USE_FLAC
  89511. #if HAVE_CONFIG_H
  89512. # include <config.h>
  89513. #endif
  89514. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89515. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89516. #ifdef _MSC_VER
  89517. #define FLAC__U64L(x) x
  89518. #else
  89519. #define FLAC__U64L(x) x##LLU
  89520. #endif
  89521. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  89522. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  89523. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  89524. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  89525. const FLAC__fixedpoint FLAC__FP_E = 178145;
  89526. /* Lookup tables for Knuth's logarithm algorithm */
  89527. #define LOG2_LOOKUP_PRECISION 16
  89528. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  89529. {
  89530. /*
  89531. * 0 fraction bits
  89532. */
  89533. /* undefined */ 0x00000000,
  89534. /* lg(2/1) = */ 0x00000001,
  89535. /* lg(4/3) = */ 0x00000000,
  89536. /* lg(8/7) = */ 0x00000000,
  89537. /* lg(16/15) = */ 0x00000000,
  89538. /* lg(32/31) = */ 0x00000000,
  89539. /* lg(64/63) = */ 0x00000000,
  89540. /* lg(128/127) = */ 0x00000000,
  89541. /* lg(256/255) = */ 0x00000000,
  89542. /* lg(512/511) = */ 0x00000000,
  89543. /* lg(1024/1023) = */ 0x00000000,
  89544. /* lg(2048/2047) = */ 0x00000000,
  89545. /* lg(4096/4095) = */ 0x00000000,
  89546. /* lg(8192/8191) = */ 0x00000000,
  89547. /* lg(16384/16383) = */ 0x00000000,
  89548. /* lg(32768/32767) = */ 0x00000000
  89549. },
  89550. {
  89551. /*
  89552. * 4 fraction bits
  89553. */
  89554. /* undefined */ 0x00000000,
  89555. /* lg(2/1) = */ 0x00000010,
  89556. /* lg(4/3) = */ 0x00000007,
  89557. /* lg(8/7) = */ 0x00000003,
  89558. /* lg(16/15) = */ 0x00000001,
  89559. /* lg(32/31) = */ 0x00000001,
  89560. /* lg(64/63) = */ 0x00000000,
  89561. /* lg(128/127) = */ 0x00000000,
  89562. /* lg(256/255) = */ 0x00000000,
  89563. /* lg(512/511) = */ 0x00000000,
  89564. /* lg(1024/1023) = */ 0x00000000,
  89565. /* lg(2048/2047) = */ 0x00000000,
  89566. /* lg(4096/4095) = */ 0x00000000,
  89567. /* lg(8192/8191) = */ 0x00000000,
  89568. /* lg(16384/16383) = */ 0x00000000,
  89569. /* lg(32768/32767) = */ 0x00000000
  89570. },
  89571. {
  89572. /*
  89573. * 8 fraction bits
  89574. */
  89575. /* undefined */ 0x00000000,
  89576. /* lg(2/1) = */ 0x00000100,
  89577. /* lg(4/3) = */ 0x0000006a,
  89578. /* lg(8/7) = */ 0x00000031,
  89579. /* lg(16/15) = */ 0x00000018,
  89580. /* lg(32/31) = */ 0x0000000c,
  89581. /* lg(64/63) = */ 0x00000006,
  89582. /* lg(128/127) = */ 0x00000003,
  89583. /* lg(256/255) = */ 0x00000001,
  89584. /* lg(512/511) = */ 0x00000001,
  89585. /* lg(1024/1023) = */ 0x00000000,
  89586. /* lg(2048/2047) = */ 0x00000000,
  89587. /* lg(4096/4095) = */ 0x00000000,
  89588. /* lg(8192/8191) = */ 0x00000000,
  89589. /* lg(16384/16383) = */ 0x00000000,
  89590. /* lg(32768/32767) = */ 0x00000000
  89591. },
  89592. {
  89593. /*
  89594. * 12 fraction bits
  89595. */
  89596. /* undefined */ 0x00000000,
  89597. /* lg(2/1) = */ 0x00001000,
  89598. /* lg(4/3) = */ 0x000006a4,
  89599. /* lg(8/7) = */ 0x00000315,
  89600. /* lg(16/15) = */ 0x0000017d,
  89601. /* lg(32/31) = */ 0x000000bc,
  89602. /* lg(64/63) = */ 0x0000005d,
  89603. /* lg(128/127) = */ 0x0000002e,
  89604. /* lg(256/255) = */ 0x00000017,
  89605. /* lg(512/511) = */ 0x0000000c,
  89606. /* lg(1024/1023) = */ 0x00000006,
  89607. /* lg(2048/2047) = */ 0x00000003,
  89608. /* lg(4096/4095) = */ 0x00000001,
  89609. /* lg(8192/8191) = */ 0x00000001,
  89610. /* lg(16384/16383) = */ 0x00000000,
  89611. /* lg(32768/32767) = */ 0x00000000
  89612. },
  89613. {
  89614. /*
  89615. * 16 fraction bits
  89616. */
  89617. /* undefined */ 0x00000000,
  89618. /* lg(2/1) = */ 0x00010000,
  89619. /* lg(4/3) = */ 0x00006a40,
  89620. /* lg(8/7) = */ 0x00003151,
  89621. /* lg(16/15) = */ 0x000017d6,
  89622. /* lg(32/31) = */ 0x00000bba,
  89623. /* lg(64/63) = */ 0x000005d1,
  89624. /* lg(128/127) = */ 0x000002e6,
  89625. /* lg(256/255) = */ 0x00000172,
  89626. /* lg(512/511) = */ 0x000000b9,
  89627. /* lg(1024/1023) = */ 0x0000005c,
  89628. /* lg(2048/2047) = */ 0x0000002e,
  89629. /* lg(4096/4095) = */ 0x00000017,
  89630. /* lg(8192/8191) = */ 0x0000000c,
  89631. /* lg(16384/16383) = */ 0x00000006,
  89632. /* lg(32768/32767) = */ 0x00000003
  89633. },
  89634. {
  89635. /*
  89636. * 20 fraction bits
  89637. */
  89638. /* undefined */ 0x00000000,
  89639. /* lg(2/1) = */ 0x00100000,
  89640. /* lg(4/3) = */ 0x0006a3fe,
  89641. /* lg(8/7) = */ 0x00031513,
  89642. /* lg(16/15) = */ 0x00017d60,
  89643. /* lg(32/31) = */ 0x0000bb9d,
  89644. /* lg(64/63) = */ 0x00005d10,
  89645. /* lg(128/127) = */ 0x00002e59,
  89646. /* lg(256/255) = */ 0x00001721,
  89647. /* lg(512/511) = */ 0x00000b8e,
  89648. /* lg(1024/1023) = */ 0x000005c6,
  89649. /* lg(2048/2047) = */ 0x000002e3,
  89650. /* lg(4096/4095) = */ 0x00000171,
  89651. /* lg(8192/8191) = */ 0x000000b9,
  89652. /* lg(16384/16383) = */ 0x0000005c,
  89653. /* lg(32768/32767) = */ 0x0000002e
  89654. },
  89655. {
  89656. /*
  89657. * 24 fraction bits
  89658. */
  89659. /* undefined */ 0x00000000,
  89660. /* lg(2/1) = */ 0x01000000,
  89661. /* lg(4/3) = */ 0x006a3fe6,
  89662. /* lg(8/7) = */ 0x00315130,
  89663. /* lg(16/15) = */ 0x0017d605,
  89664. /* lg(32/31) = */ 0x000bb9ca,
  89665. /* lg(64/63) = */ 0x0005d0fc,
  89666. /* lg(128/127) = */ 0x0002e58f,
  89667. /* lg(256/255) = */ 0x0001720e,
  89668. /* lg(512/511) = */ 0x0000b8d8,
  89669. /* lg(1024/1023) = */ 0x00005c61,
  89670. /* lg(2048/2047) = */ 0x00002e2d,
  89671. /* lg(4096/4095) = */ 0x00001716,
  89672. /* lg(8192/8191) = */ 0x00000b8b,
  89673. /* lg(16384/16383) = */ 0x000005c5,
  89674. /* lg(32768/32767) = */ 0x000002e3
  89675. },
  89676. {
  89677. /*
  89678. * 28 fraction bits
  89679. */
  89680. /* undefined */ 0x00000000,
  89681. /* lg(2/1) = */ 0x10000000,
  89682. /* lg(4/3) = */ 0x06a3fe5c,
  89683. /* lg(8/7) = */ 0x03151301,
  89684. /* lg(16/15) = */ 0x017d6049,
  89685. /* lg(32/31) = */ 0x00bb9ca6,
  89686. /* lg(64/63) = */ 0x005d0fba,
  89687. /* lg(128/127) = */ 0x002e58f7,
  89688. /* lg(256/255) = */ 0x001720da,
  89689. /* lg(512/511) = */ 0x000b8d87,
  89690. /* lg(1024/1023) = */ 0x0005c60b,
  89691. /* lg(2048/2047) = */ 0x0002e2d7,
  89692. /* lg(4096/4095) = */ 0x00017160,
  89693. /* lg(8192/8191) = */ 0x0000b8ad,
  89694. /* lg(16384/16383) = */ 0x00005c56,
  89695. /* lg(32768/32767) = */ 0x00002e2b
  89696. }
  89697. };
  89698. #if 0
  89699. static const FLAC__uint64 log2_lookup_wide[] = {
  89700. {
  89701. /*
  89702. * 32 fraction bits
  89703. */
  89704. /* undefined */ 0x00000000,
  89705. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  89706. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  89707. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  89708. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  89709. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  89710. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  89711. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  89712. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  89713. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  89714. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  89715. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  89716. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  89717. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  89718. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  89719. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  89720. },
  89721. {
  89722. /*
  89723. * 48 fraction bits
  89724. */
  89725. /* undefined */ 0x00000000,
  89726. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  89727. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  89728. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  89729. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  89730. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  89731. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  89732. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  89733. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  89734. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  89735. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  89736. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  89737. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  89738. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  89739. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  89740. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  89741. }
  89742. };
  89743. #endif
  89744. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  89745. {
  89746. const FLAC__uint32 ONE = (1u << fracbits);
  89747. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  89748. FLAC__ASSERT(fracbits < 32);
  89749. FLAC__ASSERT((fracbits & 0x3) == 0);
  89750. if(x < ONE)
  89751. return 0;
  89752. if(precision > LOG2_LOOKUP_PRECISION)
  89753. precision = LOG2_LOOKUP_PRECISION;
  89754. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  89755. {
  89756. FLAC__uint32 y = 0;
  89757. FLAC__uint32 z = x >> 1, k = 1;
  89758. while (x > ONE && k < precision) {
  89759. if (x - z >= ONE) {
  89760. x -= z;
  89761. z = x >> k;
  89762. y += table[k];
  89763. }
  89764. else {
  89765. z >>= 1;
  89766. k++;
  89767. }
  89768. }
  89769. return y;
  89770. }
  89771. }
  89772. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  89773. #endif
  89774. /********* End of inlined file: float.c *********/
  89775. /********* Start of inlined file: format.c *********/
  89776. /********* Start of inlined file: juce_FlacHeader.h *********/
  89777. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89778. // tasks..
  89779. #define VERSION "1.2.1"
  89780. #define FLAC__NO_DLL 1
  89781. #ifdef _MSC_VER
  89782. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89783. #endif
  89784. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89785. #define FLAC__SYS_DARWIN 1
  89786. #endif
  89787. /********* End of inlined file: juce_FlacHeader.h *********/
  89788. #if JUCE_USE_FLAC
  89789. #if HAVE_CONFIG_H
  89790. # include <config.h>
  89791. #endif
  89792. #include <stdio.h>
  89793. #include <stdlib.h> /* for qsort() */
  89794. #include <string.h> /* for memset() */
  89795. #ifndef FLaC__INLINE
  89796. #define FLaC__INLINE
  89797. #endif
  89798. #ifdef min
  89799. #undef min
  89800. #endif
  89801. #define min(a,b) ((a)<(b)?(a):(b))
  89802. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89803. #ifdef _MSC_VER
  89804. #define FLAC__U64L(x) x
  89805. #else
  89806. #define FLAC__U64L(x) x##LLU
  89807. #endif
  89808. /* VERSION should come from configure */
  89809. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  89810. ;
  89811. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  89812. /* yet one more hack because of MSVC6: */
  89813. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  89814. #else
  89815. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  89816. #endif
  89817. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  89818. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  89819. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  89820. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  89821. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  89822. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  89823. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  89824. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  89825. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  89826. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  89827. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  89828. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  89829. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  89830. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  89831. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  89832. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  89833. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  89834. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  89835. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  89836. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  89837. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  89838. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  89839. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  89840. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  89841. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  89842. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  89843. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  89844. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  89845. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  89846. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  89847. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  89848. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  89849. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  89850. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  89851. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  89852. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  89853. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  89854. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  89855. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  89856. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  89857. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  89858. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  89859. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  89860. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  89861. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  89862. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  89863. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  89864. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  89865. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  89866. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  89867. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  89868. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  89869. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  89870. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  89871. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  89872. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  89873. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  89874. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  89875. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  89876. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  89877. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  89878. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  89879. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  89880. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  89881. "PARTITIONED_RICE",
  89882. "PARTITIONED_RICE2"
  89883. };
  89884. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  89885. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  89886. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  89887. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  89888. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  89889. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  89890. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  89891. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  89892. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  89893. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  89894. "CONSTANT",
  89895. "VERBATIM",
  89896. "FIXED",
  89897. "LPC"
  89898. };
  89899. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  89900. "INDEPENDENT",
  89901. "LEFT_SIDE",
  89902. "RIGHT_SIDE",
  89903. "MID_SIDE"
  89904. };
  89905. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  89906. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  89907. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  89908. };
  89909. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  89910. "STREAMINFO",
  89911. "PADDING",
  89912. "APPLICATION",
  89913. "SEEKTABLE",
  89914. "VORBIS_COMMENT",
  89915. "CUESHEET",
  89916. "PICTURE"
  89917. };
  89918. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  89919. "Other",
  89920. "32x32 pixels 'file icon' (PNG only)",
  89921. "Other file icon",
  89922. "Cover (front)",
  89923. "Cover (back)",
  89924. "Leaflet page",
  89925. "Media (e.g. label side of CD)",
  89926. "Lead artist/lead performer/soloist",
  89927. "Artist/performer",
  89928. "Conductor",
  89929. "Band/Orchestra",
  89930. "Composer",
  89931. "Lyricist/text writer",
  89932. "Recording Location",
  89933. "During recording",
  89934. "During performance",
  89935. "Movie/video screen capture",
  89936. "A bright coloured fish",
  89937. "Illustration",
  89938. "Band/artist logotype",
  89939. "Publisher/Studio logotype"
  89940. };
  89941. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  89942. {
  89943. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  89944. return false;
  89945. }
  89946. else
  89947. return true;
  89948. }
  89949. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  89950. {
  89951. if(
  89952. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  89953. (
  89954. sample_rate >= (1u << 16) &&
  89955. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  89956. )
  89957. ) {
  89958. return false;
  89959. }
  89960. else
  89961. return true;
  89962. }
  89963. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  89964. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  89965. {
  89966. unsigned i;
  89967. FLAC__uint64 prev_sample_number = 0;
  89968. FLAC__bool got_prev = false;
  89969. FLAC__ASSERT(0 != seek_table);
  89970. for(i = 0; i < seek_table->num_points; i++) {
  89971. if(got_prev) {
  89972. if(
  89973. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  89974. seek_table->points[i].sample_number <= prev_sample_number
  89975. )
  89976. return false;
  89977. }
  89978. prev_sample_number = seek_table->points[i].sample_number;
  89979. got_prev = true;
  89980. }
  89981. return true;
  89982. }
  89983. /* used as the sort predicate for qsort() */
  89984. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  89985. {
  89986. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  89987. if(l->sample_number == r->sample_number)
  89988. return 0;
  89989. else if(l->sample_number < r->sample_number)
  89990. return -1;
  89991. else
  89992. return 1;
  89993. }
  89994. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  89995. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  89996. {
  89997. unsigned i, j;
  89998. FLAC__bool first;
  89999. FLAC__ASSERT(0 != seek_table);
  90000. /* sort the seekpoints */
  90001. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  90002. /* uniquify the seekpoints */
  90003. first = true;
  90004. for(i = j = 0; i < seek_table->num_points; i++) {
  90005. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  90006. if(!first) {
  90007. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  90008. continue;
  90009. }
  90010. }
  90011. first = false;
  90012. seek_table->points[j++] = seek_table->points[i];
  90013. }
  90014. for(i = j; i < seek_table->num_points; i++) {
  90015. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  90016. seek_table->points[i].stream_offset = 0;
  90017. seek_table->points[i].frame_samples = 0;
  90018. }
  90019. return j;
  90020. }
  90021. /*
  90022. * also disallows non-shortest-form encodings, c.f.
  90023. * http://www.unicode.org/versions/corrigendum1.html
  90024. * and a more clear explanation at the end of this section:
  90025. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  90026. */
  90027. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  90028. {
  90029. FLAC__ASSERT(0 != utf8);
  90030. if ((utf8[0] & 0x80) == 0) {
  90031. return 1;
  90032. }
  90033. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  90034. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  90035. return 0;
  90036. return 2;
  90037. }
  90038. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  90039. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  90040. return 0;
  90041. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  90042. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  90043. return 0;
  90044. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  90045. return 0;
  90046. return 3;
  90047. }
  90048. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  90049. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  90050. return 0;
  90051. return 4;
  90052. }
  90053. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  90054. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  90055. return 0;
  90056. return 5;
  90057. }
  90058. else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
  90059. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  90060. return 0;
  90061. return 6;
  90062. }
  90063. else {
  90064. return 0;
  90065. }
  90066. }
  90067. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  90068. {
  90069. char c;
  90070. for(c = *name; c; c = *(++name))
  90071. if(c < 0x20 || c == 0x3d || c > 0x7d)
  90072. return false;
  90073. return true;
  90074. }
  90075. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  90076. {
  90077. if(length == (unsigned)(-1)) {
  90078. while(*value) {
  90079. unsigned n = utf8len_(value);
  90080. if(n == 0)
  90081. return false;
  90082. value += n;
  90083. }
  90084. }
  90085. else {
  90086. const FLAC__byte *end = value + length;
  90087. while(value < end) {
  90088. unsigned n = utf8len_(value);
  90089. if(n == 0)
  90090. return false;
  90091. value += n;
  90092. }
  90093. if(value != end)
  90094. return false;
  90095. }
  90096. return true;
  90097. }
  90098. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  90099. {
  90100. const FLAC__byte *s, *end;
  90101. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  90102. if(*s < 0x20 || *s > 0x7D)
  90103. return false;
  90104. }
  90105. if(s == end)
  90106. return false;
  90107. s++; /* skip '=' */
  90108. while(s < end) {
  90109. unsigned n = utf8len_(s);
  90110. if(n == 0)
  90111. return false;
  90112. s += n;
  90113. }
  90114. if(s != end)
  90115. return false;
  90116. return true;
  90117. }
  90118. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90119. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  90120. {
  90121. unsigned i, j;
  90122. if(check_cd_da_subset) {
  90123. if(cue_sheet->lead_in < 2 * 44100) {
  90124. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  90125. return false;
  90126. }
  90127. if(cue_sheet->lead_in % 588 != 0) {
  90128. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  90129. return false;
  90130. }
  90131. }
  90132. if(cue_sheet->num_tracks == 0) {
  90133. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  90134. return false;
  90135. }
  90136. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  90137. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  90138. return false;
  90139. }
  90140. for(i = 0; i < cue_sheet->num_tracks; i++) {
  90141. if(cue_sheet->tracks[i].number == 0) {
  90142. if(violation) *violation = "cue sheet may not have a track number 0";
  90143. return false;
  90144. }
  90145. if(check_cd_da_subset) {
  90146. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  90147. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  90148. return false;
  90149. }
  90150. }
  90151. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  90152. if(violation) {
  90153. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  90154. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  90155. else
  90156. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  90157. }
  90158. return false;
  90159. }
  90160. if(i < cue_sheet->num_tracks - 1) {
  90161. if(cue_sheet->tracks[i].num_indices == 0) {
  90162. if(violation) *violation = "cue sheet track must have at least one index point";
  90163. return false;
  90164. }
  90165. if(cue_sheet->tracks[i].indices[0].number > 1) {
  90166. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  90167. return false;
  90168. }
  90169. }
  90170. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  90171. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  90172. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  90173. return false;
  90174. }
  90175. if(j > 0) {
  90176. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  90177. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  90178. return false;
  90179. }
  90180. }
  90181. }
  90182. }
  90183. return true;
  90184. }
  90185. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90186. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  90187. {
  90188. char *p;
  90189. FLAC__byte *b;
  90190. for(p = picture->mime_type; *p; p++) {
  90191. if(*p < 0x20 || *p > 0x7e) {
  90192. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  90193. return false;
  90194. }
  90195. }
  90196. for(b = picture->description; *b; ) {
  90197. unsigned n = utf8len_(b);
  90198. if(n == 0) {
  90199. if(violation) *violation = "description string must be valid UTF-8";
  90200. return false;
  90201. }
  90202. b += n;
  90203. }
  90204. return true;
  90205. }
  90206. /*
  90207. * These routines are private to libFLAC
  90208. */
  90209. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  90210. {
  90211. return
  90212. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  90213. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  90214. blocksize,
  90215. predictor_order
  90216. );
  90217. }
  90218. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  90219. {
  90220. unsigned max_rice_partition_order = 0;
  90221. while(!(blocksize & 1)) {
  90222. max_rice_partition_order++;
  90223. blocksize >>= 1;
  90224. }
  90225. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  90226. }
  90227. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  90228. {
  90229. unsigned max_rice_partition_order = limit;
  90230. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  90231. max_rice_partition_order--;
  90232. FLAC__ASSERT(
  90233. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  90234. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  90235. );
  90236. return max_rice_partition_order;
  90237. }
  90238. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90239. {
  90240. FLAC__ASSERT(0 != object);
  90241. object->parameters = 0;
  90242. object->raw_bits = 0;
  90243. object->capacity_by_order = 0;
  90244. }
  90245. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90246. {
  90247. FLAC__ASSERT(0 != object);
  90248. if(0 != object->parameters)
  90249. free(object->parameters);
  90250. if(0 != object->raw_bits)
  90251. free(object->raw_bits);
  90252. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  90253. }
  90254. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  90255. {
  90256. FLAC__ASSERT(0 != object);
  90257. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  90258. if(object->capacity_by_order < max_partition_order) {
  90259. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  90260. return false;
  90261. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  90262. return false;
  90263. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  90264. object->capacity_by_order = max_partition_order;
  90265. }
  90266. return true;
  90267. }
  90268. #endif
  90269. /********* End of inlined file: format.c *********/
  90270. /********* Start of inlined file: lpc_flac.c *********/
  90271. /********* Start of inlined file: juce_FlacHeader.h *********/
  90272. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90273. // tasks..
  90274. #define VERSION "1.2.1"
  90275. #define FLAC__NO_DLL 1
  90276. #ifdef _MSC_VER
  90277. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90278. #endif
  90279. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90280. #define FLAC__SYS_DARWIN 1
  90281. #endif
  90282. /********* End of inlined file: juce_FlacHeader.h *********/
  90283. #if JUCE_USE_FLAC
  90284. #if HAVE_CONFIG_H
  90285. # include <config.h>
  90286. #endif
  90287. #include <math.h>
  90288. /********* Start of inlined file: lpc.h *********/
  90289. #ifndef FLAC__PRIVATE__LPC_H
  90290. #define FLAC__PRIVATE__LPC_H
  90291. #ifdef HAVE_CONFIG_H
  90292. #include <config.h>
  90293. #endif
  90294. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90295. /*
  90296. * FLAC__lpc_window_data()
  90297. * --------------------------------------------------------------------
  90298. * Applies the given window to the data.
  90299. * OPT: asm implementation
  90300. *
  90301. * IN in[0,data_len-1]
  90302. * IN window[0,data_len-1]
  90303. * OUT out[0,lag-1]
  90304. * IN data_len
  90305. */
  90306. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  90307. /*
  90308. * FLAC__lpc_compute_autocorrelation()
  90309. * --------------------------------------------------------------------
  90310. * Compute the autocorrelation for lags between 0 and lag-1.
  90311. * Assumes data[] outside of [0,data_len-1] == 0.
  90312. * Asserts that lag > 0.
  90313. *
  90314. * IN data[0,data_len-1]
  90315. * IN data_len
  90316. * IN 0 < lag <= data_len
  90317. * OUT autoc[0,lag-1]
  90318. */
  90319. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90320. #ifndef FLAC__NO_ASM
  90321. # ifdef FLAC__CPU_IA32
  90322. # ifdef FLAC__HAS_NASM
  90323. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90324. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90325. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90326. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90327. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90328. # endif
  90329. # endif
  90330. #endif
  90331. /*
  90332. * FLAC__lpc_compute_lp_coefficients()
  90333. * --------------------------------------------------------------------
  90334. * Computes LP coefficients for orders 1..max_order.
  90335. * Do not call if autoc[0] == 0.0. This means the signal is zero
  90336. * and there is no point in calculating a predictor.
  90337. *
  90338. * IN autoc[0,max_order] autocorrelation values
  90339. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  90340. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  90341. * *** IMPORTANT:
  90342. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  90343. * OUT error[0,max_order-1] error for each order (more
  90344. * specifically, the variance of
  90345. * the error signal times # of
  90346. * samples in the signal)
  90347. *
  90348. * Example: if max_order is 9, the LP coefficients for order 9 will be
  90349. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  90350. * in lp_coeff[7][0,7], etc.
  90351. */
  90352. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  90353. /*
  90354. * FLAC__lpc_quantize_coefficients()
  90355. * --------------------------------------------------------------------
  90356. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  90357. * must be less than 32 (sizeof(FLAC__int32)*8).
  90358. *
  90359. * IN lp_coeff[0,order-1] LP coefficients
  90360. * IN order LP order
  90361. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  90362. * desired precision (in bits, including sign
  90363. * bit) of largest coefficient
  90364. * OUT qlp_coeff[0,order-1] quantized coefficients
  90365. * OUT shift # of bits to shift right to get approximated
  90366. * LP coefficients. NOTE: could be negative.
  90367. * RETURN 0 => quantization OK
  90368. * 1 => coefficients require too much shifting for *shift to
  90369. * fit in the LPC subframe header. 'shift' is unset.
  90370. * 2 => coefficients are all zero, which is bad. 'shift' is
  90371. * unset.
  90372. */
  90373. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  90374. /*
  90375. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  90376. * --------------------------------------------------------------------
  90377. * Compute the residual signal obtained from sutracting the predicted
  90378. * signal from the original.
  90379. *
  90380. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  90381. * IN data_len length of original signal
  90382. * IN qlp_coeff[0,order-1] quantized LP coefficients
  90383. * IN order > 0 LP order
  90384. * IN lp_quantization quantization of LP coefficients in bits
  90385. * OUT residual[0,data_len-1] residual signal
  90386. */
  90387. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  90388. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  90389. #ifndef FLAC__NO_ASM
  90390. # ifdef FLAC__CPU_IA32
  90391. # ifdef FLAC__HAS_NASM
  90392. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  90393. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  90394. # endif
  90395. # endif
  90396. #endif
  90397. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  90398. /*
  90399. * FLAC__lpc_restore_signal()
  90400. * --------------------------------------------------------------------
  90401. * Restore the original signal by summing the residual and the
  90402. * predictor.
  90403. *
  90404. * IN residual[0,data_len-1] residual signal
  90405. * IN data_len length of original signal
  90406. * IN qlp_coeff[0,order-1] quantized LP coefficients
  90407. * IN order > 0 LP order
  90408. * IN lp_quantization quantization of LP coefficients in bits
  90409. * *** IMPORTANT: the caller must pass in the historical samples:
  90410. * IN data[-order,-1] previously-reconstructed historical samples
  90411. * OUT data[0,data_len-1] original signal
  90412. */
  90413. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90414. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90415. #ifndef FLAC__NO_ASM
  90416. # ifdef FLAC__CPU_IA32
  90417. # ifdef FLAC__HAS_NASM
  90418. void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90419. void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90420. # endif /* FLAC__HAS_NASM */
  90421. # elif defined FLAC__CPU_PPC
  90422. void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90423. void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  90424. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  90425. #endif /* FLAC__NO_ASM */
  90426. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90427. /*
  90428. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  90429. * --------------------------------------------------------------------
  90430. * Compute the expected number of bits per residual signal sample
  90431. * based on the LP error (which is related to the residual variance).
  90432. *
  90433. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  90434. * IN total_samples > 0 # of samples in residual signal
  90435. * RETURN expected bits per sample
  90436. */
  90437. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  90438. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  90439. /*
  90440. * FLAC__lpc_compute_best_order()
  90441. * --------------------------------------------------------------------
  90442. * Compute the best order from the array of signal errors returned
  90443. * during coefficient computation.
  90444. *
  90445. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  90446. * IN max_order > 0 max LP order
  90447. * IN total_samples > 0 # of samples in residual signal
  90448. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  90449. * (includes warmup sample size and quantized LP coefficient)
  90450. * RETURN [1,max_order] best order
  90451. */
  90452. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  90453. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  90454. #endif
  90455. /********* End of inlined file: lpc.h *********/
  90456. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  90457. #include <stdio.h>
  90458. #endif
  90459. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90460. #ifndef M_LN2
  90461. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  90462. #define M_LN2 0.69314718055994530942
  90463. #endif
  90464. /* OPT: #undef'ing this may improve the speed on some architectures */
  90465. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  90466. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  90467. {
  90468. unsigned i;
  90469. for(i = 0; i < data_len; i++)
  90470. out[i] = in[i] * window[i];
  90471. }
  90472. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  90473. {
  90474. /* a readable, but slower, version */
  90475. #if 0
  90476. FLAC__real d;
  90477. unsigned i;
  90478. FLAC__ASSERT(lag > 0);
  90479. FLAC__ASSERT(lag <= data_len);
  90480. /*
  90481. * Technically we should subtract the mean first like so:
  90482. * for(i = 0; i < data_len; i++)
  90483. * data[i] -= mean;
  90484. * but it appears not to make enough of a difference to matter, and
  90485. * most signals are already closely centered around zero
  90486. */
  90487. while(lag--) {
  90488. for(i = lag, d = 0.0; i < data_len; i++)
  90489. d += data[i] * data[i - lag];
  90490. autoc[lag] = d;
  90491. }
  90492. #endif
  90493. /*
  90494. * this version tends to run faster because of better data locality
  90495. * ('data_len' is usually much larger than 'lag')
  90496. */
  90497. FLAC__real d;
  90498. unsigned sample, coeff;
  90499. const unsigned limit = data_len - lag;
  90500. FLAC__ASSERT(lag > 0);
  90501. FLAC__ASSERT(lag <= data_len);
  90502. for(coeff = 0; coeff < lag; coeff++)
  90503. autoc[coeff] = 0.0;
  90504. for(sample = 0; sample <= limit; sample++) {
  90505. d = data[sample];
  90506. for(coeff = 0; coeff < lag; coeff++)
  90507. autoc[coeff] += d * data[sample+coeff];
  90508. }
  90509. for(; sample < data_len; sample++) {
  90510. d = data[sample];
  90511. for(coeff = 0; coeff < data_len - sample; coeff++)
  90512. autoc[coeff] += d * data[sample+coeff];
  90513. }
  90514. }
  90515. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  90516. {
  90517. unsigned i, j;
  90518. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  90519. FLAC__ASSERT(0 != max_order);
  90520. FLAC__ASSERT(0 < *max_order);
  90521. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  90522. FLAC__ASSERT(autoc[0] != 0.0);
  90523. err = autoc[0];
  90524. for(i = 0; i < *max_order; i++) {
  90525. /* Sum up this iteration's reflection coefficient. */
  90526. r = -autoc[i+1];
  90527. for(j = 0; j < i; j++)
  90528. r -= lpc[j] * autoc[i-j];
  90529. ref[i] = (r/=err);
  90530. /* Update LPC coefficients and total error. */
  90531. lpc[i]=r;
  90532. for(j = 0; j < (i>>1); j++) {
  90533. FLAC__double tmp = lpc[j];
  90534. lpc[j] += r * lpc[i-1-j];
  90535. lpc[i-1-j] += r * tmp;
  90536. }
  90537. if(i & 1)
  90538. lpc[j] += lpc[j] * r;
  90539. err *= (1.0 - r * r);
  90540. /* save this order */
  90541. for(j = 0; j <= i; j++)
  90542. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  90543. error[i] = err;
  90544. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  90545. if(err == 0.0) {
  90546. *max_order = i+1;
  90547. return;
  90548. }
  90549. }
  90550. }
  90551. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  90552. {
  90553. unsigned i;
  90554. FLAC__double cmax;
  90555. FLAC__int32 qmax, qmin;
  90556. FLAC__ASSERT(precision > 0);
  90557. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  90558. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  90559. precision--;
  90560. qmax = 1 << precision;
  90561. qmin = -qmax;
  90562. qmax--;
  90563. /* calc cmax = max( |lp_coeff[i]| ) */
  90564. cmax = 0.0;
  90565. for(i = 0; i < order; i++) {
  90566. const FLAC__double d = fabs(lp_coeff[i]);
  90567. if(d > cmax)
  90568. cmax = d;
  90569. }
  90570. if(cmax <= 0.0) {
  90571. /* => coefficients are all 0, which means our constant-detect didn't work */
  90572. return 2;
  90573. }
  90574. else {
  90575. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  90576. const int min_shiftlimit = -max_shiftlimit - 1;
  90577. int log2cmax;
  90578. (void)frexp(cmax, &log2cmax);
  90579. log2cmax--;
  90580. *shift = (int)precision - log2cmax - 1;
  90581. if(*shift > max_shiftlimit)
  90582. *shift = max_shiftlimit;
  90583. else if(*shift < min_shiftlimit)
  90584. return 1;
  90585. }
  90586. if(*shift >= 0) {
  90587. FLAC__double error = 0.0;
  90588. FLAC__int32 q;
  90589. for(i = 0; i < order; i++) {
  90590. error += lp_coeff[i] * (1 << *shift);
  90591. #if 1 /* unfortunately lround() is C99 */
  90592. if(error >= 0.0)
  90593. q = (FLAC__int32)(error + 0.5);
  90594. else
  90595. q = (FLAC__int32)(error - 0.5);
  90596. #else
  90597. q = lround(error);
  90598. #endif
  90599. #ifdef FLAC__OVERFLOW_DETECT
  90600. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  90601. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  90602. else if(q < qmin)
  90603. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  90604. #endif
  90605. if(q > qmax)
  90606. q = qmax;
  90607. else if(q < qmin)
  90608. q = qmin;
  90609. error -= q;
  90610. qlp_coeff[i] = q;
  90611. }
  90612. }
  90613. /* negative shift is very rare but due to design flaw, negative shift is
  90614. * a NOP in the decoder, so it must be handled specially by scaling down
  90615. * coeffs
  90616. */
  90617. else {
  90618. const int nshift = -(*shift);
  90619. FLAC__double error = 0.0;
  90620. FLAC__int32 q;
  90621. #ifdef DEBUG
  90622. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  90623. #endif
  90624. for(i = 0; i < order; i++) {
  90625. error += lp_coeff[i] / (1 << nshift);
  90626. #if 1 /* unfortunately lround() is C99 */
  90627. if(error >= 0.0)
  90628. q = (FLAC__int32)(error + 0.5);
  90629. else
  90630. q = (FLAC__int32)(error - 0.5);
  90631. #else
  90632. q = lround(error);
  90633. #endif
  90634. #ifdef FLAC__OVERFLOW_DETECT
  90635. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  90636. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  90637. else if(q < qmin)
  90638. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  90639. #endif
  90640. if(q > qmax)
  90641. q = qmax;
  90642. else if(q < qmin)
  90643. q = qmin;
  90644. error -= q;
  90645. qlp_coeff[i] = q;
  90646. }
  90647. *shift = 0;
  90648. }
  90649. return 0;
  90650. }
  90651. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  90652. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  90653. {
  90654. FLAC__int64 sumo;
  90655. unsigned i, j;
  90656. FLAC__int32 sum;
  90657. const FLAC__int32 *history;
  90658. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  90659. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  90660. for(i=0;i<order;i++)
  90661. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  90662. fprintf(stderr,"\n");
  90663. #endif
  90664. FLAC__ASSERT(order > 0);
  90665. for(i = 0; i < data_len; i++) {
  90666. sumo = 0;
  90667. sum = 0;
  90668. history = data;
  90669. for(j = 0; j < order; j++) {
  90670. sum += qlp_coeff[j] * (*(--history));
  90671. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  90672. #if defined _MSC_VER
  90673. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  90674. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  90675. #else
  90676. if(sumo > 2147483647ll || sumo < -2147483648ll)
  90677. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  90678. #endif
  90679. }
  90680. *(residual++) = *(data++) - (sum >> lp_quantization);
  90681. }
  90682. /* Here's a slower but clearer version:
  90683. for(i = 0; i < data_len; i++) {
  90684. sum = 0;
  90685. for(j = 0; j < order; j++)
  90686. sum += qlp_coeff[j] * data[i-j-1];
  90687. residual[i] = data[i] - (sum >> lp_quantization);
  90688. }
  90689. */
  90690. }
  90691. #else /* fully unrolled version for normal use */
  90692. {
  90693. int i;
  90694. FLAC__int32 sum;
  90695. FLAC__ASSERT(order > 0);
  90696. FLAC__ASSERT(order <= 32);
  90697. /*
  90698. * We do unique versions up to 12th order since that's the subset limit.
  90699. * Also they are roughly ordered to match frequency of occurrence to
  90700. * minimize branching.
  90701. */
  90702. if(order <= 12) {
  90703. if(order > 8) {
  90704. if(order > 10) {
  90705. if(order == 12) {
  90706. for(i = 0; i < (int)data_len; i++) {
  90707. sum = 0;
  90708. sum += qlp_coeff[11] * data[i-12];
  90709. sum += qlp_coeff[10] * data[i-11];
  90710. sum += qlp_coeff[9] * data[i-10];
  90711. sum += qlp_coeff[8] * data[i-9];
  90712. sum += qlp_coeff[7] * data[i-8];
  90713. sum += qlp_coeff[6] * data[i-7];
  90714. sum += qlp_coeff[5] * data[i-6];
  90715. sum += qlp_coeff[4] * data[i-5];
  90716. sum += qlp_coeff[3] * data[i-4];
  90717. sum += qlp_coeff[2] * data[i-3];
  90718. sum += qlp_coeff[1] * data[i-2];
  90719. sum += qlp_coeff[0] * data[i-1];
  90720. residual[i] = data[i] - (sum >> lp_quantization);
  90721. }
  90722. }
  90723. else { /* order == 11 */
  90724. for(i = 0; i < (int)data_len; i++) {
  90725. sum = 0;
  90726. sum += qlp_coeff[10] * data[i-11];
  90727. sum += qlp_coeff[9] * data[i-10];
  90728. sum += qlp_coeff[8] * data[i-9];
  90729. sum += qlp_coeff[7] * data[i-8];
  90730. sum += qlp_coeff[6] * data[i-7];
  90731. sum += qlp_coeff[5] * data[i-6];
  90732. sum += qlp_coeff[4] * data[i-5];
  90733. sum += qlp_coeff[3] * data[i-4];
  90734. sum += qlp_coeff[2] * data[i-3];
  90735. sum += qlp_coeff[1] * data[i-2];
  90736. sum += qlp_coeff[0] * data[i-1];
  90737. residual[i] = data[i] - (sum >> lp_quantization);
  90738. }
  90739. }
  90740. }
  90741. else {
  90742. if(order == 10) {
  90743. for(i = 0; i < (int)data_len; i++) {
  90744. sum = 0;
  90745. sum += qlp_coeff[9] * data[i-10];
  90746. sum += qlp_coeff[8] * data[i-9];
  90747. sum += qlp_coeff[7] * data[i-8];
  90748. sum += qlp_coeff[6] * data[i-7];
  90749. sum += qlp_coeff[5] * data[i-6];
  90750. sum += qlp_coeff[4] * data[i-5];
  90751. sum += qlp_coeff[3] * data[i-4];
  90752. sum += qlp_coeff[2] * data[i-3];
  90753. sum += qlp_coeff[1] * data[i-2];
  90754. sum += qlp_coeff[0] * data[i-1];
  90755. residual[i] = data[i] - (sum >> lp_quantization);
  90756. }
  90757. }
  90758. else { /* order == 9 */
  90759. for(i = 0; i < (int)data_len; i++) {
  90760. sum = 0;
  90761. sum += qlp_coeff[8] * data[i-9];
  90762. sum += qlp_coeff[7] * data[i-8];
  90763. sum += qlp_coeff[6] * data[i-7];
  90764. sum += qlp_coeff[5] * data[i-6];
  90765. sum += qlp_coeff[4] * data[i-5];
  90766. sum += qlp_coeff[3] * data[i-4];
  90767. sum += qlp_coeff[2] * data[i-3];
  90768. sum += qlp_coeff[1] * data[i-2];
  90769. sum += qlp_coeff[0] * data[i-1];
  90770. residual[i] = data[i] - (sum >> lp_quantization);
  90771. }
  90772. }
  90773. }
  90774. }
  90775. else if(order > 4) {
  90776. if(order > 6) {
  90777. if(order == 8) {
  90778. for(i = 0; i < (int)data_len; i++) {
  90779. sum = 0;
  90780. sum += qlp_coeff[7] * data[i-8];
  90781. sum += qlp_coeff[6] * data[i-7];
  90782. sum += qlp_coeff[5] * data[i-6];
  90783. sum += qlp_coeff[4] * data[i-5];
  90784. sum += qlp_coeff[3] * data[i-4];
  90785. sum += qlp_coeff[2] * data[i-3];
  90786. sum += qlp_coeff[1] * data[i-2];
  90787. sum += qlp_coeff[0] * data[i-1];
  90788. residual[i] = data[i] - (sum >> lp_quantization);
  90789. }
  90790. }
  90791. else { /* order == 7 */
  90792. for(i = 0; i < (int)data_len; i++) {
  90793. sum = 0;
  90794. sum += qlp_coeff[6] * data[i-7];
  90795. sum += qlp_coeff[5] * data[i-6];
  90796. sum += qlp_coeff[4] * data[i-5];
  90797. sum += qlp_coeff[3] * data[i-4];
  90798. sum += qlp_coeff[2] * data[i-3];
  90799. sum += qlp_coeff[1] * data[i-2];
  90800. sum += qlp_coeff[0] * data[i-1];
  90801. residual[i] = data[i] - (sum >> lp_quantization);
  90802. }
  90803. }
  90804. }
  90805. else {
  90806. if(order == 6) {
  90807. for(i = 0; i < (int)data_len; i++) {
  90808. sum = 0;
  90809. sum += qlp_coeff[5] * data[i-6];
  90810. sum += qlp_coeff[4] * data[i-5];
  90811. sum += qlp_coeff[3] * data[i-4];
  90812. sum += qlp_coeff[2] * data[i-3];
  90813. sum += qlp_coeff[1] * data[i-2];
  90814. sum += qlp_coeff[0] * data[i-1];
  90815. residual[i] = data[i] - (sum >> lp_quantization);
  90816. }
  90817. }
  90818. else { /* order == 5 */
  90819. for(i = 0; i < (int)data_len; i++) {
  90820. sum = 0;
  90821. sum += qlp_coeff[4] * data[i-5];
  90822. sum += qlp_coeff[3] * data[i-4];
  90823. sum += qlp_coeff[2] * data[i-3];
  90824. sum += qlp_coeff[1] * data[i-2];
  90825. sum += qlp_coeff[0] * data[i-1];
  90826. residual[i] = data[i] - (sum >> lp_quantization);
  90827. }
  90828. }
  90829. }
  90830. }
  90831. else {
  90832. if(order > 2) {
  90833. if(order == 4) {
  90834. for(i = 0; i < (int)data_len; i++) {
  90835. sum = 0;
  90836. sum += qlp_coeff[3] * data[i-4];
  90837. sum += qlp_coeff[2] * data[i-3];
  90838. sum += qlp_coeff[1] * data[i-2];
  90839. sum += qlp_coeff[0] * data[i-1];
  90840. residual[i] = data[i] - (sum >> lp_quantization);
  90841. }
  90842. }
  90843. else { /* order == 3 */
  90844. for(i = 0; i < (int)data_len; i++) {
  90845. sum = 0;
  90846. sum += qlp_coeff[2] * data[i-3];
  90847. sum += qlp_coeff[1] * data[i-2];
  90848. sum += qlp_coeff[0] * data[i-1];
  90849. residual[i] = data[i] - (sum >> lp_quantization);
  90850. }
  90851. }
  90852. }
  90853. else {
  90854. if(order == 2) {
  90855. for(i = 0; i < (int)data_len; i++) {
  90856. sum = 0;
  90857. sum += qlp_coeff[1] * data[i-2];
  90858. sum += qlp_coeff[0] * data[i-1];
  90859. residual[i] = data[i] - (sum >> lp_quantization);
  90860. }
  90861. }
  90862. else { /* order == 1 */
  90863. for(i = 0; i < (int)data_len; i++)
  90864. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  90865. }
  90866. }
  90867. }
  90868. }
  90869. else { /* order > 12 */
  90870. for(i = 0; i < (int)data_len; i++) {
  90871. sum = 0;
  90872. switch(order) {
  90873. case 32: sum += qlp_coeff[31] * data[i-32];
  90874. case 31: sum += qlp_coeff[30] * data[i-31];
  90875. case 30: sum += qlp_coeff[29] * data[i-30];
  90876. case 29: sum += qlp_coeff[28] * data[i-29];
  90877. case 28: sum += qlp_coeff[27] * data[i-28];
  90878. case 27: sum += qlp_coeff[26] * data[i-27];
  90879. case 26: sum += qlp_coeff[25] * data[i-26];
  90880. case 25: sum += qlp_coeff[24] * data[i-25];
  90881. case 24: sum += qlp_coeff[23] * data[i-24];
  90882. case 23: sum += qlp_coeff[22] * data[i-23];
  90883. case 22: sum += qlp_coeff[21] * data[i-22];
  90884. case 21: sum += qlp_coeff[20] * data[i-21];
  90885. case 20: sum += qlp_coeff[19] * data[i-20];
  90886. case 19: sum += qlp_coeff[18] * data[i-19];
  90887. case 18: sum += qlp_coeff[17] * data[i-18];
  90888. case 17: sum += qlp_coeff[16] * data[i-17];
  90889. case 16: sum += qlp_coeff[15] * data[i-16];
  90890. case 15: sum += qlp_coeff[14] * data[i-15];
  90891. case 14: sum += qlp_coeff[13] * data[i-14];
  90892. case 13: sum += qlp_coeff[12] * data[i-13];
  90893. sum += qlp_coeff[11] * data[i-12];
  90894. sum += qlp_coeff[10] * data[i-11];
  90895. sum += qlp_coeff[ 9] * data[i-10];
  90896. sum += qlp_coeff[ 8] * data[i- 9];
  90897. sum += qlp_coeff[ 7] * data[i- 8];
  90898. sum += qlp_coeff[ 6] * data[i- 7];
  90899. sum += qlp_coeff[ 5] * data[i- 6];
  90900. sum += qlp_coeff[ 4] * data[i- 5];
  90901. sum += qlp_coeff[ 3] * data[i- 4];
  90902. sum += qlp_coeff[ 2] * data[i- 3];
  90903. sum += qlp_coeff[ 1] * data[i- 2];
  90904. sum += qlp_coeff[ 0] * data[i- 1];
  90905. }
  90906. residual[i] = data[i] - (sum >> lp_quantization);
  90907. }
  90908. }
  90909. }
  90910. #endif
  90911. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  90912. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  90913. {
  90914. unsigned i, j;
  90915. FLAC__int64 sum;
  90916. const FLAC__int32 *history;
  90917. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  90918. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  90919. for(i=0;i<order;i++)
  90920. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  90921. fprintf(stderr,"\n");
  90922. #endif
  90923. FLAC__ASSERT(order > 0);
  90924. for(i = 0; i < data_len; i++) {
  90925. sum = 0;
  90926. history = data;
  90927. for(j = 0; j < order; j++)
  90928. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  90929. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  90930. #if defined _MSC_VER
  90931. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  90932. #else
  90933. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  90934. #endif
  90935. break;
  90936. }
  90937. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  90938. #if defined _MSC_VER
  90939. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
  90940. #else
  90941. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
  90942. #endif
  90943. break;
  90944. }
  90945. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  90946. }
  90947. }
  90948. #else /* fully unrolled version for normal use */
  90949. {
  90950. int i;
  90951. FLAC__int64 sum;
  90952. FLAC__ASSERT(order > 0);
  90953. FLAC__ASSERT(order <= 32);
  90954. /*
  90955. * We do unique versions up to 12th order since that's the subset limit.
  90956. * Also they are roughly ordered to match frequency of occurrence to
  90957. * minimize branching.
  90958. */
  90959. if(order <= 12) {
  90960. if(order > 8) {
  90961. if(order > 10) {
  90962. if(order == 12) {
  90963. for(i = 0; i < (int)data_len; i++) {
  90964. sum = 0;
  90965. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  90966. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  90967. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  90968. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  90969. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  90970. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  90971. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  90972. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  90973. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  90974. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  90975. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  90976. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  90977. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  90978. }
  90979. }
  90980. else { /* order == 11 */
  90981. for(i = 0; i < (int)data_len; i++) {
  90982. sum = 0;
  90983. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  90984. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  90985. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  90986. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  90987. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  90988. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  90989. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  90990. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  90991. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  90992. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  90993. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  90994. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  90995. }
  90996. }
  90997. }
  90998. else {
  90999. if(order == 10) {
  91000. for(i = 0; i < (int)data_len; i++) {
  91001. sum = 0;
  91002. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91003. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91004. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91005. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91006. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91007. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91008. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91009. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91010. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91011. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91012. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91013. }
  91014. }
  91015. else { /* order == 9 */
  91016. for(i = 0; i < (int)data_len; i++) {
  91017. sum = 0;
  91018. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91019. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91020. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91021. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91022. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91023. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91024. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91025. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91026. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91027. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91028. }
  91029. }
  91030. }
  91031. }
  91032. else if(order > 4) {
  91033. if(order > 6) {
  91034. if(order == 8) {
  91035. for(i = 0; i < (int)data_len; i++) {
  91036. sum = 0;
  91037. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91038. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91039. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91040. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91041. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91042. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91043. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91044. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91045. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91046. }
  91047. }
  91048. else { /* order == 7 */
  91049. for(i = 0; i < (int)data_len; i++) {
  91050. sum = 0;
  91051. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91052. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91053. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91054. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91055. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91056. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91057. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91058. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91059. }
  91060. }
  91061. }
  91062. else {
  91063. if(order == 6) {
  91064. for(i = 0; i < (int)data_len; i++) {
  91065. sum = 0;
  91066. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91067. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91068. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91069. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91070. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91071. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91072. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91073. }
  91074. }
  91075. else { /* order == 5 */
  91076. for(i = 0; i < (int)data_len; i++) {
  91077. sum = 0;
  91078. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91079. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91080. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91081. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91082. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91083. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91084. }
  91085. }
  91086. }
  91087. }
  91088. else {
  91089. if(order > 2) {
  91090. if(order == 4) {
  91091. for(i = 0; i < (int)data_len; i++) {
  91092. sum = 0;
  91093. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91094. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91095. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91096. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91097. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91098. }
  91099. }
  91100. else { /* order == 3 */
  91101. for(i = 0; i < (int)data_len; i++) {
  91102. sum = 0;
  91103. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91104. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91105. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91106. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91107. }
  91108. }
  91109. }
  91110. else {
  91111. if(order == 2) {
  91112. for(i = 0; i < (int)data_len; i++) {
  91113. sum = 0;
  91114. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91115. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91116. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91117. }
  91118. }
  91119. else { /* order == 1 */
  91120. for(i = 0; i < (int)data_len; i++)
  91121. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91122. }
  91123. }
  91124. }
  91125. }
  91126. else { /* order > 12 */
  91127. for(i = 0; i < (int)data_len; i++) {
  91128. sum = 0;
  91129. switch(order) {
  91130. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91131. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91132. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91133. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91134. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91135. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91136. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91137. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91138. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91139. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91140. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91141. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91142. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91143. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91144. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91145. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91146. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91147. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91148. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91149. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91150. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91151. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91152. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91153. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91154. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91155. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91156. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91157. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91158. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91159. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91160. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91161. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91162. }
  91163. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91164. }
  91165. }
  91166. }
  91167. #endif
  91168. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91169. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  91170. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91171. {
  91172. FLAC__int64 sumo;
  91173. unsigned i, j;
  91174. FLAC__int32 sum;
  91175. const FLAC__int32 *r = residual, *history;
  91176. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91177. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91178. for(i=0;i<order;i++)
  91179. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91180. fprintf(stderr,"\n");
  91181. #endif
  91182. FLAC__ASSERT(order > 0);
  91183. for(i = 0; i < data_len; i++) {
  91184. sumo = 0;
  91185. sum = 0;
  91186. history = data;
  91187. for(j = 0; j < order; j++) {
  91188. sum += qlp_coeff[j] * (*(--history));
  91189. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91190. #if defined _MSC_VER
  91191. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91192. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  91193. #else
  91194. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91195. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  91196. #endif
  91197. }
  91198. *(data++) = *(r++) + (sum >> lp_quantization);
  91199. }
  91200. /* Here's a slower but clearer version:
  91201. for(i = 0; i < data_len; i++) {
  91202. sum = 0;
  91203. for(j = 0; j < order; j++)
  91204. sum += qlp_coeff[j] * data[i-j-1];
  91205. data[i] = residual[i] + (sum >> lp_quantization);
  91206. }
  91207. */
  91208. }
  91209. #else /* fully unrolled version for normal use */
  91210. {
  91211. int i;
  91212. FLAC__int32 sum;
  91213. FLAC__ASSERT(order > 0);
  91214. FLAC__ASSERT(order <= 32);
  91215. /*
  91216. * We do unique versions up to 12th order since that's the subset limit.
  91217. * Also they are roughly ordered to match frequency of occurrence to
  91218. * minimize branching.
  91219. */
  91220. if(order <= 12) {
  91221. if(order > 8) {
  91222. if(order > 10) {
  91223. if(order == 12) {
  91224. for(i = 0; i < (int)data_len; i++) {
  91225. sum = 0;
  91226. sum += qlp_coeff[11] * data[i-12];
  91227. sum += qlp_coeff[10] * data[i-11];
  91228. sum += qlp_coeff[9] * data[i-10];
  91229. sum += qlp_coeff[8] * data[i-9];
  91230. sum += qlp_coeff[7] * data[i-8];
  91231. sum += qlp_coeff[6] * data[i-7];
  91232. sum += qlp_coeff[5] * data[i-6];
  91233. sum += qlp_coeff[4] * data[i-5];
  91234. sum += qlp_coeff[3] * data[i-4];
  91235. sum += qlp_coeff[2] * data[i-3];
  91236. sum += qlp_coeff[1] * data[i-2];
  91237. sum += qlp_coeff[0] * data[i-1];
  91238. data[i] = residual[i] + (sum >> lp_quantization);
  91239. }
  91240. }
  91241. else { /* order == 11 */
  91242. for(i = 0; i < (int)data_len; i++) {
  91243. sum = 0;
  91244. sum += qlp_coeff[10] * data[i-11];
  91245. sum += qlp_coeff[9] * data[i-10];
  91246. sum += qlp_coeff[8] * data[i-9];
  91247. sum += qlp_coeff[7] * data[i-8];
  91248. sum += qlp_coeff[6] * data[i-7];
  91249. sum += qlp_coeff[5] * data[i-6];
  91250. sum += qlp_coeff[4] * data[i-5];
  91251. sum += qlp_coeff[3] * data[i-4];
  91252. sum += qlp_coeff[2] * data[i-3];
  91253. sum += qlp_coeff[1] * data[i-2];
  91254. sum += qlp_coeff[0] * data[i-1];
  91255. data[i] = residual[i] + (sum >> lp_quantization);
  91256. }
  91257. }
  91258. }
  91259. else {
  91260. if(order == 10) {
  91261. for(i = 0; i < (int)data_len; i++) {
  91262. sum = 0;
  91263. sum += qlp_coeff[9] * data[i-10];
  91264. sum += qlp_coeff[8] * data[i-9];
  91265. sum += qlp_coeff[7] * data[i-8];
  91266. sum += qlp_coeff[6] * data[i-7];
  91267. sum += qlp_coeff[5] * data[i-6];
  91268. sum += qlp_coeff[4] * data[i-5];
  91269. sum += qlp_coeff[3] * data[i-4];
  91270. sum += qlp_coeff[2] * data[i-3];
  91271. sum += qlp_coeff[1] * data[i-2];
  91272. sum += qlp_coeff[0] * data[i-1];
  91273. data[i] = residual[i] + (sum >> lp_quantization);
  91274. }
  91275. }
  91276. else { /* order == 9 */
  91277. for(i = 0; i < (int)data_len; i++) {
  91278. sum = 0;
  91279. sum += qlp_coeff[8] * data[i-9];
  91280. sum += qlp_coeff[7] * data[i-8];
  91281. sum += qlp_coeff[6] * data[i-7];
  91282. sum += qlp_coeff[5] * data[i-6];
  91283. sum += qlp_coeff[4] * data[i-5];
  91284. sum += qlp_coeff[3] * data[i-4];
  91285. sum += qlp_coeff[2] * data[i-3];
  91286. sum += qlp_coeff[1] * data[i-2];
  91287. sum += qlp_coeff[0] * data[i-1];
  91288. data[i] = residual[i] + (sum >> lp_quantization);
  91289. }
  91290. }
  91291. }
  91292. }
  91293. else if(order > 4) {
  91294. if(order > 6) {
  91295. if(order == 8) {
  91296. for(i = 0; i < (int)data_len; i++) {
  91297. sum = 0;
  91298. sum += qlp_coeff[7] * data[i-8];
  91299. sum += qlp_coeff[6] * data[i-7];
  91300. sum += qlp_coeff[5] * data[i-6];
  91301. sum += qlp_coeff[4] * data[i-5];
  91302. sum += qlp_coeff[3] * data[i-4];
  91303. sum += qlp_coeff[2] * data[i-3];
  91304. sum += qlp_coeff[1] * data[i-2];
  91305. sum += qlp_coeff[0] * data[i-1];
  91306. data[i] = residual[i] + (sum >> lp_quantization);
  91307. }
  91308. }
  91309. else { /* order == 7 */
  91310. for(i = 0; i < (int)data_len; i++) {
  91311. sum = 0;
  91312. sum += qlp_coeff[6] * data[i-7];
  91313. sum += qlp_coeff[5] * data[i-6];
  91314. sum += qlp_coeff[4] * data[i-5];
  91315. sum += qlp_coeff[3] * data[i-4];
  91316. sum += qlp_coeff[2] * data[i-3];
  91317. sum += qlp_coeff[1] * data[i-2];
  91318. sum += qlp_coeff[0] * data[i-1];
  91319. data[i] = residual[i] + (sum >> lp_quantization);
  91320. }
  91321. }
  91322. }
  91323. else {
  91324. if(order == 6) {
  91325. for(i = 0; i < (int)data_len; i++) {
  91326. sum = 0;
  91327. sum += qlp_coeff[5] * data[i-6];
  91328. sum += qlp_coeff[4] * data[i-5];
  91329. sum += qlp_coeff[3] * data[i-4];
  91330. sum += qlp_coeff[2] * data[i-3];
  91331. sum += qlp_coeff[1] * data[i-2];
  91332. sum += qlp_coeff[0] * data[i-1];
  91333. data[i] = residual[i] + (sum >> lp_quantization);
  91334. }
  91335. }
  91336. else { /* order == 5 */
  91337. for(i = 0; i < (int)data_len; i++) {
  91338. sum = 0;
  91339. sum += qlp_coeff[4] * data[i-5];
  91340. sum += qlp_coeff[3] * data[i-4];
  91341. sum += qlp_coeff[2] * data[i-3];
  91342. sum += qlp_coeff[1] * data[i-2];
  91343. sum += qlp_coeff[0] * data[i-1];
  91344. data[i] = residual[i] + (sum >> lp_quantization);
  91345. }
  91346. }
  91347. }
  91348. }
  91349. else {
  91350. if(order > 2) {
  91351. if(order == 4) {
  91352. for(i = 0; i < (int)data_len; i++) {
  91353. sum = 0;
  91354. sum += qlp_coeff[3] * data[i-4];
  91355. sum += qlp_coeff[2] * data[i-3];
  91356. sum += qlp_coeff[1] * data[i-2];
  91357. sum += qlp_coeff[0] * data[i-1];
  91358. data[i] = residual[i] + (sum >> lp_quantization);
  91359. }
  91360. }
  91361. else { /* order == 3 */
  91362. for(i = 0; i < (int)data_len; i++) {
  91363. sum = 0;
  91364. sum += qlp_coeff[2] * data[i-3];
  91365. sum += qlp_coeff[1] * data[i-2];
  91366. sum += qlp_coeff[0] * data[i-1];
  91367. data[i] = residual[i] + (sum >> lp_quantization);
  91368. }
  91369. }
  91370. }
  91371. else {
  91372. if(order == 2) {
  91373. for(i = 0; i < (int)data_len; i++) {
  91374. sum = 0;
  91375. sum += qlp_coeff[1] * data[i-2];
  91376. sum += qlp_coeff[0] * data[i-1];
  91377. data[i] = residual[i] + (sum >> lp_quantization);
  91378. }
  91379. }
  91380. else { /* order == 1 */
  91381. for(i = 0; i < (int)data_len; i++)
  91382. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  91383. }
  91384. }
  91385. }
  91386. }
  91387. else { /* order > 12 */
  91388. for(i = 0; i < (int)data_len; i++) {
  91389. sum = 0;
  91390. switch(order) {
  91391. case 32: sum += qlp_coeff[31] * data[i-32];
  91392. case 31: sum += qlp_coeff[30] * data[i-31];
  91393. case 30: sum += qlp_coeff[29] * data[i-30];
  91394. case 29: sum += qlp_coeff[28] * data[i-29];
  91395. case 28: sum += qlp_coeff[27] * data[i-28];
  91396. case 27: sum += qlp_coeff[26] * data[i-27];
  91397. case 26: sum += qlp_coeff[25] * data[i-26];
  91398. case 25: sum += qlp_coeff[24] * data[i-25];
  91399. case 24: sum += qlp_coeff[23] * data[i-24];
  91400. case 23: sum += qlp_coeff[22] * data[i-23];
  91401. case 22: sum += qlp_coeff[21] * data[i-22];
  91402. case 21: sum += qlp_coeff[20] * data[i-21];
  91403. case 20: sum += qlp_coeff[19] * data[i-20];
  91404. case 19: sum += qlp_coeff[18] * data[i-19];
  91405. case 18: sum += qlp_coeff[17] * data[i-18];
  91406. case 17: sum += qlp_coeff[16] * data[i-17];
  91407. case 16: sum += qlp_coeff[15] * data[i-16];
  91408. case 15: sum += qlp_coeff[14] * data[i-15];
  91409. case 14: sum += qlp_coeff[13] * data[i-14];
  91410. case 13: sum += qlp_coeff[12] * data[i-13];
  91411. sum += qlp_coeff[11] * data[i-12];
  91412. sum += qlp_coeff[10] * data[i-11];
  91413. sum += qlp_coeff[ 9] * data[i-10];
  91414. sum += qlp_coeff[ 8] * data[i- 9];
  91415. sum += qlp_coeff[ 7] * data[i- 8];
  91416. sum += qlp_coeff[ 6] * data[i- 7];
  91417. sum += qlp_coeff[ 5] * data[i- 6];
  91418. sum += qlp_coeff[ 4] * data[i- 5];
  91419. sum += qlp_coeff[ 3] * data[i- 4];
  91420. sum += qlp_coeff[ 2] * data[i- 3];
  91421. sum += qlp_coeff[ 1] * data[i- 2];
  91422. sum += qlp_coeff[ 0] * data[i- 1];
  91423. }
  91424. data[i] = residual[i] + (sum >> lp_quantization);
  91425. }
  91426. }
  91427. }
  91428. #endif
  91429. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  91430. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91431. {
  91432. unsigned i, j;
  91433. FLAC__int64 sum;
  91434. const FLAC__int32 *r = residual, *history;
  91435. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91436. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91437. for(i=0;i<order;i++)
  91438. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91439. fprintf(stderr,"\n");
  91440. #endif
  91441. FLAC__ASSERT(order > 0);
  91442. for(i = 0; i < data_len; i++) {
  91443. sum = 0;
  91444. history = data;
  91445. for(j = 0; j < order; j++)
  91446. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  91447. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  91448. #ifdef _MSC_VER
  91449. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  91450. #else
  91451. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  91452. #endif
  91453. break;
  91454. }
  91455. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  91456. #ifdef _MSC_VER
  91457. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization));
  91458. #else
  91459. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
  91460. #endif
  91461. break;
  91462. }
  91463. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  91464. }
  91465. }
  91466. #else /* fully unrolled version for normal use */
  91467. {
  91468. int i;
  91469. FLAC__int64 sum;
  91470. FLAC__ASSERT(order > 0);
  91471. FLAC__ASSERT(order <= 32);
  91472. /*
  91473. * We do unique versions up to 12th order since that's the subset limit.
  91474. * Also they are roughly ordered to match frequency of occurrence to
  91475. * minimize branching.
  91476. */
  91477. if(order <= 12) {
  91478. if(order > 8) {
  91479. if(order > 10) {
  91480. if(order == 12) {
  91481. for(i = 0; i < (int)data_len; i++) {
  91482. sum = 0;
  91483. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91484. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91485. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91486. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91487. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91488. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91489. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91490. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91491. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91492. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91493. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91494. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91495. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91496. }
  91497. }
  91498. else { /* order == 11 */
  91499. for(i = 0; i < (int)data_len; i++) {
  91500. sum = 0;
  91501. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91502. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91503. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91504. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91505. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91506. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91507. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91508. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91509. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91510. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91511. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91512. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91513. }
  91514. }
  91515. }
  91516. else {
  91517. if(order == 10) {
  91518. for(i = 0; i < (int)data_len; i++) {
  91519. sum = 0;
  91520. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91521. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91522. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91523. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91524. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91525. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91526. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91527. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91528. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91529. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91530. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91531. }
  91532. }
  91533. else { /* order == 9 */
  91534. for(i = 0; i < (int)data_len; i++) {
  91535. sum = 0;
  91536. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91537. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91538. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91539. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91540. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91541. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91542. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91543. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91544. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91545. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91546. }
  91547. }
  91548. }
  91549. }
  91550. else if(order > 4) {
  91551. if(order > 6) {
  91552. if(order == 8) {
  91553. for(i = 0; i < (int)data_len; i++) {
  91554. sum = 0;
  91555. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91556. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91557. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91558. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91559. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91560. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91561. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91562. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91563. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91564. }
  91565. }
  91566. else { /* order == 7 */
  91567. for(i = 0; i < (int)data_len; i++) {
  91568. sum = 0;
  91569. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91570. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91571. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91572. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91573. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91574. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91575. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91576. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91577. }
  91578. }
  91579. }
  91580. else {
  91581. if(order == 6) {
  91582. for(i = 0; i < (int)data_len; i++) {
  91583. sum = 0;
  91584. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91585. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91586. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91587. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91588. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91589. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91590. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91591. }
  91592. }
  91593. else { /* order == 5 */
  91594. for(i = 0; i < (int)data_len; i++) {
  91595. sum = 0;
  91596. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91597. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91598. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91599. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91600. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91601. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91602. }
  91603. }
  91604. }
  91605. }
  91606. else {
  91607. if(order > 2) {
  91608. if(order == 4) {
  91609. for(i = 0; i < (int)data_len; i++) {
  91610. sum = 0;
  91611. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91612. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91613. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91614. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91615. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91616. }
  91617. }
  91618. else { /* order == 3 */
  91619. for(i = 0; i < (int)data_len; i++) {
  91620. sum = 0;
  91621. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91622. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91623. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91624. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91625. }
  91626. }
  91627. }
  91628. else {
  91629. if(order == 2) {
  91630. for(i = 0; i < (int)data_len; i++) {
  91631. sum = 0;
  91632. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91633. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91634. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91635. }
  91636. }
  91637. else { /* order == 1 */
  91638. for(i = 0; i < (int)data_len; i++)
  91639. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91640. }
  91641. }
  91642. }
  91643. }
  91644. else { /* order > 12 */
  91645. for(i = 0; i < (int)data_len; i++) {
  91646. sum = 0;
  91647. switch(order) {
  91648. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91649. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91650. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91651. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91652. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91653. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91654. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91655. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91656. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91657. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91658. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91659. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91660. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91661. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91662. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91663. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91664. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91665. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91666. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91667. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91668. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91669. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91670. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91671. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91672. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91673. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91674. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91675. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91676. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91677. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91678. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91679. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91680. }
  91681. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91682. }
  91683. }
  91684. }
  91685. #endif
  91686. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91687. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  91688. {
  91689. FLAC__double error_scale;
  91690. FLAC__ASSERT(total_samples > 0);
  91691. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  91692. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  91693. }
  91694. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  91695. {
  91696. if(lpc_error > 0.0) {
  91697. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  91698. if(bps >= 0.0)
  91699. return bps;
  91700. else
  91701. return 0.0;
  91702. }
  91703. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  91704. return 1e32;
  91705. }
  91706. else {
  91707. return 0.0;
  91708. }
  91709. }
  91710. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  91711. {
  91712. unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
  91713. FLAC__double bits, best_bits, error_scale;
  91714. FLAC__ASSERT(max_order > 0);
  91715. FLAC__ASSERT(total_samples > 0);
  91716. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  91717. best_index = 0;
  91718. best_bits = (unsigned)(-1);
  91719. for(index = 0, order = 1; index < max_order; index++, order++) {
  91720. bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
  91721. if(bits < best_bits) {
  91722. best_index = index;
  91723. best_bits = bits;
  91724. }
  91725. }
  91726. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  91727. }
  91728. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91729. #endif
  91730. /********* End of inlined file: lpc_flac.c *********/
  91731. /********* Start of inlined file: md5.c *********/
  91732. /********* Start of inlined file: juce_FlacHeader.h *********/
  91733. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91734. // tasks..
  91735. #define VERSION "1.2.1"
  91736. #define FLAC__NO_DLL 1
  91737. #ifdef _MSC_VER
  91738. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91739. #endif
  91740. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91741. #define FLAC__SYS_DARWIN 1
  91742. #endif
  91743. /********* End of inlined file: juce_FlacHeader.h *********/
  91744. #if JUCE_USE_FLAC
  91745. #if HAVE_CONFIG_H
  91746. # include <config.h>
  91747. #endif
  91748. #include <stdlib.h> /* for malloc() */
  91749. #include <string.h> /* for memcpy() */
  91750. /********* Start of inlined file: md5.h *********/
  91751. #ifndef FLAC__PRIVATE__MD5_H
  91752. #define FLAC__PRIVATE__MD5_H
  91753. /*
  91754. * This is the header file for the MD5 message-digest algorithm.
  91755. * The algorithm is due to Ron Rivest. This code was
  91756. * written by Colin Plumb in 1993, no copyright is claimed.
  91757. * This code is in the public domain; do with it what you wish.
  91758. *
  91759. * Equivalent code is available from RSA Data Security, Inc.
  91760. * This code has been tested against that, and is equivalent,
  91761. * except that you don't need to include two pages of legalese
  91762. * with every copy.
  91763. *
  91764. * To compute the message digest of a chunk of bytes, declare an
  91765. * MD5Context structure, pass it to MD5Init, call MD5Update as
  91766. * needed on buffers full of bytes, and then call MD5Final, which
  91767. * will fill a supplied 16-byte array with the digest.
  91768. *
  91769. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  91770. * header definitions; now uses stuff from dpkg's config.h
  91771. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  91772. * Still in the public domain.
  91773. *
  91774. * Josh Coalson: made some changes to integrate with libFLAC.
  91775. * Still in the public domain, with no warranty.
  91776. */
  91777. typedef struct {
  91778. FLAC__uint32 in[16];
  91779. FLAC__uint32 buf[4];
  91780. FLAC__uint32 bytes[2];
  91781. FLAC__byte *internal_buf;
  91782. size_t capacity;
  91783. } FLAC__MD5Context;
  91784. void FLAC__MD5Init(FLAC__MD5Context *context);
  91785. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  91786. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  91787. #endif
  91788. /********* End of inlined file: md5.h *********/
  91789. #ifndef FLaC__INLINE
  91790. #define FLaC__INLINE
  91791. #endif
  91792. /*
  91793. * This code implements the MD5 message-digest algorithm.
  91794. * The algorithm is due to Ron Rivest. This code was
  91795. * written by Colin Plumb in 1993, no copyright is claimed.
  91796. * This code is in the public domain; do with it what you wish.
  91797. *
  91798. * Equivalent code is available from RSA Data Security, Inc.
  91799. * This code has been tested against that, and is equivalent,
  91800. * except that you don't need to include two pages of legalese
  91801. * with every copy.
  91802. *
  91803. * To compute the message digest of a chunk of bytes, declare an
  91804. * MD5Context structure, pass it to MD5Init, call MD5Update as
  91805. * needed on buffers full of bytes, and then call MD5Final, which
  91806. * will fill a supplied 16-byte array with the digest.
  91807. *
  91808. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  91809. * definitions; now uses stuff from dpkg's config.h.
  91810. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  91811. * Still in the public domain.
  91812. *
  91813. * Josh Coalson: made some changes to integrate with libFLAC.
  91814. * Still in the public domain.
  91815. */
  91816. /* The four core functions - F1 is optimized somewhat */
  91817. /* #define F1(x, y, z) (x & y | ~x & z) */
  91818. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  91819. #define F2(x, y, z) F1(z, x, y)
  91820. #define F3(x, y, z) (x ^ y ^ z)
  91821. #define F4(x, y, z) (y ^ (x | ~z))
  91822. /* This is the central step in the MD5 algorithm. */
  91823. #define MD5STEP(f,w,x,y,z,in,s) \
  91824. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  91825. /*
  91826. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  91827. * reflect the addition of 16 longwords of new data. MD5Update blocks
  91828. * the data and converts bytes into longwords for this routine.
  91829. */
  91830. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  91831. {
  91832. register FLAC__uint32 a, b, c, d;
  91833. a = buf[0];
  91834. b = buf[1];
  91835. c = buf[2];
  91836. d = buf[3];
  91837. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  91838. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  91839. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  91840. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  91841. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  91842. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  91843. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  91844. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  91845. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  91846. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  91847. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  91848. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  91849. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  91850. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  91851. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  91852. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  91853. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  91854. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  91855. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  91856. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  91857. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  91858. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  91859. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  91860. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  91861. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  91862. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  91863. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  91864. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  91865. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  91866. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  91867. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  91868. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  91869. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  91870. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  91871. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  91872. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  91873. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  91874. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  91875. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  91876. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  91877. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  91878. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  91879. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  91880. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  91881. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  91882. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  91883. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  91884. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  91885. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  91886. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  91887. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  91888. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  91889. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  91890. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  91891. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  91892. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  91893. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  91894. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  91895. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  91896. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  91897. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  91898. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  91899. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  91900. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  91901. buf[0] += a;
  91902. buf[1] += b;
  91903. buf[2] += c;
  91904. buf[3] += d;
  91905. }
  91906. #if WORDS_BIGENDIAN
  91907. //@@@@@@ OPT: use bswap/intrinsics
  91908. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  91909. {
  91910. register FLAC__uint32 x;
  91911. do {
  91912. x = *buf;
  91913. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  91914. *buf++ = (x >> 16) | (x << 16);
  91915. } while (--words);
  91916. }
  91917. static void byteSwapX16(FLAC__uint32 *buf)
  91918. {
  91919. register FLAC__uint32 x;
  91920. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91921. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91922. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91923. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91924. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91925. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91926. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91927. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91928. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91929. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91930. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91931. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91932. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91933. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91934. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91935. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  91936. }
  91937. #else
  91938. #define byteSwap(buf, words)
  91939. #define byteSwapX16(buf)
  91940. #endif
  91941. /*
  91942. * Update context to reflect the concatenation of another buffer full
  91943. * of bytes.
  91944. */
  91945. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  91946. {
  91947. FLAC__uint32 t;
  91948. /* Update byte count */
  91949. t = ctx->bytes[0];
  91950. if ((ctx->bytes[0] = t + len) < t)
  91951. ctx->bytes[1]++; /* Carry from low to high */
  91952. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  91953. if (t > len) {
  91954. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  91955. return;
  91956. }
  91957. /* First chunk is an odd size */
  91958. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  91959. byteSwapX16(ctx->in);
  91960. FLAC__MD5Transform(ctx->buf, ctx->in);
  91961. buf += t;
  91962. len -= t;
  91963. /* Process data in 64-byte chunks */
  91964. while (len >= 64) {
  91965. memcpy(ctx->in, buf, 64);
  91966. byteSwapX16(ctx->in);
  91967. FLAC__MD5Transform(ctx->buf, ctx->in);
  91968. buf += 64;
  91969. len -= 64;
  91970. }
  91971. /* Handle any remaining bytes of data. */
  91972. memcpy(ctx->in, buf, len);
  91973. }
  91974. /*
  91975. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  91976. * initialization constants.
  91977. */
  91978. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  91979. {
  91980. ctx->buf[0] = 0x67452301;
  91981. ctx->buf[1] = 0xefcdab89;
  91982. ctx->buf[2] = 0x98badcfe;
  91983. ctx->buf[3] = 0x10325476;
  91984. ctx->bytes[0] = 0;
  91985. ctx->bytes[1] = 0;
  91986. ctx->internal_buf = 0;
  91987. ctx->capacity = 0;
  91988. }
  91989. /*
  91990. * Final wrapup - pad to 64-byte boundary with the bit pattern
  91991. * 1 0* (64-bit count of bits processed, MSB-first)
  91992. */
  91993. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  91994. {
  91995. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  91996. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  91997. /* Set the first char of padding to 0x80. There is always room. */
  91998. *p++ = 0x80;
  91999. /* Bytes of padding needed to make 56 bytes (-8..55) */
  92000. count = 56 - 1 - count;
  92001. if (count < 0) { /* Padding forces an extra block */
  92002. memset(p, 0, count + 8);
  92003. byteSwapX16(ctx->in);
  92004. FLAC__MD5Transform(ctx->buf, ctx->in);
  92005. p = (FLAC__byte *)ctx->in;
  92006. count = 56;
  92007. }
  92008. memset(p, 0, count);
  92009. byteSwap(ctx->in, 14);
  92010. /* Append length in bits and transform */
  92011. ctx->in[14] = ctx->bytes[0] << 3;
  92012. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  92013. FLAC__MD5Transform(ctx->buf, ctx->in);
  92014. byteSwap(ctx->buf, 4);
  92015. memcpy(digest, ctx->buf, 16);
  92016. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  92017. if(0 != ctx->internal_buf) {
  92018. free(ctx->internal_buf);
  92019. ctx->internal_buf = 0;
  92020. ctx->capacity = 0;
  92021. }
  92022. }
  92023. /*
  92024. * Convert the incoming audio signal to a byte stream
  92025. */
  92026. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92027. {
  92028. unsigned channel, sample;
  92029. register FLAC__int32 a_word;
  92030. register FLAC__byte *buf_ = buf;
  92031. #if WORDS_BIGENDIAN
  92032. #else
  92033. if(channels == 2 && bytes_per_sample == 2) {
  92034. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  92035. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  92036. for(sample = 0; sample < samples; sample++, buf1_+=2)
  92037. *buf1_ = (FLAC__int16)signal[1][sample];
  92038. }
  92039. else if(channels == 1 && bytes_per_sample == 2) {
  92040. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  92041. for(sample = 0; sample < samples; sample++)
  92042. *buf1_++ = (FLAC__int16)signal[0][sample];
  92043. }
  92044. else
  92045. #endif
  92046. if(bytes_per_sample == 2) {
  92047. if(channels == 2) {
  92048. for(sample = 0; sample < samples; sample++) {
  92049. a_word = signal[0][sample];
  92050. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92051. *buf_++ = (FLAC__byte)a_word;
  92052. a_word = signal[1][sample];
  92053. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92054. *buf_++ = (FLAC__byte)a_word;
  92055. }
  92056. }
  92057. else if(channels == 1) {
  92058. for(sample = 0; sample < samples; sample++) {
  92059. a_word = signal[0][sample];
  92060. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92061. *buf_++ = (FLAC__byte)a_word;
  92062. }
  92063. }
  92064. else {
  92065. for(sample = 0; sample < samples; sample++) {
  92066. for(channel = 0; channel < channels; channel++) {
  92067. a_word = signal[channel][sample];
  92068. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92069. *buf_++ = (FLAC__byte)a_word;
  92070. }
  92071. }
  92072. }
  92073. }
  92074. else if(bytes_per_sample == 3) {
  92075. if(channels == 2) {
  92076. for(sample = 0; sample < samples; sample++) {
  92077. a_word = signal[0][sample];
  92078. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92079. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92080. *buf_++ = (FLAC__byte)a_word;
  92081. a_word = signal[1][sample];
  92082. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92083. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92084. *buf_++ = (FLAC__byte)a_word;
  92085. }
  92086. }
  92087. else if(channels == 1) {
  92088. for(sample = 0; sample < samples; sample++) {
  92089. a_word = signal[0][sample];
  92090. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92091. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92092. *buf_++ = (FLAC__byte)a_word;
  92093. }
  92094. }
  92095. else {
  92096. for(sample = 0; sample < samples; sample++) {
  92097. for(channel = 0; channel < channels; channel++) {
  92098. a_word = signal[channel][sample];
  92099. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92100. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92101. *buf_++ = (FLAC__byte)a_word;
  92102. }
  92103. }
  92104. }
  92105. }
  92106. else if(bytes_per_sample == 1) {
  92107. if(channels == 2) {
  92108. for(sample = 0; sample < samples; sample++) {
  92109. a_word = signal[0][sample];
  92110. *buf_++ = (FLAC__byte)a_word;
  92111. a_word = signal[1][sample];
  92112. *buf_++ = (FLAC__byte)a_word;
  92113. }
  92114. }
  92115. else if(channels == 1) {
  92116. for(sample = 0; sample < samples; sample++) {
  92117. a_word = signal[0][sample];
  92118. *buf_++ = (FLAC__byte)a_word;
  92119. }
  92120. }
  92121. else {
  92122. for(sample = 0; sample < samples; sample++) {
  92123. for(channel = 0; channel < channels; channel++) {
  92124. a_word = signal[channel][sample];
  92125. *buf_++ = (FLAC__byte)a_word;
  92126. }
  92127. }
  92128. }
  92129. }
  92130. else { /* bytes_per_sample == 4, maybe optimize more later */
  92131. for(sample = 0; sample < samples; sample++) {
  92132. for(channel = 0; channel < channels; channel++) {
  92133. a_word = signal[channel][sample];
  92134. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92135. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92136. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92137. *buf_++ = (FLAC__byte)a_word;
  92138. }
  92139. }
  92140. }
  92141. }
  92142. /*
  92143. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  92144. */
  92145. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92146. {
  92147. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  92148. /* overflow check */
  92149. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  92150. return false;
  92151. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  92152. return false;
  92153. if(ctx->capacity < bytes_needed) {
  92154. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  92155. if(0 == tmp) {
  92156. free(ctx->internal_buf);
  92157. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  92158. return false;
  92159. }
  92160. ctx->internal_buf = tmp;
  92161. ctx->capacity = bytes_needed;
  92162. }
  92163. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  92164. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  92165. return true;
  92166. }
  92167. #endif
  92168. /********* End of inlined file: md5.c *********/
  92169. /********* Start of inlined file: memory.c *********/
  92170. /********* Start of inlined file: juce_FlacHeader.h *********/
  92171. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92172. // tasks..
  92173. #define VERSION "1.2.1"
  92174. #define FLAC__NO_DLL 1
  92175. #ifdef _MSC_VER
  92176. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92177. #endif
  92178. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92179. #define FLAC__SYS_DARWIN 1
  92180. #endif
  92181. /********* End of inlined file: juce_FlacHeader.h *********/
  92182. #if JUCE_USE_FLAC
  92183. #if HAVE_CONFIG_H
  92184. # include <config.h>
  92185. #endif
  92186. /********* Start of inlined file: memory.h *********/
  92187. #ifndef FLAC__PRIVATE__MEMORY_H
  92188. #define FLAC__PRIVATE__MEMORY_H
  92189. #ifdef HAVE_CONFIG_H
  92190. #include <config.h>
  92191. #endif
  92192. #include <stdlib.h> /* for size_t */
  92193. /* Returns the unaligned address returned by malloc.
  92194. * Use free() on this address to deallocate.
  92195. */
  92196. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  92197. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  92198. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  92199. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  92200. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  92201. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92202. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  92203. #endif
  92204. #endif
  92205. /********* End of inlined file: memory.h *********/
  92206. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  92207. {
  92208. void *x;
  92209. FLAC__ASSERT(0 != aligned_address);
  92210. #ifdef FLAC__ALIGN_MALLOC_DATA
  92211. /* align on 32-byte (256-bit) boundary */
  92212. x = safe_malloc_add_2op_(bytes, /*+*/31);
  92213. #ifdef SIZEOF_VOIDP
  92214. #if SIZEOF_VOIDP == 4
  92215. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  92216. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92217. #elif SIZEOF_VOIDP == 8
  92218. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92219. #else
  92220. # error Unsupported sizeof(void*)
  92221. #endif
  92222. #else
  92223. /* there's got to be a better way to do this right for all archs */
  92224. if(sizeof(void*) == sizeof(unsigned))
  92225. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92226. else if(sizeof(void*) == sizeof(FLAC__uint64))
  92227. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92228. else
  92229. return 0;
  92230. #endif
  92231. #else
  92232. x = safe_malloc_(bytes);
  92233. *aligned_address = x;
  92234. #endif
  92235. return x;
  92236. }
  92237. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  92238. {
  92239. FLAC__int32 *pu; /* unaligned pointer */
  92240. union { /* union needed to comply with C99 pointer aliasing rules */
  92241. FLAC__int32 *pa; /* aligned pointer */
  92242. void *pv; /* aligned pointer alias */
  92243. } u;
  92244. FLAC__ASSERT(elements > 0);
  92245. FLAC__ASSERT(0 != unaligned_pointer);
  92246. FLAC__ASSERT(0 != aligned_pointer);
  92247. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92248. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92249. return false;
  92250. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  92251. if(0 == pu) {
  92252. return false;
  92253. }
  92254. else {
  92255. if(*unaligned_pointer != 0)
  92256. free(*unaligned_pointer);
  92257. *unaligned_pointer = pu;
  92258. *aligned_pointer = u.pa;
  92259. return true;
  92260. }
  92261. }
  92262. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  92263. {
  92264. FLAC__uint32 *pu; /* unaligned pointer */
  92265. union { /* union needed to comply with C99 pointer aliasing rules */
  92266. FLAC__uint32 *pa; /* aligned pointer */
  92267. void *pv; /* aligned pointer alias */
  92268. } u;
  92269. FLAC__ASSERT(elements > 0);
  92270. FLAC__ASSERT(0 != unaligned_pointer);
  92271. FLAC__ASSERT(0 != aligned_pointer);
  92272. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92273. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92274. return false;
  92275. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92276. if(0 == pu) {
  92277. return false;
  92278. }
  92279. else {
  92280. if(*unaligned_pointer != 0)
  92281. free(*unaligned_pointer);
  92282. *unaligned_pointer = pu;
  92283. *aligned_pointer = u.pa;
  92284. return true;
  92285. }
  92286. }
  92287. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  92288. {
  92289. FLAC__uint64 *pu; /* unaligned pointer */
  92290. union { /* union needed to comply with C99 pointer aliasing rules */
  92291. FLAC__uint64 *pa; /* aligned pointer */
  92292. void *pv; /* aligned pointer alias */
  92293. } u;
  92294. FLAC__ASSERT(elements > 0);
  92295. FLAC__ASSERT(0 != unaligned_pointer);
  92296. FLAC__ASSERT(0 != aligned_pointer);
  92297. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92298. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92299. return false;
  92300. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92301. if(0 == pu) {
  92302. return false;
  92303. }
  92304. else {
  92305. if(*unaligned_pointer != 0)
  92306. free(*unaligned_pointer);
  92307. *unaligned_pointer = pu;
  92308. *aligned_pointer = u.pa;
  92309. return true;
  92310. }
  92311. }
  92312. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  92313. {
  92314. unsigned *pu; /* unaligned pointer */
  92315. union { /* union needed to comply with C99 pointer aliasing rules */
  92316. unsigned *pa; /* aligned pointer */
  92317. void *pv; /* aligned pointer alias */
  92318. } u;
  92319. FLAC__ASSERT(elements > 0);
  92320. FLAC__ASSERT(0 != unaligned_pointer);
  92321. FLAC__ASSERT(0 != aligned_pointer);
  92322. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92323. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92324. return false;
  92325. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92326. if(0 == pu) {
  92327. return false;
  92328. }
  92329. else {
  92330. if(*unaligned_pointer != 0)
  92331. free(*unaligned_pointer);
  92332. *unaligned_pointer = pu;
  92333. *aligned_pointer = u.pa;
  92334. return true;
  92335. }
  92336. }
  92337. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92338. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  92339. {
  92340. FLAC__real *pu; /* unaligned pointer */
  92341. union { /* union needed to comply with C99 pointer aliasing rules */
  92342. FLAC__real *pa; /* aligned pointer */
  92343. void *pv; /* aligned pointer alias */
  92344. } u;
  92345. FLAC__ASSERT(elements > 0);
  92346. FLAC__ASSERT(0 != unaligned_pointer);
  92347. FLAC__ASSERT(0 != aligned_pointer);
  92348. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92349. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92350. return false;
  92351. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92352. if(0 == pu) {
  92353. return false;
  92354. }
  92355. else {
  92356. if(*unaligned_pointer != 0)
  92357. free(*unaligned_pointer);
  92358. *unaligned_pointer = pu;
  92359. *aligned_pointer = u.pa;
  92360. return true;
  92361. }
  92362. }
  92363. #endif
  92364. #endif
  92365. /********* End of inlined file: memory.c *********/
  92366. /********* Start of inlined file: stream_decoder.c *********/
  92367. /********* Start of inlined file: juce_FlacHeader.h *********/
  92368. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92369. // tasks..
  92370. #define VERSION "1.2.1"
  92371. #define FLAC__NO_DLL 1
  92372. #ifdef _MSC_VER
  92373. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92374. #endif
  92375. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92376. #define FLAC__SYS_DARWIN 1
  92377. #endif
  92378. /********* End of inlined file: juce_FlacHeader.h *********/
  92379. #if JUCE_USE_FLAC
  92380. #if HAVE_CONFIG_H
  92381. # include <config.h>
  92382. #endif
  92383. #if defined _MSC_VER || defined __MINGW32__
  92384. #include <io.h> /* for _setmode() */
  92385. #include <fcntl.h> /* for _O_BINARY */
  92386. #endif
  92387. #if defined __CYGWIN__ || defined __EMX__
  92388. #include <io.h> /* for setmode(), O_BINARY */
  92389. #include <fcntl.h> /* for _O_BINARY */
  92390. #endif
  92391. #include <stdio.h>
  92392. #include <stdlib.h> /* for malloc() */
  92393. #include <string.h> /* for memset/memcpy() */
  92394. #include <sys/stat.h> /* for stat() */
  92395. #include <sys/types.h> /* for off_t */
  92396. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  92397. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  92398. #define fseeko fseek
  92399. #define ftello ftell
  92400. #endif
  92401. #endif
  92402. /********* Start of inlined file: stream_decoder.h *********/
  92403. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  92404. #define FLAC__PROTECTED__STREAM_DECODER_H
  92405. #if FLAC__HAS_OGG
  92406. #include "include/private/ogg_decoder_aspect.h"
  92407. #endif
  92408. typedef struct FLAC__StreamDecoderProtected {
  92409. FLAC__StreamDecoderState state;
  92410. unsigned channels;
  92411. FLAC__ChannelAssignment channel_assignment;
  92412. unsigned bits_per_sample;
  92413. unsigned sample_rate; /* in Hz */
  92414. unsigned blocksize; /* in samples (per channel) */
  92415. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  92416. #if FLAC__HAS_OGG
  92417. FLAC__OggDecoderAspect ogg_decoder_aspect;
  92418. #endif
  92419. } FLAC__StreamDecoderProtected;
  92420. /*
  92421. * return the number of input bytes consumed
  92422. */
  92423. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  92424. #endif
  92425. /********* End of inlined file: stream_decoder.h *********/
  92426. #ifdef max
  92427. #undef max
  92428. #endif
  92429. #define max(a,b) ((a)>(b)?(a):(b))
  92430. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92431. #ifdef _MSC_VER
  92432. #define FLAC__U64L(x) x
  92433. #else
  92434. #define FLAC__U64L(x) x##LLU
  92435. #endif
  92436. /* technically this should be in an "export.c" but this is convenient enough */
  92437. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  92438. #if FLAC__HAS_OGG
  92439. 1
  92440. #else
  92441. 0
  92442. #endif
  92443. ;
  92444. /***********************************************************************
  92445. *
  92446. * Private static data
  92447. *
  92448. ***********************************************************************/
  92449. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  92450. /***********************************************************************
  92451. *
  92452. * Private class method prototypes
  92453. *
  92454. ***********************************************************************/
  92455. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  92456. static FILE *get_binary_stdin_(void);
  92457. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  92458. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  92459. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  92460. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  92461. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  92462. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  92463. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  92464. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  92465. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  92466. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  92467. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  92468. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  92469. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  92470. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92471. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92472. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  92473. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  92474. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92475. static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
  92476. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  92477. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92478. #if FLAC__HAS_OGG
  92479. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  92480. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  92481. #endif
  92482. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  92483. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  92484. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  92485. #if FLAC__HAS_OGG
  92486. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  92487. #endif
  92488. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  92489. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  92490. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  92491. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  92492. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  92493. /***********************************************************************
  92494. *
  92495. * Private class data
  92496. *
  92497. ***********************************************************************/
  92498. typedef struct FLAC__StreamDecoderPrivate {
  92499. #if FLAC__HAS_OGG
  92500. FLAC__bool is_ogg;
  92501. #endif
  92502. FLAC__StreamDecoderReadCallback read_callback;
  92503. FLAC__StreamDecoderSeekCallback seek_callback;
  92504. FLAC__StreamDecoderTellCallback tell_callback;
  92505. FLAC__StreamDecoderLengthCallback length_callback;
  92506. FLAC__StreamDecoderEofCallback eof_callback;
  92507. FLAC__StreamDecoderWriteCallback write_callback;
  92508. FLAC__StreamDecoderMetadataCallback metadata_callback;
  92509. FLAC__StreamDecoderErrorCallback error_callback;
  92510. /* generic 32-bit datapath: */
  92511. void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92512. /* generic 64-bit datapath: */
  92513. void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92514. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  92515. void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92516. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
  92517. void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92518. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  92519. void *client_data;
  92520. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  92521. FLAC__BitReader *input;
  92522. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  92523. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  92524. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  92525. unsigned output_capacity, output_channels;
  92526. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  92527. FLAC__uint64 samples_decoded;
  92528. FLAC__bool has_stream_info, has_seek_table;
  92529. FLAC__StreamMetadata stream_info;
  92530. FLAC__StreamMetadata seek_table;
  92531. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  92532. FLAC__byte *metadata_filter_ids;
  92533. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  92534. FLAC__Frame frame;
  92535. FLAC__bool cached; /* true if there is a byte in lookahead */
  92536. FLAC__CPUInfo cpuinfo;
  92537. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  92538. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  92539. /* unaligned (original) pointers to allocated data */
  92540. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  92541. FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
  92542. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  92543. FLAC__bool is_seeking;
  92544. FLAC__MD5Context md5context;
  92545. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  92546. /* (the rest of these are only used for seeking) */
  92547. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  92548. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  92549. FLAC__uint64 target_sample;
  92550. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  92551. #if FLAC__HAS_OGG
  92552. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  92553. #endif
  92554. } FLAC__StreamDecoderPrivate;
  92555. /***********************************************************************
  92556. *
  92557. * Public static class data
  92558. *
  92559. ***********************************************************************/
  92560. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  92561. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  92562. "FLAC__STREAM_DECODER_READ_METADATA",
  92563. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  92564. "FLAC__STREAM_DECODER_READ_FRAME",
  92565. "FLAC__STREAM_DECODER_END_OF_STREAM",
  92566. "FLAC__STREAM_DECODER_OGG_ERROR",
  92567. "FLAC__STREAM_DECODER_SEEK_ERROR",
  92568. "FLAC__STREAM_DECODER_ABORTED",
  92569. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  92570. "FLAC__STREAM_DECODER_UNINITIALIZED"
  92571. };
  92572. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  92573. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  92574. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  92575. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  92576. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  92577. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  92578. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  92579. };
  92580. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  92581. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  92582. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  92583. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  92584. };
  92585. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  92586. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  92587. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  92588. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  92589. };
  92590. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  92591. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  92592. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  92593. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  92594. };
  92595. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  92596. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  92597. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  92598. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  92599. };
  92600. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  92601. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  92602. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  92603. };
  92604. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  92605. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  92606. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  92607. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  92608. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  92609. };
  92610. /***********************************************************************
  92611. *
  92612. * Class constructor/destructor
  92613. *
  92614. ***********************************************************************/
  92615. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  92616. {
  92617. FLAC__StreamDecoder *decoder;
  92618. unsigned i;
  92619. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  92620. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  92621. if(decoder == 0) {
  92622. return 0;
  92623. }
  92624. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  92625. if(decoder->protected_ == 0) {
  92626. free(decoder);
  92627. return 0;
  92628. }
  92629. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  92630. if(decoder->private_ == 0) {
  92631. free(decoder->protected_);
  92632. free(decoder);
  92633. return 0;
  92634. }
  92635. decoder->private_->input = FLAC__bitreader_new();
  92636. if(decoder->private_->input == 0) {
  92637. free(decoder->private_);
  92638. free(decoder->protected_);
  92639. free(decoder);
  92640. return 0;
  92641. }
  92642. decoder->private_->metadata_filter_ids_capacity = 16;
  92643. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  92644. FLAC__bitreader_delete(decoder->private_->input);
  92645. free(decoder->private_);
  92646. free(decoder->protected_);
  92647. free(decoder);
  92648. return 0;
  92649. }
  92650. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  92651. decoder->private_->output[i] = 0;
  92652. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  92653. }
  92654. decoder->private_->output_capacity = 0;
  92655. decoder->private_->output_channels = 0;
  92656. decoder->private_->has_seek_table = false;
  92657. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  92658. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  92659. decoder->private_->file = 0;
  92660. set_defaults_dec(decoder);
  92661. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  92662. return decoder;
  92663. }
  92664. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  92665. {
  92666. unsigned i;
  92667. FLAC__ASSERT(0 != decoder);
  92668. FLAC__ASSERT(0 != decoder->protected_);
  92669. FLAC__ASSERT(0 != decoder->private_);
  92670. FLAC__ASSERT(0 != decoder->private_->input);
  92671. (void)FLAC__stream_decoder_finish(decoder);
  92672. if(0 != decoder->private_->metadata_filter_ids)
  92673. free(decoder->private_->metadata_filter_ids);
  92674. FLAC__bitreader_delete(decoder->private_->input);
  92675. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  92676. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  92677. free(decoder->private_);
  92678. free(decoder->protected_);
  92679. free(decoder);
  92680. }
  92681. /***********************************************************************
  92682. *
  92683. * Public class methods
  92684. *
  92685. ***********************************************************************/
  92686. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  92687. FLAC__StreamDecoder *decoder,
  92688. FLAC__StreamDecoderReadCallback read_callback,
  92689. FLAC__StreamDecoderSeekCallback seek_callback,
  92690. FLAC__StreamDecoderTellCallback tell_callback,
  92691. FLAC__StreamDecoderLengthCallback length_callback,
  92692. FLAC__StreamDecoderEofCallback eof_callback,
  92693. FLAC__StreamDecoderWriteCallback write_callback,
  92694. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92695. FLAC__StreamDecoderErrorCallback error_callback,
  92696. void *client_data,
  92697. FLAC__bool is_ogg
  92698. )
  92699. {
  92700. FLAC__ASSERT(0 != decoder);
  92701. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92702. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  92703. #if !FLAC__HAS_OGG
  92704. if(is_ogg)
  92705. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  92706. #endif
  92707. if(
  92708. 0 == read_callback ||
  92709. 0 == write_callback ||
  92710. 0 == error_callback ||
  92711. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  92712. )
  92713. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  92714. #if FLAC__HAS_OGG
  92715. decoder->private_->is_ogg = is_ogg;
  92716. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  92717. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  92718. #endif
  92719. /*
  92720. * get the CPU info and set the function pointers
  92721. */
  92722. FLAC__cpu_info(&decoder->private_->cpuinfo);
  92723. /* first default to the non-asm routines */
  92724. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  92725. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  92726. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  92727. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  92728. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  92729. /* now override with asm where appropriate */
  92730. #ifndef FLAC__NO_ASM
  92731. if(decoder->private_->cpuinfo.use_asm) {
  92732. #ifdef FLAC__CPU_IA32
  92733. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  92734. #ifdef FLAC__HAS_NASM
  92735. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  92736. if(decoder->private_->cpuinfo.data.ia32.bswap)
  92737. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  92738. #endif
  92739. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  92740. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  92741. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  92742. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  92743. }
  92744. else {
  92745. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  92746. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  92747. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  92748. }
  92749. #endif
  92750. #elif defined FLAC__CPU_PPC
  92751. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  92752. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  92753. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  92754. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  92755. }
  92756. #endif
  92757. }
  92758. #endif
  92759. /* from here on, errors are fatal */
  92760. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  92761. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  92762. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  92763. }
  92764. decoder->private_->read_callback = read_callback;
  92765. decoder->private_->seek_callback = seek_callback;
  92766. decoder->private_->tell_callback = tell_callback;
  92767. decoder->private_->length_callback = length_callback;
  92768. decoder->private_->eof_callback = eof_callback;
  92769. decoder->private_->write_callback = write_callback;
  92770. decoder->private_->metadata_callback = metadata_callback;
  92771. decoder->private_->error_callback = error_callback;
  92772. decoder->private_->client_data = client_data;
  92773. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  92774. decoder->private_->samples_decoded = 0;
  92775. decoder->private_->has_stream_info = false;
  92776. decoder->private_->cached = false;
  92777. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  92778. decoder->private_->is_seeking = false;
  92779. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  92780. if(!FLAC__stream_decoder_reset(decoder)) {
  92781. /* above call sets the state for us */
  92782. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  92783. }
  92784. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  92785. }
  92786. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  92787. FLAC__StreamDecoder *decoder,
  92788. FLAC__StreamDecoderReadCallback read_callback,
  92789. FLAC__StreamDecoderSeekCallback seek_callback,
  92790. FLAC__StreamDecoderTellCallback tell_callback,
  92791. FLAC__StreamDecoderLengthCallback length_callback,
  92792. FLAC__StreamDecoderEofCallback eof_callback,
  92793. FLAC__StreamDecoderWriteCallback write_callback,
  92794. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92795. FLAC__StreamDecoderErrorCallback error_callback,
  92796. void *client_data
  92797. )
  92798. {
  92799. return init_stream_internal_dec(
  92800. decoder,
  92801. read_callback,
  92802. seek_callback,
  92803. tell_callback,
  92804. length_callback,
  92805. eof_callback,
  92806. write_callback,
  92807. metadata_callback,
  92808. error_callback,
  92809. client_data,
  92810. /*is_ogg=*/false
  92811. );
  92812. }
  92813. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  92814. FLAC__StreamDecoder *decoder,
  92815. FLAC__StreamDecoderReadCallback read_callback,
  92816. FLAC__StreamDecoderSeekCallback seek_callback,
  92817. FLAC__StreamDecoderTellCallback tell_callback,
  92818. FLAC__StreamDecoderLengthCallback length_callback,
  92819. FLAC__StreamDecoderEofCallback eof_callback,
  92820. FLAC__StreamDecoderWriteCallback write_callback,
  92821. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92822. FLAC__StreamDecoderErrorCallback error_callback,
  92823. void *client_data
  92824. )
  92825. {
  92826. return init_stream_internal_dec(
  92827. decoder,
  92828. read_callback,
  92829. seek_callback,
  92830. tell_callback,
  92831. length_callback,
  92832. eof_callback,
  92833. write_callback,
  92834. metadata_callback,
  92835. error_callback,
  92836. client_data,
  92837. /*is_ogg=*/true
  92838. );
  92839. }
  92840. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  92841. FLAC__StreamDecoder *decoder,
  92842. FILE *file,
  92843. FLAC__StreamDecoderWriteCallback write_callback,
  92844. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92845. FLAC__StreamDecoderErrorCallback error_callback,
  92846. void *client_data,
  92847. FLAC__bool is_ogg
  92848. )
  92849. {
  92850. FLAC__ASSERT(0 != decoder);
  92851. FLAC__ASSERT(0 != file);
  92852. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92853. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  92854. if(0 == write_callback || 0 == error_callback)
  92855. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  92856. /*
  92857. * To make sure that our file does not go unclosed after an error, we
  92858. * must assign the FILE pointer before any further error can occur in
  92859. * this routine.
  92860. */
  92861. if(file == stdin)
  92862. file = get_binary_stdin_(); /* just to be safe */
  92863. decoder->private_->file = file;
  92864. return init_stream_internal_dec(
  92865. decoder,
  92866. file_read_callback_dec,
  92867. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  92868. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  92869. decoder->private_->file == stdin? 0: file_length_callback_,
  92870. file_eof_callback_,
  92871. write_callback,
  92872. metadata_callback,
  92873. error_callback,
  92874. client_data,
  92875. is_ogg
  92876. );
  92877. }
  92878. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  92879. FLAC__StreamDecoder *decoder,
  92880. FILE *file,
  92881. FLAC__StreamDecoderWriteCallback write_callback,
  92882. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92883. FLAC__StreamDecoderErrorCallback error_callback,
  92884. void *client_data
  92885. )
  92886. {
  92887. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  92888. }
  92889. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  92890. FLAC__StreamDecoder *decoder,
  92891. FILE *file,
  92892. FLAC__StreamDecoderWriteCallback write_callback,
  92893. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92894. FLAC__StreamDecoderErrorCallback error_callback,
  92895. void *client_data
  92896. )
  92897. {
  92898. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  92899. }
  92900. static FLAC__StreamDecoderInitStatus init_file_internal_(
  92901. FLAC__StreamDecoder *decoder,
  92902. const char *filename,
  92903. FLAC__StreamDecoderWriteCallback write_callback,
  92904. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92905. FLAC__StreamDecoderErrorCallback error_callback,
  92906. void *client_data,
  92907. FLAC__bool is_ogg
  92908. )
  92909. {
  92910. FILE *file;
  92911. FLAC__ASSERT(0 != decoder);
  92912. /*
  92913. * To make sure that our file does not go unclosed after an error, we
  92914. * have to do the same entrance checks here that are later performed
  92915. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  92916. */
  92917. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92918. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  92919. if(0 == write_callback || 0 == error_callback)
  92920. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  92921. file = filename? fopen(filename, "rb") : stdin;
  92922. if(0 == file)
  92923. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  92924. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  92925. }
  92926. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  92927. FLAC__StreamDecoder *decoder,
  92928. const char *filename,
  92929. FLAC__StreamDecoderWriteCallback write_callback,
  92930. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92931. FLAC__StreamDecoderErrorCallback error_callback,
  92932. void *client_data
  92933. )
  92934. {
  92935. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  92936. }
  92937. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  92938. FLAC__StreamDecoder *decoder,
  92939. const char *filename,
  92940. FLAC__StreamDecoderWriteCallback write_callback,
  92941. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92942. FLAC__StreamDecoderErrorCallback error_callback,
  92943. void *client_data
  92944. )
  92945. {
  92946. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  92947. }
  92948. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  92949. {
  92950. FLAC__bool md5_failed = false;
  92951. unsigned i;
  92952. FLAC__ASSERT(0 != decoder);
  92953. FLAC__ASSERT(0 != decoder->private_);
  92954. FLAC__ASSERT(0 != decoder->protected_);
  92955. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  92956. return true;
  92957. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  92958. * always call FLAC__MD5Final()
  92959. */
  92960. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  92961. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  92962. free(decoder->private_->seek_table.data.seek_table.points);
  92963. decoder->private_->seek_table.data.seek_table.points = 0;
  92964. decoder->private_->has_seek_table = false;
  92965. }
  92966. FLAC__bitreader_free(decoder->private_->input);
  92967. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  92968. /* WATCHOUT:
  92969. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  92970. * output arrays have a buffer of up to 3 zeroes in front
  92971. * (at negative indices) for alignment purposes; we use 4
  92972. * to keep the data well-aligned.
  92973. */
  92974. if(0 != decoder->private_->output[i]) {
  92975. free(decoder->private_->output[i]-4);
  92976. decoder->private_->output[i] = 0;
  92977. }
  92978. if(0 != decoder->private_->residual_unaligned[i]) {
  92979. free(decoder->private_->residual_unaligned[i]);
  92980. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  92981. }
  92982. }
  92983. decoder->private_->output_capacity = 0;
  92984. decoder->private_->output_channels = 0;
  92985. #if FLAC__HAS_OGG
  92986. if(decoder->private_->is_ogg)
  92987. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  92988. #endif
  92989. if(0 != decoder->private_->file) {
  92990. if(decoder->private_->file != stdin)
  92991. fclose(decoder->private_->file);
  92992. decoder->private_->file = 0;
  92993. }
  92994. if(decoder->private_->do_md5_checking) {
  92995. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  92996. md5_failed = true;
  92997. }
  92998. decoder->private_->is_seeking = false;
  92999. set_defaults_dec(decoder);
  93000. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93001. return !md5_failed;
  93002. }
  93003. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  93004. {
  93005. FLAC__ASSERT(0 != decoder);
  93006. FLAC__ASSERT(0 != decoder->private_);
  93007. FLAC__ASSERT(0 != decoder->protected_);
  93008. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93009. return false;
  93010. #if FLAC__HAS_OGG
  93011. /* can't check decoder->private_->is_ogg since that's not set until init time */
  93012. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  93013. return true;
  93014. #else
  93015. (void)value;
  93016. return false;
  93017. #endif
  93018. }
  93019. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  93020. {
  93021. FLAC__ASSERT(0 != decoder);
  93022. FLAC__ASSERT(0 != decoder->protected_);
  93023. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93024. return false;
  93025. decoder->protected_->md5_checking = value;
  93026. return true;
  93027. }
  93028. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93029. {
  93030. FLAC__ASSERT(0 != decoder);
  93031. FLAC__ASSERT(0 != decoder->private_);
  93032. FLAC__ASSERT(0 != decoder->protected_);
  93033. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93034. /* double protection */
  93035. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93036. return false;
  93037. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93038. return false;
  93039. decoder->private_->metadata_filter[type] = true;
  93040. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93041. decoder->private_->metadata_filter_ids_count = 0;
  93042. return true;
  93043. }
  93044. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93045. {
  93046. FLAC__ASSERT(0 != decoder);
  93047. FLAC__ASSERT(0 != decoder->private_);
  93048. FLAC__ASSERT(0 != decoder->protected_);
  93049. FLAC__ASSERT(0 != id);
  93050. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93051. return false;
  93052. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93053. return true;
  93054. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93055. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93056. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  93057. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93058. return false;
  93059. }
  93060. decoder->private_->metadata_filter_ids_capacity *= 2;
  93061. }
  93062. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  93063. decoder->private_->metadata_filter_ids_count++;
  93064. return true;
  93065. }
  93066. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  93067. {
  93068. unsigned i;
  93069. FLAC__ASSERT(0 != decoder);
  93070. FLAC__ASSERT(0 != decoder->private_);
  93071. FLAC__ASSERT(0 != decoder->protected_);
  93072. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93073. return false;
  93074. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  93075. decoder->private_->metadata_filter[i] = true;
  93076. decoder->private_->metadata_filter_ids_count = 0;
  93077. return true;
  93078. }
  93079. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93080. {
  93081. FLAC__ASSERT(0 != decoder);
  93082. FLAC__ASSERT(0 != decoder->private_);
  93083. FLAC__ASSERT(0 != decoder->protected_);
  93084. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93085. /* double protection */
  93086. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93087. return false;
  93088. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93089. return false;
  93090. decoder->private_->metadata_filter[type] = false;
  93091. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93092. decoder->private_->metadata_filter_ids_count = 0;
  93093. return true;
  93094. }
  93095. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93096. {
  93097. FLAC__ASSERT(0 != decoder);
  93098. FLAC__ASSERT(0 != decoder->private_);
  93099. FLAC__ASSERT(0 != decoder->protected_);
  93100. FLAC__ASSERT(0 != id);
  93101. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93102. return false;
  93103. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93104. return true;
  93105. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93106. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93107. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  93108. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93109. return false;
  93110. }
  93111. decoder->private_->metadata_filter_ids_capacity *= 2;
  93112. }
  93113. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  93114. decoder->private_->metadata_filter_ids_count++;
  93115. return true;
  93116. }
  93117. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  93118. {
  93119. FLAC__ASSERT(0 != decoder);
  93120. FLAC__ASSERT(0 != decoder->private_);
  93121. FLAC__ASSERT(0 != decoder->protected_);
  93122. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93123. return false;
  93124. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93125. decoder->private_->metadata_filter_ids_count = 0;
  93126. return true;
  93127. }
  93128. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  93129. {
  93130. FLAC__ASSERT(0 != decoder);
  93131. FLAC__ASSERT(0 != decoder->protected_);
  93132. return decoder->protected_->state;
  93133. }
  93134. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  93135. {
  93136. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  93137. }
  93138. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  93139. {
  93140. FLAC__ASSERT(0 != decoder);
  93141. FLAC__ASSERT(0 != decoder->protected_);
  93142. return decoder->protected_->md5_checking;
  93143. }
  93144. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  93145. {
  93146. FLAC__ASSERT(0 != decoder);
  93147. FLAC__ASSERT(0 != decoder->protected_);
  93148. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  93149. }
  93150. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  93151. {
  93152. FLAC__ASSERT(0 != decoder);
  93153. FLAC__ASSERT(0 != decoder->protected_);
  93154. return decoder->protected_->channels;
  93155. }
  93156. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  93157. {
  93158. FLAC__ASSERT(0 != decoder);
  93159. FLAC__ASSERT(0 != decoder->protected_);
  93160. return decoder->protected_->channel_assignment;
  93161. }
  93162. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  93163. {
  93164. FLAC__ASSERT(0 != decoder);
  93165. FLAC__ASSERT(0 != decoder->protected_);
  93166. return decoder->protected_->bits_per_sample;
  93167. }
  93168. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  93169. {
  93170. FLAC__ASSERT(0 != decoder);
  93171. FLAC__ASSERT(0 != decoder->protected_);
  93172. return decoder->protected_->sample_rate;
  93173. }
  93174. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  93175. {
  93176. FLAC__ASSERT(0 != decoder);
  93177. FLAC__ASSERT(0 != decoder->protected_);
  93178. return decoder->protected_->blocksize;
  93179. }
  93180. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  93181. {
  93182. FLAC__ASSERT(0 != decoder);
  93183. FLAC__ASSERT(0 != decoder->private_);
  93184. FLAC__ASSERT(0 != position);
  93185. #if FLAC__HAS_OGG
  93186. if(decoder->private_->is_ogg)
  93187. return false;
  93188. #endif
  93189. if(0 == decoder->private_->tell_callback)
  93190. return false;
  93191. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  93192. return false;
  93193. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  93194. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  93195. return false;
  93196. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  93197. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  93198. return true;
  93199. }
  93200. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  93201. {
  93202. FLAC__ASSERT(0 != decoder);
  93203. FLAC__ASSERT(0 != decoder->private_);
  93204. FLAC__ASSERT(0 != decoder->protected_);
  93205. decoder->private_->samples_decoded = 0;
  93206. decoder->private_->do_md5_checking = false;
  93207. #if FLAC__HAS_OGG
  93208. if(decoder->private_->is_ogg)
  93209. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  93210. #endif
  93211. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  93212. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93213. return false;
  93214. }
  93215. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93216. return true;
  93217. }
  93218. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  93219. {
  93220. FLAC__ASSERT(0 != decoder);
  93221. FLAC__ASSERT(0 != decoder->private_);
  93222. FLAC__ASSERT(0 != decoder->protected_);
  93223. if(!FLAC__stream_decoder_flush(decoder)) {
  93224. /* above call sets the state for us */
  93225. return false;
  93226. }
  93227. #if FLAC__HAS_OGG
  93228. /*@@@ could go in !internal_reset_hack block below */
  93229. if(decoder->private_->is_ogg)
  93230. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  93231. #endif
  93232. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  93233. * (internal_reset_hack) don't try to rewind since we are already at
  93234. * the beginning of the stream and don't want to fail if the input is
  93235. * not seekable.
  93236. */
  93237. if(!decoder->private_->internal_reset_hack) {
  93238. if(decoder->private_->file == stdin)
  93239. return false; /* can't rewind stdin, reset fails */
  93240. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  93241. return false; /* seekable and seek fails, reset fails */
  93242. }
  93243. else
  93244. decoder->private_->internal_reset_hack = false;
  93245. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  93246. decoder->private_->has_stream_info = false;
  93247. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93248. free(decoder->private_->seek_table.data.seek_table.points);
  93249. decoder->private_->seek_table.data.seek_table.points = 0;
  93250. decoder->private_->has_seek_table = false;
  93251. }
  93252. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93253. /*
  93254. * This goes in reset() and not flush() because according to the spec, a
  93255. * fixed-blocksize stream must stay that way through the whole stream.
  93256. */
  93257. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93258. /* We initialize the FLAC__MD5Context even though we may never use it. This
  93259. * is because md5 checking may be turned on to start and then turned off if
  93260. * a seek occurs. So we init the context here and finalize it in
  93261. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  93262. * properly.
  93263. */
  93264. FLAC__MD5Init(&decoder->private_->md5context);
  93265. decoder->private_->first_frame_offset = 0;
  93266. decoder->private_->unparseable_frame_count = 0;
  93267. return true;
  93268. }
  93269. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  93270. {
  93271. FLAC__bool got_a_frame;
  93272. FLAC__ASSERT(0 != decoder);
  93273. FLAC__ASSERT(0 != decoder->protected_);
  93274. while(1) {
  93275. switch(decoder->protected_->state) {
  93276. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93277. if(!find_metadata_(decoder))
  93278. return false; /* above function sets the status for us */
  93279. break;
  93280. case FLAC__STREAM_DECODER_READ_METADATA:
  93281. if(!read_metadata_(decoder))
  93282. return false; /* above function sets the status for us */
  93283. else
  93284. return true;
  93285. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93286. if(!frame_sync_(decoder))
  93287. return true; /* above function sets the status for us */
  93288. break;
  93289. case FLAC__STREAM_DECODER_READ_FRAME:
  93290. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  93291. return false; /* above function sets the status for us */
  93292. if(got_a_frame)
  93293. return true; /* above function sets the status for us */
  93294. break;
  93295. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93296. case FLAC__STREAM_DECODER_ABORTED:
  93297. return true;
  93298. default:
  93299. FLAC__ASSERT(0);
  93300. return false;
  93301. }
  93302. }
  93303. }
  93304. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  93305. {
  93306. FLAC__ASSERT(0 != decoder);
  93307. FLAC__ASSERT(0 != decoder->protected_);
  93308. while(1) {
  93309. switch(decoder->protected_->state) {
  93310. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93311. if(!find_metadata_(decoder))
  93312. return false; /* above function sets the status for us */
  93313. break;
  93314. case FLAC__STREAM_DECODER_READ_METADATA:
  93315. if(!read_metadata_(decoder))
  93316. return false; /* above function sets the status for us */
  93317. break;
  93318. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93319. case FLAC__STREAM_DECODER_READ_FRAME:
  93320. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93321. case FLAC__STREAM_DECODER_ABORTED:
  93322. return true;
  93323. default:
  93324. FLAC__ASSERT(0);
  93325. return false;
  93326. }
  93327. }
  93328. }
  93329. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  93330. {
  93331. FLAC__bool dummy;
  93332. FLAC__ASSERT(0 != decoder);
  93333. FLAC__ASSERT(0 != decoder->protected_);
  93334. while(1) {
  93335. switch(decoder->protected_->state) {
  93336. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93337. if(!find_metadata_(decoder))
  93338. return false; /* above function sets the status for us */
  93339. break;
  93340. case FLAC__STREAM_DECODER_READ_METADATA:
  93341. if(!read_metadata_(decoder))
  93342. return false; /* above function sets the status for us */
  93343. break;
  93344. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93345. if(!frame_sync_(decoder))
  93346. return true; /* above function sets the status for us */
  93347. break;
  93348. case FLAC__STREAM_DECODER_READ_FRAME:
  93349. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  93350. return false; /* above function sets the status for us */
  93351. break;
  93352. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93353. case FLAC__STREAM_DECODER_ABORTED:
  93354. return true;
  93355. default:
  93356. FLAC__ASSERT(0);
  93357. return false;
  93358. }
  93359. }
  93360. }
  93361. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  93362. {
  93363. FLAC__bool got_a_frame;
  93364. FLAC__ASSERT(0 != decoder);
  93365. FLAC__ASSERT(0 != decoder->protected_);
  93366. while(1) {
  93367. switch(decoder->protected_->state) {
  93368. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93369. case FLAC__STREAM_DECODER_READ_METADATA:
  93370. return false; /* above function sets the status for us */
  93371. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93372. if(!frame_sync_(decoder))
  93373. return true; /* above function sets the status for us */
  93374. break;
  93375. case FLAC__STREAM_DECODER_READ_FRAME:
  93376. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  93377. return false; /* above function sets the status for us */
  93378. if(got_a_frame)
  93379. return true; /* above function sets the status for us */
  93380. break;
  93381. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93382. case FLAC__STREAM_DECODER_ABORTED:
  93383. return true;
  93384. default:
  93385. FLAC__ASSERT(0);
  93386. return false;
  93387. }
  93388. }
  93389. }
  93390. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  93391. {
  93392. FLAC__uint64 length;
  93393. FLAC__ASSERT(0 != decoder);
  93394. if(
  93395. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  93396. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  93397. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  93398. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  93399. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  93400. )
  93401. return false;
  93402. if(0 == decoder->private_->seek_callback)
  93403. return false;
  93404. FLAC__ASSERT(decoder->private_->seek_callback);
  93405. FLAC__ASSERT(decoder->private_->tell_callback);
  93406. FLAC__ASSERT(decoder->private_->length_callback);
  93407. FLAC__ASSERT(decoder->private_->eof_callback);
  93408. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  93409. return false;
  93410. decoder->private_->is_seeking = true;
  93411. /* turn off md5 checking if a seek is attempted */
  93412. decoder->private_->do_md5_checking = false;
  93413. /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
  93414. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  93415. decoder->private_->is_seeking = false;
  93416. return false;
  93417. }
  93418. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  93419. if(
  93420. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  93421. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  93422. ) {
  93423. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  93424. /* above call sets the state for us */
  93425. decoder->private_->is_seeking = false;
  93426. return false;
  93427. }
  93428. /* check this again in case we didn't know total_samples the first time */
  93429. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  93430. decoder->private_->is_seeking = false;
  93431. return false;
  93432. }
  93433. }
  93434. {
  93435. const FLAC__bool ok =
  93436. #if FLAC__HAS_OGG
  93437. decoder->private_->is_ogg?
  93438. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  93439. #endif
  93440. seek_to_absolute_sample_(decoder, length, sample)
  93441. ;
  93442. decoder->private_->is_seeking = false;
  93443. return ok;
  93444. }
  93445. }
  93446. /***********************************************************************
  93447. *
  93448. * Protected class methods
  93449. *
  93450. ***********************************************************************/
  93451. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  93452. {
  93453. FLAC__ASSERT(0 != decoder);
  93454. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93455. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  93456. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  93457. }
  93458. /***********************************************************************
  93459. *
  93460. * Private class methods
  93461. *
  93462. ***********************************************************************/
  93463. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  93464. {
  93465. #if FLAC__HAS_OGG
  93466. decoder->private_->is_ogg = false;
  93467. #endif
  93468. decoder->private_->read_callback = 0;
  93469. decoder->private_->seek_callback = 0;
  93470. decoder->private_->tell_callback = 0;
  93471. decoder->private_->length_callback = 0;
  93472. decoder->private_->eof_callback = 0;
  93473. decoder->private_->write_callback = 0;
  93474. decoder->private_->metadata_callback = 0;
  93475. decoder->private_->error_callback = 0;
  93476. decoder->private_->client_data = 0;
  93477. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93478. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  93479. decoder->private_->metadata_filter_ids_count = 0;
  93480. decoder->protected_->md5_checking = false;
  93481. #if FLAC__HAS_OGG
  93482. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  93483. #endif
  93484. }
  93485. /*
  93486. * This will forcibly set stdin to binary mode (for OSes that require it)
  93487. */
  93488. FILE *get_binary_stdin_(void)
  93489. {
  93490. /* if something breaks here it is probably due to the presence or
  93491. * absence of an underscore before the identifiers 'setmode',
  93492. * 'fileno', and/or 'O_BINARY'; check your system header files.
  93493. */
  93494. #if defined _MSC_VER || defined __MINGW32__
  93495. _setmode(_fileno(stdin), _O_BINARY);
  93496. #elif defined __CYGWIN__
  93497. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  93498. setmode(_fileno(stdin), _O_BINARY);
  93499. #elif defined __EMX__
  93500. setmode(fileno(stdin), O_BINARY);
  93501. #endif
  93502. return stdin;
  93503. }
  93504. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  93505. {
  93506. unsigned i;
  93507. FLAC__int32 *tmp;
  93508. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  93509. return true;
  93510. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  93511. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93512. if(0 != decoder->private_->output[i]) {
  93513. free(decoder->private_->output[i]-4);
  93514. decoder->private_->output[i] = 0;
  93515. }
  93516. if(0 != decoder->private_->residual_unaligned[i]) {
  93517. free(decoder->private_->residual_unaligned[i]);
  93518. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93519. }
  93520. }
  93521. for(i = 0; i < channels; i++) {
  93522. /* WATCHOUT:
  93523. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  93524. * output arrays have a buffer of up to 3 zeroes in front
  93525. * (at negative indices) for alignment purposes; we use 4
  93526. * to keep the data well-aligned.
  93527. */
  93528. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  93529. if(tmp == 0) {
  93530. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93531. return false;
  93532. }
  93533. memset(tmp, 0, sizeof(FLAC__int32)*4);
  93534. decoder->private_->output[i] = tmp + 4;
  93535. /* WATCHOUT:
  93536. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  93537. */
  93538. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  93539. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93540. return false;
  93541. }
  93542. }
  93543. decoder->private_->output_capacity = size;
  93544. decoder->private_->output_channels = channels;
  93545. return true;
  93546. }
  93547. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  93548. {
  93549. size_t i;
  93550. FLAC__ASSERT(0 != decoder);
  93551. FLAC__ASSERT(0 != decoder->private_);
  93552. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  93553. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  93554. return true;
  93555. return false;
  93556. }
  93557. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  93558. {
  93559. FLAC__uint32 x;
  93560. unsigned i, id_;
  93561. FLAC__bool first = true;
  93562. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93563. for(i = id_ = 0; i < 4; ) {
  93564. if(decoder->private_->cached) {
  93565. x = (FLAC__uint32)decoder->private_->lookahead;
  93566. decoder->private_->cached = false;
  93567. }
  93568. else {
  93569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  93570. return false; /* read_callback_ sets the state for us */
  93571. }
  93572. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  93573. first = true;
  93574. i++;
  93575. id_ = 0;
  93576. continue;
  93577. }
  93578. if(x == ID3V2_TAG_[id_]) {
  93579. id_++;
  93580. i = 0;
  93581. if(id_ == 3) {
  93582. if(!skip_id3v2_tag_(decoder))
  93583. return false; /* skip_id3v2_tag_ sets the state for us */
  93584. }
  93585. continue;
  93586. }
  93587. id_ = 0;
  93588. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  93589. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  93590. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  93591. return false; /* read_callback_ sets the state for us */
  93592. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  93593. /* else we have to check if the second byte is the end of a sync code */
  93594. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  93595. decoder->private_->lookahead = (FLAC__byte)x;
  93596. decoder->private_->cached = true;
  93597. }
  93598. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  93599. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  93600. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  93601. return true;
  93602. }
  93603. }
  93604. i = 0;
  93605. if(first) {
  93606. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  93607. first = false;
  93608. }
  93609. }
  93610. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  93611. return true;
  93612. }
  93613. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  93614. {
  93615. FLAC__bool is_last;
  93616. FLAC__uint32 i, x, type, length;
  93617. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93618. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  93619. return false; /* read_callback_ sets the state for us */
  93620. is_last = x? true : false;
  93621. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  93622. return false; /* read_callback_ sets the state for us */
  93623. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  93624. return false; /* read_callback_ sets the state for us */
  93625. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  93626. if(!read_metadata_streaminfo_(decoder, is_last, length))
  93627. return false;
  93628. decoder->private_->has_stream_info = true;
  93629. if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
  93630. decoder->private_->do_md5_checking = false;
  93631. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  93632. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  93633. }
  93634. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  93635. if(!read_metadata_seektable_(decoder, is_last, length))
  93636. return false;
  93637. decoder->private_->has_seek_table = true;
  93638. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  93639. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  93640. }
  93641. else {
  93642. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  93643. unsigned real_length = length;
  93644. FLAC__StreamMetadata block;
  93645. block.is_last = is_last;
  93646. block.type = (FLAC__MetadataType)type;
  93647. block.length = length;
  93648. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  93649. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  93650. return false; /* read_callback_ sets the state for us */
  93651. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  93652. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  93653. return false;
  93654. }
  93655. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  93656. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  93657. skip_it = !skip_it;
  93658. }
  93659. if(skip_it) {
  93660. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  93661. return false; /* read_callback_ sets the state for us */
  93662. }
  93663. else {
  93664. switch(type) {
  93665. case FLAC__METADATA_TYPE_PADDING:
  93666. /* skip the padding bytes */
  93667. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  93668. return false; /* read_callback_ sets the state for us */
  93669. break;
  93670. case FLAC__METADATA_TYPE_APPLICATION:
  93671. /* remember, we read the ID already */
  93672. if(real_length > 0) {
  93673. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  93674. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93675. return false;
  93676. }
  93677. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  93678. return false; /* read_callback_ sets the state for us */
  93679. }
  93680. else
  93681. block.data.application.data = 0;
  93682. break;
  93683. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  93684. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  93685. return false;
  93686. break;
  93687. case FLAC__METADATA_TYPE_CUESHEET:
  93688. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  93689. return false;
  93690. break;
  93691. case FLAC__METADATA_TYPE_PICTURE:
  93692. if(!read_metadata_picture_(decoder, &block.data.picture))
  93693. return false;
  93694. break;
  93695. case FLAC__METADATA_TYPE_STREAMINFO:
  93696. case FLAC__METADATA_TYPE_SEEKTABLE:
  93697. FLAC__ASSERT(0);
  93698. break;
  93699. default:
  93700. if(real_length > 0) {
  93701. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  93702. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93703. return false;
  93704. }
  93705. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  93706. return false; /* read_callback_ sets the state for us */
  93707. }
  93708. else
  93709. block.data.unknown.data = 0;
  93710. break;
  93711. }
  93712. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  93713. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  93714. /* now we have to free any malloc()ed data in the block */
  93715. switch(type) {
  93716. case FLAC__METADATA_TYPE_PADDING:
  93717. break;
  93718. case FLAC__METADATA_TYPE_APPLICATION:
  93719. if(0 != block.data.application.data)
  93720. free(block.data.application.data);
  93721. break;
  93722. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  93723. if(0 != block.data.vorbis_comment.vendor_string.entry)
  93724. free(block.data.vorbis_comment.vendor_string.entry);
  93725. if(block.data.vorbis_comment.num_comments > 0)
  93726. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  93727. if(0 != block.data.vorbis_comment.comments[i].entry)
  93728. free(block.data.vorbis_comment.comments[i].entry);
  93729. if(0 != block.data.vorbis_comment.comments)
  93730. free(block.data.vorbis_comment.comments);
  93731. break;
  93732. case FLAC__METADATA_TYPE_CUESHEET:
  93733. if(block.data.cue_sheet.num_tracks > 0)
  93734. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  93735. if(0 != block.data.cue_sheet.tracks[i].indices)
  93736. free(block.data.cue_sheet.tracks[i].indices);
  93737. if(0 != block.data.cue_sheet.tracks)
  93738. free(block.data.cue_sheet.tracks);
  93739. break;
  93740. case FLAC__METADATA_TYPE_PICTURE:
  93741. if(0 != block.data.picture.mime_type)
  93742. free(block.data.picture.mime_type);
  93743. if(0 != block.data.picture.description)
  93744. free(block.data.picture.description);
  93745. if(0 != block.data.picture.data)
  93746. free(block.data.picture.data);
  93747. break;
  93748. case FLAC__METADATA_TYPE_STREAMINFO:
  93749. case FLAC__METADATA_TYPE_SEEKTABLE:
  93750. FLAC__ASSERT(0);
  93751. default:
  93752. if(0 != block.data.unknown.data)
  93753. free(block.data.unknown.data);
  93754. break;
  93755. }
  93756. }
  93757. }
  93758. if(is_last) {
  93759. /* if this fails, it's OK, it's just a hint for the seek routine */
  93760. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  93761. decoder->private_->first_frame_offset = 0;
  93762. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93763. }
  93764. return true;
  93765. }
  93766. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  93767. {
  93768. FLAC__uint32 x;
  93769. unsigned bits, used_bits = 0;
  93770. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93771. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  93772. decoder->private_->stream_info.is_last = is_last;
  93773. decoder->private_->stream_info.length = length;
  93774. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  93775. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  93776. return false; /* read_callback_ sets the state for us */
  93777. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  93778. used_bits += bits;
  93779. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  93780. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  93781. return false; /* read_callback_ sets the state for us */
  93782. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  93783. used_bits += bits;
  93784. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  93785. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  93786. return false; /* read_callback_ sets the state for us */
  93787. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  93788. used_bits += bits;
  93789. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  93790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  93791. return false; /* read_callback_ sets the state for us */
  93792. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  93793. used_bits += bits;
  93794. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  93795. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  93796. return false; /* read_callback_ sets the state for us */
  93797. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  93798. used_bits += bits;
  93799. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  93800. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  93801. return false; /* read_callback_ sets the state for us */
  93802. decoder->private_->stream_info.data.stream_info.channels = x+1;
  93803. used_bits += bits;
  93804. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  93805. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  93806. return false; /* read_callback_ sets the state for us */
  93807. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  93808. used_bits += bits;
  93809. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  93810. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  93811. return false; /* read_callback_ sets the state for us */
  93812. used_bits += bits;
  93813. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  93814. return false; /* read_callback_ sets the state for us */
  93815. used_bits += 16*8;
  93816. /* skip the rest of the block */
  93817. FLAC__ASSERT(used_bits % 8 == 0);
  93818. length -= (used_bits / 8);
  93819. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  93820. return false; /* read_callback_ sets the state for us */
  93821. return true;
  93822. }
  93823. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  93824. {
  93825. FLAC__uint32 i, x;
  93826. FLAC__uint64 xx;
  93827. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93828. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  93829. decoder->private_->seek_table.is_last = is_last;
  93830. decoder->private_->seek_table.length = length;
  93831. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  93832. /* use realloc since we may pass through here several times (e.g. after seeking) */
  93833. if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
  93834. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93835. return false;
  93836. }
  93837. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  93838. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  93839. return false; /* read_callback_ sets the state for us */
  93840. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  93841. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  93842. return false; /* read_callback_ sets the state for us */
  93843. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  93844. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  93845. return false; /* read_callback_ sets the state for us */
  93846. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  93847. }
  93848. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  93849. /* if there is a partial point left, skip over it */
  93850. if(length > 0) {
  93851. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  93852. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  93853. return false; /* read_callback_ sets the state for us */
  93854. }
  93855. return true;
  93856. }
  93857. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  93858. {
  93859. FLAC__uint32 i;
  93860. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93861. /* read vendor string */
  93862. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  93863. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  93864. return false; /* read_callback_ sets the state for us */
  93865. if(obj->vendor_string.length > 0) {
  93866. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  93867. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93868. return false;
  93869. }
  93870. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  93871. return false; /* read_callback_ sets the state for us */
  93872. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  93873. }
  93874. else
  93875. obj->vendor_string.entry = 0;
  93876. /* read num comments */
  93877. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  93878. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  93879. return false; /* read_callback_ sets the state for us */
  93880. /* read comments */
  93881. if(obj->num_comments > 0) {
  93882. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  93883. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93884. return false;
  93885. }
  93886. for(i = 0; i < obj->num_comments; i++) {
  93887. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  93888. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  93889. return false; /* read_callback_ sets the state for us */
  93890. if(obj->comments[i].length > 0) {
  93891. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  93892. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93893. return false;
  93894. }
  93895. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  93896. return false; /* read_callback_ sets the state for us */
  93897. obj->comments[i].entry[obj->comments[i].length] = '\0';
  93898. }
  93899. else
  93900. obj->comments[i].entry = 0;
  93901. }
  93902. }
  93903. else {
  93904. obj->comments = 0;
  93905. }
  93906. return true;
  93907. }
  93908. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  93909. {
  93910. FLAC__uint32 i, j, x;
  93911. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93912. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  93913. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  93914. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  93915. return false; /* read_callback_ sets the state for us */
  93916. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  93917. return false; /* read_callback_ sets the state for us */
  93918. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  93919. return false; /* read_callback_ sets the state for us */
  93920. obj->is_cd = x? true : false;
  93921. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  93922. return false; /* read_callback_ sets the state for us */
  93923. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  93924. return false; /* read_callback_ sets the state for us */
  93925. obj->num_tracks = x;
  93926. if(obj->num_tracks > 0) {
  93927. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  93928. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93929. return false;
  93930. }
  93931. for(i = 0; i < obj->num_tracks; i++) {
  93932. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  93933. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  93934. return false; /* read_callback_ sets the state for us */
  93935. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  93936. return false; /* read_callback_ sets the state for us */
  93937. track->number = (FLAC__byte)x;
  93938. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  93939. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  93940. return false; /* read_callback_ sets the state for us */
  93941. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  93942. return false; /* read_callback_ sets the state for us */
  93943. track->type = x;
  93944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  93945. return false; /* read_callback_ sets the state for us */
  93946. track->pre_emphasis = x;
  93947. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  93948. return false; /* read_callback_ sets the state for us */
  93949. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  93950. return false; /* read_callback_ sets the state for us */
  93951. track->num_indices = (FLAC__byte)x;
  93952. if(track->num_indices > 0) {
  93953. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  93954. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93955. return false;
  93956. }
  93957. for(j = 0; j < track->num_indices; j++) {
  93958. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  93959. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  93960. return false; /* read_callback_ sets the state for us */
  93961. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  93962. return false; /* read_callback_ sets the state for us */
  93963. index->number = (FLAC__byte)x;
  93964. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  93965. return false; /* read_callback_ sets the state for us */
  93966. }
  93967. }
  93968. }
  93969. }
  93970. return true;
  93971. }
  93972. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  93973. {
  93974. FLAC__uint32 x;
  93975. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93976. /* read type */
  93977. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  93978. return false; /* read_callback_ sets the state for us */
  93979. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  93980. /* read MIME type */
  93981. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  93982. return false; /* read_callback_ sets the state for us */
  93983. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  93984. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93985. return false;
  93986. }
  93987. if(x > 0) {
  93988. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  93989. return false; /* read_callback_ sets the state for us */
  93990. }
  93991. obj->mime_type[x] = '\0';
  93992. /* read description */
  93993. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  93994. return false; /* read_callback_ sets the state for us */
  93995. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  93996. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93997. return false;
  93998. }
  93999. if(x > 0) {
  94000. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  94001. return false; /* read_callback_ sets the state for us */
  94002. }
  94003. obj->description[x] = '\0';
  94004. /* read width */
  94005. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  94006. return false; /* read_callback_ sets the state for us */
  94007. /* read height */
  94008. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  94009. return false; /* read_callback_ sets the state for us */
  94010. /* read depth */
  94011. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  94012. return false; /* read_callback_ sets the state for us */
  94013. /* read colors */
  94014. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  94015. return false; /* read_callback_ sets the state for us */
  94016. /* read data */
  94017. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  94018. return false; /* read_callback_ sets the state for us */
  94019. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  94020. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94021. return false;
  94022. }
  94023. if(obj->data_length > 0) {
  94024. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  94025. return false; /* read_callback_ sets the state for us */
  94026. }
  94027. return true;
  94028. }
  94029. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  94030. {
  94031. FLAC__uint32 x;
  94032. unsigned i, skip;
  94033. /* skip the version and flags bytes */
  94034. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  94035. return false; /* read_callback_ sets the state for us */
  94036. /* get the size (in bytes) to skip */
  94037. skip = 0;
  94038. for(i = 0; i < 4; i++) {
  94039. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94040. return false; /* read_callback_ sets the state for us */
  94041. skip <<= 7;
  94042. skip |= (x & 0x7f);
  94043. }
  94044. /* skip the rest of the tag */
  94045. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  94046. return false; /* read_callback_ sets the state for us */
  94047. return true;
  94048. }
  94049. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  94050. {
  94051. FLAC__uint32 x;
  94052. FLAC__bool first = true;
  94053. /* If we know the total number of samples in the stream, stop if we've read that many. */
  94054. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  94055. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  94056. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94057. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94058. return true;
  94059. }
  94060. }
  94061. /* make sure we're byte aligned */
  94062. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94063. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94064. return false; /* read_callback_ sets the state for us */
  94065. }
  94066. while(1) {
  94067. if(decoder->private_->cached) {
  94068. x = (FLAC__uint32)decoder->private_->lookahead;
  94069. decoder->private_->cached = false;
  94070. }
  94071. else {
  94072. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94073. return false; /* read_callback_ sets the state for us */
  94074. }
  94075. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94076. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94077. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94078. return false; /* read_callback_ sets the state for us */
  94079. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  94080. /* else we have to check if the second byte is the end of a sync code */
  94081. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94082. decoder->private_->lookahead = (FLAC__byte)x;
  94083. decoder->private_->cached = true;
  94084. }
  94085. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94086. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94087. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94088. return true;
  94089. }
  94090. }
  94091. if(first) {
  94092. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94093. first = false;
  94094. }
  94095. }
  94096. return true;
  94097. }
  94098. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  94099. {
  94100. unsigned channel;
  94101. unsigned i;
  94102. FLAC__int32 mid, side;
  94103. unsigned frame_crc; /* the one we calculate from the input stream */
  94104. FLAC__uint32 x;
  94105. *got_a_frame = false;
  94106. /* init the CRC */
  94107. frame_crc = 0;
  94108. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  94109. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  94110. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  94111. if(!read_frame_header_(decoder))
  94112. return false;
  94113. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  94114. return true;
  94115. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  94116. return false;
  94117. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94118. /*
  94119. * first figure the correct bits-per-sample of the subframe
  94120. */
  94121. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  94122. switch(decoder->private_->frame.header.channel_assignment) {
  94123. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94124. /* no adjustment needed */
  94125. break;
  94126. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94127. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94128. if(channel == 1)
  94129. bps++;
  94130. break;
  94131. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94132. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94133. if(channel == 0)
  94134. bps++;
  94135. break;
  94136. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94137. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94138. if(channel == 1)
  94139. bps++;
  94140. break;
  94141. default:
  94142. FLAC__ASSERT(0);
  94143. }
  94144. /*
  94145. * now read it
  94146. */
  94147. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  94148. return false;
  94149. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94150. return true;
  94151. }
  94152. if(!read_zero_padding_(decoder))
  94153. return false;
  94154. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
  94155. return true;
  94156. /*
  94157. * Read the frame CRC-16 from the footer and check
  94158. */
  94159. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  94160. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  94161. return false; /* read_callback_ sets the state for us */
  94162. if(frame_crc == x) {
  94163. if(do_full_decode) {
  94164. /* Undo any special channel coding */
  94165. switch(decoder->private_->frame.header.channel_assignment) {
  94166. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94167. /* do nothing */
  94168. break;
  94169. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94170. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94171. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94172. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  94173. break;
  94174. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94175. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94176. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94177. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  94178. break;
  94179. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94180. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94181. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94182. #if 1
  94183. mid = decoder->private_->output[0][i];
  94184. side = decoder->private_->output[1][i];
  94185. mid <<= 1;
  94186. mid |= (side & 1); /* i.e. if 'side' is odd... */
  94187. decoder->private_->output[0][i] = (mid + side) >> 1;
  94188. decoder->private_->output[1][i] = (mid - side) >> 1;
  94189. #else
  94190. /* OPT: without 'side' temp variable */
  94191. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  94192. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  94193. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  94194. #endif
  94195. }
  94196. break;
  94197. default:
  94198. FLAC__ASSERT(0);
  94199. break;
  94200. }
  94201. }
  94202. }
  94203. else {
  94204. /* Bad frame, emit error and zero the output signal */
  94205. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  94206. if(do_full_decode) {
  94207. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94208. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94209. }
  94210. }
  94211. }
  94212. *got_a_frame = true;
  94213. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  94214. if(decoder->private_->next_fixed_block_size)
  94215. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  94216. /* put the latest values into the public section of the decoder instance */
  94217. decoder->protected_->channels = decoder->private_->frame.header.channels;
  94218. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  94219. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  94220. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  94221. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  94222. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94223. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  94224. /* write it */
  94225. if(do_full_decode) {
  94226. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  94227. return false;
  94228. }
  94229. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94230. return true;
  94231. }
  94232. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  94233. {
  94234. FLAC__uint32 x;
  94235. FLAC__uint64 xx;
  94236. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  94237. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  94238. unsigned raw_header_len;
  94239. FLAC__bool is_unparseable = false;
  94240. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94241. /* init the raw header with the saved bits from synchronization */
  94242. raw_header[0] = decoder->private_->header_warmup[0];
  94243. raw_header[1] = decoder->private_->header_warmup[1];
  94244. raw_header_len = 2;
  94245. /* check to make sure that reserved bit is 0 */
  94246. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  94247. is_unparseable = true;
  94248. /*
  94249. * Note that along the way as we read the header, we look for a sync
  94250. * code inside. If we find one it would indicate that our original
  94251. * sync was bad since there cannot be a sync code in a valid header.
  94252. *
  94253. * Three kinds of things can go wrong when reading the frame header:
  94254. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  94255. * If we don't find a sync code, it can end up looking like we read
  94256. * a valid but unparseable header, until getting to the frame header
  94257. * CRC. Even then we could get a false positive on the CRC.
  94258. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  94259. * future encoder).
  94260. * 3) We may be on a damaged frame which appears valid but unparseable.
  94261. *
  94262. * For all these reasons, we try and read a complete frame header as
  94263. * long as it seems valid, even if unparseable, up until the frame
  94264. * header CRC.
  94265. */
  94266. /*
  94267. * read in the raw header as bytes so we can CRC it, and parse it on the way
  94268. */
  94269. for(i = 0; i < 2; i++) {
  94270. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94271. return false; /* read_callback_ sets the state for us */
  94272. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94273. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  94274. decoder->private_->lookahead = (FLAC__byte)x;
  94275. decoder->private_->cached = true;
  94276. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94277. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94278. return true;
  94279. }
  94280. raw_header[raw_header_len++] = (FLAC__byte)x;
  94281. }
  94282. switch(x = raw_header[2] >> 4) {
  94283. case 0:
  94284. is_unparseable = true;
  94285. break;
  94286. case 1:
  94287. decoder->private_->frame.header.blocksize = 192;
  94288. break;
  94289. case 2:
  94290. case 3:
  94291. case 4:
  94292. case 5:
  94293. decoder->private_->frame.header.blocksize = 576 << (x-2);
  94294. break;
  94295. case 6:
  94296. case 7:
  94297. blocksize_hint = x;
  94298. break;
  94299. case 8:
  94300. case 9:
  94301. case 10:
  94302. case 11:
  94303. case 12:
  94304. case 13:
  94305. case 14:
  94306. case 15:
  94307. decoder->private_->frame.header.blocksize = 256 << (x-8);
  94308. break;
  94309. default:
  94310. FLAC__ASSERT(0);
  94311. break;
  94312. }
  94313. switch(x = raw_header[2] & 0x0f) {
  94314. case 0:
  94315. if(decoder->private_->has_stream_info)
  94316. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  94317. else
  94318. is_unparseable = true;
  94319. break;
  94320. case 1:
  94321. decoder->private_->frame.header.sample_rate = 88200;
  94322. break;
  94323. case 2:
  94324. decoder->private_->frame.header.sample_rate = 176400;
  94325. break;
  94326. case 3:
  94327. decoder->private_->frame.header.sample_rate = 192000;
  94328. break;
  94329. case 4:
  94330. decoder->private_->frame.header.sample_rate = 8000;
  94331. break;
  94332. case 5:
  94333. decoder->private_->frame.header.sample_rate = 16000;
  94334. break;
  94335. case 6:
  94336. decoder->private_->frame.header.sample_rate = 22050;
  94337. break;
  94338. case 7:
  94339. decoder->private_->frame.header.sample_rate = 24000;
  94340. break;
  94341. case 8:
  94342. decoder->private_->frame.header.sample_rate = 32000;
  94343. break;
  94344. case 9:
  94345. decoder->private_->frame.header.sample_rate = 44100;
  94346. break;
  94347. case 10:
  94348. decoder->private_->frame.header.sample_rate = 48000;
  94349. break;
  94350. case 11:
  94351. decoder->private_->frame.header.sample_rate = 96000;
  94352. break;
  94353. case 12:
  94354. case 13:
  94355. case 14:
  94356. sample_rate_hint = x;
  94357. break;
  94358. case 15:
  94359. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94360. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94361. return true;
  94362. default:
  94363. FLAC__ASSERT(0);
  94364. }
  94365. x = (unsigned)(raw_header[3] >> 4);
  94366. if(x & 8) {
  94367. decoder->private_->frame.header.channels = 2;
  94368. switch(x & 7) {
  94369. case 0:
  94370. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  94371. break;
  94372. case 1:
  94373. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  94374. break;
  94375. case 2:
  94376. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  94377. break;
  94378. default:
  94379. is_unparseable = true;
  94380. break;
  94381. }
  94382. }
  94383. else {
  94384. decoder->private_->frame.header.channels = (unsigned)x + 1;
  94385. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  94386. }
  94387. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  94388. case 0:
  94389. if(decoder->private_->has_stream_info)
  94390. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  94391. else
  94392. is_unparseable = true;
  94393. break;
  94394. case 1:
  94395. decoder->private_->frame.header.bits_per_sample = 8;
  94396. break;
  94397. case 2:
  94398. decoder->private_->frame.header.bits_per_sample = 12;
  94399. break;
  94400. case 4:
  94401. decoder->private_->frame.header.bits_per_sample = 16;
  94402. break;
  94403. case 5:
  94404. decoder->private_->frame.header.bits_per_sample = 20;
  94405. break;
  94406. case 6:
  94407. decoder->private_->frame.header.bits_per_sample = 24;
  94408. break;
  94409. case 3:
  94410. case 7:
  94411. is_unparseable = true;
  94412. break;
  94413. default:
  94414. FLAC__ASSERT(0);
  94415. break;
  94416. }
  94417. /* check to make sure that reserved bit is 0 */
  94418. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  94419. is_unparseable = true;
  94420. /* read the frame's starting sample number (or frame number as the case may be) */
  94421. if(
  94422. raw_header[1] & 0x01 ||
  94423. /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
  94424. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  94425. ) { /* variable blocksize */
  94426. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  94427. return false; /* read_callback_ sets the state for us */
  94428. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  94429. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  94430. decoder->private_->cached = true;
  94431. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94432. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94433. return true;
  94434. }
  94435. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  94436. decoder->private_->frame.header.number.sample_number = xx;
  94437. }
  94438. else { /* fixed blocksize */
  94439. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  94440. return false; /* read_callback_ sets the state for us */
  94441. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  94442. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  94443. decoder->private_->cached = true;
  94444. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94445. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94446. return true;
  94447. }
  94448. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  94449. decoder->private_->frame.header.number.frame_number = x;
  94450. }
  94451. if(blocksize_hint) {
  94452. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94453. return false; /* read_callback_ sets the state for us */
  94454. raw_header[raw_header_len++] = (FLAC__byte)x;
  94455. if(blocksize_hint == 7) {
  94456. FLAC__uint32 _x;
  94457. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  94458. return false; /* read_callback_ sets the state for us */
  94459. raw_header[raw_header_len++] = (FLAC__byte)_x;
  94460. x = (x << 8) | _x;
  94461. }
  94462. decoder->private_->frame.header.blocksize = x+1;
  94463. }
  94464. if(sample_rate_hint) {
  94465. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94466. return false; /* read_callback_ sets the state for us */
  94467. raw_header[raw_header_len++] = (FLAC__byte)x;
  94468. if(sample_rate_hint != 12) {
  94469. FLAC__uint32 _x;
  94470. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  94471. return false; /* read_callback_ sets the state for us */
  94472. raw_header[raw_header_len++] = (FLAC__byte)_x;
  94473. x = (x << 8) | _x;
  94474. }
  94475. if(sample_rate_hint == 12)
  94476. decoder->private_->frame.header.sample_rate = x*1000;
  94477. else if(sample_rate_hint == 13)
  94478. decoder->private_->frame.header.sample_rate = x;
  94479. else
  94480. decoder->private_->frame.header.sample_rate = x*10;
  94481. }
  94482. /* read the CRC-8 byte */
  94483. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94484. return false; /* read_callback_ sets the state for us */
  94485. crc8 = (FLAC__byte)x;
  94486. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  94487. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94488. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94489. return true;
  94490. }
  94491. /* calculate the sample number from the frame number if needed */
  94492. decoder->private_->next_fixed_block_size = 0;
  94493. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  94494. x = decoder->private_->frame.header.number.frame_number;
  94495. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  94496. if(decoder->private_->fixed_block_size)
  94497. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  94498. else if(decoder->private_->has_stream_info) {
  94499. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  94500. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  94501. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  94502. }
  94503. else
  94504. is_unparseable = true;
  94505. }
  94506. else if(x == 0) {
  94507. decoder->private_->frame.header.number.sample_number = 0;
  94508. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  94509. }
  94510. else {
  94511. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  94512. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  94513. }
  94514. }
  94515. if(is_unparseable) {
  94516. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94517. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94518. return true;
  94519. }
  94520. return true;
  94521. }
  94522. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94523. {
  94524. FLAC__uint32 x;
  94525. FLAC__bool wasted_bits;
  94526. unsigned i;
  94527. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  94528. return false; /* read_callback_ sets the state for us */
  94529. wasted_bits = (x & 1);
  94530. x &= 0xfe;
  94531. if(wasted_bits) {
  94532. unsigned u;
  94533. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  94534. return false; /* read_callback_ sets the state for us */
  94535. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  94536. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  94537. }
  94538. else
  94539. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  94540. /*
  94541. * Lots of magic numbers here
  94542. */
  94543. if(x & 0x80) {
  94544. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94545. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94546. return true;
  94547. }
  94548. else if(x == 0) {
  94549. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  94550. return false;
  94551. }
  94552. else if(x == 2) {
  94553. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  94554. return false;
  94555. }
  94556. else if(x < 16) {
  94557. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94558. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94559. return true;
  94560. }
  94561. else if(x <= 24) {
  94562. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  94563. return false;
  94564. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94565. return true;
  94566. }
  94567. else if(x < 64) {
  94568. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94569. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94570. return true;
  94571. }
  94572. else {
  94573. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  94574. return false;
  94575. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94576. return true;
  94577. }
  94578. if(wasted_bits && do_full_decode) {
  94579. x = decoder->private_->frame.subframes[channel].wasted_bits;
  94580. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94581. decoder->private_->output[channel][i] <<= x;
  94582. }
  94583. return true;
  94584. }
  94585. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94586. {
  94587. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  94588. FLAC__int32 x;
  94589. unsigned i;
  94590. FLAC__int32 *output = decoder->private_->output[channel];
  94591. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  94592. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  94593. return false; /* read_callback_ sets the state for us */
  94594. subframe->value = x;
  94595. /* decode the subframe */
  94596. if(do_full_decode) {
  94597. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94598. output[i] = x;
  94599. }
  94600. return true;
  94601. }
  94602. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  94603. {
  94604. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  94605. FLAC__int32 i32;
  94606. FLAC__uint32 u32;
  94607. unsigned u;
  94608. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  94609. subframe->residual = decoder->private_->residual[channel];
  94610. subframe->order = order;
  94611. /* read warm-up samples */
  94612. for(u = 0; u < order; u++) {
  94613. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  94614. return false; /* read_callback_ sets the state for us */
  94615. subframe->warmup[u] = i32;
  94616. }
  94617. /* read entropy coding method info */
  94618. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  94619. return false; /* read_callback_ sets the state for us */
  94620. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  94621. switch(subframe->entropy_coding_method.type) {
  94622. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94623. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94624. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  94625. return false; /* read_callback_ sets the state for us */
  94626. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  94627. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  94628. break;
  94629. default:
  94630. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94631. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94632. return true;
  94633. }
  94634. /* read residual */
  94635. switch(subframe->entropy_coding_method.type) {
  94636. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94637. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94638. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  94639. return false;
  94640. break;
  94641. default:
  94642. FLAC__ASSERT(0);
  94643. }
  94644. /* decode the subframe */
  94645. if(do_full_decode) {
  94646. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  94647. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  94648. }
  94649. return true;
  94650. }
  94651. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  94652. {
  94653. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  94654. FLAC__int32 i32;
  94655. FLAC__uint32 u32;
  94656. unsigned u;
  94657. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  94658. subframe->residual = decoder->private_->residual[channel];
  94659. subframe->order = order;
  94660. /* read warm-up samples */
  94661. for(u = 0; u < order; u++) {
  94662. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  94663. return false; /* read_callback_ sets the state for us */
  94664. subframe->warmup[u] = i32;
  94665. }
  94666. /* read qlp coeff precision */
  94667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  94668. return false; /* read_callback_ sets the state for us */
  94669. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  94670. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94671. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94672. return true;
  94673. }
  94674. subframe->qlp_coeff_precision = u32+1;
  94675. /* read qlp shift */
  94676. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  94677. return false; /* read_callback_ sets the state for us */
  94678. subframe->quantization_level = i32;
  94679. /* read quantized lp coefficiencts */
  94680. for(u = 0; u < order; u++) {
  94681. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  94682. return false; /* read_callback_ sets the state for us */
  94683. subframe->qlp_coeff[u] = i32;
  94684. }
  94685. /* read entropy coding method info */
  94686. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  94687. return false; /* read_callback_ sets the state for us */
  94688. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  94689. switch(subframe->entropy_coding_method.type) {
  94690. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94691. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94692. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  94693. return false; /* read_callback_ sets the state for us */
  94694. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  94695. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  94696. break;
  94697. default:
  94698. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94699. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94700. return true;
  94701. }
  94702. /* read residual */
  94703. switch(subframe->entropy_coding_method.type) {
  94704. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94705. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94706. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  94707. return false;
  94708. break;
  94709. default:
  94710. FLAC__ASSERT(0);
  94711. }
  94712. /* decode the subframe */
  94713. if(do_full_decode) {
  94714. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  94715. /*@@@@@@ technically not pessimistic enough, should be more like
  94716. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  94717. */
  94718. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  94719. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  94720. if(order <= 8)
  94721. decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  94722. else
  94723. decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  94724. }
  94725. else
  94726. decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  94727. else
  94728. decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  94729. }
  94730. return true;
  94731. }
  94732. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94733. {
  94734. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  94735. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  94736. unsigned i;
  94737. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  94738. subframe->data = residual;
  94739. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94740. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  94741. return false; /* read_callback_ sets the state for us */
  94742. residual[i] = x;
  94743. }
  94744. /* decode the subframe */
  94745. if(do_full_decode)
  94746. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94747. return true;
  94748. }
  94749. FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
  94750. {
  94751. FLAC__uint32 rice_parameter;
  94752. int i;
  94753. unsigned partition, sample, u;
  94754. const unsigned partitions = 1u << partition_order;
  94755. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  94756. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  94757. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  94758. /* sanity checks */
  94759. if(partition_order == 0) {
  94760. if(decoder->private_->frame.header.blocksize < predictor_order) {
  94761. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94762. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94763. return true;
  94764. }
  94765. }
  94766. else {
  94767. if(partition_samples < predictor_order) {
  94768. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94769. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94770. return true;
  94771. }
  94772. }
  94773. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  94774. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94775. return false;
  94776. }
  94777. sample = 0;
  94778. for(partition = 0; partition < partitions; partition++) {
  94779. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  94780. return false; /* read_callback_ sets the state for us */
  94781. partitioned_rice_contents->parameters[partition] = rice_parameter;
  94782. if(rice_parameter < pesc) {
  94783. partitioned_rice_contents->raw_bits[partition] = 0;
  94784. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  94785. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  94786. return false; /* read_callback_ sets the state for us */
  94787. sample += u;
  94788. }
  94789. else {
  94790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  94791. return false; /* read_callback_ sets the state for us */
  94792. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  94793. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  94794. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  94795. return false; /* read_callback_ sets the state for us */
  94796. residual[sample] = i;
  94797. }
  94798. }
  94799. }
  94800. return true;
  94801. }
  94802. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  94803. {
  94804. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94805. FLAC__uint32 zero = 0;
  94806. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94807. return false; /* read_callback_ sets the state for us */
  94808. if(zero != 0) {
  94809. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94810. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94811. }
  94812. }
  94813. return true;
  94814. }
  94815. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  94816. {
  94817. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  94818. if(
  94819. #if FLAC__HAS_OGG
  94820. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  94821. !decoder->private_->is_ogg &&
  94822. #endif
  94823. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  94824. ) {
  94825. *bytes = 0;
  94826. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94827. return false;
  94828. }
  94829. else if(*bytes > 0) {
  94830. /* While seeking, it is possible for our seek to land in the
  94831. * middle of audio data that looks exactly like a frame header
  94832. * from a future version of an encoder. When that happens, our
  94833. * error callback will get an
  94834. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  94835. * unparseable_frame_count. But there is a remote possibility
  94836. * that it is properly synced at such a "future-codec frame",
  94837. * so to make sure, we wait to see many "unparseable" errors in
  94838. * a row before bailing out.
  94839. */
  94840. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  94841. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94842. return false;
  94843. }
  94844. else {
  94845. const FLAC__StreamDecoderReadStatus status =
  94846. #if FLAC__HAS_OGG
  94847. decoder->private_->is_ogg?
  94848. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  94849. #endif
  94850. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  94851. ;
  94852. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  94853. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94854. return false;
  94855. }
  94856. else if(*bytes == 0) {
  94857. if(
  94858. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  94859. (
  94860. #if FLAC__HAS_OGG
  94861. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  94862. !decoder->private_->is_ogg &&
  94863. #endif
  94864. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  94865. )
  94866. ) {
  94867. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94868. return false;
  94869. }
  94870. else
  94871. return true;
  94872. }
  94873. else
  94874. return true;
  94875. }
  94876. }
  94877. else {
  94878. /* abort to avoid a deadlock */
  94879. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94880. return false;
  94881. }
  94882. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  94883. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  94884. * and at the same time hit the end of the stream (for example, seeking
  94885. * to a point that is after the beginning of the last Ogg page). There
  94886. * is no way to report an Ogg sync loss through the callbacks (see note
  94887. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  94888. * So to keep the decoder from stopping at this point we gate the call
  94889. * to the eof_callback and let the Ogg decoder aspect set the
  94890. * end-of-stream state when it is needed.
  94891. */
  94892. }
  94893. #if FLAC__HAS_OGG
  94894. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  94895. {
  94896. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  94897. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  94898. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  94899. /* we don't really have a way to handle lost sync via read
  94900. * callback so we'll let it pass and let the underlying
  94901. * FLAC decoder catch the error
  94902. */
  94903. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  94904. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  94905. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  94906. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  94907. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  94908. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  94909. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  94910. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  94911. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  94912. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  94913. default:
  94914. FLAC__ASSERT(0);
  94915. /* double protection */
  94916. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  94917. }
  94918. }
  94919. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  94920. {
  94921. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  94922. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  94923. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  94924. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  94925. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  94926. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  94927. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  94928. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  94929. default:
  94930. /* double protection: */
  94931. FLAC__ASSERT(0);
  94932. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  94933. }
  94934. }
  94935. #endif
  94936. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  94937. {
  94938. if(decoder->private_->is_seeking) {
  94939. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  94940. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  94941. FLAC__uint64 target_sample = decoder->private_->target_sample;
  94942. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94943. #if FLAC__HAS_OGG
  94944. decoder->private_->got_a_frame = true;
  94945. #endif
  94946. decoder->private_->last_frame = *frame; /* save the frame */
  94947. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  94948. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  94949. /* kick out of seek mode */
  94950. decoder->private_->is_seeking = false;
  94951. /* shift out the samples before target_sample */
  94952. if(delta > 0) {
  94953. unsigned channel;
  94954. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  94955. for(channel = 0; channel < frame->header.channels; channel++)
  94956. newbuffer[channel] = buffer[channel] + delta;
  94957. decoder->private_->last_frame.header.blocksize -= delta;
  94958. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  94959. /* write the relevant samples */
  94960. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  94961. }
  94962. else {
  94963. /* write the relevant samples */
  94964. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  94965. }
  94966. }
  94967. else {
  94968. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  94969. }
  94970. }
  94971. else {
  94972. /*
  94973. * If we never got STREAMINFO, turn off MD5 checking to save
  94974. * cycles since we don't have a sum to compare to anyway
  94975. */
  94976. if(!decoder->private_->has_stream_info)
  94977. decoder->private_->do_md5_checking = false;
  94978. if(decoder->private_->do_md5_checking) {
  94979. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  94980. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  94981. }
  94982. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  94983. }
  94984. }
  94985. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  94986. {
  94987. if(!decoder->private_->is_seeking)
  94988. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  94989. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  94990. decoder->private_->unparseable_frame_count++;
  94991. }
  94992. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  94993. {
  94994. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  94995. FLAC__int64 pos = -1;
  94996. int i;
  94997. unsigned approx_bytes_per_frame;
  94998. FLAC__bool first_seek = true;
  94999. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  95000. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  95001. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95002. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  95003. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  95004. /* take these from the current frame in case they've changed mid-stream */
  95005. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  95006. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  95007. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  95008. /* use values from stream info if we didn't decode a frame */
  95009. if(channels == 0)
  95010. channels = decoder->private_->stream_info.data.stream_info.channels;
  95011. if(bps == 0)
  95012. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95013. /* we are just guessing here */
  95014. if(max_framesize > 0)
  95015. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  95016. /*
  95017. * Check if it's a known fixed-blocksize stream. Note that though
  95018. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  95019. * never get a STREAMINFO block when decoding so the value of
  95020. * min_blocksize might be zero.
  95021. */
  95022. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  95023. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  95024. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  95025. }
  95026. else
  95027. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  95028. /*
  95029. * First, we set an upper and lower bound on where in the
  95030. * stream we will search. For now we assume the worst case
  95031. * scenario, which is our best guess at the beginning of
  95032. * the first frame and end of the stream.
  95033. */
  95034. lower_bound = first_frame_offset;
  95035. lower_bound_sample = 0;
  95036. upper_bound = stream_length;
  95037. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  95038. /*
  95039. * Now we refine the bounds if we have a seektable with
  95040. * suitable points. Note that according to the spec they
  95041. * must be ordered by ascending sample number.
  95042. *
  95043. * Note: to protect against invalid seek tables we will ignore points
  95044. * that have frame_samples==0 or sample_number>=total_samples
  95045. */
  95046. if(seek_table) {
  95047. FLAC__uint64 new_lower_bound = lower_bound;
  95048. FLAC__uint64 new_upper_bound = upper_bound;
  95049. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  95050. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  95051. /* find the closest seek point <= target_sample, if it exists */
  95052. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  95053. if(
  95054. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95055. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95056. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95057. seek_table->points[i].sample_number <= target_sample
  95058. )
  95059. break;
  95060. }
  95061. if(i >= 0) { /* i.e. we found a suitable seek point... */
  95062. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95063. new_lower_bound_sample = seek_table->points[i].sample_number;
  95064. }
  95065. /* find the closest seek point > target_sample, if it exists */
  95066. for(i = 0; i < (int)seek_table->num_points; i++) {
  95067. if(
  95068. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95069. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95070. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95071. seek_table->points[i].sample_number > target_sample
  95072. )
  95073. break;
  95074. }
  95075. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  95076. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95077. new_upper_bound_sample = seek_table->points[i].sample_number;
  95078. }
  95079. /* final protection against unsorted seek tables; keep original values if bogus */
  95080. if(new_upper_bound >= new_lower_bound) {
  95081. lower_bound = new_lower_bound;
  95082. upper_bound = new_upper_bound;
  95083. lower_bound_sample = new_lower_bound_sample;
  95084. upper_bound_sample = new_upper_bound_sample;
  95085. }
  95086. }
  95087. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  95088. /* there are 2 insidious ways that the following equality occurs, which
  95089. * we need to fix:
  95090. * 1) total_samples is 0 (unknown) and target_sample is 0
  95091. * 2) total_samples is 0 (unknown) and target_sample happens to be
  95092. * exactly equal to the last seek point in the seek table; this
  95093. * means there is no seek point above it, and upper_bound_samples
  95094. * remains equal to the estimate (of target_samples) we made above
  95095. * in either case it does not hurt to move upper_bound_sample up by 1
  95096. */
  95097. if(upper_bound_sample == lower_bound_sample)
  95098. upper_bound_sample++;
  95099. decoder->private_->target_sample = target_sample;
  95100. while(1) {
  95101. /* check if the bounds are still ok */
  95102. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  95103. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95104. return false;
  95105. }
  95106. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95107. #if defined _MSC_VER || defined __MINGW32__
  95108. /* with VC++ you have to spoon feed it the casting */
  95109. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  95110. #else
  95111. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  95112. #endif
  95113. #else
  95114. /* a little less accurate: */
  95115. if(upper_bound - lower_bound < 0xffffffff)
  95116. pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
  95117. else /* @@@ WATCHOUT, ~2TB limit */
  95118. pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
  95119. #endif
  95120. if(pos >= (FLAC__int64)upper_bound)
  95121. pos = (FLAC__int64)upper_bound - 1;
  95122. if(pos < (FLAC__int64)lower_bound)
  95123. pos = (FLAC__int64)lower_bound;
  95124. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95125. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95126. return false;
  95127. }
  95128. if(!FLAC__stream_decoder_flush(decoder)) {
  95129. /* above call sets the state for us */
  95130. return false;
  95131. }
  95132. /* Now we need to get a frame. First we need to reset our
  95133. * unparseable_frame_count; if we get too many unparseable
  95134. * frames in a row, the read callback will return
  95135. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  95136. * FLAC__stream_decoder_process_single() to return false.
  95137. */
  95138. decoder->private_->unparseable_frame_count = 0;
  95139. if(!FLAC__stream_decoder_process_single(decoder)) {
  95140. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95141. return false;
  95142. }
  95143. /* our write callback will change the state when it gets to the target frame */
  95144. /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
  95145. #if 0
  95146. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  95147. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  95148. break;
  95149. #endif
  95150. if(!decoder->private_->is_seeking)
  95151. break;
  95152. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95153. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95154. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  95155. if (pos == (FLAC__int64)lower_bound) {
  95156. /* can't move back any more than the first frame, something is fatally wrong */
  95157. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95158. return false;
  95159. }
  95160. /* our last move backwards wasn't big enough, try again */
  95161. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  95162. continue;
  95163. }
  95164. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  95165. first_seek = false;
  95166. /* make sure we are not seeking in corrupted stream */
  95167. if (this_frame_sample < lower_bound_sample) {
  95168. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95169. return false;
  95170. }
  95171. /* we need to narrow the search */
  95172. if(target_sample < this_frame_sample) {
  95173. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95174. /*@@@@@@ what will decode position be if at end of stream? */
  95175. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  95176. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95177. return false;
  95178. }
  95179. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  95180. }
  95181. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  95182. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95183. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  95184. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95185. return false;
  95186. }
  95187. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  95188. }
  95189. }
  95190. return true;
  95191. }
  95192. #if FLAC__HAS_OGG
  95193. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95194. {
  95195. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  95196. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  95197. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  95198. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  95199. FLAC__bool did_a_seek;
  95200. unsigned iteration = 0;
  95201. /* In the first iterations, we will calculate the target byte position
  95202. * by the distance from the target sample to left_sample and
  95203. * right_sample (let's call it "proportional search"). After that, we
  95204. * will switch to binary search.
  95205. */
  95206. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  95207. /* We will switch to a linear search once our current sample is less
  95208. * than this number of samples ahead of the target sample
  95209. */
  95210. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  95211. /* If the total number of samples is unknown, use a large value, and
  95212. * force binary search immediately.
  95213. */
  95214. if(right_sample == 0) {
  95215. right_sample = (FLAC__uint64)(-1);
  95216. BINARY_SEARCH_AFTER_ITERATION = 0;
  95217. }
  95218. decoder->private_->target_sample = target_sample;
  95219. for( ; ; iteration++) {
  95220. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  95221. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  95222. pos = (right_pos + left_pos) / 2;
  95223. }
  95224. else {
  95225. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95226. #if defined _MSC_VER || defined __MINGW32__
  95227. /* with MSVC you have to spoon feed it the casting */
  95228. pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
  95229. #else
  95230. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  95231. #endif
  95232. #else
  95233. /* a little less accurate: */
  95234. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  95235. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  95236. else /* @@@ WATCHOUT, ~2TB limit */
  95237. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  95238. #endif
  95239. /* @@@ TODO: might want to limit pos to some distance
  95240. * before EOF, to make sure we land before the last frame,
  95241. * thereby getting a this_frame_sample and so having a better
  95242. * estimate.
  95243. */
  95244. }
  95245. /* physical seek */
  95246. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95247. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95248. return false;
  95249. }
  95250. if(!FLAC__stream_decoder_flush(decoder)) {
  95251. /* above call sets the state for us */
  95252. return false;
  95253. }
  95254. did_a_seek = true;
  95255. }
  95256. else
  95257. did_a_seek = false;
  95258. decoder->private_->got_a_frame = false;
  95259. if(!FLAC__stream_decoder_process_single(decoder)) {
  95260. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95261. return false;
  95262. }
  95263. if(!decoder->private_->got_a_frame) {
  95264. if(did_a_seek) {
  95265. /* this can happen if we seek to a point after the last frame; we drop
  95266. * to binary search right away in this case to avoid any wasted
  95267. * iterations of proportional search.
  95268. */
  95269. right_pos = pos;
  95270. BINARY_SEARCH_AFTER_ITERATION = 0;
  95271. }
  95272. else {
  95273. /* this can probably only happen if total_samples is unknown and the
  95274. * target_sample is past the end of the stream
  95275. */
  95276. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95277. return false;
  95278. }
  95279. }
  95280. /* our write callback will change the state when it gets to the target frame */
  95281. else if(!decoder->private_->is_seeking) {
  95282. break;
  95283. }
  95284. else {
  95285. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95286. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95287. if (did_a_seek) {
  95288. if (this_frame_sample <= target_sample) {
  95289. /* The 'equal' case should not happen, since
  95290. * FLAC__stream_decoder_process_single()
  95291. * should recognize that it has hit the
  95292. * target sample and we would exit through
  95293. * the 'break' above.
  95294. */
  95295. FLAC__ASSERT(this_frame_sample != target_sample);
  95296. left_sample = this_frame_sample;
  95297. /* sanity check to avoid infinite loop */
  95298. if (left_pos == pos) {
  95299. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95300. return false;
  95301. }
  95302. left_pos = pos;
  95303. }
  95304. else if(this_frame_sample > target_sample) {
  95305. right_sample = this_frame_sample;
  95306. /* sanity check to avoid infinite loop */
  95307. if (right_pos == pos) {
  95308. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95309. return false;
  95310. }
  95311. right_pos = pos;
  95312. }
  95313. }
  95314. }
  95315. }
  95316. return true;
  95317. }
  95318. #endif
  95319. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  95320. {
  95321. (void)client_data;
  95322. if(*bytes > 0) {
  95323. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  95324. if(ferror(decoder->private_->file))
  95325. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95326. else if(*bytes == 0)
  95327. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  95328. else
  95329. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95330. }
  95331. else
  95332. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  95333. }
  95334. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  95335. {
  95336. (void)client_data;
  95337. if(decoder->private_->file == stdin)
  95338. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  95339. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  95340. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  95341. else
  95342. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  95343. }
  95344. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  95345. {
  95346. off_t pos;
  95347. (void)client_data;
  95348. if(decoder->private_->file == stdin)
  95349. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  95350. else if((pos = ftello(decoder->private_->file)) < 0)
  95351. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  95352. else {
  95353. *absolute_byte_offset = (FLAC__uint64)pos;
  95354. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  95355. }
  95356. }
  95357. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  95358. {
  95359. struct stat filestats;
  95360. (void)client_data;
  95361. if(decoder->private_->file == stdin)
  95362. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  95363. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  95364. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  95365. else {
  95366. *stream_length = (FLAC__uint64)filestats.st_size;
  95367. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  95368. }
  95369. }
  95370. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  95371. {
  95372. (void)client_data;
  95373. return feof(decoder->private_->file)? true : false;
  95374. }
  95375. #endif
  95376. /********* End of inlined file: stream_decoder.c *********/
  95377. /********* Start of inlined file: stream_encoder.c *********/
  95378. /********* Start of inlined file: juce_FlacHeader.h *********/
  95379. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95380. // tasks..
  95381. #define VERSION "1.2.1"
  95382. #define FLAC__NO_DLL 1
  95383. #ifdef _MSC_VER
  95384. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95385. #endif
  95386. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  95387. #define FLAC__SYS_DARWIN 1
  95388. #endif
  95389. /********* End of inlined file: juce_FlacHeader.h *********/
  95390. #if JUCE_USE_FLAC
  95391. #if HAVE_CONFIG_H
  95392. # include <config.h>
  95393. #endif
  95394. #if defined _MSC_VER || defined __MINGW32__
  95395. #include <io.h> /* for _setmode() */
  95396. #include <fcntl.h> /* for _O_BINARY */
  95397. #endif
  95398. #if defined __CYGWIN__ || defined __EMX__
  95399. #include <io.h> /* for setmode(), O_BINARY */
  95400. #include <fcntl.h> /* for _O_BINARY */
  95401. #endif
  95402. #include <limits.h>
  95403. #include <stdio.h>
  95404. #include <stdlib.h> /* for malloc() */
  95405. #include <string.h> /* for memcpy() */
  95406. #include <sys/types.h> /* for off_t */
  95407. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  95408. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  95409. #define fseeko fseek
  95410. #define ftello ftell
  95411. #endif
  95412. #endif
  95413. /********* Start of inlined file: stream_encoder.h *********/
  95414. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  95415. #define FLAC__PROTECTED__STREAM_ENCODER_H
  95416. #if FLAC__HAS_OGG
  95417. #include "private/ogg_encoder_aspect.h"
  95418. #endif
  95419. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95420. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  95421. typedef enum {
  95422. FLAC__APODIZATION_BARTLETT,
  95423. FLAC__APODIZATION_BARTLETT_HANN,
  95424. FLAC__APODIZATION_BLACKMAN,
  95425. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  95426. FLAC__APODIZATION_CONNES,
  95427. FLAC__APODIZATION_FLATTOP,
  95428. FLAC__APODIZATION_GAUSS,
  95429. FLAC__APODIZATION_HAMMING,
  95430. FLAC__APODIZATION_HANN,
  95431. FLAC__APODIZATION_KAISER_BESSEL,
  95432. FLAC__APODIZATION_NUTTALL,
  95433. FLAC__APODIZATION_RECTANGLE,
  95434. FLAC__APODIZATION_TRIANGLE,
  95435. FLAC__APODIZATION_TUKEY,
  95436. FLAC__APODIZATION_WELCH
  95437. } FLAC__ApodizationFunction;
  95438. typedef struct {
  95439. FLAC__ApodizationFunction type;
  95440. union {
  95441. struct {
  95442. FLAC__real stddev;
  95443. } gauss;
  95444. struct {
  95445. FLAC__real p;
  95446. } tukey;
  95447. } parameters;
  95448. } FLAC__ApodizationSpecification;
  95449. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95450. typedef struct FLAC__StreamEncoderProtected {
  95451. FLAC__StreamEncoderState state;
  95452. FLAC__bool verify;
  95453. FLAC__bool streamable_subset;
  95454. FLAC__bool do_md5;
  95455. FLAC__bool do_mid_side_stereo;
  95456. FLAC__bool loose_mid_side_stereo;
  95457. unsigned channels;
  95458. unsigned bits_per_sample;
  95459. unsigned sample_rate;
  95460. unsigned blocksize;
  95461. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95462. unsigned num_apodizations;
  95463. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  95464. #endif
  95465. unsigned max_lpc_order;
  95466. unsigned qlp_coeff_precision;
  95467. FLAC__bool do_qlp_coeff_prec_search;
  95468. FLAC__bool do_exhaustive_model_search;
  95469. FLAC__bool do_escape_coding;
  95470. unsigned min_residual_partition_order;
  95471. unsigned max_residual_partition_order;
  95472. unsigned rice_parameter_search_dist;
  95473. FLAC__uint64 total_samples_estimate;
  95474. FLAC__StreamMetadata **metadata;
  95475. unsigned num_metadata_blocks;
  95476. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  95477. #if FLAC__HAS_OGG
  95478. FLAC__OggEncoderAspect ogg_encoder_aspect;
  95479. #endif
  95480. } FLAC__StreamEncoderProtected;
  95481. #endif
  95482. /********* End of inlined file: stream_encoder.h *********/
  95483. #if FLAC__HAS_OGG
  95484. #include "include/private/ogg_helper.h"
  95485. #include "include/private/ogg_mapping.h"
  95486. #endif
  95487. /********* Start of inlined file: stream_encoder_framing.h *********/
  95488. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  95489. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  95490. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  95491. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  95492. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95493. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95494. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95495. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95496. #endif
  95497. /********* End of inlined file: stream_encoder_framing.h *********/
  95498. /********* Start of inlined file: window.h *********/
  95499. #ifndef FLAC__PRIVATE__WINDOW_H
  95500. #define FLAC__PRIVATE__WINDOW_H
  95501. #ifdef HAVE_CONFIG_H
  95502. #include <config.h>
  95503. #endif
  95504. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95505. /*
  95506. * FLAC__window_*()
  95507. * --------------------------------------------------------------------
  95508. * Calculates window coefficients according to different apodization
  95509. * functions.
  95510. *
  95511. * OUT window[0,L-1]
  95512. * IN L (number of points in window)
  95513. */
  95514. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  95515. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  95516. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  95517. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  95518. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  95519. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  95520. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  95521. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  95522. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  95523. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  95524. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  95525. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  95526. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  95527. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  95528. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  95529. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95530. #endif
  95531. /********* End of inlined file: window.h *********/
  95532. #ifndef FLaC__INLINE
  95533. #define FLaC__INLINE
  95534. #endif
  95535. #ifdef min
  95536. #undef min
  95537. #endif
  95538. #define min(x,y) ((x)<(y)?(x):(y))
  95539. #ifdef max
  95540. #undef max
  95541. #endif
  95542. #define max(x,y) ((x)>(y)?(x):(y))
  95543. /* Exact Rice codeword length calculation is off by default. The simple
  95544. * (and fast) estimation (of how many bits a residual value will be
  95545. * encoded with) in this encoder is very good, almost always yielding
  95546. * compression within 0.1% of exact calculation.
  95547. */
  95548. #undef EXACT_RICE_BITS_CALCULATION
  95549. /* Rice parameter searching is off by default. The simple (and fast)
  95550. * parameter estimation in this encoder is very good, almost always
  95551. * yielding compression within 0.1% of the optimal parameters.
  95552. */
  95553. #undef ENABLE_RICE_PARAMETER_SEARCH
  95554. typedef struct {
  95555. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  95556. unsigned size; /* of each data[] in samples */
  95557. unsigned tail;
  95558. } verify_input_fifo;
  95559. typedef struct {
  95560. const FLAC__byte *data;
  95561. unsigned capacity;
  95562. unsigned bytes;
  95563. } verify_output;
  95564. typedef enum {
  95565. ENCODER_IN_MAGIC = 0,
  95566. ENCODER_IN_METADATA = 1,
  95567. ENCODER_IN_AUDIO = 2
  95568. } EncoderStateHint;
  95569. static struct CompressionLevels {
  95570. FLAC__bool do_mid_side_stereo;
  95571. FLAC__bool loose_mid_side_stereo;
  95572. unsigned max_lpc_order;
  95573. unsigned qlp_coeff_precision;
  95574. FLAC__bool do_qlp_coeff_prec_search;
  95575. FLAC__bool do_escape_coding;
  95576. FLAC__bool do_exhaustive_model_search;
  95577. unsigned min_residual_partition_order;
  95578. unsigned max_residual_partition_order;
  95579. unsigned rice_parameter_search_dist;
  95580. } compression_levels_[] = {
  95581. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  95582. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  95583. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  95584. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  95585. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  95586. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  95587. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  95588. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  95589. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  95590. };
  95591. /***********************************************************************
  95592. *
  95593. * Private class method prototypes
  95594. *
  95595. ***********************************************************************/
  95596. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  95597. static void free_(FLAC__StreamEncoder *encoder);
  95598. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  95599. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  95600. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  95601. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  95602. #if FLAC__HAS_OGG
  95603. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  95604. #endif
  95605. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  95606. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  95607. static FLAC__bool process_subframe_(
  95608. FLAC__StreamEncoder *encoder,
  95609. unsigned min_partition_order,
  95610. unsigned max_partition_order,
  95611. const FLAC__FrameHeader *frame_header,
  95612. unsigned subframe_bps,
  95613. const FLAC__int32 integer_signal[],
  95614. FLAC__Subframe *subframe[2],
  95615. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  95616. FLAC__int32 *residual[2],
  95617. unsigned *best_subframe,
  95618. unsigned *best_bits
  95619. );
  95620. static FLAC__bool add_subframe_(
  95621. FLAC__StreamEncoder *encoder,
  95622. unsigned blocksize,
  95623. unsigned subframe_bps,
  95624. const FLAC__Subframe *subframe,
  95625. FLAC__BitWriter *frame
  95626. );
  95627. static unsigned evaluate_constant_subframe_(
  95628. FLAC__StreamEncoder *encoder,
  95629. const FLAC__int32 signal,
  95630. unsigned blocksize,
  95631. unsigned subframe_bps,
  95632. FLAC__Subframe *subframe
  95633. );
  95634. static unsigned evaluate_fixed_subframe_(
  95635. FLAC__StreamEncoder *encoder,
  95636. const FLAC__int32 signal[],
  95637. FLAC__int32 residual[],
  95638. FLAC__uint64 abs_residual_partition_sums[],
  95639. unsigned raw_bits_per_partition[],
  95640. unsigned blocksize,
  95641. unsigned subframe_bps,
  95642. unsigned order,
  95643. unsigned rice_parameter,
  95644. unsigned rice_parameter_limit,
  95645. unsigned min_partition_order,
  95646. unsigned max_partition_order,
  95647. FLAC__bool do_escape_coding,
  95648. unsigned rice_parameter_search_dist,
  95649. FLAC__Subframe *subframe,
  95650. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  95651. );
  95652. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95653. static unsigned evaluate_lpc_subframe_(
  95654. FLAC__StreamEncoder *encoder,
  95655. const FLAC__int32 signal[],
  95656. FLAC__int32 residual[],
  95657. FLAC__uint64 abs_residual_partition_sums[],
  95658. unsigned raw_bits_per_partition[],
  95659. const FLAC__real lp_coeff[],
  95660. unsigned blocksize,
  95661. unsigned subframe_bps,
  95662. unsigned order,
  95663. unsigned qlp_coeff_precision,
  95664. unsigned rice_parameter,
  95665. unsigned rice_parameter_limit,
  95666. unsigned min_partition_order,
  95667. unsigned max_partition_order,
  95668. FLAC__bool do_escape_coding,
  95669. unsigned rice_parameter_search_dist,
  95670. FLAC__Subframe *subframe,
  95671. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  95672. );
  95673. #endif
  95674. static unsigned evaluate_verbatim_subframe_(
  95675. FLAC__StreamEncoder *encoder,
  95676. const FLAC__int32 signal[],
  95677. unsigned blocksize,
  95678. unsigned subframe_bps,
  95679. FLAC__Subframe *subframe
  95680. );
  95681. static unsigned find_best_partition_order_(
  95682. struct FLAC__StreamEncoderPrivate *private_,
  95683. const FLAC__int32 residual[],
  95684. FLAC__uint64 abs_residual_partition_sums[],
  95685. unsigned raw_bits_per_partition[],
  95686. unsigned residual_samples,
  95687. unsigned predictor_order,
  95688. unsigned rice_parameter,
  95689. unsigned rice_parameter_limit,
  95690. unsigned min_partition_order,
  95691. unsigned max_partition_order,
  95692. unsigned bps,
  95693. FLAC__bool do_escape_coding,
  95694. unsigned rice_parameter_search_dist,
  95695. FLAC__EntropyCodingMethod *best_ecm
  95696. );
  95697. static void precompute_partition_info_sums_(
  95698. const FLAC__int32 residual[],
  95699. FLAC__uint64 abs_residual_partition_sums[],
  95700. unsigned residual_samples,
  95701. unsigned predictor_order,
  95702. unsigned min_partition_order,
  95703. unsigned max_partition_order,
  95704. unsigned bps
  95705. );
  95706. static void precompute_partition_info_escapes_(
  95707. const FLAC__int32 residual[],
  95708. unsigned raw_bits_per_partition[],
  95709. unsigned residual_samples,
  95710. unsigned predictor_order,
  95711. unsigned min_partition_order,
  95712. unsigned max_partition_order
  95713. );
  95714. static FLAC__bool set_partitioned_rice_(
  95715. #ifdef EXACT_RICE_BITS_CALCULATION
  95716. const FLAC__int32 residual[],
  95717. #endif
  95718. const FLAC__uint64 abs_residual_partition_sums[],
  95719. const unsigned raw_bits_per_partition[],
  95720. const unsigned residual_samples,
  95721. const unsigned predictor_order,
  95722. const unsigned suggested_rice_parameter,
  95723. const unsigned rice_parameter_limit,
  95724. const unsigned rice_parameter_search_dist,
  95725. const unsigned partition_order,
  95726. const FLAC__bool search_for_escapes,
  95727. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  95728. unsigned *bits
  95729. );
  95730. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  95731. /* verify-related routines: */
  95732. static void append_to_verify_fifo_(
  95733. verify_input_fifo *fifo,
  95734. const FLAC__int32 * const input[],
  95735. unsigned input_offset,
  95736. unsigned channels,
  95737. unsigned wide_samples
  95738. );
  95739. static void append_to_verify_fifo_interleaved_(
  95740. verify_input_fifo *fifo,
  95741. const FLAC__int32 input[],
  95742. unsigned input_offset,
  95743. unsigned channels,
  95744. unsigned wide_samples
  95745. );
  95746. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95747. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  95748. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  95749. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  95750. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95751. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  95752. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  95753. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  95754. static FILE *get_binary_stdout_(void);
  95755. /***********************************************************************
  95756. *
  95757. * Private class data
  95758. *
  95759. ***********************************************************************/
  95760. typedef struct FLAC__StreamEncoderPrivate {
  95761. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  95762. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  95763. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  95764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95765. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  95766. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  95767. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  95768. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  95769. #endif
  95770. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  95771. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  95772. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  95773. FLAC__int32 *residual_workspace_mid_side[2][2];
  95774. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  95775. FLAC__Subframe subframe_workspace_mid_side[2][2];
  95776. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  95777. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  95778. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  95779. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  95780. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  95781. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  95782. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  95783. unsigned best_subframe_mid_side[2];
  95784. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  95785. unsigned best_subframe_bits_mid_side[2];
  95786. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  95787. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  95788. FLAC__BitWriter *frame; /* the current frame being worked on */
  95789. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  95790. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  95791. FLAC__ChannelAssignment last_channel_assignment;
  95792. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  95793. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  95794. unsigned current_sample_number;
  95795. unsigned current_frame_number;
  95796. FLAC__MD5Context md5context;
  95797. FLAC__CPUInfo cpuinfo;
  95798. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95799. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95800. #else
  95801. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95802. #endif
  95803. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95804. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95805. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95806. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95807. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95808. #endif
  95809. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  95810. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  95811. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  95812. FLAC__bool disable_constant_subframes;
  95813. FLAC__bool disable_fixed_subframes;
  95814. FLAC__bool disable_verbatim_subframes;
  95815. #if FLAC__HAS_OGG
  95816. FLAC__bool is_ogg;
  95817. #endif
  95818. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  95819. FLAC__StreamEncoderSeekCallback seek_callback;
  95820. FLAC__StreamEncoderTellCallback tell_callback;
  95821. FLAC__StreamEncoderWriteCallback write_callback;
  95822. FLAC__StreamEncoderMetadataCallback metadata_callback;
  95823. FLAC__StreamEncoderProgressCallback progress_callback;
  95824. void *client_data;
  95825. unsigned first_seekpoint_to_check;
  95826. FILE *file; /* only used when encoding to a file */
  95827. FLAC__uint64 bytes_written;
  95828. FLAC__uint64 samples_written;
  95829. unsigned frames_written;
  95830. unsigned total_frames_estimate;
  95831. /* unaligned (original) pointers to allocated data */
  95832. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  95833. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  95834. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95835. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  95836. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  95837. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  95838. FLAC__real *windowed_signal_unaligned;
  95839. #endif
  95840. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  95841. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  95842. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  95843. unsigned *raw_bits_per_partition_unaligned;
  95844. /*
  95845. * These fields have been moved here from private function local
  95846. * declarations merely to save stack space during encoding.
  95847. */
  95848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95849. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  95850. #endif
  95851. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  95852. /*
  95853. * The data for the verify section
  95854. */
  95855. struct {
  95856. FLAC__StreamDecoder *decoder;
  95857. EncoderStateHint state_hint;
  95858. FLAC__bool needs_magic_hack;
  95859. verify_input_fifo input_fifo;
  95860. verify_output output;
  95861. struct {
  95862. FLAC__uint64 absolute_sample;
  95863. unsigned frame_number;
  95864. unsigned channel;
  95865. unsigned sample;
  95866. FLAC__int32 expected;
  95867. FLAC__int32 got;
  95868. } error_stats;
  95869. } verify;
  95870. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  95871. } FLAC__StreamEncoderPrivate;
  95872. /***********************************************************************
  95873. *
  95874. * Public static class data
  95875. *
  95876. ***********************************************************************/
  95877. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  95878. "FLAC__STREAM_ENCODER_OK",
  95879. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  95880. "FLAC__STREAM_ENCODER_OGG_ERROR",
  95881. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  95882. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  95883. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  95884. "FLAC__STREAM_ENCODER_IO_ERROR",
  95885. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  95886. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  95887. };
  95888. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  95889. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  95890. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  95891. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  95892. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  95893. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  95894. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  95895. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  95896. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  95897. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  95898. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  95899. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  95900. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  95901. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  95902. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  95903. };
  95904. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  95905. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  95906. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  95907. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  95908. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  95909. };
  95910. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  95911. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  95912. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  95913. };
  95914. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  95915. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  95916. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  95917. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  95918. };
  95919. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  95920. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  95921. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  95922. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  95923. };
  95924. /* Number of samples that will be overread to watch for end of stream. By
  95925. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  95926. * always try to read blocksize+1 samples before encoding a block, so that
  95927. * even if the stream has a total sample count that is an integral multiple
  95928. * of the blocksize, we will still notice when we are encoding the last
  95929. * block. This is needed, for example, to correctly set the end-of-stream
  95930. * marker in Ogg FLAC.
  95931. *
  95932. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  95933. * not really any reason to change it.
  95934. */
  95935. static const unsigned OVERREAD_ = 1;
  95936. /***********************************************************************
  95937. *
  95938. * Class constructor/destructor
  95939. *
  95940. */
  95941. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  95942. {
  95943. FLAC__StreamEncoder *encoder;
  95944. unsigned i;
  95945. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95946. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  95947. if(encoder == 0) {
  95948. return 0;
  95949. }
  95950. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  95951. if(encoder->protected_ == 0) {
  95952. free(encoder);
  95953. return 0;
  95954. }
  95955. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  95956. if(encoder->private_ == 0) {
  95957. free(encoder->protected_);
  95958. free(encoder);
  95959. return 0;
  95960. }
  95961. encoder->private_->frame = FLAC__bitwriter_new();
  95962. if(encoder->private_->frame == 0) {
  95963. free(encoder->private_);
  95964. free(encoder->protected_);
  95965. free(encoder);
  95966. return 0;
  95967. }
  95968. encoder->private_->file = 0;
  95969. set_defaults_enc(encoder);
  95970. encoder->private_->is_being_deleted = false;
  95971. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95972. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  95973. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  95974. }
  95975. for(i = 0; i < 2; i++) {
  95976. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  95977. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  95978. }
  95979. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95980. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  95981. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  95982. }
  95983. for(i = 0; i < 2; i++) {
  95984. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  95985. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  95986. }
  95987. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95988. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  95989. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  95990. }
  95991. for(i = 0; i < 2; i++) {
  95992. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  95993. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  95994. }
  95995. for(i = 0; i < 2; i++)
  95996. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  95997. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  95998. return encoder;
  95999. }
  96000. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  96001. {
  96002. unsigned i;
  96003. FLAC__ASSERT(0 != encoder);
  96004. FLAC__ASSERT(0 != encoder->protected_);
  96005. FLAC__ASSERT(0 != encoder->private_);
  96006. FLAC__ASSERT(0 != encoder->private_->frame);
  96007. encoder->private_->is_being_deleted = true;
  96008. (void)FLAC__stream_encoder_finish(encoder);
  96009. if(0 != encoder->private_->verify.decoder)
  96010. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  96011. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96012. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96013. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96014. }
  96015. for(i = 0; i < 2; i++) {
  96016. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96017. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96018. }
  96019. for(i = 0; i < 2; i++)
  96020. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  96021. FLAC__bitwriter_delete(encoder->private_->frame);
  96022. free(encoder->private_);
  96023. free(encoder->protected_);
  96024. free(encoder);
  96025. }
  96026. /***********************************************************************
  96027. *
  96028. * Public class methods
  96029. *
  96030. ***********************************************************************/
  96031. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  96032. FLAC__StreamEncoder *encoder,
  96033. FLAC__StreamEncoderReadCallback read_callback,
  96034. FLAC__StreamEncoderWriteCallback write_callback,
  96035. FLAC__StreamEncoderSeekCallback seek_callback,
  96036. FLAC__StreamEncoderTellCallback tell_callback,
  96037. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96038. void *client_data,
  96039. FLAC__bool is_ogg
  96040. )
  96041. {
  96042. unsigned i;
  96043. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  96044. FLAC__ASSERT(0 != encoder);
  96045. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96046. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96047. #if !FLAC__HAS_OGG
  96048. if(is_ogg)
  96049. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96050. #endif
  96051. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  96052. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  96053. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  96054. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  96055. if(encoder->protected_->channels != 2) {
  96056. encoder->protected_->do_mid_side_stereo = false;
  96057. encoder->protected_->loose_mid_side_stereo = false;
  96058. }
  96059. else if(!encoder->protected_->do_mid_side_stereo)
  96060. encoder->protected_->loose_mid_side_stereo = false;
  96061. if(encoder->protected_->bits_per_sample >= 32)
  96062. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  96063. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  96064. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  96065. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  96066. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  96067. if(encoder->protected_->blocksize == 0) {
  96068. if(encoder->protected_->max_lpc_order == 0)
  96069. encoder->protected_->blocksize = 1152;
  96070. else
  96071. encoder->protected_->blocksize = 4096;
  96072. }
  96073. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  96074. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  96075. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  96076. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  96077. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  96078. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  96079. if(encoder->protected_->qlp_coeff_precision == 0) {
  96080. if(encoder->protected_->bits_per_sample < 16) {
  96081. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  96082. /* @@@ until then we'll make a guess */
  96083. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  96084. }
  96085. else if(encoder->protected_->bits_per_sample == 16) {
  96086. if(encoder->protected_->blocksize <= 192)
  96087. encoder->protected_->qlp_coeff_precision = 7;
  96088. else if(encoder->protected_->blocksize <= 384)
  96089. encoder->protected_->qlp_coeff_precision = 8;
  96090. else if(encoder->protected_->blocksize <= 576)
  96091. encoder->protected_->qlp_coeff_precision = 9;
  96092. else if(encoder->protected_->blocksize <= 1152)
  96093. encoder->protected_->qlp_coeff_precision = 10;
  96094. else if(encoder->protected_->blocksize <= 2304)
  96095. encoder->protected_->qlp_coeff_precision = 11;
  96096. else if(encoder->protected_->blocksize <= 4608)
  96097. encoder->protected_->qlp_coeff_precision = 12;
  96098. else
  96099. encoder->protected_->qlp_coeff_precision = 13;
  96100. }
  96101. else {
  96102. if(encoder->protected_->blocksize <= 384)
  96103. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  96104. else if(encoder->protected_->blocksize <= 1152)
  96105. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  96106. else
  96107. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  96108. }
  96109. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  96110. }
  96111. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  96112. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  96113. if(encoder->protected_->streamable_subset) {
  96114. if(
  96115. encoder->protected_->blocksize != 192 &&
  96116. encoder->protected_->blocksize != 576 &&
  96117. encoder->protected_->blocksize != 1152 &&
  96118. encoder->protected_->blocksize != 2304 &&
  96119. encoder->protected_->blocksize != 4608 &&
  96120. encoder->protected_->blocksize != 256 &&
  96121. encoder->protected_->blocksize != 512 &&
  96122. encoder->protected_->blocksize != 1024 &&
  96123. encoder->protected_->blocksize != 2048 &&
  96124. encoder->protected_->blocksize != 4096 &&
  96125. encoder->protected_->blocksize != 8192 &&
  96126. encoder->protected_->blocksize != 16384
  96127. )
  96128. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96129. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  96130. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96131. if(
  96132. encoder->protected_->bits_per_sample != 8 &&
  96133. encoder->protected_->bits_per_sample != 12 &&
  96134. encoder->protected_->bits_per_sample != 16 &&
  96135. encoder->protected_->bits_per_sample != 20 &&
  96136. encoder->protected_->bits_per_sample != 24
  96137. )
  96138. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96139. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  96140. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96141. if(
  96142. encoder->protected_->sample_rate <= 48000 &&
  96143. (
  96144. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  96145. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  96146. )
  96147. ) {
  96148. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96149. }
  96150. }
  96151. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96152. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  96153. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  96154. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  96155. #if FLAC__HAS_OGG
  96156. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  96157. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  96158. unsigned i;
  96159. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  96160. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96161. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  96162. for( ; i > 0; i--)
  96163. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  96164. encoder->protected_->metadata[0] = vc;
  96165. break;
  96166. }
  96167. }
  96168. }
  96169. #endif
  96170. /* keep track of any SEEKTABLE block */
  96171. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  96172. unsigned i;
  96173. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96174. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96175. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  96176. break; /* take only the first one */
  96177. }
  96178. }
  96179. }
  96180. /* validate metadata */
  96181. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  96182. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96183. metadata_has_seektable = false;
  96184. metadata_has_vorbis_comment = false;
  96185. metadata_picture_has_type1 = false;
  96186. metadata_picture_has_type2 = false;
  96187. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96188. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  96189. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  96190. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96191. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96192. if(metadata_has_seektable) /* only one is allowed */
  96193. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96194. metadata_has_seektable = true;
  96195. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  96196. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96197. }
  96198. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96199. if(metadata_has_vorbis_comment) /* only one is allowed */
  96200. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96201. metadata_has_vorbis_comment = true;
  96202. }
  96203. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  96204. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  96205. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96206. }
  96207. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  96208. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  96209. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96210. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  96211. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  96212. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96213. metadata_picture_has_type1 = true;
  96214. /* standard icon must be 32x32 pixel PNG */
  96215. if(
  96216. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  96217. (
  96218. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  96219. m->data.picture.width != 32 ||
  96220. m->data.picture.height != 32
  96221. )
  96222. )
  96223. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96224. }
  96225. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  96226. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  96227. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96228. metadata_picture_has_type2 = true;
  96229. }
  96230. }
  96231. }
  96232. encoder->private_->input_capacity = 0;
  96233. for(i = 0; i < encoder->protected_->channels; i++) {
  96234. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  96235. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96236. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  96237. #endif
  96238. }
  96239. for(i = 0; i < 2; i++) {
  96240. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  96241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96242. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  96243. #endif
  96244. }
  96245. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96246. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  96247. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  96248. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  96249. #endif
  96250. for(i = 0; i < encoder->protected_->channels; i++) {
  96251. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  96252. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  96253. encoder->private_->best_subframe[i] = 0;
  96254. }
  96255. for(i = 0; i < 2; i++) {
  96256. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  96257. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  96258. encoder->private_->best_subframe_mid_side[i] = 0;
  96259. }
  96260. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  96261. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  96262. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96263. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  96264. #else
  96265. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  96266. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  96267. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  96268. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  96269. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  96270. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  96271. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  96272. #endif
  96273. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  96274. encoder->private_->loose_mid_side_stereo_frames = 1;
  96275. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  96276. encoder->private_->current_sample_number = 0;
  96277. encoder->private_->current_frame_number = 0;
  96278. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  96279. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  96280. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  96281. /*
  96282. * get the CPU info and set the function pointers
  96283. */
  96284. FLAC__cpu_info(&encoder->private_->cpuinfo);
  96285. /* first default to the non-asm routines */
  96286. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96287. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  96288. #endif
  96289. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  96290. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96291. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96292. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  96293. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96294. #endif
  96295. /* now override with asm where appropriate */
  96296. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96297. # ifndef FLAC__NO_ASM
  96298. if(encoder->private_->cpuinfo.use_asm) {
  96299. # ifdef FLAC__CPU_IA32
  96300. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  96301. # ifdef FLAC__HAS_NASM
  96302. if(encoder->private_->cpuinfo.data.ia32.sse) {
  96303. if(encoder->protected_->max_lpc_order < 4)
  96304. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  96305. else if(encoder->protected_->max_lpc_order < 8)
  96306. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  96307. else if(encoder->protected_->max_lpc_order < 12)
  96308. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  96309. else
  96310. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  96311. }
  96312. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  96313. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  96314. else
  96315. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  96316. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  96317. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96318. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  96319. }
  96320. else {
  96321. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96322. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96323. }
  96324. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  96325. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  96326. # endif /* FLAC__HAS_NASM */
  96327. # endif /* FLAC__CPU_IA32 */
  96328. }
  96329. # endif /* !FLAC__NO_ASM */
  96330. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  96331. /* finally override based on wide-ness if necessary */
  96332. if(encoder->private_->use_wide_by_block) {
  96333. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  96334. }
  96335. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  96336. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  96337. #if FLAC__HAS_OGG
  96338. encoder->private_->is_ogg = is_ogg;
  96339. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  96340. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  96341. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96342. }
  96343. #endif
  96344. encoder->private_->read_callback = read_callback;
  96345. encoder->private_->write_callback = write_callback;
  96346. encoder->private_->seek_callback = seek_callback;
  96347. encoder->private_->tell_callback = tell_callback;
  96348. encoder->private_->metadata_callback = metadata_callback;
  96349. encoder->private_->client_data = client_data;
  96350. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  96351. /* the above function sets the state for us in case of an error */
  96352. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96353. }
  96354. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  96355. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  96356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96357. }
  96358. /*
  96359. * Set up the verify stuff if necessary
  96360. */
  96361. if(encoder->protected_->verify) {
  96362. /*
  96363. * First, set up the fifo which will hold the
  96364. * original signal to compare against
  96365. */
  96366. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  96367. for(i = 0; i < encoder->protected_->channels; i++) {
  96368. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  96369. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  96370. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96371. }
  96372. }
  96373. encoder->private_->verify.input_fifo.tail = 0;
  96374. /*
  96375. * Now set up a stream decoder for verification
  96376. */
  96377. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  96378. if(0 == encoder->private_->verify.decoder) {
  96379. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  96380. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96381. }
  96382. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  96383. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  96384. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96385. }
  96386. }
  96387. encoder->private_->verify.error_stats.absolute_sample = 0;
  96388. encoder->private_->verify.error_stats.frame_number = 0;
  96389. encoder->private_->verify.error_stats.channel = 0;
  96390. encoder->private_->verify.error_stats.sample = 0;
  96391. encoder->private_->verify.error_stats.expected = 0;
  96392. encoder->private_->verify.error_stats.got = 0;
  96393. /*
  96394. * These must be done before we write any metadata, because that
  96395. * calls the write_callback, which uses these values.
  96396. */
  96397. encoder->private_->first_seekpoint_to_check = 0;
  96398. encoder->private_->samples_written = 0;
  96399. encoder->protected_->streaminfo_offset = 0;
  96400. encoder->protected_->seektable_offset = 0;
  96401. encoder->protected_->audio_offset = 0;
  96402. /*
  96403. * write the stream header
  96404. */
  96405. if(encoder->protected_->verify)
  96406. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  96407. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  96408. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96409. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96410. }
  96411. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96412. /* the above function sets the state for us in case of an error */
  96413. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96414. }
  96415. /*
  96416. * write the STREAMINFO metadata block
  96417. */
  96418. if(encoder->protected_->verify)
  96419. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  96420. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  96421. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  96422. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  96423. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  96424. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  96425. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  96426. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  96427. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  96428. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  96429. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  96430. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  96431. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  96432. if(encoder->protected_->do_md5)
  96433. FLAC__MD5Init(&encoder->private_->md5context);
  96434. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  96435. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96436. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96437. }
  96438. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96439. /* the above function sets the state for us in case of an error */
  96440. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96441. }
  96442. /*
  96443. * Now that the STREAMINFO block is written, we can init this to an
  96444. * absurdly-high value...
  96445. */
  96446. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  96447. /* ... and clear this to 0 */
  96448. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  96449. /*
  96450. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  96451. * if not, we will write an empty one (FLAC__add_metadata_block()
  96452. * automatically supplies the vendor string).
  96453. *
  96454. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  96455. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  96456. * true it will have already insured that the metadata list is properly
  96457. * ordered.)
  96458. */
  96459. if(!metadata_has_vorbis_comment) {
  96460. FLAC__StreamMetadata vorbis_comment;
  96461. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  96462. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  96463. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  96464. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  96465. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  96466. vorbis_comment.data.vorbis_comment.num_comments = 0;
  96467. vorbis_comment.data.vorbis_comment.comments = 0;
  96468. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  96469. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96470. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96471. }
  96472. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96473. /* the above function sets the state for us in case of an error */
  96474. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96475. }
  96476. }
  96477. /*
  96478. * write the user's metadata blocks
  96479. */
  96480. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96481. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  96482. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  96483. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96484. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96485. }
  96486. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96487. /* the above function sets the state for us in case of an error */
  96488. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96489. }
  96490. }
  96491. /* now that all the metadata is written, we save the stream offset */
  96492. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  96493. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  96494. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96495. }
  96496. if(encoder->protected_->verify)
  96497. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  96498. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  96499. }
  96500. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  96501. FLAC__StreamEncoder *encoder,
  96502. FLAC__StreamEncoderWriteCallback write_callback,
  96503. FLAC__StreamEncoderSeekCallback seek_callback,
  96504. FLAC__StreamEncoderTellCallback tell_callback,
  96505. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96506. void *client_data
  96507. )
  96508. {
  96509. return init_stream_internal_enc(
  96510. encoder,
  96511. /*read_callback=*/0,
  96512. write_callback,
  96513. seek_callback,
  96514. tell_callback,
  96515. metadata_callback,
  96516. client_data,
  96517. /*is_ogg=*/false
  96518. );
  96519. }
  96520. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  96521. FLAC__StreamEncoder *encoder,
  96522. FLAC__StreamEncoderReadCallback read_callback,
  96523. FLAC__StreamEncoderWriteCallback write_callback,
  96524. FLAC__StreamEncoderSeekCallback seek_callback,
  96525. FLAC__StreamEncoderTellCallback tell_callback,
  96526. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96527. void *client_data
  96528. )
  96529. {
  96530. return init_stream_internal_enc(
  96531. encoder,
  96532. read_callback,
  96533. write_callback,
  96534. seek_callback,
  96535. tell_callback,
  96536. metadata_callback,
  96537. client_data,
  96538. /*is_ogg=*/true
  96539. );
  96540. }
  96541. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  96542. FLAC__StreamEncoder *encoder,
  96543. FILE *file,
  96544. FLAC__StreamEncoderProgressCallback progress_callback,
  96545. void *client_data,
  96546. FLAC__bool is_ogg
  96547. )
  96548. {
  96549. FLAC__StreamEncoderInitStatus init_status;
  96550. FLAC__ASSERT(0 != encoder);
  96551. FLAC__ASSERT(0 != file);
  96552. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96553. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96554. /* double protection */
  96555. if(file == 0) {
  96556. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  96557. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96558. }
  96559. /*
  96560. * To make sure that our file does not go unclosed after an error, we
  96561. * must assign the FILE pointer before any further error can occur in
  96562. * this routine.
  96563. */
  96564. if(file == stdout)
  96565. file = get_binary_stdout_(); /* just to be safe */
  96566. encoder->private_->file = file;
  96567. encoder->private_->progress_callback = progress_callback;
  96568. encoder->private_->bytes_written = 0;
  96569. encoder->private_->samples_written = 0;
  96570. encoder->private_->frames_written = 0;
  96571. init_status = init_stream_internal_enc(
  96572. encoder,
  96573. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  96574. file_write_callback_,
  96575. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  96576. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  96577. /*metadata_callback=*/0,
  96578. client_data,
  96579. is_ogg
  96580. );
  96581. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  96582. /* the above function sets the state for us in case of an error */
  96583. return init_status;
  96584. }
  96585. {
  96586. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  96587. FLAC__ASSERT(blocksize != 0);
  96588. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  96589. }
  96590. return init_status;
  96591. }
  96592. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  96593. FLAC__StreamEncoder *encoder,
  96594. FILE *file,
  96595. FLAC__StreamEncoderProgressCallback progress_callback,
  96596. void *client_data
  96597. )
  96598. {
  96599. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  96600. }
  96601. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  96602. FLAC__StreamEncoder *encoder,
  96603. FILE *file,
  96604. FLAC__StreamEncoderProgressCallback progress_callback,
  96605. void *client_data
  96606. )
  96607. {
  96608. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  96609. }
  96610. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  96611. FLAC__StreamEncoder *encoder,
  96612. const char *filename,
  96613. FLAC__StreamEncoderProgressCallback progress_callback,
  96614. void *client_data,
  96615. FLAC__bool is_ogg
  96616. )
  96617. {
  96618. FILE *file;
  96619. FLAC__ASSERT(0 != encoder);
  96620. /*
  96621. * To make sure that our file does not go unclosed after an error, we
  96622. * have to do the same entrance checks here that are later performed
  96623. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  96624. */
  96625. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96626. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96627. file = filename? fopen(filename, "w+b") : stdout;
  96628. if(file == 0) {
  96629. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  96630. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96631. }
  96632. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  96633. }
  96634. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  96635. FLAC__StreamEncoder *encoder,
  96636. const char *filename,
  96637. FLAC__StreamEncoderProgressCallback progress_callback,
  96638. void *client_data
  96639. )
  96640. {
  96641. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  96642. }
  96643. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  96644. FLAC__StreamEncoder *encoder,
  96645. const char *filename,
  96646. FLAC__StreamEncoderProgressCallback progress_callback,
  96647. void *client_data
  96648. )
  96649. {
  96650. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  96651. }
  96652. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  96653. {
  96654. FLAC__bool error = false;
  96655. FLAC__ASSERT(0 != encoder);
  96656. FLAC__ASSERT(0 != encoder->private_);
  96657. FLAC__ASSERT(0 != encoder->protected_);
  96658. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  96659. return true;
  96660. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  96661. if(encoder->private_->current_sample_number != 0) {
  96662. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  96663. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  96664. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  96665. error = true;
  96666. }
  96667. }
  96668. if(encoder->protected_->do_md5)
  96669. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  96670. if(!encoder->private_->is_being_deleted) {
  96671. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  96672. if(encoder->private_->seek_callback) {
  96673. #if FLAC__HAS_OGG
  96674. if(encoder->private_->is_ogg)
  96675. update_ogg_metadata_(encoder);
  96676. else
  96677. #endif
  96678. update_metadata_(encoder);
  96679. /* check if an error occurred while updating metadata */
  96680. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  96681. error = true;
  96682. }
  96683. if(encoder->private_->metadata_callback)
  96684. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  96685. }
  96686. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  96687. if(!error)
  96688. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  96689. error = true;
  96690. }
  96691. }
  96692. if(0 != encoder->private_->file) {
  96693. if(encoder->private_->file != stdout)
  96694. fclose(encoder->private_->file);
  96695. encoder->private_->file = 0;
  96696. }
  96697. #if FLAC__HAS_OGG
  96698. if(encoder->private_->is_ogg)
  96699. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  96700. #endif
  96701. free_(encoder);
  96702. set_defaults_enc(encoder);
  96703. if(!error)
  96704. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96705. return !error;
  96706. }
  96707. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  96708. {
  96709. FLAC__ASSERT(0 != encoder);
  96710. FLAC__ASSERT(0 != encoder->private_);
  96711. FLAC__ASSERT(0 != encoder->protected_);
  96712. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96713. return false;
  96714. #if FLAC__HAS_OGG
  96715. /* can't check encoder->private_->is_ogg since that's not set until init time */
  96716. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  96717. return true;
  96718. #else
  96719. (void)value;
  96720. return false;
  96721. #endif
  96722. }
  96723. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96724. {
  96725. FLAC__ASSERT(0 != encoder);
  96726. FLAC__ASSERT(0 != encoder->private_);
  96727. FLAC__ASSERT(0 != encoder->protected_);
  96728. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96729. return false;
  96730. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  96731. encoder->protected_->verify = value;
  96732. #endif
  96733. return true;
  96734. }
  96735. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96736. {
  96737. FLAC__ASSERT(0 != encoder);
  96738. FLAC__ASSERT(0 != encoder->private_);
  96739. FLAC__ASSERT(0 != encoder->protected_);
  96740. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96741. return false;
  96742. encoder->protected_->streamable_subset = value;
  96743. return true;
  96744. }
  96745. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96746. {
  96747. FLAC__ASSERT(0 != encoder);
  96748. FLAC__ASSERT(0 != encoder->private_);
  96749. FLAC__ASSERT(0 != encoder->protected_);
  96750. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96751. return false;
  96752. encoder->protected_->do_md5 = value;
  96753. return true;
  96754. }
  96755. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  96756. {
  96757. FLAC__ASSERT(0 != encoder);
  96758. FLAC__ASSERT(0 != encoder->private_);
  96759. FLAC__ASSERT(0 != encoder->protected_);
  96760. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96761. return false;
  96762. encoder->protected_->channels = value;
  96763. return true;
  96764. }
  96765. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  96766. {
  96767. FLAC__ASSERT(0 != encoder);
  96768. FLAC__ASSERT(0 != encoder->private_);
  96769. FLAC__ASSERT(0 != encoder->protected_);
  96770. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96771. return false;
  96772. encoder->protected_->bits_per_sample = value;
  96773. return true;
  96774. }
  96775. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  96776. {
  96777. FLAC__ASSERT(0 != encoder);
  96778. FLAC__ASSERT(0 != encoder->private_);
  96779. FLAC__ASSERT(0 != encoder->protected_);
  96780. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96781. return false;
  96782. encoder->protected_->sample_rate = value;
  96783. return true;
  96784. }
  96785. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  96786. {
  96787. FLAC__bool ok = true;
  96788. FLAC__ASSERT(0 != encoder);
  96789. FLAC__ASSERT(0 != encoder->private_);
  96790. FLAC__ASSERT(0 != encoder->protected_);
  96791. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96792. return false;
  96793. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  96794. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  96795. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  96796. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  96797. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96798. #if 0
  96799. /* was: */
  96800. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  96801. /* but it's too hard to specify the string in a locale-specific way */
  96802. #else
  96803. encoder->protected_->num_apodizations = 1;
  96804. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  96805. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  96806. #endif
  96807. #endif
  96808. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  96809. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  96810. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  96811. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  96812. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  96813. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  96814. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  96815. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  96816. return ok;
  96817. }
  96818. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  96819. {
  96820. FLAC__ASSERT(0 != encoder);
  96821. FLAC__ASSERT(0 != encoder->private_);
  96822. FLAC__ASSERT(0 != encoder->protected_);
  96823. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96824. return false;
  96825. encoder->protected_->blocksize = value;
  96826. return true;
  96827. }
  96828. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96829. {
  96830. FLAC__ASSERT(0 != encoder);
  96831. FLAC__ASSERT(0 != encoder->private_);
  96832. FLAC__ASSERT(0 != encoder->protected_);
  96833. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96834. return false;
  96835. encoder->protected_->do_mid_side_stereo = value;
  96836. return true;
  96837. }
  96838. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96839. {
  96840. FLAC__ASSERT(0 != encoder);
  96841. FLAC__ASSERT(0 != encoder->private_);
  96842. FLAC__ASSERT(0 != encoder->protected_);
  96843. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96844. return false;
  96845. encoder->protected_->loose_mid_side_stereo = value;
  96846. return true;
  96847. }
  96848. /*@@@@add to tests*/
  96849. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  96850. {
  96851. FLAC__ASSERT(0 != encoder);
  96852. FLAC__ASSERT(0 != encoder->private_);
  96853. FLAC__ASSERT(0 != encoder->protected_);
  96854. FLAC__ASSERT(0 != specification);
  96855. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96856. return false;
  96857. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96858. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  96859. #else
  96860. encoder->protected_->num_apodizations = 0;
  96861. while(1) {
  96862. const char *s = strchr(specification, ';');
  96863. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  96864. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  96865. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  96866. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  96867. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  96868. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  96869. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  96870. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  96871. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  96872. else if(n==6 && 0 == strncmp("connes" , specification, n))
  96873. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  96874. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  96875. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  96876. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  96877. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  96878. if (stddev > 0.0 && stddev <= 0.5) {
  96879. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  96880. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  96881. }
  96882. }
  96883. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  96884. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  96885. else if(n==4 && 0 == strncmp("hann" , specification, n))
  96886. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  96887. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  96888. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  96889. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  96890. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  96891. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  96892. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  96893. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  96894. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  96895. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  96896. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  96897. if (p >= 0.0 && p <= 1.0) {
  96898. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  96899. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  96900. }
  96901. }
  96902. else if(n==5 && 0 == strncmp("welch" , specification, n))
  96903. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  96904. if (encoder->protected_->num_apodizations == 32)
  96905. break;
  96906. if (s)
  96907. specification = s+1;
  96908. else
  96909. break;
  96910. }
  96911. if(encoder->protected_->num_apodizations == 0) {
  96912. encoder->protected_->num_apodizations = 1;
  96913. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  96914. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  96915. }
  96916. #endif
  96917. return true;
  96918. }
  96919. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  96920. {
  96921. FLAC__ASSERT(0 != encoder);
  96922. FLAC__ASSERT(0 != encoder->private_);
  96923. FLAC__ASSERT(0 != encoder->protected_);
  96924. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96925. return false;
  96926. encoder->protected_->max_lpc_order = value;
  96927. return true;
  96928. }
  96929. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  96930. {
  96931. FLAC__ASSERT(0 != encoder);
  96932. FLAC__ASSERT(0 != encoder->private_);
  96933. FLAC__ASSERT(0 != encoder->protected_);
  96934. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96935. return false;
  96936. encoder->protected_->qlp_coeff_precision = value;
  96937. return true;
  96938. }
  96939. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96940. {
  96941. FLAC__ASSERT(0 != encoder);
  96942. FLAC__ASSERT(0 != encoder->private_);
  96943. FLAC__ASSERT(0 != encoder->protected_);
  96944. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96945. return false;
  96946. encoder->protected_->do_qlp_coeff_prec_search = value;
  96947. return true;
  96948. }
  96949. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96950. {
  96951. FLAC__ASSERT(0 != encoder);
  96952. FLAC__ASSERT(0 != encoder->private_);
  96953. FLAC__ASSERT(0 != encoder->protected_);
  96954. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96955. return false;
  96956. #if 0
  96957. /*@@@ deprecated: */
  96958. encoder->protected_->do_escape_coding = value;
  96959. #else
  96960. (void)value;
  96961. #endif
  96962. return true;
  96963. }
  96964. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96965. {
  96966. FLAC__ASSERT(0 != encoder);
  96967. FLAC__ASSERT(0 != encoder->private_);
  96968. FLAC__ASSERT(0 != encoder->protected_);
  96969. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96970. return false;
  96971. encoder->protected_->do_exhaustive_model_search = value;
  96972. return true;
  96973. }
  96974. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  96975. {
  96976. FLAC__ASSERT(0 != encoder);
  96977. FLAC__ASSERT(0 != encoder->private_);
  96978. FLAC__ASSERT(0 != encoder->protected_);
  96979. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96980. return false;
  96981. encoder->protected_->min_residual_partition_order = value;
  96982. return true;
  96983. }
  96984. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  96985. {
  96986. FLAC__ASSERT(0 != encoder);
  96987. FLAC__ASSERT(0 != encoder->private_);
  96988. FLAC__ASSERT(0 != encoder->protected_);
  96989. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96990. return false;
  96991. encoder->protected_->max_residual_partition_order = value;
  96992. return true;
  96993. }
  96994. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  96995. {
  96996. FLAC__ASSERT(0 != encoder);
  96997. FLAC__ASSERT(0 != encoder->private_);
  96998. FLAC__ASSERT(0 != encoder->protected_);
  96999. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97000. return false;
  97001. #if 0
  97002. /*@@@ deprecated: */
  97003. encoder->protected_->rice_parameter_search_dist = value;
  97004. #else
  97005. (void)value;
  97006. #endif
  97007. return true;
  97008. }
  97009. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  97010. {
  97011. FLAC__ASSERT(0 != encoder);
  97012. FLAC__ASSERT(0 != encoder->private_);
  97013. FLAC__ASSERT(0 != encoder->protected_);
  97014. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97015. return false;
  97016. encoder->protected_->total_samples_estimate = value;
  97017. return true;
  97018. }
  97019. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  97020. {
  97021. FLAC__ASSERT(0 != encoder);
  97022. FLAC__ASSERT(0 != encoder->private_);
  97023. FLAC__ASSERT(0 != encoder->protected_);
  97024. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97025. return false;
  97026. if(0 == metadata)
  97027. num_blocks = 0;
  97028. if(0 == num_blocks)
  97029. metadata = 0;
  97030. /* realloc() does not do exactly what we want so... */
  97031. if(encoder->protected_->metadata) {
  97032. free(encoder->protected_->metadata);
  97033. encoder->protected_->metadata = 0;
  97034. encoder->protected_->num_metadata_blocks = 0;
  97035. }
  97036. if(num_blocks) {
  97037. FLAC__StreamMetadata **m;
  97038. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  97039. return false;
  97040. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  97041. encoder->protected_->metadata = m;
  97042. encoder->protected_->num_metadata_blocks = num_blocks;
  97043. }
  97044. #if FLAC__HAS_OGG
  97045. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  97046. return false;
  97047. #endif
  97048. return true;
  97049. }
  97050. /*
  97051. * These three functions are not static, but not publically exposed in
  97052. * include/FLAC/ either. They are used by the test suite.
  97053. */
  97054. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97055. {
  97056. FLAC__ASSERT(0 != encoder);
  97057. FLAC__ASSERT(0 != encoder->private_);
  97058. FLAC__ASSERT(0 != encoder->protected_);
  97059. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97060. return false;
  97061. encoder->private_->disable_constant_subframes = value;
  97062. return true;
  97063. }
  97064. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97065. {
  97066. FLAC__ASSERT(0 != encoder);
  97067. FLAC__ASSERT(0 != encoder->private_);
  97068. FLAC__ASSERT(0 != encoder->protected_);
  97069. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97070. return false;
  97071. encoder->private_->disable_fixed_subframes = value;
  97072. return true;
  97073. }
  97074. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97075. {
  97076. FLAC__ASSERT(0 != encoder);
  97077. FLAC__ASSERT(0 != encoder->private_);
  97078. FLAC__ASSERT(0 != encoder->protected_);
  97079. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97080. return false;
  97081. encoder->private_->disable_verbatim_subframes = value;
  97082. return true;
  97083. }
  97084. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  97085. {
  97086. FLAC__ASSERT(0 != encoder);
  97087. FLAC__ASSERT(0 != encoder->private_);
  97088. FLAC__ASSERT(0 != encoder->protected_);
  97089. return encoder->protected_->state;
  97090. }
  97091. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  97092. {
  97093. FLAC__ASSERT(0 != encoder);
  97094. FLAC__ASSERT(0 != encoder->private_);
  97095. FLAC__ASSERT(0 != encoder->protected_);
  97096. if(encoder->protected_->verify)
  97097. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  97098. else
  97099. return FLAC__STREAM_DECODER_UNINITIALIZED;
  97100. }
  97101. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  97102. {
  97103. FLAC__ASSERT(0 != encoder);
  97104. FLAC__ASSERT(0 != encoder->private_);
  97105. FLAC__ASSERT(0 != encoder->protected_);
  97106. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  97107. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  97108. else
  97109. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  97110. }
  97111. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  97112. {
  97113. FLAC__ASSERT(0 != encoder);
  97114. FLAC__ASSERT(0 != encoder->private_);
  97115. FLAC__ASSERT(0 != encoder->protected_);
  97116. if(0 != absolute_sample)
  97117. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  97118. if(0 != frame_number)
  97119. *frame_number = encoder->private_->verify.error_stats.frame_number;
  97120. if(0 != channel)
  97121. *channel = encoder->private_->verify.error_stats.channel;
  97122. if(0 != sample)
  97123. *sample = encoder->private_->verify.error_stats.sample;
  97124. if(0 != expected)
  97125. *expected = encoder->private_->verify.error_stats.expected;
  97126. if(0 != got)
  97127. *got = encoder->private_->verify.error_stats.got;
  97128. }
  97129. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  97130. {
  97131. FLAC__ASSERT(0 != encoder);
  97132. FLAC__ASSERT(0 != encoder->private_);
  97133. FLAC__ASSERT(0 != encoder->protected_);
  97134. return encoder->protected_->verify;
  97135. }
  97136. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  97137. {
  97138. FLAC__ASSERT(0 != encoder);
  97139. FLAC__ASSERT(0 != encoder->private_);
  97140. FLAC__ASSERT(0 != encoder->protected_);
  97141. return encoder->protected_->streamable_subset;
  97142. }
  97143. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  97144. {
  97145. FLAC__ASSERT(0 != encoder);
  97146. FLAC__ASSERT(0 != encoder->private_);
  97147. FLAC__ASSERT(0 != encoder->protected_);
  97148. return encoder->protected_->do_md5;
  97149. }
  97150. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  97151. {
  97152. FLAC__ASSERT(0 != encoder);
  97153. FLAC__ASSERT(0 != encoder->private_);
  97154. FLAC__ASSERT(0 != encoder->protected_);
  97155. return encoder->protected_->channels;
  97156. }
  97157. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  97158. {
  97159. FLAC__ASSERT(0 != encoder);
  97160. FLAC__ASSERT(0 != encoder->private_);
  97161. FLAC__ASSERT(0 != encoder->protected_);
  97162. return encoder->protected_->bits_per_sample;
  97163. }
  97164. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  97165. {
  97166. FLAC__ASSERT(0 != encoder);
  97167. FLAC__ASSERT(0 != encoder->private_);
  97168. FLAC__ASSERT(0 != encoder->protected_);
  97169. return encoder->protected_->sample_rate;
  97170. }
  97171. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  97172. {
  97173. FLAC__ASSERT(0 != encoder);
  97174. FLAC__ASSERT(0 != encoder->private_);
  97175. FLAC__ASSERT(0 != encoder->protected_);
  97176. return encoder->protected_->blocksize;
  97177. }
  97178. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97179. {
  97180. FLAC__ASSERT(0 != encoder);
  97181. FLAC__ASSERT(0 != encoder->private_);
  97182. FLAC__ASSERT(0 != encoder->protected_);
  97183. return encoder->protected_->do_mid_side_stereo;
  97184. }
  97185. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97186. {
  97187. FLAC__ASSERT(0 != encoder);
  97188. FLAC__ASSERT(0 != encoder->private_);
  97189. FLAC__ASSERT(0 != encoder->protected_);
  97190. return encoder->protected_->loose_mid_side_stereo;
  97191. }
  97192. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  97193. {
  97194. FLAC__ASSERT(0 != encoder);
  97195. FLAC__ASSERT(0 != encoder->private_);
  97196. FLAC__ASSERT(0 != encoder->protected_);
  97197. return encoder->protected_->max_lpc_order;
  97198. }
  97199. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  97200. {
  97201. FLAC__ASSERT(0 != encoder);
  97202. FLAC__ASSERT(0 != encoder->private_);
  97203. FLAC__ASSERT(0 != encoder->protected_);
  97204. return encoder->protected_->qlp_coeff_precision;
  97205. }
  97206. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  97207. {
  97208. FLAC__ASSERT(0 != encoder);
  97209. FLAC__ASSERT(0 != encoder->private_);
  97210. FLAC__ASSERT(0 != encoder->protected_);
  97211. return encoder->protected_->do_qlp_coeff_prec_search;
  97212. }
  97213. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  97214. {
  97215. FLAC__ASSERT(0 != encoder);
  97216. FLAC__ASSERT(0 != encoder->private_);
  97217. FLAC__ASSERT(0 != encoder->protected_);
  97218. return encoder->protected_->do_escape_coding;
  97219. }
  97220. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  97221. {
  97222. FLAC__ASSERT(0 != encoder);
  97223. FLAC__ASSERT(0 != encoder->private_);
  97224. FLAC__ASSERT(0 != encoder->protected_);
  97225. return encoder->protected_->do_exhaustive_model_search;
  97226. }
  97227. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97228. {
  97229. FLAC__ASSERT(0 != encoder);
  97230. FLAC__ASSERT(0 != encoder->private_);
  97231. FLAC__ASSERT(0 != encoder->protected_);
  97232. return encoder->protected_->min_residual_partition_order;
  97233. }
  97234. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97235. {
  97236. FLAC__ASSERT(0 != encoder);
  97237. FLAC__ASSERT(0 != encoder->private_);
  97238. FLAC__ASSERT(0 != encoder->protected_);
  97239. return encoder->protected_->max_residual_partition_order;
  97240. }
  97241. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  97242. {
  97243. FLAC__ASSERT(0 != encoder);
  97244. FLAC__ASSERT(0 != encoder->private_);
  97245. FLAC__ASSERT(0 != encoder->protected_);
  97246. return encoder->protected_->rice_parameter_search_dist;
  97247. }
  97248. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  97249. {
  97250. FLAC__ASSERT(0 != encoder);
  97251. FLAC__ASSERT(0 != encoder->private_);
  97252. FLAC__ASSERT(0 != encoder->protected_);
  97253. return encoder->protected_->total_samples_estimate;
  97254. }
  97255. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  97256. {
  97257. unsigned i, j = 0, channel;
  97258. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97259. FLAC__ASSERT(0 != encoder);
  97260. FLAC__ASSERT(0 != encoder->private_);
  97261. FLAC__ASSERT(0 != encoder->protected_);
  97262. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97263. do {
  97264. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  97265. if(encoder->protected_->verify)
  97266. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  97267. for(channel = 0; channel < channels; channel++)
  97268. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  97269. if(encoder->protected_->do_mid_side_stereo) {
  97270. FLAC__ASSERT(channels == 2);
  97271. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97272. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97273. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  97274. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  97275. }
  97276. }
  97277. else
  97278. j += n;
  97279. encoder->private_->current_sample_number += n;
  97280. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97281. if(encoder->private_->current_sample_number > blocksize) {
  97282. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  97283. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97284. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97285. return false;
  97286. /* move unprocessed overread samples to beginnings of arrays */
  97287. for(channel = 0; channel < channels; channel++)
  97288. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  97289. if(encoder->protected_->do_mid_side_stereo) {
  97290. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  97291. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  97292. }
  97293. encoder->private_->current_sample_number = 1;
  97294. }
  97295. } while(j < samples);
  97296. return true;
  97297. }
  97298. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  97299. {
  97300. unsigned i, j, k, channel;
  97301. FLAC__int32 x, mid, side;
  97302. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97303. FLAC__ASSERT(0 != encoder);
  97304. FLAC__ASSERT(0 != encoder->private_);
  97305. FLAC__ASSERT(0 != encoder->protected_);
  97306. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97307. j = k = 0;
  97308. /*
  97309. * we have several flavors of the same basic loop, optimized for
  97310. * different conditions:
  97311. */
  97312. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  97313. /*
  97314. * stereo coding: unroll channel loop
  97315. */
  97316. do {
  97317. if(encoder->protected_->verify)
  97318. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  97319. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97320. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97321. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  97322. x = buffer[k++];
  97323. encoder->private_->integer_signal[1][i] = x;
  97324. mid += x;
  97325. side -= x;
  97326. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  97327. encoder->private_->integer_signal_mid_side[1][i] = side;
  97328. encoder->private_->integer_signal_mid_side[0][i] = mid;
  97329. }
  97330. encoder->private_->current_sample_number = i;
  97331. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97332. if(i > blocksize) {
  97333. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97334. return false;
  97335. /* move unprocessed overread samples to beginnings of arrays */
  97336. FLAC__ASSERT(i == blocksize+OVERREAD_);
  97337. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97338. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  97339. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  97340. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  97341. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  97342. encoder->private_->current_sample_number = 1;
  97343. }
  97344. } while(j < samples);
  97345. }
  97346. else {
  97347. /*
  97348. * independent channel coding: buffer each channel in inner loop
  97349. */
  97350. do {
  97351. if(encoder->protected_->verify)
  97352. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  97353. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97354. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97355. for(channel = 0; channel < channels; channel++)
  97356. encoder->private_->integer_signal[channel][i] = buffer[k++];
  97357. }
  97358. encoder->private_->current_sample_number = i;
  97359. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97360. if(i > blocksize) {
  97361. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97362. return false;
  97363. /* move unprocessed overread samples to beginnings of arrays */
  97364. FLAC__ASSERT(i == blocksize+OVERREAD_);
  97365. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97366. for(channel = 0; channel < channels; channel++)
  97367. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  97368. encoder->private_->current_sample_number = 1;
  97369. }
  97370. } while(j < samples);
  97371. }
  97372. return true;
  97373. }
  97374. /***********************************************************************
  97375. *
  97376. * Private class methods
  97377. *
  97378. ***********************************************************************/
  97379. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  97380. {
  97381. FLAC__ASSERT(0 != encoder);
  97382. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  97383. encoder->protected_->verify = true;
  97384. #else
  97385. encoder->protected_->verify = false;
  97386. #endif
  97387. encoder->protected_->streamable_subset = true;
  97388. encoder->protected_->do_md5 = true;
  97389. encoder->protected_->do_mid_side_stereo = false;
  97390. encoder->protected_->loose_mid_side_stereo = false;
  97391. encoder->protected_->channels = 2;
  97392. encoder->protected_->bits_per_sample = 16;
  97393. encoder->protected_->sample_rate = 44100;
  97394. encoder->protected_->blocksize = 0;
  97395. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97396. encoder->protected_->num_apodizations = 1;
  97397. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97398. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97399. #endif
  97400. encoder->protected_->max_lpc_order = 0;
  97401. encoder->protected_->qlp_coeff_precision = 0;
  97402. encoder->protected_->do_qlp_coeff_prec_search = false;
  97403. encoder->protected_->do_exhaustive_model_search = false;
  97404. encoder->protected_->do_escape_coding = false;
  97405. encoder->protected_->min_residual_partition_order = 0;
  97406. encoder->protected_->max_residual_partition_order = 0;
  97407. encoder->protected_->rice_parameter_search_dist = 0;
  97408. encoder->protected_->total_samples_estimate = 0;
  97409. encoder->protected_->metadata = 0;
  97410. encoder->protected_->num_metadata_blocks = 0;
  97411. encoder->private_->seek_table = 0;
  97412. encoder->private_->disable_constant_subframes = false;
  97413. encoder->private_->disable_fixed_subframes = false;
  97414. encoder->private_->disable_verbatim_subframes = false;
  97415. #if FLAC__HAS_OGG
  97416. encoder->private_->is_ogg = false;
  97417. #endif
  97418. encoder->private_->read_callback = 0;
  97419. encoder->private_->write_callback = 0;
  97420. encoder->private_->seek_callback = 0;
  97421. encoder->private_->tell_callback = 0;
  97422. encoder->private_->metadata_callback = 0;
  97423. encoder->private_->progress_callback = 0;
  97424. encoder->private_->client_data = 0;
  97425. #if FLAC__HAS_OGG
  97426. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  97427. #endif
  97428. }
  97429. void free_(FLAC__StreamEncoder *encoder)
  97430. {
  97431. unsigned i, channel;
  97432. FLAC__ASSERT(0 != encoder);
  97433. if(encoder->protected_->metadata) {
  97434. free(encoder->protected_->metadata);
  97435. encoder->protected_->metadata = 0;
  97436. encoder->protected_->num_metadata_blocks = 0;
  97437. }
  97438. for(i = 0; i < encoder->protected_->channels; i++) {
  97439. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  97440. free(encoder->private_->integer_signal_unaligned[i]);
  97441. encoder->private_->integer_signal_unaligned[i] = 0;
  97442. }
  97443. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97444. if(0 != encoder->private_->real_signal_unaligned[i]) {
  97445. free(encoder->private_->real_signal_unaligned[i]);
  97446. encoder->private_->real_signal_unaligned[i] = 0;
  97447. }
  97448. #endif
  97449. }
  97450. for(i = 0; i < 2; i++) {
  97451. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  97452. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  97453. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  97454. }
  97455. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97456. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  97457. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  97458. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  97459. }
  97460. #endif
  97461. }
  97462. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97463. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  97464. if(0 != encoder->private_->window_unaligned[i]) {
  97465. free(encoder->private_->window_unaligned[i]);
  97466. encoder->private_->window_unaligned[i] = 0;
  97467. }
  97468. }
  97469. if(0 != encoder->private_->windowed_signal_unaligned) {
  97470. free(encoder->private_->windowed_signal_unaligned);
  97471. encoder->private_->windowed_signal_unaligned = 0;
  97472. }
  97473. #endif
  97474. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  97475. for(i = 0; i < 2; i++) {
  97476. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  97477. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  97478. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  97479. }
  97480. }
  97481. }
  97482. for(channel = 0; channel < 2; channel++) {
  97483. for(i = 0; i < 2; i++) {
  97484. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  97485. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  97486. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  97487. }
  97488. }
  97489. }
  97490. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  97491. free(encoder->private_->abs_residual_partition_sums_unaligned);
  97492. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  97493. }
  97494. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  97495. free(encoder->private_->raw_bits_per_partition_unaligned);
  97496. encoder->private_->raw_bits_per_partition_unaligned = 0;
  97497. }
  97498. if(encoder->protected_->verify) {
  97499. for(i = 0; i < encoder->protected_->channels; i++) {
  97500. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  97501. free(encoder->private_->verify.input_fifo.data[i]);
  97502. encoder->private_->verify.input_fifo.data[i] = 0;
  97503. }
  97504. }
  97505. }
  97506. FLAC__bitwriter_free(encoder->private_->frame);
  97507. }
  97508. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  97509. {
  97510. FLAC__bool ok;
  97511. unsigned i, channel;
  97512. FLAC__ASSERT(new_blocksize > 0);
  97513. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97514. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  97515. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  97516. if(new_blocksize <= encoder->private_->input_capacity)
  97517. return true;
  97518. ok = true;
  97519. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  97520. * requires that the input arrays (in our case the integer signals)
  97521. * have a buffer of up to 3 zeroes in front (at negative indices) for
  97522. * alignment purposes; we use 4 in front to keep the data well-aligned.
  97523. */
  97524. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  97525. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  97526. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  97527. encoder->private_->integer_signal[i] += 4;
  97528. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97529. #if 0 /* @@@ currently unused */
  97530. if(encoder->protected_->max_lpc_order > 0)
  97531. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  97532. #endif
  97533. #endif
  97534. }
  97535. for(i = 0; ok && i < 2; i++) {
  97536. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  97537. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  97538. encoder->private_->integer_signal_mid_side[i] += 4;
  97539. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97540. #if 0 /* @@@ currently unused */
  97541. if(encoder->protected_->max_lpc_order > 0)
  97542. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  97543. #endif
  97544. #endif
  97545. }
  97546. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97547. if(ok && encoder->protected_->max_lpc_order > 0) {
  97548. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  97549. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  97550. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  97551. }
  97552. #endif
  97553. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  97554. for(i = 0; ok && i < 2; i++) {
  97555. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  97556. }
  97557. }
  97558. for(channel = 0; ok && channel < 2; channel++) {
  97559. for(i = 0; ok && i < 2; i++) {
  97560. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  97561. }
  97562. }
  97563. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  97564. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  97565. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  97566. if(encoder->protected_->do_escape_coding)
  97567. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  97568. /* now adjust the windows if the blocksize has changed */
  97569. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97570. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  97571. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  97572. switch(encoder->protected_->apodizations[i].type) {
  97573. case FLAC__APODIZATION_BARTLETT:
  97574. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  97575. break;
  97576. case FLAC__APODIZATION_BARTLETT_HANN:
  97577. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  97578. break;
  97579. case FLAC__APODIZATION_BLACKMAN:
  97580. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  97581. break;
  97582. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  97583. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  97584. break;
  97585. case FLAC__APODIZATION_CONNES:
  97586. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  97587. break;
  97588. case FLAC__APODIZATION_FLATTOP:
  97589. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  97590. break;
  97591. case FLAC__APODIZATION_GAUSS:
  97592. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  97593. break;
  97594. case FLAC__APODIZATION_HAMMING:
  97595. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  97596. break;
  97597. case FLAC__APODIZATION_HANN:
  97598. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  97599. break;
  97600. case FLAC__APODIZATION_KAISER_BESSEL:
  97601. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  97602. break;
  97603. case FLAC__APODIZATION_NUTTALL:
  97604. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  97605. break;
  97606. case FLAC__APODIZATION_RECTANGLE:
  97607. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  97608. break;
  97609. case FLAC__APODIZATION_TRIANGLE:
  97610. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  97611. break;
  97612. case FLAC__APODIZATION_TUKEY:
  97613. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  97614. break;
  97615. case FLAC__APODIZATION_WELCH:
  97616. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  97617. break;
  97618. default:
  97619. FLAC__ASSERT(0);
  97620. /* double protection */
  97621. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  97622. break;
  97623. }
  97624. }
  97625. }
  97626. #endif
  97627. if(ok)
  97628. encoder->private_->input_capacity = new_blocksize;
  97629. else
  97630. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97631. return ok;
  97632. }
  97633. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  97634. {
  97635. const FLAC__byte *buffer;
  97636. size_t bytes;
  97637. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  97638. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  97639. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97640. return false;
  97641. }
  97642. if(encoder->protected_->verify) {
  97643. encoder->private_->verify.output.data = buffer;
  97644. encoder->private_->verify.output.bytes = bytes;
  97645. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  97646. encoder->private_->verify.needs_magic_hack = true;
  97647. }
  97648. else {
  97649. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  97650. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97651. FLAC__bitwriter_clear(encoder->private_->frame);
  97652. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  97653. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97654. return false;
  97655. }
  97656. }
  97657. }
  97658. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97659. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97660. FLAC__bitwriter_clear(encoder->private_->frame);
  97661. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97662. return false;
  97663. }
  97664. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97665. FLAC__bitwriter_clear(encoder->private_->frame);
  97666. if(samples > 0) {
  97667. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  97668. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  97669. }
  97670. return true;
  97671. }
  97672. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  97673. {
  97674. FLAC__StreamEncoderWriteStatus status;
  97675. FLAC__uint64 output_position = 0;
  97676. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  97677. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  97678. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97679. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  97680. }
  97681. /*
  97682. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  97683. */
  97684. if(samples == 0) {
  97685. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  97686. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  97687. encoder->protected_->streaminfo_offset = output_position;
  97688. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  97689. encoder->protected_->seektable_offset = output_position;
  97690. }
  97691. /*
  97692. * Mark the current seek point if hit (if audio_offset == 0 that
  97693. * means we're still writing metadata and haven't hit the first
  97694. * frame yet)
  97695. */
  97696. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  97697. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  97698. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  97699. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  97700. FLAC__uint64 test_sample;
  97701. unsigned i;
  97702. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  97703. test_sample = encoder->private_->seek_table->points[i].sample_number;
  97704. if(test_sample > frame_last_sample) {
  97705. break;
  97706. }
  97707. else if(test_sample >= frame_first_sample) {
  97708. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  97709. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  97710. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  97711. encoder->private_->first_seekpoint_to_check++;
  97712. /* DO NOT: "break;" and here's why:
  97713. * The seektable template may contain more than one target
  97714. * sample for any given frame; we will keep looping, generating
  97715. * duplicate seekpoints for them, and we'll clean it up later,
  97716. * just before writing the seektable back to the metadata.
  97717. */
  97718. }
  97719. else {
  97720. encoder->private_->first_seekpoint_to_check++;
  97721. }
  97722. }
  97723. }
  97724. #if FLAC__HAS_OGG
  97725. if(encoder->private_->is_ogg) {
  97726. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  97727. &encoder->protected_->ogg_encoder_aspect,
  97728. buffer,
  97729. bytes,
  97730. samples,
  97731. encoder->private_->current_frame_number,
  97732. is_last_block,
  97733. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  97734. encoder,
  97735. encoder->private_->client_data
  97736. );
  97737. }
  97738. else
  97739. #endif
  97740. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  97741. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97742. encoder->private_->bytes_written += bytes;
  97743. encoder->private_->samples_written += samples;
  97744. /* we keep a high watermark on the number of frames written because
  97745. * when the encoder goes back to write metadata, 'current_frame'
  97746. * will drop back to 0.
  97747. */
  97748. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  97749. }
  97750. else
  97751. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97752. return status;
  97753. }
  97754. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  97755. void update_metadata_(const FLAC__StreamEncoder *encoder)
  97756. {
  97757. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  97758. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  97759. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  97760. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  97761. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  97762. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  97763. FLAC__StreamEncoderSeekStatus seek_status;
  97764. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  97765. /* All this is based on intimate knowledge of the stream header
  97766. * layout, but a change to the header format that would break this
  97767. * would also break all streams encoded in the previous format.
  97768. */
  97769. /*
  97770. * Write MD5 signature
  97771. */
  97772. {
  97773. const unsigned md5_offset =
  97774. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97775. (
  97776. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97777. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97778. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97779. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97780. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97781. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97782. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  97783. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  97784. ) / 8;
  97785. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  97786. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97787. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97788. return;
  97789. }
  97790. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97791. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97792. return;
  97793. }
  97794. }
  97795. /*
  97796. * Write total samples
  97797. */
  97798. {
  97799. const unsigned total_samples_byte_offset =
  97800. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97801. (
  97802. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97803. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97804. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97805. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97806. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97807. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97808. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  97809. - 4
  97810. ) / 8;
  97811. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  97812. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  97813. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  97814. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  97815. b[4] = (FLAC__byte)(samples & 0xFF);
  97816. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  97817. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97818. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97819. return;
  97820. }
  97821. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97822. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97823. return;
  97824. }
  97825. }
  97826. /*
  97827. * Write min/max framesize
  97828. */
  97829. {
  97830. const unsigned min_framesize_offset =
  97831. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97832. (
  97833. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97834. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  97835. ) / 8;
  97836. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  97837. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  97838. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  97839. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  97840. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  97841. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  97842. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  97843. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97844. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97845. return;
  97846. }
  97847. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97848. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97849. return;
  97850. }
  97851. }
  97852. /*
  97853. * Write seektable
  97854. */
  97855. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  97856. unsigned i;
  97857. FLAC__format_seektable_sort(encoder->private_->seek_table);
  97858. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  97859. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  97860. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97861. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97862. return;
  97863. }
  97864. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  97865. FLAC__uint64 xx;
  97866. unsigned x;
  97867. xx = encoder->private_->seek_table->points[i].sample_number;
  97868. b[7] = (FLAC__byte)xx; xx >>= 8;
  97869. b[6] = (FLAC__byte)xx; xx >>= 8;
  97870. b[5] = (FLAC__byte)xx; xx >>= 8;
  97871. b[4] = (FLAC__byte)xx; xx >>= 8;
  97872. b[3] = (FLAC__byte)xx; xx >>= 8;
  97873. b[2] = (FLAC__byte)xx; xx >>= 8;
  97874. b[1] = (FLAC__byte)xx; xx >>= 8;
  97875. b[0] = (FLAC__byte)xx; xx >>= 8;
  97876. xx = encoder->private_->seek_table->points[i].stream_offset;
  97877. b[15] = (FLAC__byte)xx; xx >>= 8;
  97878. b[14] = (FLAC__byte)xx; xx >>= 8;
  97879. b[13] = (FLAC__byte)xx; xx >>= 8;
  97880. b[12] = (FLAC__byte)xx; xx >>= 8;
  97881. b[11] = (FLAC__byte)xx; xx >>= 8;
  97882. b[10] = (FLAC__byte)xx; xx >>= 8;
  97883. b[9] = (FLAC__byte)xx; xx >>= 8;
  97884. b[8] = (FLAC__byte)xx; xx >>= 8;
  97885. x = encoder->private_->seek_table->points[i].frame_samples;
  97886. b[17] = (FLAC__byte)x; x >>= 8;
  97887. b[16] = (FLAC__byte)x; x >>= 8;
  97888. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97889. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97890. return;
  97891. }
  97892. }
  97893. }
  97894. }
  97895. #if FLAC__HAS_OGG
  97896. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  97897. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  97898. {
  97899. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  97900. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  97901. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  97902. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  97903. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  97904. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  97905. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  97906. FLAC__STREAM_SYNC_LENGTH
  97907. ;
  97908. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  97909. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  97910. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  97911. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  97912. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  97913. ogg_page page;
  97914. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  97915. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  97916. /* Pre-check that client supports seeking, since we don't want the
  97917. * ogg_helper code to ever have to deal with this condition.
  97918. */
  97919. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  97920. return;
  97921. /* All this is based on intimate knowledge of the stream header
  97922. * layout, but a change to the header format that would break this
  97923. * would also break all streams encoded in the previous format.
  97924. */
  97925. /**
  97926. ** Write STREAMINFO stats
  97927. **/
  97928. simple_ogg_page__init(&page);
  97929. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  97930. simple_ogg_page__clear(&page);
  97931. return; /* state already set */
  97932. }
  97933. /*
  97934. * Write MD5 signature
  97935. */
  97936. {
  97937. const unsigned md5_offset =
  97938. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  97939. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97940. (
  97941. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97942. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97943. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97944. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97945. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97946. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97947. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  97948. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  97949. ) / 8;
  97950. if(md5_offset + 16 > (unsigned)page.body_len) {
  97951. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97952. simple_ogg_page__clear(&page);
  97953. return;
  97954. }
  97955. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  97956. }
  97957. /*
  97958. * Write total samples
  97959. */
  97960. {
  97961. const unsigned total_samples_byte_offset =
  97962. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  97963. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97964. (
  97965. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97966. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97967. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97968. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97969. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97970. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97971. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  97972. - 4
  97973. ) / 8;
  97974. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  97975. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97976. simple_ogg_page__clear(&page);
  97977. return;
  97978. }
  97979. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  97980. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  97981. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  97982. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  97983. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  97984. b[4] = (FLAC__byte)(samples & 0xFF);
  97985. memcpy(page.body + total_samples_byte_offset, b, 5);
  97986. }
  97987. /*
  97988. * Write min/max framesize
  97989. */
  97990. {
  97991. const unsigned min_framesize_offset =
  97992. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  97993. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97994. (
  97995. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97996. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  97997. ) / 8;
  97998. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  97999. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98000. simple_ogg_page__clear(&page);
  98001. return;
  98002. }
  98003. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98004. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98005. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98006. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98007. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98008. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98009. memcpy(page.body + min_framesize_offset, b, 6);
  98010. }
  98011. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98012. simple_ogg_page__clear(&page);
  98013. return; /* state already set */
  98014. }
  98015. simple_ogg_page__clear(&page);
  98016. /*
  98017. * Write seektable
  98018. */
  98019. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98020. unsigned i;
  98021. FLAC__byte *p;
  98022. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98023. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98024. simple_ogg_page__init(&page);
  98025. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98026. simple_ogg_page__clear(&page);
  98027. return; /* state already set */
  98028. }
  98029. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  98030. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98031. simple_ogg_page__clear(&page);
  98032. return;
  98033. }
  98034. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  98035. FLAC__uint64 xx;
  98036. unsigned x;
  98037. xx = encoder->private_->seek_table->points[i].sample_number;
  98038. b[7] = (FLAC__byte)xx; xx >>= 8;
  98039. b[6] = (FLAC__byte)xx; xx >>= 8;
  98040. b[5] = (FLAC__byte)xx; xx >>= 8;
  98041. b[4] = (FLAC__byte)xx; xx >>= 8;
  98042. b[3] = (FLAC__byte)xx; xx >>= 8;
  98043. b[2] = (FLAC__byte)xx; xx >>= 8;
  98044. b[1] = (FLAC__byte)xx; xx >>= 8;
  98045. b[0] = (FLAC__byte)xx; xx >>= 8;
  98046. xx = encoder->private_->seek_table->points[i].stream_offset;
  98047. b[15] = (FLAC__byte)xx; xx >>= 8;
  98048. b[14] = (FLAC__byte)xx; xx >>= 8;
  98049. b[13] = (FLAC__byte)xx; xx >>= 8;
  98050. b[12] = (FLAC__byte)xx; xx >>= 8;
  98051. b[11] = (FLAC__byte)xx; xx >>= 8;
  98052. b[10] = (FLAC__byte)xx; xx >>= 8;
  98053. b[9] = (FLAC__byte)xx; xx >>= 8;
  98054. b[8] = (FLAC__byte)xx; xx >>= 8;
  98055. x = encoder->private_->seek_table->points[i].frame_samples;
  98056. b[17] = (FLAC__byte)x; x >>= 8;
  98057. b[16] = (FLAC__byte)x; x >>= 8;
  98058. memcpy(p, b, 18);
  98059. }
  98060. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98061. simple_ogg_page__clear(&page);
  98062. return; /* state already set */
  98063. }
  98064. simple_ogg_page__clear(&page);
  98065. }
  98066. }
  98067. #endif
  98068. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  98069. {
  98070. FLAC__uint16 crc;
  98071. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98072. /*
  98073. * Accumulate raw signal to the MD5 signature
  98074. */
  98075. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  98076. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98077. return false;
  98078. }
  98079. /*
  98080. * Process the frame header and subframes into the frame bitbuffer
  98081. */
  98082. if(!process_subframes_(encoder, is_fractional_block)) {
  98083. /* the above function sets the state for us in case of an error */
  98084. return false;
  98085. }
  98086. /*
  98087. * Zero-pad the frame to a byte_boundary
  98088. */
  98089. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  98090. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98091. return false;
  98092. }
  98093. /*
  98094. * CRC-16 the whole thing
  98095. */
  98096. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98097. if(
  98098. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  98099. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  98100. ) {
  98101. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98102. return false;
  98103. }
  98104. /*
  98105. * Write it
  98106. */
  98107. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  98108. /* the above function sets the state for us in case of an error */
  98109. return false;
  98110. }
  98111. /*
  98112. * Get ready for the next frame
  98113. */
  98114. encoder->private_->current_sample_number = 0;
  98115. encoder->private_->current_frame_number++;
  98116. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  98117. return true;
  98118. }
  98119. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  98120. {
  98121. FLAC__FrameHeader frame_header;
  98122. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  98123. FLAC__bool do_independent, do_mid_side;
  98124. /*
  98125. * Calculate the min,max Rice partition orders
  98126. */
  98127. if(is_fractional_block) {
  98128. max_partition_order = 0;
  98129. }
  98130. else {
  98131. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  98132. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  98133. }
  98134. min_partition_order = min(min_partition_order, max_partition_order);
  98135. /*
  98136. * Setup the frame
  98137. */
  98138. frame_header.blocksize = encoder->protected_->blocksize;
  98139. frame_header.sample_rate = encoder->protected_->sample_rate;
  98140. frame_header.channels = encoder->protected_->channels;
  98141. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  98142. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  98143. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98144. frame_header.number.frame_number = encoder->private_->current_frame_number;
  98145. /*
  98146. * Figure out what channel assignments to try
  98147. */
  98148. if(encoder->protected_->do_mid_side_stereo) {
  98149. if(encoder->protected_->loose_mid_side_stereo) {
  98150. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  98151. do_independent = true;
  98152. do_mid_side = true;
  98153. }
  98154. else {
  98155. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  98156. do_mid_side = !do_independent;
  98157. }
  98158. }
  98159. else {
  98160. do_independent = true;
  98161. do_mid_side = true;
  98162. }
  98163. }
  98164. else {
  98165. do_independent = true;
  98166. do_mid_side = false;
  98167. }
  98168. FLAC__ASSERT(do_independent || do_mid_side);
  98169. /*
  98170. * Check for wasted bits; set effective bps for each subframe
  98171. */
  98172. if(do_independent) {
  98173. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98174. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  98175. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  98176. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  98177. }
  98178. }
  98179. if(do_mid_side) {
  98180. FLAC__ASSERT(encoder->protected_->channels == 2);
  98181. for(channel = 0; channel < 2; channel++) {
  98182. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  98183. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  98184. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  98185. }
  98186. }
  98187. /*
  98188. * First do a normal encoding pass of each independent channel
  98189. */
  98190. if(do_independent) {
  98191. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98192. if(!
  98193. process_subframe_(
  98194. encoder,
  98195. min_partition_order,
  98196. max_partition_order,
  98197. &frame_header,
  98198. encoder->private_->subframe_bps[channel],
  98199. encoder->private_->integer_signal[channel],
  98200. encoder->private_->subframe_workspace_ptr[channel],
  98201. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  98202. encoder->private_->residual_workspace[channel],
  98203. encoder->private_->best_subframe+channel,
  98204. encoder->private_->best_subframe_bits+channel
  98205. )
  98206. )
  98207. return false;
  98208. }
  98209. }
  98210. /*
  98211. * Now do mid and side channels if requested
  98212. */
  98213. if(do_mid_side) {
  98214. FLAC__ASSERT(encoder->protected_->channels == 2);
  98215. for(channel = 0; channel < 2; channel++) {
  98216. if(!
  98217. process_subframe_(
  98218. encoder,
  98219. min_partition_order,
  98220. max_partition_order,
  98221. &frame_header,
  98222. encoder->private_->subframe_bps_mid_side[channel],
  98223. encoder->private_->integer_signal_mid_side[channel],
  98224. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  98225. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  98226. encoder->private_->residual_workspace_mid_side[channel],
  98227. encoder->private_->best_subframe_mid_side+channel,
  98228. encoder->private_->best_subframe_bits_mid_side+channel
  98229. )
  98230. )
  98231. return false;
  98232. }
  98233. }
  98234. /*
  98235. * Compose the frame bitbuffer
  98236. */
  98237. if(do_mid_side) {
  98238. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  98239. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  98240. FLAC__ChannelAssignment channel_assignment;
  98241. FLAC__ASSERT(encoder->protected_->channels == 2);
  98242. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  98243. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  98244. }
  98245. else {
  98246. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  98247. unsigned min_bits;
  98248. int ca;
  98249. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  98250. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  98251. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  98252. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  98253. FLAC__ASSERT(do_independent && do_mid_side);
  98254. /* We have to figure out which channel assignent results in the smallest frame */
  98255. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  98256. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  98257. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  98258. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  98259. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98260. min_bits = bits[channel_assignment];
  98261. for(ca = 1; ca <= 3; ca++) {
  98262. if(bits[ca] < min_bits) {
  98263. min_bits = bits[ca];
  98264. channel_assignment = (FLAC__ChannelAssignment)ca;
  98265. }
  98266. }
  98267. }
  98268. frame_header.channel_assignment = channel_assignment;
  98269. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98270. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98271. return false;
  98272. }
  98273. switch(channel_assignment) {
  98274. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98275. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98276. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98277. break;
  98278. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98279. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98280. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98281. break;
  98282. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98283. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98284. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98285. break;
  98286. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  98287. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  98288. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98289. break;
  98290. default:
  98291. FLAC__ASSERT(0);
  98292. }
  98293. switch(channel_assignment) {
  98294. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98295. left_bps = encoder->private_->subframe_bps [0];
  98296. right_bps = encoder->private_->subframe_bps [1];
  98297. break;
  98298. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98299. left_bps = encoder->private_->subframe_bps [0];
  98300. right_bps = encoder->private_->subframe_bps_mid_side[1];
  98301. break;
  98302. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98303. left_bps = encoder->private_->subframe_bps_mid_side[1];
  98304. right_bps = encoder->private_->subframe_bps [1];
  98305. break;
  98306. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  98307. left_bps = encoder->private_->subframe_bps_mid_side[0];
  98308. right_bps = encoder->private_->subframe_bps_mid_side[1];
  98309. break;
  98310. default:
  98311. FLAC__ASSERT(0);
  98312. }
  98313. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  98314. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  98315. return false;
  98316. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  98317. return false;
  98318. }
  98319. else {
  98320. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98321. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98322. return false;
  98323. }
  98324. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98325. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  98326. /* the above function sets the state for us in case of an error */
  98327. return false;
  98328. }
  98329. }
  98330. }
  98331. if(encoder->protected_->loose_mid_side_stereo) {
  98332. encoder->private_->loose_mid_side_stereo_frame_count++;
  98333. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  98334. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98335. }
  98336. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  98337. return true;
  98338. }
  98339. FLAC__bool process_subframe_(
  98340. FLAC__StreamEncoder *encoder,
  98341. unsigned min_partition_order,
  98342. unsigned max_partition_order,
  98343. const FLAC__FrameHeader *frame_header,
  98344. unsigned subframe_bps,
  98345. const FLAC__int32 integer_signal[],
  98346. FLAC__Subframe *subframe[2],
  98347. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98348. FLAC__int32 *residual[2],
  98349. unsigned *best_subframe,
  98350. unsigned *best_bits
  98351. )
  98352. {
  98353. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98354. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  98355. #else
  98356. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  98357. #endif
  98358. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98359. FLAC__double lpc_residual_bits_per_sample;
  98360. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  98361. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  98362. unsigned min_lpc_order, max_lpc_order, lpc_order;
  98363. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  98364. #endif
  98365. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  98366. unsigned rice_parameter;
  98367. unsigned _candidate_bits, _best_bits;
  98368. unsigned _best_subframe;
  98369. /* only use RICE2 partitions if stream bps > 16 */
  98370. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  98371. FLAC__ASSERT(frame_header->blocksize > 0);
  98372. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  98373. _best_subframe = 0;
  98374. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  98375. _best_bits = UINT_MAX;
  98376. else
  98377. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  98378. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  98379. unsigned signal_is_constant = false;
  98380. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  98381. /* check for constant subframe */
  98382. if(
  98383. !encoder->private_->disable_constant_subframes &&
  98384. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98385. fixed_residual_bits_per_sample[1] == 0.0
  98386. #else
  98387. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  98388. #endif
  98389. ) {
  98390. /* the above means it's possible all samples are the same value; now double-check it: */
  98391. unsigned i;
  98392. signal_is_constant = true;
  98393. for(i = 1; i < frame_header->blocksize; i++) {
  98394. if(integer_signal[0] != integer_signal[i]) {
  98395. signal_is_constant = false;
  98396. break;
  98397. }
  98398. }
  98399. }
  98400. if(signal_is_constant) {
  98401. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  98402. if(_candidate_bits < _best_bits) {
  98403. _best_subframe = !_best_subframe;
  98404. _best_bits = _candidate_bits;
  98405. }
  98406. }
  98407. else {
  98408. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  98409. /* encode fixed */
  98410. if(encoder->protected_->do_exhaustive_model_search) {
  98411. min_fixed_order = 0;
  98412. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  98413. }
  98414. else {
  98415. min_fixed_order = max_fixed_order = guess_fixed_order;
  98416. }
  98417. if(max_fixed_order >= frame_header->blocksize)
  98418. max_fixed_order = frame_header->blocksize - 1;
  98419. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  98420. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98421. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  98422. continue; /* don't even try */
  98423. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  98424. #else
  98425. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  98426. continue; /* don't even try */
  98427. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  98428. #endif
  98429. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  98430. if(rice_parameter >= rice_parameter_limit) {
  98431. #ifdef DEBUG_VERBOSE
  98432. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  98433. #endif
  98434. rice_parameter = rice_parameter_limit - 1;
  98435. }
  98436. _candidate_bits =
  98437. evaluate_fixed_subframe_(
  98438. encoder,
  98439. integer_signal,
  98440. residual[!_best_subframe],
  98441. encoder->private_->abs_residual_partition_sums,
  98442. encoder->private_->raw_bits_per_partition,
  98443. frame_header->blocksize,
  98444. subframe_bps,
  98445. fixed_order,
  98446. rice_parameter,
  98447. rice_parameter_limit,
  98448. min_partition_order,
  98449. max_partition_order,
  98450. encoder->protected_->do_escape_coding,
  98451. encoder->protected_->rice_parameter_search_dist,
  98452. subframe[!_best_subframe],
  98453. partitioned_rice_contents[!_best_subframe]
  98454. );
  98455. if(_candidate_bits < _best_bits) {
  98456. _best_subframe = !_best_subframe;
  98457. _best_bits = _candidate_bits;
  98458. }
  98459. }
  98460. }
  98461. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98462. /* encode lpc */
  98463. if(encoder->protected_->max_lpc_order > 0) {
  98464. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  98465. max_lpc_order = frame_header->blocksize-1;
  98466. else
  98467. max_lpc_order = encoder->protected_->max_lpc_order;
  98468. if(max_lpc_order > 0) {
  98469. unsigned a;
  98470. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  98471. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  98472. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  98473. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  98474. if(autoc[0] != 0.0) {
  98475. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  98476. if(encoder->protected_->do_exhaustive_model_search) {
  98477. min_lpc_order = 1;
  98478. }
  98479. else {
  98480. const unsigned guess_lpc_order =
  98481. FLAC__lpc_compute_best_order(
  98482. lpc_error,
  98483. max_lpc_order,
  98484. frame_header->blocksize,
  98485. subframe_bps + (
  98486. encoder->protected_->do_qlp_coeff_prec_search?
  98487. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  98488. encoder->protected_->qlp_coeff_precision
  98489. )
  98490. );
  98491. min_lpc_order = max_lpc_order = guess_lpc_order;
  98492. }
  98493. if(max_lpc_order >= frame_header->blocksize)
  98494. max_lpc_order = frame_header->blocksize - 1;
  98495. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  98496. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  98497. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  98498. continue; /* don't even try */
  98499. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  98500. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  98501. if(rice_parameter >= rice_parameter_limit) {
  98502. #ifdef DEBUG_VERBOSE
  98503. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  98504. #endif
  98505. rice_parameter = rice_parameter_limit - 1;
  98506. }
  98507. if(encoder->protected_->do_qlp_coeff_prec_search) {
  98508. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  98509. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  98510. if(subframe_bps <= 17) {
  98511. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  98512. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  98513. }
  98514. else
  98515. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98516. }
  98517. else {
  98518. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  98519. }
  98520. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  98521. _candidate_bits =
  98522. evaluate_lpc_subframe_(
  98523. encoder,
  98524. integer_signal,
  98525. residual[!_best_subframe],
  98526. encoder->private_->abs_residual_partition_sums,
  98527. encoder->private_->raw_bits_per_partition,
  98528. encoder->private_->lp_coeff[lpc_order-1],
  98529. frame_header->blocksize,
  98530. subframe_bps,
  98531. lpc_order,
  98532. qlp_coeff_precision,
  98533. rice_parameter,
  98534. rice_parameter_limit,
  98535. min_partition_order,
  98536. max_partition_order,
  98537. encoder->protected_->do_escape_coding,
  98538. encoder->protected_->rice_parameter_search_dist,
  98539. subframe[!_best_subframe],
  98540. partitioned_rice_contents[!_best_subframe]
  98541. );
  98542. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  98543. if(_candidate_bits < _best_bits) {
  98544. _best_subframe = !_best_subframe;
  98545. _best_bits = _candidate_bits;
  98546. }
  98547. }
  98548. }
  98549. }
  98550. }
  98551. }
  98552. }
  98553. }
  98554. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98555. }
  98556. }
  98557. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  98558. if(_best_bits == UINT_MAX) {
  98559. FLAC__ASSERT(_best_subframe == 0);
  98560. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  98561. }
  98562. *best_subframe = _best_subframe;
  98563. *best_bits = _best_bits;
  98564. return true;
  98565. }
  98566. FLAC__bool add_subframe_(
  98567. FLAC__StreamEncoder *encoder,
  98568. unsigned blocksize,
  98569. unsigned subframe_bps,
  98570. const FLAC__Subframe *subframe,
  98571. FLAC__BitWriter *frame
  98572. )
  98573. {
  98574. switch(subframe->type) {
  98575. case FLAC__SUBFRAME_TYPE_CONSTANT:
  98576. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  98577. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98578. return false;
  98579. }
  98580. break;
  98581. case FLAC__SUBFRAME_TYPE_FIXED:
  98582. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  98583. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98584. return false;
  98585. }
  98586. break;
  98587. case FLAC__SUBFRAME_TYPE_LPC:
  98588. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  98589. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98590. return false;
  98591. }
  98592. break;
  98593. case FLAC__SUBFRAME_TYPE_VERBATIM:
  98594. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  98595. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98596. return false;
  98597. }
  98598. break;
  98599. default:
  98600. FLAC__ASSERT(0);
  98601. }
  98602. return true;
  98603. }
  98604. #define SPOTCHECK_ESTIMATE 0
  98605. #if SPOTCHECK_ESTIMATE
  98606. static void spotcheck_subframe_estimate_(
  98607. FLAC__StreamEncoder *encoder,
  98608. unsigned blocksize,
  98609. unsigned subframe_bps,
  98610. const FLAC__Subframe *subframe,
  98611. unsigned estimate
  98612. )
  98613. {
  98614. FLAC__bool ret;
  98615. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  98616. if(frame == 0) {
  98617. fprintf(stderr, "EST: can't allocate frame\n");
  98618. return;
  98619. }
  98620. if(!FLAC__bitwriter_init(frame)) {
  98621. fprintf(stderr, "EST: can't init frame\n");
  98622. return;
  98623. }
  98624. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  98625. FLAC__ASSERT(ret);
  98626. {
  98627. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  98628. if(estimate != actual)
  98629. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  98630. }
  98631. FLAC__bitwriter_delete(frame);
  98632. }
  98633. #endif
  98634. unsigned evaluate_constant_subframe_(
  98635. FLAC__StreamEncoder *encoder,
  98636. const FLAC__int32 signal,
  98637. unsigned blocksize,
  98638. unsigned subframe_bps,
  98639. FLAC__Subframe *subframe
  98640. )
  98641. {
  98642. unsigned estimate;
  98643. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  98644. subframe->data.constant.value = signal;
  98645. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  98646. #if SPOTCHECK_ESTIMATE
  98647. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98648. #else
  98649. (void)encoder, (void)blocksize;
  98650. #endif
  98651. return estimate;
  98652. }
  98653. unsigned evaluate_fixed_subframe_(
  98654. FLAC__StreamEncoder *encoder,
  98655. const FLAC__int32 signal[],
  98656. FLAC__int32 residual[],
  98657. FLAC__uint64 abs_residual_partition_sums[],
  98658. unsigned raw_bits_per_partition[],
  98659. unsigned blocksize,
  98660. unsigned subframe_bps,
  98661. unsigned order,
  98662. unsigned rice_parameter,
  98663. unsigned rice_parameter_limit,
  98664. unsigned min_partition_order,
  98665. unsigned max_partition_order,
  98666. FLAC__bool do_escape_coding,
  98667. unsigned rice_parameter_search_dist,
  98668. FLAC__Subframe *subframe,
  98669. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98670. )
  98671. {
  98672. unsigned i, residual_bits, estimate;
  98673. const unsigned residual_samples = blocksize - order;
  98674. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  98675. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  98676. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  98677. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  98678. subframe->data.fixed.residual = residual;
  98679. residual_bits =
  98680. find_best_partition_order_(
  98681. encoder->private_,
  98682. residual,
  98683. abs_residual_partition_sums,
  98684. raw_bits_per_partition,
  98685. residual_samples,
  98686. order,
  98687. rice_parameter,
  98688. rice_parameter_limit,
  98689. min_partition_order,
  98690. max_partition_order,
  98691. subframe_bps,
  98692. do_escape_coding,
  98693. rice_parameter_search_dist,
  98694. &subframe->data.fixed.entropy_coding_method
  98695. );
  98696. subframe->data.fixed.order = order;
  98697. for(i = 0; i < order; i++)
  98698. subframe->data.fixed.warmup[i] = signal[i];
  98699. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  98700. #if SPOTCHECK_ESTIMATE
  98701. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98702. #endif
  98703. return estimate;
  98704. }
  98705. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98706. unsigned evaluate_lpc_subframe_(
  98707. FLAC__StreamEncoder *encoder,
  98708. const FLAC__int32 signal[],
  98709. FLAC__int32 residual[],
  98710. FLAC__uint64 abs_residual_partition_sums[],
  98711. unsigned raw_bits_per_partition[],
  98712. const FLAC__real lp_coeff[],
  98713. unsigned blocksize,
  98714. unsigned subframe_bps,
  98715. unsigned order,
  98716. unsigned qlp_coeff_precision,
  98717. unsigned rice_parameter,
  98718. unsigned rice_parameter_limit,
  98719. unsigned min_partition_order,
  98720. unsigned max_partition_order,
  98721. FLAC__bool do_escape_coding,
  98722. unsigned rice_parameter_search_dist,
  98723. FLAC__Subframe *subframe,
  98724. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98725. )
  98726. {
  98727. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  98728. unsigned i, residual_bits, estimate;
  98729. int quantization, ret;
  98730. const unsigned residual_samples = blocksize - order;
  98731. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  98732. if(subframe_bps <= 16) {
  98733. FLAC__ASSERT(order > 0);
  98734. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  98735. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  98736. }
  98737. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  98738. if(ret != 0)
  98739. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  98740. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  98741. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  98742. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98743. else
  98744. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98745. else
  98746. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98747. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  98748. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  98749. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  98750. subframe->data.lpc.residual = residual;
  98751. residual_bits =
  98752. find_best_partition_order_(
  98753. encoder->private_,
  98754. residual,
  98755. abs_residual_partition_sums,
  98756. raw_bits_per_partition,
  98757. residual_samples,
  98758. order,
  98759. rice_parameter,
  98760. rice_parameter_limit,
  98761. min_partition_order,
  98762. max_partition_order,
  98763. subframe_bps,
  98764. do_escape_coding,
  98765. rice_parameter_search_dist,
  98766. &subframe->data.lpc.entropy_coding_method
  98767. );
  98768. subframe->data.lpc.order = order;
  98769. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  98770. subframe->data.lpc.quantization_level = quantization;
  98771. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  98772. for(i = 0; i < order; i++)
  98773. subframe->data.lpc.warmup[i] = signal[i];
  98774. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  98775. #if SPOTCHECK_ESTIMATE
  98776. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98777. #endif
  98778. return estimate;
  98779. }
  98780. #endif
  98781. unsigned evaluate_verbatim_subframe_(
  98782. FLAC__StreamEncoder *encoder,
  98783. const FLAC__int32 signal[],
  98784. unsigned blocksize,
  98785. unsigned subframe_bps,
  98786. FLAC__Subframe *subframe
  98787. )
  98788. {
  98789. unsigned estimate;
  98790. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  98791. subframe->data.verbatim.data = signal;
  98792. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  98793. #if SPOTCHECK_ESTIMATE
  98794. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98795. #else
  98796. (void)encoder;
  98797. #endif
  98798. return estimate;
  98799. }
  98800. unsigned find_best_partition_order_(
  98801. FLAC__StreamEncoderPrivate *private_,
  98802. const FLAC__int32 residual[],
  98803. FLAC__uint64 abs_residual_partition_sums[],
  98804. unsigned raw_bits_per_partition[],
  98805. unsigned residual_samples,
  98806. unsigned predictor_order,
  98807. unsigned rice_parameter,
  98808. unsigned rice_parameter_limit,
  98809. unsigned min_partition_order,
  98810. unsigned max_partition_order,
  98811. unsigned bps,
  98812. FLAC__bool do_escape_coding,
  98813. unsigned rice_parameter_search_dist,
  98814. FLAC__EntropyCodingMethod *best_ecm
  98815. )
  98816. {
  98817. unsigned residual_bits, best_residual_bits = 0;
  98818. unsigned best_parameters_index = 0;
  98819. unsigned best_partition_order = 0;
  98820. const unsigned blocksize = residual_samples + predictor_order;
  98821. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  98822. min_partition_order = min(min_partition_order, max_partition_order);
  98823. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  98824. if(do_escape_coding)
  98825. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  98826. {
  98827. int partition_order;
  98828. unsigned sum;
  98829. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  98830. if(!
  98831. set_partitioned_rice_(
  98832. #ifdef EXACT_RICE_BITS_CALCULATION
  98833. residual,
  98834. #endif
  98835. abs_residual_partition_sums+sum,
  98836. raw_bits_per_partition+sum,
  98837. residual_samples,
  98838. predictor_order,
  98839. rice_parameter,
  98840. rice_parameter_limit,
  98841. rice_parameter_search_dist,
  98842. (unsigned)partition_order,
  98843. do_escape_coding,
  98844. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  98845. &residual_bits
  98846. )
  98847. )
  98848. {
  98849. FLAC__ASSERT(best_residual_bits != 0);
  98850. break;
  98851. }
  98852. sum += 1u << partition_order;
  98853. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  98854. best_residual_bits = residual_bits;
  98855. best_parameters_index = !best_parameters_index;
  98856. best_partition_order = partition_order;
  98857. }
  98858. }
  98859. }
  98860. best_ecm->data.partitioned_rice.order = best_partition_order;
  98861. {
  98862. /*
  98863. * We are allowed to de-const the pointer based on our special
  98864. * knowledge; it is const to the outside world.
  98865. */
  98866. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  98867. unsigned partition;
  98868. /* save best parameters and raw_bits */
  98869. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  98870. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  98871. if(do_escape_coding)
  98872. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  98873. /*
  98874. * Now need to check if the type should be changed to
  98875. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  98876. * size of the rice parameters.
  98877. */
  98878. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  98879. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  98880. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  98881. break;
  98882. }
  98883. }
  98884. }
  98885. return best_residual_bits;
  98886. }
  98887. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  98888. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  98889. const FLAC__int32 residual[],
  98890. FLAC__uint64 abs_residual_partition_sums[],
  98891. unsigned blocksize,
  98892. unsigned predictor_order,
  98893. unsigned min_partition_order,
  98894. unsigned max_partition_order
  98895. );
  98896. #endif
  98897. void precompute_partition_info_sums_(
  98898. const FLAC__int32 residual[],
  98899. FLAC__uint64 abs_residual_partition_sums[],
  98900. unsigned residual_samples,
  98901. unsigned predictor_order,
  98902. unsigned min_partition_order,
  98903. unsigned max_partition_order,
  98904. unsigned bps
  98905. )
  98906. {
  98907. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  98908. unsigned partitions = 1u << max_partition_order;
  98909. FLAC__ASSERT(default_partition_samples > predictor_order);
  98910. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  98911. /* slightly pessimistic but still catches all common cases */
  98912. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  98913. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  98914. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  98915. return;
  98916. }
  98917. #endif
  98918. /* first do max_partition_order */
  98919. {
  98920. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  98921. /* slightly pessimistic but still catches all common cases */
  98922. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  98923. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  98924. FLAC__uint32 abs_residual_partition_sum;
  98925. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98926. end += default_partition_samples;
  98927. abs_residual_partition_sum = 0;
  98928. for( ; residual_sample < end; residual_sample++)
  98929. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  98930. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  98931. }
  98932. }
  98933. else { /* have to pessimistically use 64 bits for accumulator */
  98934. FLAC__uint64 abs_residual_partition_sum;
  98935. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98936. end += default_partition_samples;
  98937. abs_residual_partition_sum = 0;
  98938. for( ; residual_sample < end; residual_sample++)
  98939. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  98940. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  98941. }
  98942. }
  98943. }
  98944. /* now merge partitions for lower orders */
  98945. {
  98946. unsigned from_partition = 0, to_partition = partitions;
  98947. int partition_order;
  98948. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  98949. unsigned i;
  98950. partitions >>= 1;
  98951. for(i = 0; i < partitions; i++) {
  98952. abs_residual_partition_sums[to_partition++] =
  98953. abs_residual_partition_sums[from_partition ] +
  98954. abs_residual_partition_sums[from_partition+1];
  98955. from_partition += 2;
  98956. }
  98957. }
  98958. }
  98959. }
  98960. void precompute_partition_info_escapes_(
  98961. const FLAC__int32 residual[],
  98962. unsigned raw_bits_per_partition[],
  98963. unsigned residual_samples,
  98964. unsigned predictor_order,
  98965. unsigned min_partition_order,
  98966. unsigned max_partition_order
  98967. )
  98968. {
  98969. int partition_order;
  98970. unsigned from_partition, to_partition = 0;
  98971. const unsigned blocksize = residual_samples + predictor_order;
  98972. /* first do max_partition_order */
  98973. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  98974. FLAC__int32 r;
  98975. FLAC__uint32 rmax;
  98976. unsigned partition, partition_sample, partition_samples, residual_sample;
  98977. const unsigned partitions = 1u << partition_order;
  98978. const unsigned default_partition_samples = blocksize >> partition_order;
  98979. FLAC__ASSERT(default_partition_samples > predictor_order);
  98980. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98981. partition_samples = default_partition_samples;
  98982. if(partition == 0)
  98983. partition_samples -= predictor_order;
  98984. rmax = 0;
  98985. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  98986. r = residual[residual_sample++];
  98987. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  98988. if(r < 0)
  98989. rmax |= ~r;
  98990. else
  98991. rmax |= r;
  98992. }
  98993. /* now we know all residual values are in the range [-rmax-1,rmax] */
  98994. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  98995. }
  98996. to_partition = partitions;
  98997. break; /*@@@ yuck, should remove the 'for' loop instead */
  98998. }
  98999. /* now merge partitions for lower orders */
  99000. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  99001. unsigned m;
  99002. unsigned i;
  99003. const unsigned partitions = 1u << partition_order;
  99004. for(i = 0; i < partitions; i++) {
  99005. m = raw_bits_per_partition[from_partition];
  99006. from_partition++;
  99007. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  99008. from_partition++;
  99009. to_partition++;
  99010. }
  99011. }
  99012. }
  99013. #ifdef EXACT_RICE_BITS_CALCULATION
  99014. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99015. const unsigned rice_parameter,
  99016. const unsigned partition_samples,
  99017. const FLAC__int32 *residual
  99018. )
  99019. {
  99020. unsigned i, partition_bits =
  99021. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  99022. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  99023. ;
  99024. for(i = 0; i < partition_samples; i++)
  99025. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  99026. return partition_bits;
  99027. }
  99028. #else
  99029. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99030. const unsigned rice_parameter,
  99031. const unsigned partition_samples,
  99032. const FLAC__uint64 abs_residual_partition_sum
  99033. )
  99034. {
  99035. return
  99036. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  99037. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  99038. (
  99039. rice_parameter?
  99040. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  99041. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  99042. )
  99043. - (partition_samples >> 1)
  99044. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  99045. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  99046. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  99047. * So the subtraction term tries to guess how many extra bits were contributed.
  99048. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  99049. */
  99050. ;
  99051. }
  99052. #endif
  99053. FLAC__bool set_partitioned_rice_(
  99054. #ifdef EXACT_RICE_BITS_CALCULATION
  99055. const FLAC__int32 residual[],
  99056. #endif
  99057. const FLAC__uint64 abs_residual_partition_sums[],
  99058. const unsigned raw_bits_per_partition[],
  99059. const unsigned residual_samples,
  99060. const unsigned predictor_order,
  99061. const unsigned suggested_rice_parameter,
  99062. const unsigned rice_parameter_limit,
  99063. const unsigned rice_parameter_search_dist,
  99064. const unsigned partition_order,
  99065. const FLAC__bool search_for_escapes,
  99066. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99067. unsigned *bits
  99068. )
  99069. {
  99070. unsigned rice_parameter, partition_bits;
  99071. unsigned best_partition_bits, best_rice_parameter = 0;
  99072. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  99073. unsigned *parameters, *raw_bits;
  99074. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99075. unsigned min_rice_parameter, max_rice_parameter;
  99076. #else
  99077. (void)rice_parameter_search_dist;
  99078. #endif
  99079. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99080. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99081. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  99082. parameters = partitioned_rice_contents->parameters;
  99083. raw_bits = partitioned_rice_contents->raw_bits;
  99084. if(partition_order == 0) {
  99085. best_partition_bits = (unsigned)(-1);
  99086. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99087. if(rice_parameter_search_dist) {
  99088. if(suggested_rice_parameter < rice_parameter_search_dist)
  99089. min_rice_parameter = 0;
  99090. else
  99091. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  99092. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  99093. if(max_rice_parameter >= rice_parameter_limit) {
  99094. #ifdef DEBUG_VERBOSE
  99095. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  99096. #endif
  99097. max_rice_parameter = rice_parameter_limit - 1;
  99098. }
  99099. }
  99100. else
  99101. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  99102. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99103. #else
  99104. rice_parameter = suggested_rice_parameter;
  99105. #endif
  99106. #ifdef EXACT_RICE_BITS_CALCULATION
  99107. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  99108. #else
  99109. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  99110. #endif
  99111. if(partition_bits < best_partition_bits) {
  99112. best_rice_parameter = rice_parameter;
  99113. best_partition_bits = partition_bits;
  99114. }
  99115. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99116. }
  99117. #endif
  99118. if(search_for_escapes) {
  99119. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  99120. if(partition_bits <= best_partition_bits) {
  99121. raw_bits[0] = raw_bits_per_partition[0];
  99122. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99123. best_partition_bits = partition_bits;
  99124. }
  99125. else
  99126. raw_bits[0] = 0;
  99127. }
  99128. parameters[0] = best_rice_parameter;
  99129. bits_ += best_partition_bits;
  99130. }
  99131. else {
  99132. unsigned partition, residual_sample;
  99133. unsigned partition_samples;
  99134. FLAC__uint64 mean, k;
  99135. const unsigned partitions = 1u << partition_order;
  99136. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99137. partition_samples = (residual_samples+predictor_order) >> partition_order;
  99138. if(partition == 0) {
  99139. if(partition_samples <= predictor_order)
  99140. return false;
  99141. else
  99142. partition_samples -= predictor_order;
  99143. }
  99144. mean = abs_residual_partition_sums[partition];
  99145. /* we are basically calculating the size in bits of the
  99146. * average residual magnitude in the partition:
  99147. * rice_parameter = floor(log2(mean/partition_samples))
  99148. * 'mean' is not a good name for the variable, it is
  99149. * actually the sum of magnitudes of all residual values
  99150. * in the partition, so the actual mean is
  99151. * mean/partition_samples
  99152. */
  99153. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  99154. ;
  99155. if(rice_parameter >= rice_parameter_limit) {
  99156. #ifdef DEBUG_VERBOSE
  99157. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  99158. #endif
  99159. rice_parameter = rice_parameter_limit - 1;
  99160. }
  99161. best_partition_bits = (unsigned)(-1);
  99162. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99163. if(rice_parameter_search_dist) {
  99164. if(rice_parameter < rice_parameter_search_dist)
  99165. min_rice_parameter = 0;
  99166. else
  99167. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  99168. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  99169. if(max_rice_parameter >= rice_parameter_limit) {
  99170. #ifdef DEBUG_VERBOSE
  99171. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  99172. #endif
  99173. max_rice_parameter = rice_parameter_limit - 1;
  99174. }
  99175. }
  99176. else
  99177. min_rice_parameter = max_rice_parameter = rice_parameter;
  99178. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99179. #endif
  99180. #ifdef EXACT_RICE_BITS_CALCULATION
  99181. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  99182. #else
  99183. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  99184. #endif
  99185. if(partition_bits < best_partition_bits) {
  99186. best_rice_parameter = rice_parameter;
  99187. best_partition_bits = partition_bits;
  99188. }
  99189. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99190. }
  99191. #endif
  99192. if(search_for_escapes) {
  99193. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  99194. if(partition_bits <= best_partition_bits) {
  99195. raw_bits[partition] = raw_bits_per_partition[partition];
  99196. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99197. best_partition_bits = partition_bits;
  99198. }
  99199. else
  99200. raw_bits[partition] = 0;
  99201. }
  99202. parameters[partition] = best_rice_parameter;
  99203. bits_ += best_partition_bits;
  99204. residual_sample += partition_samples;
  99205. }
  99206. }
  99207. *bits = bits_;
  99208. return true;
  99209. }
  99210. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  99211. {
  99212. unsigned i, shift;
  99213. FLAC__int32 x = 0;
  99214. for(i = 0; i < samples && !(x&1); i++)
  99215. x |= signal[i];
  99216. if(x == 0) {
  99217. shift = 0;
  99218. }
  99219. else {
  99220. for(shift = 0; !(x&1); shift++)
  99221. x >>= 1;
  99222. }
  99223. if(shift > 0) {
  99224. for(i = 0; i < samples; i++)
  99225. signal[i] >>= shift;
  99226. }
  99227. return shift;
  99228. }
  99229. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99230. {
  99231. unsigned channel;
  99232. for(channel = 0; channel < channels; channel++)
  99233. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  99234. fifo->tail += wide_samples;
  99235. FLAC__ASSERT(fifo->tail <= fifo->size);
  99236. }
  99237. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99238. {
  99239. unsigned channel;
  99240. unsigned sample, wide_sample;
  99241. unsigned tail = fifo->tail;
  99242. sample = input_offset * channels;
  99243. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  99244. for(channel = 0; channel < channels; channel++)
  99245. fifo->data[channel][tail] = input[sample++];
  99246. tail++;
  99247. }
  99248. fifo->tail = tail;
  99249. FLAC__ASSERT(fifo->tail <= fifo->size);
  99250. }
  99251. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99252. {
  99253. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99254. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  99255. (void)decoder;
  99256. if(encoder->private_->verify.needs_magic_hack) {
  99257. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  99258. *bytes = FLAC__STREAM_SYNC_LENGTH;
  99259. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  99260. encoder->private_->verify.needs_magic_hack = false;
  99261. }
  99262. else {
  99263. if(encoded_bytes == 0) {
  99264. /*
  99265. * If we get here, a FIFO underflow has occurred,
  99266. * which means there is a bug somewhere.
  99267. */
  99268. FLAC__ASSERT(0);
  99269. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  99270. }
  99271. else if(encoded_bytes < *bytes)
  99272. *bytes = encoded_bytes;
  99273. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  99274. encoder->private_->verify.output.data += *bytes;
  99275. encoder->private_->verify.output.bytes -= *bytes;
  99276. }
  99277. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  99278. }
  99279. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  99280. {
  99281. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  99282. unsigned channel;
  99283. const unsigned channels = frame->header.channels;
  99284. const unsigned blocksize = frame->header.blocksize;
  99285. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  99286. (void)decoder;
  99287. for(channel = 0; channel < channels; channel++) {
  99288. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  99289. unsigned i, sample = 0;
  99290. FLAC__int32 expect = 0, got = 0;
  99291. for(i = 0; i < blocksize; i++) {
  99292. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  99293. sample = i;
  99294. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  99295. got = (FLAC__int32)buffer[channel][i];
  99296. break;
  99297. }
  99298. }
  99299. FLAC__ASSERT(i < blocksize);
  99300. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99301. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  99302. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  99303. encoder->private_->verify.error_stats.channel = channel;
  99304. encoder->private_->verify.error_stats.sample = sample;
  99305. encoder->private_->verify.error_stats.expected = expect;
  99306. encoder->private_->verify.error_stats.got = got;
  99307. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99308. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  99309. }
  99310. }
  99311. /* dequeue the frame from the fifo */
  99312. encoder->private_->verify.input_fifo.tail -= blocksize;
  99313. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  99314. for(channel = 0; channel < channels; channel++)
  99315. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  99316. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  99317. }
  99318. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  99319. {
  99320. (void)decoder, (void)metadata, (void)client_data;
  99321. }
  99322. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  99323. {
  99324. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99325. (void)decoder, (void)status;
  99326. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99327. }
  99328. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99329. {
  99330. (void)client_data;
  99331. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  99332. if (*bytes == 0) {
  99333. if (feof(encoder->private_->file))
  99334. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  99335. else if (ferror(encoder->private_->file))
  99336. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  99337. }
  99338. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  99339. }
  99340. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  99341. {
  99342. (void)client_data;
  99343. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  99344. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  99345. else
  99346. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  99347. }
  99348. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  99349. {
  99350. off_t offset;
  99351. (void)client_data;
  99352. offset = ftello(encoder->private_->file);
  99353. if(offset < 0) {
  99354. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  99355. }
  99356. else {
  99357. *absolute_byte_offset = (FLAC__uint64)offset;
  99358. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  99359. }
  99360. }
  99361. #ifdef FLAC__VALGRIND_TESTING
  99362. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  99363. {
  99364. size_t ret = fwrite(ptr, size, nmemb, stream);
  99365. if(!ferror(stream))
  99366. fflush(stream);
  99367. return ret;
  99368. }
  99369. #else
  99370. #define local__fwrite fwrite
  99371. #endif
  99372. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  99373. {
  99374. (void)client_data, (void)current_frame;
  99375. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  99376. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  99377. #if FLAC__HAS_OGG
  99378. /* We would like to be able to use 'samples > 0' in the
  99379. * clause here but currently because of the nature of our
  99380. * Ogg writing implementation, 'samples' is always 0 (see
  99381. * ogg_encoder_aspect.c). The downside is extra progress
  99382. * callbacks.
  99383. */
  99384. encoder->private_->is_ogg? true :
  99385. #endif
  99386. samples > 0
  99387. );
  99388. if(call_it) {
  99389. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  99390. * because at this point in the callback chain, the stats
  99391. * have not been updated. Only after we return and control
  99392. * gets back to write_frame_() are the stats updated
  99393. */
  99394. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  99395. }
  99396. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  99397. }
  99398. else
  99399. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99400. }
  99401. /*
  99402. * This will forcibly set stdout to binary mode (for OSes that require it)
  99403. */
  99404. FILE *get_binary_stdout_(void)
  99405. {
  99406. /* if something breaks here it is probably due to the presence or
  99407. * absence of an underscore before the identifiers 'setmode',
  99408. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99409. */
  99410. #if defined _MSC_VER || defined __MINGW32__
  99411. _setmode(_fileno(stdout), _O_BINARY);
  99412. #elif defined __CYGWIN__
  99413. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99414. setmode(_fileno(stdout), _O_BINARY);
  99415. #elif defined __EMX__
  99416. setmode(fileno(stdout), O_BINARY);
  99417. #endif
  99418. return stdout;
  99419. }
  99420. #endif
  99421. /********* End of inlined file: stream_encoder.c *********/
  99422. /********* Start of inlined file: stream_encoder_framing.c *********/
  99423. /********* Start of inlined file: juce_FlacHeader.h *********/
  99424. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99425. // tasks..
  99426. #define VERSION "1.2.1"
  99427. #define FLAC__NO_DLL 1
  99428. #ifdef _MSC_VER
  99429. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99430. #endif
  99431. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  99432. #define FLAC__SYS_DARWIN 1
  99433. #endif
  99434. /********* End of inlined file: juce_FlacHeader.h *********/
  99435. #if JUCE_USE_FLAC
  99436. #if HAVE_CONFIG_H
  99437. # include <config.h>
  99438. #endif
  99439. #include <stdio.h>
  99440. #include <string.h> /* for strlen() */
  99441. #ifdef max
  99442. #undef max
  99443. #endif
  99444. #define max(x,y) ((x)>(y)?(x):(y))
  99445. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  99446. static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
  99447. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  99448. {
  99449. unsigned i, j;
  99450. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  99451. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99452. return false;
  99453. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  99454. return false;
  99455. /*
  99456. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  99457. */
  99458. i = metadata->length;
  99459. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99460. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  99461. i -= metadata->data.vorbis_comment.vendor_string.length;
  99462. i += vendor_string_length;
  99463. }
  99464. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  99465. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  99466. return false;
  99467. switch(metadata->type) {
  99468. case FLAC__METADATA_TYPE_STREAMINFO:
  99469. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  99470. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  99471. return false;
  99472. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  99473. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99474. return false;
  99475. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  99476. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99477. return false;
  99478. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  99479. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99480. return false;
  99481. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  99482. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99483. return false;
  99484. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  99485. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  99486. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99487. return false;
  99488. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  99489. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  99490. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99491. return false;
  99492. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  99493. return false;
  99494. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  99495. return false;
  99496. break;
  99497. case FLAC__METADATA_TYPE_PADDING:
  99498. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  99499. return false;
  99500. break;
  99501. case FLAC__METADATA_TYPE_APPLICATION:
  99502. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  99503. return false;
  99504. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  99505. return false;
  99506. break;
  99507. case FLAC__METADATA_TYPE_SEEKTABLE:
  99508. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  99509. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99510. return false;
  99511. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99512. return false;
  99513. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99514. return false;
  99515. }
  99516. break;
  99517. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99518. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  99519. return false;
  99520. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  99521. return false;
  99522. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  99523. return false;
  99524. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  99525. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  99526. return false;
  99527. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  99528. return false;
  99529. }
  99530. break;
  99531. case FLAC__METADATA_TYPE_CUESHEET:
  99532. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99533. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  99534. return false;
  99535. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99536. return false;
  99537. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99538. return false;
  99539. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99540. return false;
  99541. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99542. return false;
  99543. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  99544. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  99545. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99546. return false;
  99547. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99548. return false;
  99549. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99550. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99551. return false;
  99552. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99553. return false;
  99554. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99555. return false;
  99556. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99557. return false;
  99558. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99559. return false;
  99560. for(j = 0; j < track->num_indices; j++) {
  99561. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  99562. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99563. return false;
  99564. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99565. return false;
  99566. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99567. return false;
  99568. }
  99569. }
  99570. break;
  99571. case FLAC__METADATA_TYPE_PICTURE:
  99572. {
  99573. size_t len;
  99574. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99575. return false;
  99576. len = strlen(metadata->data.picture.mime_type);
  99577. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99578. return false;
  99579. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  99580. return false;
  99581. len = strlen((const char *)metadata->data.picture.description);
  99582. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99583. return false;
  99584. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  99585. return false;
  99586. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99587. return false;
  99588. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99589. return false;
  99590. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99591. return false;
  99592. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99593. return false;
  99594. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99595. return false;
  99596. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  99597. return false;
  99598. }
  99599. break;
  99600. default:
  99601. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  99602. return false;
  99603. break;
  99604. }
  99605. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  99606. return true;
  99607. }
  99608. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  99609. {
  99610. unsigned u, blocksize_hint, sample_rate_hint;
  99611. FLAC__byte crc;
  99612. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  99613. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  99614. return false;
  99615. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  99616. return false;
  99617. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  99618. return false;
  99619. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  99620. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  99621. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  99622. blocksize_hint = 0;
  99623. switch(header->blocksize) {
  99624. case 192: u = 1; break;
  99625. case 576: u = 2; break;
  99626. case 1152: u = 3; break;
  99627. case 2304: u = 4; break;
  99628. case 4608: u = 5; break;
  99629. case 256: u = 8; break;
  99630. case 512: u = 9; break;
  99631. case 1024: u = 10; break;
  99632. case 2048: u = 11; break;
  99633. case 4096: u = 12; break;
  99634. case 8192: u = 13; break;
  99635. case 16384: u = 14; break;
  99636. case 32768: u = 15; break;
  99637. default:
  99638. if(header->blocksize <= 0x100)
  99639. blocksize_hint = u = 6;
  99640. else
  99641. blocksize_hint = u = 7;
  99642. break;
  99643. }
  99644. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  99645. return false;
  99646. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  99647. sample_rate_hint = 0;
  99648. switch(header->sample_rate) {
  99649. case 88200: u = 1; break;
  99650. case 176400: u = 2; break;
  99651. case 192000: u = 3; break;
  99652. case 8000: u = 4; break;
  99653. case 16000: u = 5; break;
  99654. case 22050: u = 6; break;
  99655. case 24000: u = 7; break;
  99656. case 32000: u = 8; break;
  99657. case 44100: u = 9; break;
  99658. case 48000: u = 10; break;
  99659. case 96000: u = 11; break;
  99660. default:
  99661. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  99662. sample_rate_hint = u = 12;
  99663. else if(header->sample_rate % 10 == 0)
  99664. sample_rate_hint = u = 14;
  99665. else if(header->sample_rate <= 0xffff)
  99666. sample_rate_hint = u = 13;
  99667. else
  99668. u = 0;
  99669. break;
  99670. }
  99671. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  99672. return false;
  99673. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  99674. switch(header->channel_assignment) {
  99675. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99676. u = header->channels - 1;
  99677. break;
  99678. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99679. FLAC__ASSERT(header->channels == 2);
  99680. u = 8;
  99681. break;
  99682. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99683. FLAC__ASSERT(header->channels == 2);
  99684. u = 9;
  99685. break;
  99686. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99687. FLAC__ASSERT(header->channels == 2);
  99688. u = 10;
  99689. break;
  99690. default:
  99691. FLAC__ASSERT(0);
  99692. }
  99693. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  99694. return false;
  99695. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  99696. switch(header->bits_per_sample) {
  99697. case 8 : u = 1; break;
  99698. case 12: u = 2; break;
  99699. case 16: u = 4; break;
  99700. case 20: u = 5; break;
  99701. case 24: u = 6; break;
  99702. default: u = 0; break;
  99703. }
  99704. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  99705. return false;
  99706. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  99707. return false;
  99708. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  99709. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  99710. return false;
  99711. }
  99712. else {
  99713. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  99714. return false;
  99715. }
  99716. if(blocksize_hint)
  99717. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  99718. return false;
  99719. switch(sample_rate_hint) {
  99720. case 12:
  99721. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  99722. return false;
  99723. break;
  99724. case 13:
  99725. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  99726. return false;
  99727. break;
  99728. case 14:
  99729. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  99730. return false;
  99731. break;
  99732. }
  99733. /* write the CRC */
  99734. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  99735. return false;
  99736. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  99737. return false;
  99738. return true;
  99739. }
  99740. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99741. {
  99742. FLAC__bool ok;
  99743. ok =
  99744. FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
  99745. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  99746. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  99747. ;
  99748. return ok;
  99749. }
  99750. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99751. {
  99752. unsigned i;
  99753. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  99754. return false;
  99755. if(wasted_bits)
  99756. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99757. return false;
  99758. for(i = 0; i < subframe->order; i++)
  99759. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  99760. return false;
  99761. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  99762. return false;
  99763. switch(subframe->entropy_coding_method.type) {
  99764. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99765. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99766. if(!add_residual_partitioned_rice_(
  99767. bw,
  99768. subframe->residual,
  99769. residual_samples,
  99770. subframe->order,
  99771. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  99772. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  99773. subframe->entropy_coding_method.data.partitioned_rice.order,
  99774. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  99775. ))
  99776. return false;
  99777. break;
  99778. default:
  99779. FLAC__ASSERT(0);
  99780. }
  99781. return true;
  99782. }
  99783. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99784. {
  99785. unsigned i;
  99786. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  99787. return false;
  99788. if(wasted_bits)
  99789. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99790. return false;
  99791. for(i = 0; i < subframe->order; i++)
  99792. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  99793. return false;
  99794. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  99795. return false;
  99796. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  99797. return false;
  99798. for(i = 0; i < subframe->order; i++)
  99799. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  99800. return false;
  99801. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  99802. return false;
  99803. switch(subframe->entropy_coding_method.type) {
  99804. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99805. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99806. if(!add_residual_partitioned_rice_(
  99807. bw,
  99808. subframe->residual,
  99809. residual_samples,
  99810. subframe->order,
  99811. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  99812. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  99813. subframe->entropy_coding_method.data.partitioned_rice.order,
  99814. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  99815. ))
  99816. return false;
  99817. break;
  99818. default:
  99819. FLAC__ASSERT(0);
  99820. }
  99821. return true;
  99822. }
  99823. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99824. {
  99825. unsigned i;
  99826. const FLAC__int32 *signal = subframe->data;
  99827. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  99828. return false;
  99829. if(wasted_bits)
  99830. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99831. return false;
  99832. for(i = 0; i < samples; i++)
  99833. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  99834. return false;
  99835. return true;
  99836. }
  99837. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  99838. {
  99839. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  99840. return false;
  99841. switch(method->type) {
  99842. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99843. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99844. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99845. return false;
  99846. break;
  99847. default:
  99848. FLAC__ASSERT(0);
  99849. }
  99850. return true;
  99851. }
  99852. FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
  99853. {
  99854. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  99855. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  99856. if(partition_order == 0) {
  99857. unsigned i;
  99858. if(raw_bits[0] == 0) {
  99859. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  99860. return false;
  99861. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  99862. return false;
  99863. }
  99864. else {
  99865. FLAC__ASSERT(rice_parameters[0] == 0);
  99866. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  99867. return false;
  99868. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  99869. return false;
  99870. for(i = 0; i < residual_samples; i++) {
  99871. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  99872. return false;
  99873. }
  99874. }
  99875. return true;
  99876. }
  99877. else {
  99878. unsigned i, j, k = 0, k_last = 0;
  99879. unsigned partition_samples;
  99880. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  99881. for(i = 0; i < (1u<<partition_order); i++) {
  99882. partition_samples = default_partition_samples;
  99883. if(i == 0)
  99884. partition_samples -= predictor_order;
  99885. k += partition_samples;
  99886. if(raw_bits[i] == 0) {
  99887. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  99888. return false;
  99889. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  99890. return false;
  99891. }
  99892. else {
  99893. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  99894. return false;
  99895. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  99896. return false;
  99897. for(j = k_last; j < k; j++) {
  99898. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  99899. return false;
  99900. }
  99901. }
  99902. k_last = k;
  99903. }
  99904. return true;
  99905. }
  99906. }
  99907. #endif
  99908. /********* End of inlined file: stream_encoder_framing.c *********/
  99909. /********* Start of inlined file: window_flac.c *********/
  99910. /********* Start of inlined file: juce_FlacHeader.h *********/
  99911. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99912. // tasks..
  99913. #define VERSION "1.2.1"
  99914. #define FLAC__NO_DLL 1
  99915. #ifdef _MSC_VER
  99916. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99917. #endif
  99918. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  99919. #define FLAC__SYS_DARWIN 1
  99920. #endif
  99921. /********* End of inlined file: juce_FlacHeader.h *********/
  99922. #if JUCE_USE_FLAC
  99923. #if HAVE_CONFIG_H
  99924. # include <config.h>
  99925. #endif
  99926. #include <math.h>
  99927. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99928. #ifndef M_PI
  99929. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  99930. #define M_PI 3.14159265358979323846
  99931. #endif
  99932. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  99933. {
  99934. const FLAC__int32 N = L - 1;
  99935. FLAC__int32 n;
  99936. if (L & 1) {
  99937. for (n = 0; n <= N/2; n++)
  99938. window[n] = 2.0f * n / (float)N;
  99939. for (; n <= N; n++)
  99940. window[n] = 2.0f - 2.0f * n / (float)N;
  99941. }
  99942. else {
  99943. for (n = 0; n <= L/2-1; n++)
  99944. window[n] = 2.0f * n / (float)N;
  99945. for (; n <= N; n++)
  99946. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  99947. }
  99948. }
  99949. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  99950. {
  99951. const FLAC__int32 N = L - 1;
  99952. FLAC__int32 n;
  99953. for (n = 0; n < L; n++)
  99954. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  99955. }
  99956. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  99957. {
  99958. const FLAC__int32 N = L - 1;
  99959. FLAC__int32 n;
  99960. for (n = 0; n < L; n++)
  99961. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  99962. }
  99963. /* 4-term -92dB side-lobe */
  99964. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  99965. {
  99966. const FLAC__int32 N = L - 1;
  99967. FLAC__int32 n;
  99968. for (n = 0; n <= N; n++)
  99969. window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
  99970. }
  99971. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  99972. {
  99973. const FLAC__int32 N = L - 1;
  99974. const double N2 = (double)N / 2.;
  99975. FLAC__int32 n;
  99976. for (n = 0; n <= N; n++) {
  99977. double k = ((double)n - N2) / N2;
  99978. k = 1.0f - k * k;
  99979. window[n] = (FLAC__real)(k * k);
  99980. }
  99981. }
  99982. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  99983. {
  99984. const FLAC__int32 N = L - 1;
  99985. FLAC__int32 n;
  99986. for (n = 0; n < L; n++)
  99987. window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
  99988. }
  99989. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  99990. {
  99991. const FLAC__int32 N = L - 1;
  99992. const double N2 = (double)N / 2.;
  99993. FLAC__int32 n;
  99994. for (n = 0; n <= N; n++) {
  99995. const double k = ((double)n - N2) / (stddev * N2);
  99996. window[n] = (FLAC__real)exp(-0.5f * k * k);
  99997. }
  99998. }
  99999. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  100000. {
  100001. const FLAC__int32 N = L - 1;
  100002. FLAC__int32 n;
  100003. for (n = 0; n < L; n++)
  100004. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  100005. }
  100006. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  100007. {
  100008. const FLAC__int32 N = L - 1;
  100009. FLAC__int32 n;
  100010. for (n = 0; n < L; n++)
  100011. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  100012. }
  100013. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  100014. {
  100015. const FLAC__int32 N = L - 1;
  100016. FLAC__int32 n;
  100017. for (n = 0; n < L; n++)
  100018. window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
  100019. }
  100020. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  100021. {
  100022. const FLAC__int32 N = L - 1;
  100023. FLAC__int32 n;
  100024. for (n = 0; n < L; n++)
  100025. window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
  100026. }
  100027. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  100028. {
  100029. FLAC__int32 n;
  100030. for (n = 0; n < L; n++)
  100031. window[n] = 1.0f;
  100032. }
  100033. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  100034. {
  100035. FLAC__int32 n;
  100036. if (L & 1) {
  100037. for (n = 1; n <= L+1/2; n++)
  100038. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  100039. for (; n <= L; n++)
  100040. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  100041. }
  100042. else {
  100043. for (n = 1; n <= L/2; n++)
  100044. window[n-1] = 2.0f * n / (float)L;
  100045. for (; n <= L; n++)
  100046. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  100047. }
  100048. }
  100049. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  100050. {
  100051. if (p <= 0.0)
  100052. FLAC__window_rectangle(window, L);
  100053. else if (p >= 1.0)
  100054. FLAC__window_hann(window, L);
  100055. else {
  100056. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  100057. FLAC__int32 n;
  100058. /* start with rectangle... */
  100059. FLAC__window_rectangle(window, L);
  100060. /* ...replace ends with hann */
  100061. if (Np > 0) {
  100062. for (n = 0; n <= Np; n++) {
  100063. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  100064. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  100065. }
  100066. }
  100067. }
  100068. }
  100069. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  100070. {
  100071. const FLAC__int32 N = L - 1;
  100072. const double N2 = (double)N / 2.;
  100073. FLAC__int32 n;
  100074. for (n = 0; n <= N; n++) {
  100075. const double k = ((double)n - N2) / N2;
  100076. window[n] = (FLAC__real)(1.0f - k * k);
  100077. }
  100078. }
  100079. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100080. #endif
  100081. /********* End of inlined file: window_flac.c *********/
  100082. }
  100083. #ifdef _MSC_VER
  100084. #pragma warning (pop)
  100085. #endif
  100086. BEGIN_JUCE_NAMESPACE
  100087. using namespace FlacNamespace;
  100088. #define flacFormatName TRANS("FLAC file")
  100089. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  100090. class FlacReader : public AudioFormatReader
  100091. {
  100092. FLAC__StreamDecoder* decoder;
  100093. AudioSampleBuffer reservoir;
  100094. int reservoirStart, samplesInReservoir;
  100095. bool ok, scanningForLength;
  100096. public:
  100097. FlacReader (InputStream* const in)
  100098. : AudioFormatReader (in, flacFormatName),
  100099. reservoir (2, 0),
  100100. reservoirStart (0),
  100101. samplesInReservoir (0),
  100102. scanningForLength (false)
  100103. {
  100104. using namespace FlacNamespace;
  100105. lengthInSamples = 0;
  100106. decoder = FLAC__stream_decoder_new();
  100107. ok = FLAC__stream_decoder_init_stream (decoder,
  100108. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  100109. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  100110. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  100111. if (ok)
  100112. {
  100113. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100114. if (lengthInSamples == 0 && sampleRate > 0)
  100115. {
  100116. // the length hasn't been stored in the metadata, so we'll need to
  100117. // work it out the length the hard way, by scanning the whole file..
  100118. scanningForLength = true;
  100119. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  100120. scanningForLength = false;
  100121. const int64 tempLength = lengthInSamples;
  100122. FLAC__stream_decoder_reset (decoder);
  100123. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100124. lengthInSamples = tempLength;
  100125. }
  100126. }
  100127. }
  100128. ~FlacReader()
  100129. {
  100130. FLAC__stream_decoder_delete (decoder);
  100131. }
  100132. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  100133. {
  100134. sampleRate = info.sample_rate;
  100135. bitsPerSample = info.bits_per_sample;
  100136. lengthInSamples = (unsigned int) info.total_samples;
  100137. numChannels = info.channels;
  100138. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  100139. }
  100140. // returns the number of samples read
  100141. bool read (int** destSamples,
  100142. int64 startSampleInFile,
  100143. int numSamples)
  100144. {
  100145. using namespace FlacNamespace;
  100146. if (! ok)
  100147. return false;
  100148. int offset = 0;
  100149. if (startSampleInFile < 0)
  100150. {
  100151. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  100152. int n = 0;
  100153. while (destSamples[n] != 0)
  100154. {
  100155. zeromem (destSamples[n], sizeof (int) * num);
  100156. ++n;
  100157. }
  100158. offset += num;
  100159. startSampleInFile += num;
  100160. numSamples -= num;
  100161. }
  100162. while (numSamples > 0)
  100163. {
  100164. if (startSampleInFile >= reservoirStart
  100165. && startSampleInFile < reservoirStart + samplesInReservoir)
  100166. {
  100167. const int num = (int) jmin ((int64) numSamples,
  100168. reservoirStart + samplesInReservoir - startSampleInFile);
  100169. jassert (num > 0);
  100170. int n = 0;
  100171. while (destSamples[n] != 0)
  100172. {
  100173. memcpy (destSamples[n] + offset,
  100174. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  100175. sizeof (int) * num);
  100176. ++n;
  100177. }
  100178. offset += num;
  100179. startSampleInFile += num;
  100180. numSamples -= num;
  100181. }
  100182. else
  100183. {
  100184. if (startSampleInFile < reservoirStart
  100185. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  100186. {
  100187. if (startSampleInFile >= (int) lengthInSamples)
  100188. {
  100189. samplesInReservoir = 0;
  100190. break;
  100191. }
  100192. // had some problems with flac crashing if the read pos is aligned more
  100193. // accurately than this. Probably fixed in newer versions of the library, though.
  100194. reservoirStart = (int) (startSampleInFile & ~511);
  100195. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  100196. }
  100197. else
  100198. {
  100199. reservoirStart += samplesInReservoir;
  100200. }
  100201. samplesInReservoir = 0;
  100202. FLAC__stream_decoder_process_single (decoder);
  100203. if (samplesInReservoir == 0)
  100204. break;
  100205. }
  100206. }
  100207. if (numSamples > 0)
  100208. {
  100209. int n = 0;
  100210. while (destSamples[n] != 0)
  100211. {
  100212. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  100213. ++n;
  100214. }
  100215. }
  100216. return true;
  100217. }
  100218. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  100219. {
  100220. if (scanningForLength)
  100221. {
  100222. lengthInSamples += numSamples;
  100223. }
  100224. else
  100225. {
  100226. if (numSamples > reservoir.getNumSamples())
  100227. reservoir.setSize (numChannels, numSamples, false, false, true);
  100228. const int bitsToShift = 32 - bitsPerSample;
  100229. for (int i = 0; i < (int) numChannels; ++i)
  100230. {
  100231. const FLAC__int32* src = buffer[i];
  100232. int n = i;
  100233. while (src == 0 && n > 0)
  100234. src = buffer [--n];
  100235. if (src != 0)
  100236. {
  100237. int* dest = (int*) reservoir.getSampleData(i);
  100238. for (int j = 0; j < numSamples; ++j)
  100239. dest[j] = src[j] << bitsToShift;
  100240. }
  100241. }
  100242. samplesInReservoir = numSamples;
  100243. }
  100244. }
  100245. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  100246. {
  100247. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  100248. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100249. }
  100250. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  100251. {
  100252. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  100253. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100254. }
  100255. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  100256. {
  100257. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  100258. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100259. }
  100260. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  100261. {
  100262. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  100263. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100264. }
  100265. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  100266. {
  100267. return ((const FlacReader*) client_data)->input->isExhausted();
  100268. }
  100269. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  100270. const FLAC__Frame* frame,
  100271. const FLAC__int32* const buffer[],
  100272. void* client_data)
  100273. {
  100274. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  100275. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100276. }
  100277. static void metadataCallback_ (const FLAC__StreamDecoder*,
  100278. const FLAC__StreamMetadata* metadata,
  100279. void* client_data)
  100280. {
  100281. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  100282. }
  100283. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  100284. {
  100285. }
  100286. juce_UseDebuggingNewOperator
  100287. };
  100288. class FlacWriter : public AudioFormatWriter
  100289. {
  100290. FLAC__StreamEncoder* encoder;
  100291. MemoryBlock temp;
  100292. public:
  100293. bool ok;
  100294. FlacWriter (OutputStream* const out,
  100295. const double sampleRate,
  100296. const int numChannels,
  100297. const int bitsPerSample_)
  100298. : AudioFormatWriter (out, flacFormatName,
  100299. sampleRate,
  100300. numChannels,
  100301. bitsPerSample_)
  100302. {
  100303. using namespace FlacNamespace;
  100304. encoder = FLAC__stream_encoder_new();
  100305. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  100306. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  100307. FLAC__stream_encoder_set_channels (encoder, numChannels);
  100308. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  100309. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  100310. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  100311. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  100312. ok = FLAC__stream_encoder_init_stream (encoder,
  100313. encodeWriteCallback, encodeSeekCallback,
  100314. encodeTellCallback, encodeMetadataCallback,
  100315. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  100316. }
  100317. ~FlacWriter()
  100318. {
  100319. if (ok)
  100320. {
  100321. FLAC__stream_encoder_finish (encoder);
  100322. output->flush();
  100323. }
  100324. else
  100325. {
  100326. output = 0; // to stop the base class deleting this, as it needs to be returned
  100327. // to the caller of createWriter()
  100328. }
  100329. FLAC__stream_encoder_delete (encoder);
  100330. }
  100331. bool write (const int** samplesToWrite, int numSamples)
  100332. {
  100333. if (! ok)
  100334. return false;
  100335. int* buf[3];
  100336. const int bitsToShift = 32 - bitsPerSample;
  100337. if (bitsToShift > 0)
  100338. {
  100339. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  100340. temp.setSize (sizeof (int) * numSamples * numChannels);
  100341. buf[0] = (int*) temp.getData();
  100342. buf[1] = buf[0] + numSamples;
  100343. buf[2] = 0;
  100344. for (int i = numChannels; --i >= 0;)
  100345. {
  100346. if (samplesToWrite[i] != 0)
  100347. {
  100348. for (int j = 0; j < numSamples; ++j)
  100349. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  100350. }
  100351. }
  100352. samplesToWrite = (const int**) buf;
  100353. }
  100354. return FLAC__stream_encoder_process (encoder,
  100355. (const FLAC__int32**) samplesToWrite,
  100356. numSamples) != 0;
  100357. }
  100358. bool writeData (const void* const data, const int size) const
  100359. {
  100360. return output->write (data, size);
  100361. }
  100362. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  100363. {
  100364. b += bytes;
  100365. for (int i = 0; i < bytes; ++i)
  100366. {
  100367. *(--b) = (FLAC__byte) (val & 0xff);
  100368. val >>= 8;
  100369. }
  100370. }
  100371. void writeMetaData (const FLAC__StreamMetadata* metadata)
  100372. {
  100373. using namespace FlacNamespace;
  100374. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  100375. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  100376. const unsigned int channelsMinus1 = info.channels - 1;
  100377. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  100378. packUint32 (info.min_blocksize, buffer, 2);
  100379. packUint32 (info.max_blocksize, buffer + 2, 2);
  100380. packUint32 (info.min_framesize, buffer + 4, 3);
  100381. packUint32 (info.max_framesize, buffer + 7, 3);
  100382. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  100383. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  100384. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  100385. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  100386. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  100387. memcpy (buffer + 18, info.md5sum, 16);
  100388. const bool ok = output->setPosition (4);
  100389. (void) ok;
  100390. // if this fails, you've given it an output stream that can't seek! It needs
  100391. // to be able to seek back to write the header
  100392. jassert (ok);
  100393. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  100394. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  100395. }
  100396. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  100397. const FLAC__byte buffer[],
  100398. size_t bytes,
  100399. unsigned int /*samples*/,
  100400. unsigned int /*current_frame*/,
  100401. void* client_data)
  100402. {
  100403. using namespace FlacNamespace;
  100404. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  100405. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  100406. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100407. }
  100408. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  100409. {
  100410. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  100411. }
  100412. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  100413. {
  100414. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  100415. }
  100416. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  100417. const FLAC__StreamMetadata* metadata,
  100418. void* client_data)
  100419. {
  100420. ((FlacWriter*) client_data)->writeMetaData (metadata);
  100421. }
  100422. juce_UseDebuggingNewOperator
  100423. };
  100424. FlacAudioFormat::FlacAudioFormat()
  100425. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  100426. {
  100427. }
  100428. FlacAudioFormat::~FlacAudioFormat()
  100429. {
  100430. }
  100431. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  100432. {
  100433. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  100434. return Array <int> (rates);
  100435. }
  100436. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  100437. {
  100438. const int depths[] = { 16, 24, 0 };
  100439. return Array <int> (depths);
  100440. }
  100441. bool FlacAudioFormat::canDoStereo()
  100442. {
  100443. return true;
  100444. }
  100445. bool FlacAudioFormat::canDoMono()
  100446. {
  100447. return true;
  100448. }
  100449. bool FlacAudioFormat::isCompressed()
  100450. {
  100451. return true;
  100452. }
  100453. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  100454. const bool deleteStreamIfOpeningFails)
  100455. {
  100456. FlacReader* r = new FlacReader (in);
  100457. if (r->sampleRate == 0)
  100458. {
  100459. if (! deleteStreamIfOpeningFails)
  100460. r->input = 0;
  100461. deleteAndZero (r);
  100462. }
  100463. return r;
  100464. }
  100465. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  100466. double sampleRate,
  100467. unsigned int numberOfChannels,
  100468. int bitsPerSample,
  100469. const StringPairArray& /*metadataValues*/,
  100470. int /*qualityOptionIndex*/)
  100471. {
  100472. if (getPossibleBitDepths().contains (bitsPerSample))
  100473. {
  100474. FlacWriter* w = new FlacWriter (out,
  100475. sampleRate,
  100476. numberOfChannels,
  100477. bitsPerSample);
  100478. if (! w->ok)
  100479. deleteAndZero (w);
  100480. return w;
  100481. }
  100482. return 0;
  100483. }
  100484. END_JUCE_NAMESPACE
  100485. #endif
  100486. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  100487. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  100488. #if JUCE_USE_OGGVORBIS
  100489. #if JUCE_MAC
  100490. #define __MACOSX__ 1
  100491. #endif
  100492. namespace OggVorbisNamespace
  100493. {
  100494. /********* Start of inlined file: vorbisenc.h *********/
  100495. #ifndef _OV_ENC_H_
  100496. #define _OV_ENC_H_
  100497. #ifdef __cplusplus
  100498. extern "C"
  100499. {
  100500. #endif /* __cplusplus */
  100501. /********* Start of inlined file: codec.h *********/
  100502. #ifndef _vorbis_codec_h_
  100503. #define _vorbis_codec_h_
  100504. #ifdef __cplusplus
  100505. extern "C"
  100506. {
  100507. #endif /* __cplusplus */
  100508. /********* Start of inlined file: ogg.h *********/
  100509. #ifndef _OGG_H
  100510. #define _OGG_H
  100511. #ifdef __cplusplus
  100512. extern "C" {
  100513. #endif
  100514. /********* Start of inlined file: os_types.h *********/
  100515. #ifndef _OS_TYPES_H
  100516. #define _OS_TYPES_H
  100517. /* make it easy on the folks that want to compile the libs with a
  100518. different malloc than stdlib */
  100519. #define _ogg_malloc malloc
  100520. #define _ogg_calloc calloc
  100521. #define _ogg_realloc realloc
  100522. #define _ogg_free free
  100523. #if defined(_WIN32)
  100524. # if defined(__CYGWIN__)
  100525. # include <_G_config.h>
  100526. typedef _G_int64_t ogg_int64_t;
  100527. typedef _G_int32_t ogg_int32_t;
  100528. typedef _G_uint32_t ogg_uint32_t;
  100529. typedef _G_int16_t ogg_int16_t;
  100530. typedef _G_uint16_t ogg_uint16_t;
  100531. # elif defined(__MINGW32__)
  100532. typedef short ogg_int16_t;
  100533. typedef unsigned short ogg_uint16_t;
  100534. typedef int ogg_int32_t;
  100535. typedef unsigned int ogg_uint32_t;
  100536. typedef long long ogg_int64_t;
  100537. typedef unsigned long long ogg_uint64_t;
  100538. # elif defined(__MWERKS__)
  100539. typedef long long ogg_int64_t;
  100540. typedef int ogg_int32_t;
  100541. typedef unsigned int ogg_uint32_t;
  100542. typedef short ogg_int16_t;
  100543. typedef unsigned short ogg_uint16_t;
  100544. # else
  100545. /* MSVC/Borland */
  100546. typedef __int64 ogg_int64_t;
  100547. typedef __int32 ogg_int32_t;
  100548. typedef unsigned __int32 ogg_uint32_t;
  100549. typedef __int16 ogg_int16_t;
  100550. typedef unsigned __int16 ogg_uint16_t;
  100551. # endif
  100552. #elif defined(__MACOS__)
  100553. # include <sys/types.h>
  100554. typedef SInt16 ogg_int16_t;
  100555. typedef UInt16 ogg_uint16_t;
  100556. typedef SInt32 ogg_int32_t;
  100557. typedef UInt32 ogg_uint32_t;
  100558. typedef SInt64 ogg_int64_t;
  100559. #elif defined(__MACOSX__) /* MacOS X Framework build */
  100560. # include <sys/types.h>
  100561. typedef int16_t ogg_int16_t;
  100562. typedef u_int16_t ogg_uint16_t;
  100563. typedef int32_t ogg_int32_t;
  100564. typedef u_int32_t ogg_uint32_t;
  100565. typedef int64_t ogg_int64_t;
  100566. #elif defined(__BEOS__)
  100567. /* Be */
  100568. # include <inttypes.h>
  100569. typedef int16_t ogg_int16_t;
  100570. typedef u_int16_t ogg_uint16_t;
  100571. typedef int32_t ogg_int32_t;
  100572. typedef u_int32_t ogg_uint32_t;
  100573. typedef int64_t ogg_int64_t;
  100574. #elif defined (__EMX__)
  100575. /* OS/2 GCC */
  100576. typedef short ogg_int16_t;
  100577. typedef unsigned short ogg_uint16_t;
  100578. typedef int ogg_int32_t;
  100579. typedef unsigned int ogg_uint32_t;
  100580. typedef long long ogg_int64_t;
  100581. #elif defined (DJGPP)
  100582. /* DJGPP */
  100583. typedef short ogg_int16_t;
  100584. typedef int ogg_int32_t;
  100585. typedef unsigned int ogg_uint32_t;
  100586. typedef long long ogg_int64_t;
  100587. #elif defined(R5900)
  100588. /* PS2 EE */
  100589. typedef long ogg_int64_t;
  100590. typedef int ogg_int32_t;
  100591. typedef unsigned ogg_uint32_t;
  100592. typedef short ogg_int16_t;
  100593. #elif defined(__SYMBIAN32__)
  100594. /* Symbian GCC */
  100595. typedef signed short ogg_int16_t;
  100596. typedef unsigned short ogg_uint16_t;
  100597. typedef signed int ogg_int32_t;
  100598. typedef unsigned int ogg_uint32_t;
  100599. typedef long long int ogg_int64_t;
  100600. #else
  100601. # include <sys/types.h>
  100602. /********* Start of inlined file: config_types.h *********/
  100603. #ifndef __CONFIG_TYPES_H__
  100604. #define __CONFIG_TYPES_H__
  100605. typedef int16_t ogg_int16_t;
  100606. typedef unsigned short ogg_uint16_t;
  100607. typedef int32_t ogg_int32_t;
  100608. typedef unsigned int ogg_uint32_t;
  100609. typedef int64_t ogg_int64_t;
  100610. #endif
  100611. /********* End of inlined file: config_types.h *********/
  100612. #endif
  100613. #endif /* _OS_TYPES_H */
  100614. /********* End of inlined file: os_types.h *********/
  100615. typedef struct {
  100616. long endbyte;
  100617. int endbit;
  100618. unsigned char *buffer;
  100619. unsigned char *ptr;
  100620. long storage;
  100621. } oggpack_buffer;
  100622. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  100623. typedef struct {
  100624. unsigned char *header;
  100625. long header_len;
  100626. unsigned char *body;
  100627. long body_len;
  100628. } ogg_page;
  100629. ogg_uint32_t bitreverse(ogg_uint32_t x){
  100630. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  100631. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  100632. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  100633. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  100634. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  100635. }
  100636. /* ogg_stream_state contains the current encode/decode state of a logical
  100637. Ogg bitstream **********************************************************/
  100638. typedef struct {
  100639. unsigned char *body_data; /* bytes from packet bodies */
  100640. long body_storage; /* storage elements allocated */
  100641. long body_fill; /* elements stored; fill mark */
  100642. long body_returned; /* elements of fill returned */
  100643. int *lacing_vals; /* The values that will go to the segment table */
  100644. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  100645. this way, but it is simple coupled to the
  100646. lacing fifo */
  100647. long lacing_storage;
  100648. long lacing_fill;
  100649. long lacing_packet;
  100650. long lacing_returned;
  100651. unsigned char header[282]; /* working space for header encode */
  100652. int header_fill;
  100653. int e_o_s; /* set when we have buffered the last packet in the
  100654. logical bitstream */
  100655. int b_o_s; /* set after we've written the initial page
  100656. of a logical bitstream */
  100657. long serialno;
  100658. long pageno;
  100659. ogg_int64_t packetno; /* sequence number for decode; the framing
  100660. knows where there's a hole in the data,
  100661. but we need coupling so that the codec
  100662. (which is in a seperate abstraction
  100663. layer) also knows about the gap */
  100664. ogg_int64_t granulepos;
  100665. } ogg_stream_state;
  100666. /* ogg_packet is used to encapsulate the data and metadata belonging
  100667. to a single raw Ogg/Vorbis packet *************************************/
  100668. typedef struct {
  100669. unsigned char *packet;
  100670. long bytes;
  100671. long b_o_s;
  100672. long e_o_s;
  100673. ogg_int64_t granulepos;
  100674. ogg_int64_t packetno; /* sequence number for decode; the framing
  100675. knows where there's a hole in the data,
  100676. but we need coupling so that the codec
  100677. (which is in a seperate abstraction
  100678. layer) also knows about the gap */
  100679. } ogg_packet;
  100680. typedef struct {
  100681. unsigned char *data;
  100682. int storage;
  100683. int fill;
  100684. int returned;
  100685. int unsynced;
  100686. int headerbytes;
  100687. int bodybytes;
  100688. } ogg_sync_state;
  100689. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  100690. extern void oggpack_writeinit(oggpack_buffer *b);
  100691. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  100692. extern void oggpack_writealign(oggpack_buffer *b);
  100693. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  100694. extern void oggpack_reset(oggpack_buffer *b);
  100695. extern void oggpack_writeclear(oggpack_buffer *b);
  100696. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  100697. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  100698. extern long oggpack_look(oggpack_buffer *b,int bits);
  100699. extern long oggpack_look1(oggpack_buffer *b);
  100700. extern void oggpack_adv(oggpack_buffer *b,int bits);
  100701. extern void oggpack_adv1(oggpack_buffer *b);
  100702. extern long oggpack_read(oggpack_buffer *b,int bits);
  100703. extern long oggpack_read1(oggpack_buffer *b);
  100704. extern long oggpack_bytes(oggpack_buffer *b);
  100705. extern long oggpack_bits(oggpack_buffer *b);
  100706. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  100707. extern void oggpackB_writeinit(oggpack_buffer *b);
  100708. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  100709. extern void oggpackB_writealign(oggpack_buffer *b);
  100710. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  100711. extern void oggpackB_reset(oggpack_buffer *b);
  100712. extern void oggpackB_writeclear(oggpack_buffer *b);
  100713. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  100714. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  100715. extern long oggpackB_look(oggpack_buffer *b,int bits);
  100716. extern long oggpackB_look1(oggpack_buffer *b);
  100717. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  100718. extern void oggpackB_adv1(oggpack_buffer *b);
  100719. extern long oggpackB_read(oggpack_buffer *b,int bits);
  100720. extern long oggpackB_read1(oggpack_buffer *b);
  100721. extern long oggpackB_bytes(oggpack_buffer *b);
  100722. extern long oggpackB_bits(oggpack_buffer *b);
  100723. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  100724. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  100725. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  100726. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  100727. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  100728. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  100729. extern int ogg_sync_init(ogg_sync_state *oy);
  100730. extern int ogg_sync_clear(ogg_sync_state *oy);
  100731. extern int ogg_sync_reset(ogg_sync_state *oy);
  100732. extern int ogg_sync_destroy(ogg_sync_state *oy);
  100733. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  100734. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  100735. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  100736. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  100737. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  100738. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  100739. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  100740. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  100741. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  100742. extern int ogg_stream_clear(ogg_stream_state *os);
  100743. extern int ogg_stream_reset(ogg_stream_state *os);
  100744. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  100745. extern int ogg_stream_destroy(ogg_stream_state *os);
  100746. extern int ogg_stream_eos(ogg_stream_state *os);
  100747. extern void ogg_page_checksum_set(ogg_page *og);
  100748. extern int ogg_page_version(ogg_page *og);
  100749. extern int ogg_page_continued(ogg_page *og);
  100750. extern int ogg_page_bos(ogg_page *og);
  100751. extern int ogg_page_eos(ogg_page *og);
  100752. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  100753. extern int ogg_page_serialno(ogg_page *og);
  100754. extern long ogg_page_pageno(ogg_page *og);
  100755. extern int ogg_page_packets(ogg_page *og);
  100756. extern void ogg_packet_clear(ogg_packet *op);
  100757. #ifdef __cplusplus
  100758. }
  100759. #endif
  100760. #endif /* _OGG_H */
  100761. /********* End of inlined file: ogg.h *********/
  100762. typedef struct vorbis_info{
  100763. int version;
  100764. int channels;
  100765. long rate;
  100766. /* The below bitrate declarations are *hints*.
  100767. Combinations of the three values carry the following implications:
  100768. all three set to the same value:
  100769. implies a fixed rate bitstream
  100770. only nominal set:
  100771. implies a VBR stream that averages the nominal bitrate. No hard
  100772. upper/lower limit
  100773. upper and or lower set:
  100774. implies a VBR bitstream that obeys the bitrate limits. nominal
  100775. may also be set to give a nominal rate.
  100776. none set:
  100777. the coder does not care to speculate.
  100778. */
  100779. long bitrate_upper;
  100780. long bitrate_nominal;
  100781. long bitrate_lower;
  100782. long bitrate_window;
  100783. void *codec_setup;
  100784. } vorbis_info;
  100785. /* vorbis_dsp_state buffers the current vorbis audio
  100786. analysis/synthesis state. The DSP state belongs to a specific
  100787. logical bitstream ****************************************************/
  100788. typedef struct vorbis_dsp_state{
  100789. int analysisp;
  100790. vorbis_info *vi;
  100791. float **pcm;
  100792. float **pcmret;
  100793. int pcm_storage;
  100794. int pcm_current;
  100795. int pcm_returned;
  100796. int preextrapolate;
  100797. int eofflag;
  100798. long lW;
  100799. long W;
  100800. long nW;
  100801. long centerW;
  100802. ogg_int64_t granulepos;
  100803. ogg_int64_t sequence;
  100804. ogg_int64_t glue_bits;
  100805. ogg_int64_t time_bits;
  100806. ogg_int64_t floor_bits;
  100807. ogg_int64_t res_bits;
  100808. void *backend_state;
  100809. } vorbis_dsp_state;
  100810. typedef struct vorbis_block{
  100811. /* necessary stream state for linking to the framing abstraction */
  100812. float **pcm; /* this is a pointer into local storage */
  100813. oggpack_buffer opb;
  100814. long lW;
  100815. long W;
  100816. long nW;
  100817. int pcmend;
  100818. int mode;
  100819. int eofflag;
  100820. ogg_int64_t granulepos;
  100821. ogg_int64_t sequence;
  100822. vorbis_dsp_state *vd; /* For read-only access of configuration */
  100823. /* local storage to avoid remallocing; it's up to the mapping to
  100824. structure it */
  100825. void *localstore;
  100826. long localtop;
  100827. long localalloc;
  100828. long totaluse;
  100829. struct alloc_chain *reap;
  100830. /* bitmetrics for the frame */
  100831. long glue_bits;
  100832. long time_bits;
  100833. long floor_bits;
  100834. long res_bits;
  100835. void *internal;
  100836. } vorbis_block;
  100837. /* vorbis_block is a single block of data to be processed as part of
  100838. the analysis/synthesis stream; it belongs to a specific logical
  100839. bitstream, but is independant from other vorbis_blocks belonging to
  100840. that logical bitstream. *************************************************/
  100841. struct alloc_chain{
  100842. void *ptr;
  100843. struct alloc_chain *next;
  100844. };
  100845. /* vorbis_info contains all the setup information specific to the
  100846. specific compression/decompression mode in progress (eg,
  100847. psychoacoustic settings, channel setup, options, codebook
  100848. etc). vorbis_info and substructures are in backends.h.
  100849. *********************************************************************/
  100850. /* the comments are not part of vorbis_info so that vorbis_info can be
  100851. static storage */
  100852. typedef struct vorbis_comment{
  100853. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  100854. whatever vendor is set to in encode */
  100855. char **user_comments;
  100856. int *comment_lengths;
  100857. int comments;
  100858. char *vendor;
  100859. } vorbis_comment;
  100860. /* libvorbis encodes in two abstraction layers; first we perform DSP
  100861. and produce a packet (see docs/analysis.txt). The packet is then
  100862. coded into a framed OggSquish bitstream by the second layer (see
  100863. docs/framing.txt). Decode is the reverse process; we sync/frame
  100864. the bitstream and extract individual packets, then decode the
  100865. packet back into PCM audio.
  100866. The extra framing/packetizing is used in streaming formats, such as
  100867. files. Over the net (such as with UDP), the framing and
  100868. packetization aren't necessary as they're provided by the transport
  100869. and the streaming layer is not used */
  100870. /* Vorbis PRIMITIVES: general ***************************************/
  100871. extern void vorbis_info_init(vorbis_info *vi);
  100872. extern void vorbis_info_clear(vorbis_info *vi);
  100873. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  100874. extern void vorbis_comment_init(vorbis_comment *vc);
  100875. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  100876. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  100877. char *tag, char *contents);
  100878. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  100879. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  100880. extern void vorbis_comment_clear(vorbis_comment *vc);
  100881. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  100882. extern int vorbis_block_clear(vorbis_block *vb);
  100883. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  100884. extern double vorbis_granule_time(vorbis_dsp_state *v,
  100885. ogg_int64_t granulepos);
  100886. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  100887. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  100888. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  100889. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  100890. vorbis_comment *vc,
  100891. ogg_packet *op,
  100892. ogg_packet *op_comm,
  100893. ogg_packet *op_code);
  100894. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  100895. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  100896. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  100897. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  100898. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  100899. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  100900. ogg_packet *op);
  100901. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  100902. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  100903. ogg_packet *op);
  100904. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  100905. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  100906. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  100907. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  100908. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  100909. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  100910. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  100911. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  100912. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  100913. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  100914. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  100915. /* Vorbis ERRORS and return codes ***********************************/
  100916. #define OV_FALSE -1
  100917. #define OV_EOF -2
  100918. #define OV_HOLE -3
  100919. #define OV_EREAD -128
  100920. #define OV_EFAULT -129
  100921. #define OV_EIMPL -130
  100922. #define OV_EINVAL -131
  100923. #define OV_ENOTVORBIS -132
  100924. #define OV_EBADHEADER -133
  100925. #define OV_EVERSION -134
  100926. #define OV_ENOTAUDIO -135
  100927. #define OV_EBADPACKET -136
  100928. #define OV_EBADLINK -137
  100929. #define OV_ENOSEEK -138
  100930. #ifdef __cplusplus
  100931. }
  100932. #endif /* __cplusplus */
  100933. #endif
  100934. /********* End of inlined file: codec.h *********/
  100935. extern int vorbis_encode_init(vorbis_info *vi,
  100936. long channels,
  100937. long rate,
  100938. long max_bitrate,
  100939. long nominal_bitrate,
  100940. long min_bitrate);
  100941. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  100942. long channels,
  100943. long rate,
  100944. long max_bitrate,
  100945. long nominal_bitrate,
  100946. long min_bitrate);
  100947. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  100948. long channels,
  100949. long rate,
  100950. float quality /* quality level from 0. (lo) to 1. (hi) */
  100951. );
  100952. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  100953. long channels,
  100954. long rate,
  100955. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  100956. );
  100957. extern int vorbis_encode_setup_init(vorbis_info *vi);
  100958. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  100959. /* deprecated rate management supported only for compatability */
  100960. #define OV_ECTL_RATEMANAGE_GET 0x10
  100961. #define OV_ECTL_RATEMANAGE_SET 0x11
  100962. #define OV_ECTL_RATEMANAGE_AVG 0x12
  100963. #define OV_ECTL_RATEMANAGE_HARD 0x13
  100964. struct ovectl_ratemanage_arg {
  100965. int management_active;
  100966. long bitrate_hard_min;
  100967. long bitrate_hard_max;
  100968. double bitrate_hard_window;
  100969. long bitrate_av_lo;
  100970. long bitrate_av_hi;
  100971. double bitrate_av_window;
  100972. double bitrate_av_window_center;
  100973. };
  100974. /* new rate setup */
  100975. #define OV_ECTL_RATEMANAGE2_GET 0x14
  100976. #define OV_ECTL_RATEMANAGE2_SET 0x15
  100977. struct ovectl_ratemanage2_arg {
  100978. int management_active;
  100979. long bitrate_limit_min_kbps;
  100980. long bitrate_limit_max_kbps;
  100981. long bitrate_limit_reservoir_bits;
  100982. double bitrate_limit_reservoir_bias;
  100983. long bitrate_average_kbps;
  100984. double bitrate_average_damping;
  100985. };
  100986. #define OV_ECTL_LOWPASS_GET 0x20
  100987. #define OV_ECTL_LOWPASS_SET 0x21
  100988. #define OV_ECTL_IBLOCK_GET 0x30
  100989. #define OV_ECTL_IBLOCK_SET 0x31
  100990. #ifdef __cplusplus
  100991. }
  100992. #endif /* __cplusplus */
  100993. #endif
  100994. /********* End of inlined file: vorbisenc.h *********/
  100995. /********* Start of inlined file: vorbisfile.h *********/
  100996. #ifndef _OV_FILE_H_
  100997. #define _OV_FILE_H_
  100998. #ifdef __cplusplus
  100999. extern "C"
  101000. {
  101001. #endif /* __cplusplus */
  101002. #include <stdio.h>
  101003. /* The function prototypes for the callbacks are basically the same as for
  101004. * the stdio functions fread, fseek, fclose, ftell.
  101005. * The one difference is that the FILE * arguments have been replaced with
  101006. * a void * - this is to be used as a pointer to whatever internal data these
  101007. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  101008. *
  101009. * If you use other functions, check the docs for these functions and return
  101010. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  101011. * unseekable
  101012. */
  101013. typedef struct {
  101014. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  101015. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  101016. int (*close_func) (void *datasource);
  101017. long (*tell_func) (void *datasource);
  101018. } ov_callbacks;
  101019. #define NOTOPEN 0
  101020. #define PARTOPEN 1
  101021. #define OPENED 2
  101022. #define STREAMSET 3
  101023. #define INITSET 4
  101024. typedef struct OggVorbis_File {
  101025. void *datasource; /* Pointer to a FILE *, etc. */
  101026. int seekable;
  101027. ogg_int64_t offset;
  101028. ogg_int64_t end;
  101029. ogg_sync_state oy;
  101030. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  101031. stream appears */
  101032. int links;
  101033. ogg_int64_t *offsets;
  101034. ogg_int64_t *dataoffsets;
  101035. long *serialnos;
  101036. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  101037. compatability; x2 size, stores both
  101038. beginning and end values */
  101039. vorbis_info *vi;
  101040. vorbis_comment *vc;
  101041. /* Decoding working state local storage */
  101042. ogg_int64_t pcm_offset;
  101043. int ready_state;
  101044. long current_serialno;
  101045. int current_link;
  101046. double bittrack;
  101047. double samptrack;
  101048. ogg_stream_state os; /* take physical pages, weld into a logical
  101049. stream of packets */
  101050. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  101051. vorbis_block vb; /* local working space for packet->PCM decode */
  101052. ov_callbacks callbacks;
  101053. } OggVorbis_File;
  101054. extern int ov_clear(OggVorbis_File *vf);
  101055. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101056. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  101057. char *initial, long ibytes, ov_callbacks callbacks);
  101058. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101059. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  101060. char *initial, long ibytes, ov_callbacks callbacks);
  101061. extern int ov_test_open(OggVorbis_File *vf);
  101062. extern long ov_bitrate(OggVorbis_File *vf,int i);
  101063. extern long ov_bitrate_instant(OggVorbis_File *vf);
  101064. extern long ov_streams(OggVorbis_File *vf);
  101065. extern long ov_seekable(OggVorbis_File *vf);
  101066. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  101067. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  101068. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  101069. extern double ov_time_total(OggVorbis_File *vf,int i);
  101070. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101071. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101072. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  101073. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  101074. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  101075. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101076. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101077. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101078. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  101079. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  101080. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  101081. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  101082. extern double ov_time_tell(OggVorbis_File *vf);
  101083. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  101084. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  101085. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  101086. int *bitstream);
  101087. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  101088. int bigendianp,int word,int sgned,int *bitstream);
  101089. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  101090. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  101091. extern int ov_halfrate_p(OggVorbis_File *vf);
  101092. #ifdef __cplusplus
  101093. }
  101094. #endif /* __cplusplus */
  101095. #endif
  101096. /********* End of inlined file: vorbisfile.h *********/
  101097. /********* Start of inlined file: bitwise.c *********/
  101098. /* We're 'LSb' endian; if we write a word but read individual bits,
  101099. then we'll read the lsb first */
  101100. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101101. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101102. // tasks..
  101103. #ifdef _MSC_VER
  101104. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101105. #endif
  101106. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101107. #if JUCE_USE_OGGVORBIS
  101108. #include <string.h>
  101109. #include <stdlib.h>
  101110. #define BUFFER_INCREMENT 256
  101111. static const unsigned long mask[]=
  101112. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  101113. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  101114. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  101115. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  101116. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  101117. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  101118. 0x3fffffff,0x7fffffff,0xffffffff };
  101119. static const unsigned int mask8B[]=
  101120. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  101121. void oggpack_writeinit(oggpack_buffer *b){
  101122. memset(b,0,sizeof(*b));
  101123. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  101124. b->buffer[0]='\0';
  101125. b->storage=BUFFER_INCREMENT;
  101126. }
  101127. void oggpackB_writeinit(oggpack_buffer *b){
  101128. oggpack_writeinit(b);
  101129. }
  101130. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  101131. long bytes=bits>>3;
  101132. bits-=bytes*8;
  101133. b->ptr=b->buffer+bytes;
  101134. b->endbit=bits;
  101135. b->endbyte=bytes;
  101136. *b->ptr&=mask[bits];
  101137. }
  101138. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  101139. long bytes=bits>>3;
  101140. bits-=bytes*8;
  101141. b->ptr=b->buffer+bytes;
  101142. b->endbit=bits;
  101143. b->endbyte=bytes;
  101144. *b->ptr&=mask8B[bits];
  101145. }
  101146. /* Takes only up to 32 bits. */
  101147. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  101148. if(b->endbyte+4>=b->storage){
  101149. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101150. b->storage+=BUFFER_INCREMENT;
  101151. b->ptr=b->buffer+b->endbyte;
  101152. }
  101153. value&=mask[bits];
  101154. bits+=b->endbit;
  101155. b->ptr[0]|=value<<b->endbit;
  101156. if(bits>=8){
  101157. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  101158. if(bits>=16){
  101159. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  101160. if(bits>=24){
  101161. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  101162. if(bits>=32){
  101163. if(b->endbit)
  101164. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  101165. else
  101166. b->ptr[4]=0;
  101167. }
  101168. }
  101169. }
  101170. }
  101171. b->endbyte+=bits/8;
  101172. b->ptr+=bits/8;
  101173. b->endbit=bits&7;
  101174. }
  101175. /* Takes only up to 32 bits. */
  101176. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  101177. if(b->endbyte+4>=b->storage){
  101178. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101179. b->storage+=BUFFER_INCREMENT;
  101180. b->ptr=b->buffer+b->endbyte;
  101181. }
  101182. value=(value&mask[bits])<<(32-bits);
  101183. bits+=b->endbit;
  101184. b->ptr[0]|=value>>(24+b->endbit);
  101185. if(bits>=8){
  101186. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  101187. if(bits>=16){
  101188. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  101189. if(bits>=24){
  101190. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  101191. if(bits>=32){
  101192. if(b->endbit)
  101193. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  101194. else
  101195. b->ptr[4]=0;
  101196. }
  101197. }
  101198. }
  101199. }
  101200. b->endbyte+=bits/8;
  101201. b->ptr+=bits/8;
  101202. b->endbit=bits&7;
  101203. }
  101204. void oggpack_writealign(oggpack_buffer *b){
  101205. int bits=8-b->endbit;
  101206. if(bits<8)
  101207. oggpack_write(b,0,bits);
  101208. }
  101209. void oggpackB_writealign(oggpack_buffer *b){
  101210. int bits=8-b->endbit;
  101211. if(bits<8)
  101212. oggpackB_write(b,0,bits);
  101213. }
  101214. static void oggpack_writecopy_helper(oggpack_buffer *b,
  101215. void *source,
  101216. long bits,
  101217. void (*w)(oggpack_buffer *,
  101218. unsigned long,
  101219. int),
  101220. int msb){
  101221. unsigned char *ptr=(unsigned char *)source;
  101222. long bytes=bits/8;
  101223. bits-=bytes*8;
  101224. if(b->endbit){
  101225. int i;
  101226. /* unaligned copy. Do it the hard way. */
  101227. for(i=0;i<bytes;i++)
  101228. w(b,(unsigned long)(ptr[i]),8);
  101229. }else{
  101230. /* aligned block copy */
  101231. if(b->endbyte+bytes+1>=b->storage){
  101232. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  101233. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  101234. b->ptr=b->buffer+b->endbyte;
  101235. }
  101236. memmove(b->ptr,source,bytes);
  101237. b->ptr+=bytes;
  101238. b->endbyte+=bytes;
  101239. *b->ptr=0;
  101240. }
  101241. if(bits){
  101242. if(msb)
  101243. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  101244. else
  101245. w(b,(unsigned long)(ptr[bytes]),bits);
  101246. }
  101247. }
  101248. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  101249. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  101250. }
  101251. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  101252. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  101253. }
  101254. void oggpack_reset(oggpack_buffer *b){
  101255. b->ptr=b->buffer;
  101256. b->buffer[0]=0;
  101257. b->endbit=b->endbyte=0;
  101258. }
  101259. void oggpackB_reset(oggpack_buffer *b){
  101260. oggpack_reset(b);
  101261. }
  101262. void oggpack_writeclear(oggpack_buffer *b){
  101263. _ogg_free(b->buffer);
  101264. memset(b,0,sizeof(*b));
  101265. }
  101266. void oggpackB_writeclear(oggpack_buffer *b){
  101267. oggpack_writeclear(b);
  101268. }
  101269. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101270. memset(b,0,sizeof(*b));
  101271. b->buffer=b->ptr=buf;
  101272. b->storage=bytes;
  101273. }
  101274. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101275. oggpack_readinit(b,buf,bytes);
  101276. }
  101277. /* Read in bits without advancing the bitptr; bits <= 32 */
  101278. long oggpack_look(oggpack_buffer *b,int bits){
  101279. unsigned long ret;
  101280. unsigned long m=mask[bits];
  101281. bits+=b->endbit;
  101282. if(b->endbyte+4>=b->storage){
  101283. /* not the main path */
  101284. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101285. }
  101286. ret=b->ptr[0]>>b->endbit;
  101287. if(bits>8){
  101288. ret|=b->ptr[1]<<(8-b->endbit);
  101289. if(bits>16){
  101290. ret|=b->ptr[2]<<(16-b->endbit);
  101291. if(bits>24){
  101292. ret|=b->ptr[3]<<(24-b->endbit);
  101293. if(bits>32 && b->endbit)
  101294. ret|=b->ptr[4]<<(32-b->endbit);
  101295. }
  101296. }
  101297. }
  101298. return(m&ret);
  101299. }
  101300. /* Read in bits without advancing the bitptr; bits <= 32 */
  101301. long oggpackB_look(oggpack_buffer *b,int bits){
  101302. unsigned long ret;
  101303. int m=32-bits;
  101304. bits+=b->endbit;
  101305. if(b->endbyte+4>=b->storage){
  101306. /* not the main path */
  101307. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101308. }
  101309. ret=b->ptr[0]<<(24+b->endbit);
  101310. if(bits>8){
  101311. ret|=b->ptr[1]<<(16+b->endbit);
  101312. if(bits>16){
  101313. ret|=b->ptr[2]<<(8+b->endbit);
  101314. if(bits>24){
  101315. ret|=b->ptr[3]<<(b->endbit);
  101316. if(bits>32 && b->endbit)
  101317. ret|=b->ptr[4]>>(8-b->endbit);
  101318. }
  101319. }
  101320. }
  101321. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  101322. }
  101323. long oggpack_look1(oggpack_buffer *b){
  101324. if(b->endbyte>=b->storage)return(-1);
  101325. return((b->ptr[0]>>b->endbit)&1);
  101326. }
  101327. long oggpackB_look1(oggpack_buffer *b){
  101328. if(b->endbyte>=b->storage)return(-1);
  101329. return((b->ptr[0]>>(7-b->endbit))&1);
  101330. }
  101331. void oggpack_adv(oggpack_buffer *b,int bits){
  101332. bits+=b->endbit;
  101333. b->ptr+=bits/8;
  101334. b->endbyte+=bits/8;
  101335. b->endbit=bits&7;
  101336. }
  101337. void oggpackB_adv(oggpack_buffer *b,int bits){
  101338. oggpack_adv(b,bits);
  101339. }
  101340. void oggpack_adv1(oggpack_buffer *b){
  101341. if(++(b->endbit)>7){
  101342. b->endbit=0;
  101343. b->ptr++;
  101344. b->endbyte++;
  101345. }
  101346. }
  101347. void oggpackB_adv1(oggpack_buffer *b){
  101348. oggpack_adv1(b);
  101349. }
  101350. /* bits <= 32 */
  101351. long oggpack_read(oggpack_buffer *b,int bits){
  101352. long ret;
  101353. unsigned long m=mask[bits];
  101354. bits+=b->endbit;
  101355. if(b->endbyte+4>=b->storage){
  101356. /* not the main path */
  101357. ret=-1L;
  101358. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  101359. }
  101360. ret=b->ptr[0]>>b->endbit;
  101361. if(bits>8){
  101362. ret|=b->ptr[1]<<(8-b->endbit);
  101363. if(bits>16){
  101364. ret|=b->ptr[2]<<(16-b->endbit);
  101365. if(bits>24){
  101366. ret|=b->ptr[3]<<(24-b->endbit);
  101367. if(bits>32 && b->endbit){
  101368. ret|=b->ptr[4]<<(32-b->endbit);
  101369. }
  101370. }
  101371. }
  101372. }
  101373. ret&=m;
  101374. overflow:
  101375. b->ptr+=bits/8;
  101376. b->endbyte+=bits/8;
  101377. b->endbit=bits&7;
  101378. return(ret);
  101379. }
  101380. /* bits <= 32 */
  101381. long oggpackB_read(oggpack_buffer *b,int bits){
  101382. long ret;
  101383. long m=32-bits;
  101384. bits+=b->endbit;
  101385. if(b->endbyte+4>=b->storage){
  101386. /* not the main path */
  101387. ret=-1L;
  101388. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  101389. }
  101390. ret=b->ptr[0]<<(24+b->endbit);
  101391. if(bits>8){
  101392. ret|=b->ptr[1]<<(16+b->endbit);
  101393. if(bits>16){
  101394. ret|=b->ptr[2]<<(8+b->endbit);
  101395. if(bits>24){
  101396. ret|=b->ptr[3]<<(b->endbit);
  101397. if(bits>32 && b->endbit)
  101398. ret|=b->ptr[4]>>(8-b->endbit);
  101399. }
  101400. }
  101401. }
  101402. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  101403. overflow:
  101404. b->ptr+=bits/8;
  101405. b->endbyte+=bits/8;
  101406. b->endbit=bits&7;
  101407. return(ret);
  101408. }
  101409. long oggpack_read1(oggpack_buffer *b){
  101410. long ret;
  101411. if(b->endbyte>=b->storage){
  101412. /* not the main path */
  101413. ret=-1L;
  101414. goto overflow;
  101415. }
  101416. ret=(b->ptr[0]>>b->endbit)&1;
  101417. overflow:
  101418. b->endbit++;
  101419. if(b->endbit>7){
  101420. b->endbit=0;
  101421. b->ptr++;
  101422. b->endbyte++;
  101423. }
  101424. return(ret);
  101425. }
  101426. long oggpackB_read1(oggpack_buffer *b){
  101427. long ret;
  101428. if(b->endbyte>=b->storage){
  101429. /* not the main path */
  101430. ret=-1L;
  101431. goto overflow;
  101432. }
  101433. ret=(b->ptr[0]>>(7-b->endbit))&1;
  101434. overflow:
  101435. b->endbit++;
  101436. if(b->endbit>7){
  101437. b->endbit=0;
  101438. b->ptr++;
  101439. b->endbyte++;
  101440. }
  101441. return(ret);
  101442. }
  101443. long oggpack_bytes(oggpack_buffer *b){
  101444. return(b->endbyte+(b->endbit+7)/8);
  101445. }
  101446. long oggpack_bits(oggpack_buffer *b){
  101447. return(b->endbyte*8+b->endbit);
  101448. }
  101449. long oggpackB_bytes(oggpack_buffer *b){
  101450. return oggpack_bytes(b);
  101451. }
  101452. long oggpackB_bits(oggpack_buffer *b){
  101453. return oggpack_bits(b);
  101454. }
  101455. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  101456. return(b->buffer);
  101457. }
  101458. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  101459. return oggpack_get_buffer(b);
  101460. }
  101461. /* Self test of the bitwise routines; everything else is based on
  101462. them, so they damned well better be solid. */
  101463. #ifdef _V_SELFTEST
  101464. #include <stdio.h>
  101465. static int ilog(unsigned int v){
  101466. int ret=0;
  101467. while(v){
  101468. ret++;
  101469. v>>=1;
  101470. }
  101471. return(ret);
  101472. }
  101473. oggpack_buffer o;
  101474. oggpack_buffer r;
  101475. void report(char *in){
  101476. fprintf(stderr,"%s",in);
  101477. exit(1);
  101478. }
  101479. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  101480. long bytes,i;
  101481. unsigned char *buffer;
  101482. oggpack_reset(&o);
  101483. for(i=0;i<vals;i++)
  101484. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  101485. buffer=oggpack_get_buffer(&o);
  101486. bytes=oggpack_bytes(&o);
  101487. if(bytes!=compsize)report("wrong number of bytes!\n");
  101488. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  101489. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  101490. report("wrote incorrect value!\n");
  101491. }
  101492. oggpack_readinit(&r,buffer,bytes);
  101493. for(i=0;i<vals;i++){
  101494. int tbit=bits?bits:ilog(b[i]);
  101495. if(oggpack_look(&r,tbit)==-1)
  101496. report("out of data!\n");
  101497. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  101498. report("looked at incorrect value!\n");
  101499. if(tbit==1)
  101500. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  101501. report("looked at single bit incorrect value!\n");
  101502. if(tbit==1){
  101503. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  101504. report("read incorrect single bit value!\n");
  101505. }else{
  101506. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  101507. report("read incorrect value!\n");
  101508. }
  101509. }
  101510. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101511. }
  101512. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  101513. long bytes,i;
  101514. unsigned char *buffer;
  101515. oggpackB_reset(&o);
  101516. for(i=0;i<vals;i++)
  101517. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  101518. buffer=oggpackB_get_buffer(&o);
  101519. bytes=oggpackB_bytes(&o);
  101520. if(bytes!=compsize)report("wrong number of bytes!\n");
  101521. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  101522. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  101523. report("wrote incorrect value!\n");
  101524. }
  101525. oggpackB_readinit(&r,buffer,bytes);
  101526. for(i=0;i<vals;i++){
  101527. int tbit=bits?bits:ilog(b[i]);
  101528. if(oggpackB_look(&r,tbit)==-1)
  101529. report("out of data!\n");
  101530. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  101531. report("looked at incorrect value!\n");
  101532. if(tbit==1)
  101533. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  101534. report("looked at single bit incorrect value!\n");
  101535. if(tbit==1){
  101536. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  101537. report("read incorrect single bit value!\n");
  101538. }else{
  101539. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  101540. report("read incorrect value!\n");
  101541. }
  101542. }
  101543. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101544. }
  101545. int main(void){
  101546. unsigned char *buffer;
  101547. long bytes,i;
  101548. static unsigned long testbuffer1[]=
  101549. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  101550. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  101551. int test1size=43;
  101552. static unsigned long testbuffer2[]=
  101553. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  101554. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  101555. 85525151,0,12321,1,349528352};
  101556. int test2size=21;
  101557. static unsigned long testbuffer3[]=
  101558. {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
  101559. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  101560. int test3size=56;
  101561. static unsigned long large[]=
  101562. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  101563. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  101564. 85525151,0,12321,1,2146528352};
  101565. int onesize=33;
  101566. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  101567. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  101568. 223,4};
  101569. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  101570. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  101571. 245,251,128};
  101572. int twosize=6;
  101573. static int two[6]={61,255,255,251,231,29};
  101574. static int twoB[6]={247,63,255,253,249,120};
  101575. int threesize=54;
  101576. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  101577. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  101578. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  101579. 100,52,4,14,18,86,77,1};
  101580. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  101581. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  101582. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  101583. 200,20,254,4,58,106,176,144,0};
  101584. int foursize=38;
  101585. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  101586. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  101587. 28,2,133,0,1};
  101588. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  101589. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  101590. 129,10,4,32};
  101591. int fivesize=45;
  101592. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  101593. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  101594. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  101595. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  101596. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  101597. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  101598. int sixsize=7;
  101599. static int six[7]={17,177,170,242,169,19,148};
  101600. static int sixB[7]={136,141,85,79,149,200,41};
  101601. /* Test read/write together */
  101602. /* Later we test against pregenerated bitstreams */
  101603. oggpack_writeinit(&o);
  101604. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  101605. cliptest(testbuffer1,test1size,0,one,onesize);
  101606. fprintf(stderr,"ok.");
  101607. fprintf(stderr,"\nNull bit call (LSb): ");
  101608. cliptest(testbuffer3,test3size,0,two,twosize);
  101609. fprintf(stderr,"ok.");
  101610. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  101611. cliptest(testbuffer2,test2size,0,three,threesize);
  101612. fprintf(stderr,"ok.");
  101613. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  101614. oggpack_reset(&o);
  101615. for(i=0;i<test2size;i++)
  101616. oggpack_write(&o,large[i],32);
  101617. buffer=oggpack_get_buffer(&o);
  101618. bytes=oggpack_bytes(&o);
  101619. oggpack_readinit(&r,buffer,bytes);
  101620. for(i=0;i<test2size;i++){
  101621. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  101622. if(oggpack_look(&r,32)!=large[i]){
  101623. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  101624. oggpack_look(&r,32),large[i]);
  101625. report("read incorrect value!\n");
  101626. }
  101627. oggpack_adv(&r,32);
  101628. }
  101629. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101630. fprintf(stderr,"ok.");
  101631. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  101632. cliptest(testbuffer1,test1size,7,four,foursize);
  101633. fprintf(stderr,"ok.");
  101634. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  101635. cliptest(testbuffer2,test2size,17,five,fivesize);
  101636. fprintf(stderr,"ok.");
  101637. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  101638. cliptest(testbuffer3,test3size,1,six,sixsize);
  101639. fprintf(stderr,"ok.");
  101640. fprintf(stderr,"\nTesting read past end (LSb): ");
  101641. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101642. for(i=0;i<64;i++){
  101643. if(oggpack_read(&r,1)!=0){
  101644. fprintf(stderr,"failed; got -1 prematurely.\n");
  101645. exit(1);
  101646. }
  101647. }
  101648. if(oggpack_look(&r,1)!=-1 ||
  101649. oggpack_read(&r,1)!=-1){
  101650. fprintf(stderr,"failed; read past end without -1.\n");
  101651. exit(1);
  101652. }
  101653. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101654. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  101655. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  101656. exit(1);
  101657. }
  101658. if(oggpack_look(&r,18)!=0 ||
  101659. oggpack_look(&r,18)!=0){
  101660. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  101661. exit(1);
  101662. }
  101663. if(oggpack_look(&r,19)!=-1 ||
  101664. oggpack_look(&r,19)!=-1){
  101665. fprintf(stderr,"failed; read past end without -1.\n");
  101666. exit(1);
  101667. }
  101668. if(oggpack_look(&r,32)!=-1 ||
  101669. oggpack_look(&r,32)!=-1){
  101670. fprintf(stderr,"failed; read past end without -1.\n");
  101671. exit(1);
  101672. }
  101673. oggpack_writeclear(&o);
  101674. fprintf(stderr,"ok.\n");
  101675. /********** lazy, cut-n-paste retest with MSb packing ***********/
  101676. /* Test read/write together */
  101677. /* Later we test against pregenerated bitstreams */
  101678. oggpackB_writeinit(&o);
  101679. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  101680. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  101681. fprintf(stderr,"ok.");
  101682. fprintf(stderr,"\nNull bit call (MSb): ");
  101683. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  101684. fprintf(stderr,"ok.");
  101685. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  101686. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  101687. fprintf(stderr,"ok.");
  101688. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  101689. oggpackB_reset(&o);
  101690. for(i=0;i<test2size;i++)
  101691. oggpackB_write(&o,large[i],32);
  101692. buffer=oggpackB_get_buffer(&o);
  101693. bytes=oggpackB_bytes(&o);
  101694. oggpackB_readinit(&r,buffer,bytes);
  101695. for(i=0;i<test2size;i++){
  101696. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  101697. if(oggpackB_look(&r,32)!=large[i]){
  101698. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  101699. oggpackB_look(&r,32),large[i]);
  101700. report("read incorrect value!\n");
  101701. }
  101702. oggpackB_adv(&r,32);
  101703. }
  101704. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101705. fprintf(stderr,"ok.");
  101706. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  101707. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  101708. fprintf(stderr,"ok.");
  101709. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  101710. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  101711. fprintf(stderr,"ok.");
  101712. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  101713. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  101714. fprintf(stderr,"ok.");
  101715. fprintf(stderr,"\nTesting read past end (MSb): ");
  101716. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101717. for(i=0;i<64;i++){
  101718. if(oggpackB_read(&r,1)!=0){
  101719. fprintf(stderr,"failed; got -1 prematurely.\n");
  101720. exit(1);
  101721. }
  101722. }
  101723. if(oggpackB_look(&r,1)!=-1 ||
  101724. oggpackB_read(&r,1)!=-1){
  101725. fprintf(stderr,"failed; read past end without -1.\n");
  101726. exit(1);
  101727. }
  101728. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101729. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  101730. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  101731. exit(1);
  101732. }
  101733. if(oggpackB_look(&r,18)!=0 ||
  101734. oggpackB_look(&r,18)!=0){
  101735. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  101736. exit(1);
  101737. }
  101738. if(oggpackB_look(&r,19)!=-1 ||
  101739. oggpackB_look(&r,19)!=-1){
  101740. fprintf(stderr,"failed; read past end without -1.\n");
  101741. exit(1);
  101742. }
  101743. if(oggpackB_look(&r,32)!=-1 ||
  101744. oggpackB_look(&r,32)!=-1){
  101745. fprintf(stderr,"failed; read past end without -1.\n");
  101746. exit(1);
  101747. }
  101748. oggpackB_writeclear(&o);
  101749. fprintf(stderr,"ok.\n\n");
  101750. return(0);
  101751. }
  101752. #endif /* _V_SELFTEST */
  101753. #undef BUFFER_INCREMENT
  101754. #endif
  101755. /********* End of inlined file: bitwise.c *********/
  101756. /********* Start of inlined file: framing.c *********/
  101757. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101758. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101759. // tasks..
  101760. #ifdef _MSC_VER
  101761. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101762. #endif
  101763. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101764. #if JUCE_USE_OGGVORBIS
  101765. #include <stdlib.h>
  101766. #include <string.h>
  101767. /* A complete description of Ogg framing exists in docs/framing.html */
  101768. int ogg_page_version(ogg_page *og){
  101769. return((int)(og->header[4]));
  101770. }
  101771. int ogg_page_continued(ogg_page *og){
  101772. return((int)(og->header[5]&0x01));
  101773. }
  101774. int ogg_page_bos(ogg_page *og){
  101775. return((int)(og->header[5]&0x02));
  101776. }
  101777. int ogg_page_eos(ogg_page *og){
  101778. return((int)(og->header[5]&0x04));
  101779. }
  101780. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  101781. unsigned char *page=og->header;
  101782. ogg_int64_t granulepos=page[13]&(0xff);
  101783. granulepos= (granulepos<<8)|(page[12]&0xff);
  101784. granulepos= (granulepos<<8)|(page[11]&0xff);
  101785. granulepos= (granulepos<<8)|(page[10]&0xff);
  101786. granulepos= (granulepos<<8)|(page[9]&0xff);
  101787. granulepos= (granulepos<<8)|(page[8]&0xff);
  101788. granulepos= (granulepos<<8)|(page[7]&0xff);
  101789. granulepos= (granulepos<<8)|(page[6]&0xff);
  101790. return(granulepos);
  101791. }
  101792. int ogg_page_serialno(ogg_page *og){
  101793. return(og->header[14] |
  101794. (og->header[15]<<8) |
  101795. (og->header[16]<<16) |
  101796. (og->header[17]<<24));
  101797. }
  101798. long ogg_page_pageno(ogg_page *og){
  101799. return(og->header[18] |
  101800. (og->header[19]<<8) |
  101801. (og->header[20]<<16) |
  101802. (og->header[21]<<24));
  101803. }
  101804. /* returns the number of packets that are completed on this page (if
  101805. the leading packet is begun on a previous page, but ends on this
  101806. page, it's counted */
  101807. /* NOTE:
  101808. If a page consists of a packet begun on a previous page, and a new
  101809. packet begun (but not completed) on this page, the return will be:
  101810. ogg_page_packets(page) ==1,
  101811. ogg_page_continued(page) !=0
  101812. If a page happens to be a single packet that was begun on a
  101813. previous page, and spans to the next page (in the case of a three or
  101814. more page packet), the return will be:
  101815. ogg_page_packets(page) ==0,
  101816. ogg_page_continued(page) !=0
  101817. */
  101818. int ogg_page_packets(ogg_page *og){
  101819. int i,n=og->header[26],count=0;
  101820. for(i=0;i<n;i++)
  101821. if(og->header[27+i]<255)count++;
  101822. return(count);
  101823. }
  101824. #if 0
  101825. /* helper to initialize lookup for direct-table CRC (illustrative; we
  101826. use the static init below) */
  101827. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  101828. int i;
  101829. unsigned long r;
  101830. r = index << 24;
  101831. for (i=0; i<8; i++)
  101832. if (r & 0x80000000UL)
  101833. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  101834. polynomial, although we use an
  101835. unreflected alg and an init/final
  101836. of 0, not 0xffffffff */
  101837. else
  101838. r<<=1;
  101839. return (r & 0xffffffffUL);
  101840. }
  101841. #endif
  101842. static const ogg_uint32_t crc_lookup[256]={
  101843. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  101844. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  101845. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  101846. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  101847. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  101848. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  101849. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  101850. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  101851. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  101852. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  101853. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  101854. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  101855. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  101856. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  101857. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  101858. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  101859. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  101860. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  101861. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  101862. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  101863. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  101864. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  101865. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  101866. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  101867. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  101868. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  101869. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  101870. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  101871. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  101872. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  101873. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  101874. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  101875. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  101876. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  101877. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  101878. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  101879. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  101880. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  101881. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  101882. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  101883. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  101884. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  101885. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  101886. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  101887. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  101888. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  101889. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  101890. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  101891. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  101892. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  101893. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  101894. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  101895. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  101896. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  101897. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  101898. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  101899. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  101900. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  101901. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  101902. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  101903. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  101904. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  101905. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  101906. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  101907. /* init the encode/decode logical stream state */
  101908. int ogg_stream_init(ogg_stream_state *os,int serialno){
  101909. if(os){
  101910. memset(os,0,sizeof(*os));
  101911. os->body_storage=16*1024;
  101912. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  101913. os->lacing_storage=1024;
  101914. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  101915. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  101916. os->serialno=serialno;
  101917. return(0);
  101918. }
  101919. return(-1);
  101920. }
  101921. /* _clear does not free os, only the non-flat storage within */
  101922. int ogg_stream_clear(ogg_stream_state *os){
  101923. if(os){
  101924. if(os->body_data)_ogg_free(os->body_data);
  101925. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  101926. if(os->granule_vals)_ogg_free(os->granule_vals);
  101927. memset(os,0,sizeof(*os));
  101928. }
  101929. return(0);
  101930. }
  101931. int ogg_stream_destroy(ogg_stream_state *os){
  101932. if(os){
  101933. ogg_stream_clear(os);
  101934. _ogg_free(os);
  101935. }
  101936. return(0);
  101937. }
  101938. /* Helpers for ogg_stream_encode; this keeps the structure and
  101939. what's happening fairly clear */
  101940. static void _os_body_expand(ogg_stream_state *os,int needed){
  101941. if(os->body_storage<=os->body_fill+needed){
  101942. os->body_storage+=(needed+1024);
  101943. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  101944. }
  101945. }
  101946. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  101947. if(os->lacing_storage<=os->lacing_fill+needed){
  101948. os->lacing_storage+=(needed+32);
  101949. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  101950. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  101951. }
  101952. }
  101953. /* checksum the page */
  101954. /* Direct table CRC; note that this will be faster in the future if we
  101955. perform the checksum silmultaneously with other copies */
  101956. void ogg_page_checksum_set(ogg_page *og){
  101957. if(og){
  101958. ogg_uint32_t crc_reg=0;
  101959. int i;
  101960. /* safety; needed for API behavior, but not framing code */
  101961. og->header[22]=0;
  101962. og->header[23]=0;
  101963. og->header[24]=0;
  101964. og->header[25]=0;
  101965. for(i=0;i<og->header_len;i++)
  101966. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  101967. for(i=0;i<og->body_len;i++)
  101968. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  101969. og->header[22]=(unsigned char)(crc_reg&0xff);
  101970. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  101971. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  101972. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  101973. }
  101974. }
  101975. /* submit data to the internal buffer of the framing engine */
  101976. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  101977. int lacing_vals=op->bytes/255+1,i;
  101978. if(os->body_returned){
  101979. /* advance packet data according to the body_returned pointer. We
  101980. had to keep it around to return a pointer into the buffer last
  101981. call */
  101982. os->body_fill-=os->body_returned;
  101983. if(os->body_fill)
  101984. memmove(os->body_data,os->body_data+os->body_returned,
  101985. os->body_fill);
  101986. os->body_returned=0;
  101987. }
  101988. /* make sure we have the buffer storage */
  101989. _os_body_expand(os,op->bytes);
  101990. _os_lacing_expand(os,lacing_vals);
  101991. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  101992. the liability of overly clean abstraction for the time being. It
  101993. will actually be fairly easy to eliminate the extra copy in the
  101994. future */
  101995. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  101996. os->body_fill+=op->bytes;
  101997. /* Store lacing vals for this packet */
  101998. for(i=0;i<lacing_vals-1;i++){
  101999. os->lacing_vals[os->lacing_fill+i]=255;
  102000. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  102001. }
  102002. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  102003. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  102004. /* flag the first segment as the beginning of the packet */
  102005. os->lacing_vals[os->lacing_fill]|= 0x100;
  102006. os->lacing_fill+=lacing_vals;
  102007. /* for the sake of completeness */
  102008. os->packetno++;
  102009. if(op->e_o_s)os->e_o_s=1;
  102010. return(0);
  102011. }
  102012. /* This will flush remaining packets into a page (returning nonzero),
  102013. even if there is not enough data to trigger a flush normally
  102014. (undersized page). If there are no packets or partial packets to
  102015. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  102016. try to flush a normal sized page like ogg_stream_pageout; a call to
  102017. ogg_stream_flush does not guarantee that all packets have flushed.
  102018. Only a return value of 0 from ogg_stream_flush indicates all packet
  102019. data is flushed into pages.
  102020. since ogg_stream_flush will flush the last page in a stream even if
  102021. it's undersized, you almost certainly want to use ogg_stream_pageout
  102022. (and *not* ogg_stream_flush) unless you specifically need to flush
  102023. an page regardless of size in the middle of a stream. */
  102024. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  102025. int i;
  102026. int vals=0;
  102027. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  102028. int bytes=0;
  102029. long acc=0;
  102030. ogg_int64_t granule_pos=-1;
  102031. if(maxvals==0)return(0);
  102032. /* construct a page */
  102033. /* decide how many segments to include */
  102034. /* If this is the initial header case, the first page must only include
  102035. the initial header packet */
  102036. if(os->b_o_s==0){ /* 'initial header page' case */
  102037. granule_pos=0;
  102038. for(vals=0;vals<maxvals;vals++){
  102039. if((os->lacing_vals[vals]&0x0ff)<255){
  102040. vals++;
  102041. break;
  102042. }
  102043. }
  102044. }else{
  102045. for(vals=0;vals<maxvals;vals++){
  102046. if(acc>4096)break;
  102047. acc+=os->lacing_vals[vals]&0x0ff;
  102048. if((os->lacing_vals[vals]&0xff)<255)
  102049. granule_pos=os->granule_vals[vals];
  102050. }
  102051. }
  102052. /* construct the header in temp storage */
  102053. memcpy(os->header,"OggS",4);
  102054. /* stream structure version */
  102055. os->header[4]=0x00;
  102056. /* continued packet flag? */
  102057. os->header[5]=0x00;
  102058. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  102059. /* first page flag? */
  102060. if(os->b_o_s==0)os->header[5]|=0x02;
  102061. /* last page flag? */
  102062. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  102063. os->b_o_s=1;
  102064. /* 64 bits of PCM position */
  102065. for(i=6;i<14;i++){
  102066. os->header[i]=(unsigned char)(granule_pos&0xff);
  102067. granule_pos>>=8;
  102068. }
  102069. /* 32 bits of stream serial number */
  102070. {
  102071. long serialno=os->serialno;
  102072. for(i=14;i<18;i++){
  102073. os->header[i]=(unsigned char)(serialno&0xff);
  102074. serialno>>=8;
  102075. }
  102076. }
  102077. /* 32 bits of page counter (we have both counter and page header
  102078. because this val can roll over) */
  102079. if(os->pageno==-1)os->pageno=0; /* because someone called
  102080. stream_reset; this would be a
  102081. strange thing to do in an
  102082. encode stream, but it has
  102083. plausible uses */
  102084. {
  102085. long pageno=os->pageno++;
  102086. for(i=18;i<22;i++){
  102087. os->header[i]=(unsigned char)(pageno&0xff);
  102088. pageno>>=8;
  102089. }
  102090. }
  102091. /* zero for computation; filled in later */
  102092. os->header[22]=0;
  102093. os->header[23]=0;
  102094. os->header[24]=0;
  102095. os->header[25]=0;
  102096. /* segment table */
  102097. os->header[26]=(unsigned char)(vals&0xff);
  102098. for(i=0;i<vals;i++)
  102099. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  102100. /* set pointers in the ogg_page struct */
  102101. og->header=os->header;
  102102. og->header_len=os->header_fill=vals+27;
  102103. og->body=os->body_data+os->body_returned;
  102104. og->body_len=bytes;
  102105. /* advance the lacing data and set the body_returned pointer */
  102106. os->lacing_fill-=vals;
  102107. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  102108. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  102109. os->body_returned+=bytes;
  102110. /* calculate the checksum */
  102111. ogg_page_checksum_set(og);
  102112. /* done */
  102113. return(1);
  102114. }
  102115. /* This constructs pages from buffered packet segments. The pointers
  102116. returned are to static buffers; do not free. The returned buffers are
  102117. good only until the next call (using the same ogg_stream_state) */
  102118. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  102119. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  102120. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  102121. os->lacing_fill>=255 || /* 'segment table full' case */
  102122. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  102123. return(ogg_stream_flush(os,og));
  102124. }
  102125. /* not enough data to construct a page and not end of stream */
  102126. return(0);
  102127. }
  102128. int ogg_stream_eos(ogg_stream_state *os){
  102129. return os->e_o_s;
  102130. }
  102131. /* DECODING PRIMITIVES: packet streaming layer **********************/
  102132. /* This has two layers to place more of the multi-serialno and paging
  102133. control in the application's hands. First, we expose a data buffer
  102134. using ogg_sync_buffer(). The app either copies into the
  102135. buffer, or passes it directly to read(), etc. We then call
  102136. ogg_sync_wrote() to tell how many bytes we just added.
  102137. Pages are returned (pointers into the buffer in ogg_sync_state)
  102138. by ogg_sync_pageout(). The page is then submitted to
  102139. ogg_stream_pagein() along with the appropriate
  102140. ogg_stream_state* (ie, matching serialno). We then get raw
  102141. packets out calling ogg_stream_packetout() with a
  102142. ogg_stream_state. */
  102143. /* initialize the struct to a known state */
  102144. int ogg_sync_init(ogg_sync_state *oy){
  102145. if(oy){
  102146. memset(oy,0,sizeof(*oy));
  102147. }
  102148. return(0);
  102149. }
  102150. /* clear non-flat storage within */
  102151. int ogg_sync_clear(ogg_sync_state *oy){
  102152. if(oy){
  102153. if(oy->data)_ogg_free(oy->data);
  102154. ogg_sync_init(oy);
  102155. }
  102156. return(0);
  102157. }
  102158. int ogg_sync_destroy(ogg_sync_state *oy){
  102159. if(oy){
  102160. ogg_sync_clear(oy);
  102161. _ogg_free(oy);
  102162. }
  102163. return(0);
  102164. }
  102165. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  102166. /* first, clear out any space that has been previously returned */
  102167. if(oy->returned){
  102168. oy->fill-=oy->returned;
  102169. if(oy->fill>0)
  102170. memmove(oy->data,oy->data+oy->returned,oy->fill);
  102171. oy->returned=0;
  102172. }
  102173. if(size>oy->storage-oy->fill){
  102174. /* We need to extend the internal buffer */
  102175. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  102176. if(oy->data)
  102177. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  102178. else
  102179. oy->data=(unsigned char*) _ogg_malloc(newsize);
  102180. oy->storage=newsize;
  102181. }
  102182. /* expose a segment at least as large as requested at the fill mark */
  102183. return((char *)oy->data+oy->fill);
  102184. }
  102185. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  102186. if(oy->fill+bytes>oy->storage)return(-1);
  102187. oy->fill+=bytes;
  102188. return(0);
  102189. }
  102190. /* sync the stream. This is meant to be useful for finding page
  102191. boundaries.
  102192. return values for this:
  102193. -n) skipped n bytes
  102194. 0) page not ready; more data (no bytes skipped)
  102195. n) page synced at current location; page length n bytes
  102196. */
  102197. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  102198. unsigned char *page=oy->data+oy->returned;
  102199. unsigned char *next;
  102200. long bytes=oy->fill-oy->returned;
  102201. if(oy->headerbytes==0){
  102202. int headerbytes,i;
  102203. if(bytes<27)return(0); /* not enough for a header */
  102204. /* verify capture pattern */
  102205. if(memcmp(page,"OggS",4))goto sync_fail;
  102206. headerbytes=page[26]+27;
  102207. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  102208. /* count up body length in the segment table */
  102209. for(i=0;i<page[26];i++)
  102210. oy->bodybytes+=page[27+i];
  102211. oy->headerbytes=headerbytes;
  102212. }
  102213. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  102214. /* The whole test page is buffered. Verify the checksum */
  102215. {
  102216. /* Grab the checksum bytes, set the header field to zero */
  102217. char chksum[4];
  102218. ogg_page log;
  102219. memcpy(chksum,page+22,4);
  102220. memset(page+22,0,4);
  102221. /* set up a temp page struct and recompute the checksum */
  102222. log.header=page;
  102223. log.header_len=oy->headerbytes;
  102224. log.body=page+oy->headerbytes;
  102225. log.body_len=oy->bodybytes;
  102226. ogg_page_checksum_set(&log);
  102227. /* Compare */
  102228. if(memcmp(chksum,page+22,4)){
  102229. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  102230. at all) */
  102231. /* replace the computed checksum with the one actually read in */
  102232. memcpy(page+22,chksum,4);
  102233. /* Bad checksum. Lose sync */
  102234. goto sync_fail;
  102235. }
  102236. }
  102237. /* yes, have a whole page all ready to go */
  102238. {
  102239. unsigned char *page=oy->data+oy->returned;
  102240. long bytes;
  102241. if(og){
  102242. og->header=page;
  102243. og->header_len=oy->headerbytes;
  102244. og->body=page+oy->headerbytes;
  102245. og->body_len=oy->bodybytes;
  102246. }
  102247. oy->unsynced=0;
  102248. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  102249. oy->headerbytes=0;
  102250. oy->bodybytes=0;
  102251. return(bytes);
  102252. }
  102253. sync_fail:
  102254. oy->headerbytes=0;
  102255. oy->bodybytes=0;
  102256. /* search for possible capture */
  102257. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  102258. if(!next)
  102259. next=oy->data+oy->fill;
  102260. oy->returned=next-oy->data;
  102261. return(-(next-page));
  102262. }
  102263. /* sync the stream and get a page. Keep trying until we find a page.
  102264. Supress 'sync errors' after reporting the first.
  102265. return values:
  102266. -1) recapture (hole in data)
  102267. 0) need more data
  102268. 1) page returned
  102269. Returns pointers into buffered data; invalidated by next call to
  102270. _stream, _clear, _init, or _buffer */
  102271. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  102272. /* all we need to do is verify a page at the head of the stream
  102273. buffer. If it doesn't verify, we look for the next potential
  102274. frame */
  102275. for(;;){
  102276. long ret=ogg_sync_pageseek(oy,og);
  102277. if(ret>0){
  102278. /* have a page */
  102279. return(1);
  102280. }
  102281. if(ret==0){
  102282. /* need more data */
  102283. return(0);
  102284. }
  102285. /* head did not start a synced page... skipped some bytes */
  102286. if(!oy->unsynced){
  102287. oy->unsynced=1;
  102288. return(-1);
  102289. }
  102290. /* loop. keep looking */
  102291. }
  102292. }
  102293. /* add the incoming page to the stream state; we decompose the page
  102294. into packet segments here as well. */
  102295. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  102296. unsigned char *header=og->header;
  102297. unsigned char *body=og->body;
  102298. long bodysize=og->body_len;
  102299. int segptr=0;
  102300. int version=ogg_page_version(og);
  102301. int continued=ogg_page_continued(og);
  102302. int bos=ogg_page_bos(og);
  102303. int eos=ogg_page_eos(og);
  102304. ogg_int64_t granulepos=ogg_page_granulepos(og);
  102305. int serialno=ogg_page_serialno(og);
  102306. long pageno=ogg_page_pageno(og);
  102307. int segments=header[26];
  102308. /* clean up 'returned data' */
  102309. {
  102310. long lr=os->lacing_returned;
  102311. long br=os->body_returned;
  102312. /* body data */
  102313. if(br){
  102314. os->body_fill-=br;
  102315. if(os->body_fill)
  102316. memmove(os->body_data,os->body_data+br,os->body_fill);
  102317. os->body_returned=0;
  102318. }
  102319. if(lr){
  102320. /* segment table */
  102321. if(os->lacing_fill-lr){
  102322. memmove(os->lacing_vals,os->lacing_vals+lr,
  102323. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  102324. memmove(os->granule_vals,os->granule_vals+lr,
  102325. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  102326. }
  102327. os->lacing_fill-=lr;
  102328. os->lacing_packet-=lr;
  102329. os->lacing_returned=0;
  102330. }
  102331. }
  102332. /* check the serial number */
  102333. if(serialno!=os->serialno)return(-1);
  102334. if(version>0)return(-1);
  102335. _os_lacing_expand(os,segments+1);
  102336. /* are we in sequence? */
  102337. if(pageno!=os->pageno){
  102338. int i;
  102339. /* unroll previous partial packet (if any) */
  102340. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  102341. os->body_fill-=os->lacing_vals[i]&0xff;
  102342. os->lacing_fill=os->lacing_packet;
  102343. /* make a note of dropped data in segment table */
  102344. if(os->pageno!=-1){
  102345. os->lacing_vals[os->lacing_fill++]=0x400;
  102346. os->lacing_packet++;
  102347. }
  102348. }
  102349. /* are we a 'continued packet' page? If so, we may need to skip
  102350. some segments */
  102351. if(continued){
  102352. if(os->lacing_fill<1 ||
  102353. os->lacing_vals[os->lacing_fill-1]==0x400){
  102354. bos=0;
  102355. for(;segptr<segments;segptr++){
  102356. int val=header[27+segptr];
  102357. body+=val;
  102358. bodysize-=val;
  102359. if(val<255){
  102360. segptr++;
  102361. break;
  102362. }
  102363. }
  102364. }
  102365. }
  102366. if(bodysize){
  102367. _os_body_expand(os,bodysize);
  102368. memcpy(os->body_data+os->body_fill,body,bodysize);
  102369. os->body_fill+=bodysize;
  102370. }
  102371. {
  102372. int saved=-1;
  102373. while(segptr<segments){
  102374. int val=header[27+segptr];
  102375. os->lacing_vals[os->lacing_fill]=val;
  102376. os->granule_vals[os->lacing_fill]=-1;
  102377. if(bos){
  102378. os->lacing_vals[os->lacing_fill]|=0x100;
  102379. bos=0;
  102380. }
  102381. if(val<255)saved=os->lacing_fill;
  102382. os->lacing_fill++;
  102383. segptr++;
  102384. if(val<255)os->lacing_packet=os->lacing_fill;
  102385. }
  102386. /* set the granulepos on the last granuleval of the last full packet */
  102387. if(saved!=-1){
  102388. os->granule_vals[saved]=granulepos;
  102389. }
  102390. }
  102391. if(eos){
  102392. os->e_o_s=1;
  102393. if(os->lacing_fill>0)
  102394. os->lacing_vals[os->lacing_fill-1]|=0x200;
  102395. }
  102396. os->pageno=pageno+1;
  102397. return(0);
  102398. }
  102399. /* clear things to an initial state. Good to call, eg, before seeking */
  102400. int ogg_sync_reset(ogg_sync_state *oy){
  102401. oy->fill=0;
  102402. oy->returned=0;
  102403. oy->unsynced=0;
  102404. oy->headerbytes=0;
  102405. oy->bodybytes=0;
  102406. return(0);
  102407. }
  102408. int ogg_stream_reset(ogg_stream_state *os){
  102409. os->body_fill=0;
  102410. os->body_returned=0;
  102411. os->lacing_fill=0;
  102412. os->lacing_packet=0;
  102413. os->lacing_returned=0;
  102414. os->header_fill=0;
  102415. os->e_o_s=0;
  102416. os->b_o_s=0;
  102417. os->pageno=-1;
  102418. os->packetno=0;
  102419. os->granulepos=0;
  102420. return(0);
  102421. }
  102422. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  102423. ogg_stream_reset(os);
  102424. os->serialno=serialno;
  102425. return(0);
  102426. }
  102427. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  102428. /* The last part of decode. We have the stream broken into packet
  102429. segments. Now we need to group them into packets (or return the
  102430. out of sync markers) */
  102431. int ptr=os->lacing_returned;
  102432. if(os->lacing_packet<=ptr)return(0);
  102433. if(os->lacing_vals[ptr]&0x400){
  102434. /* we need to tell the codec there's a gap; it might need to
  102435. handle previous packet dependencies. */
  102436. os->lacing_returned++;
  102437. os->packetno++;
  102438. return(-1);
  102439. }
  102440. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  102441. to ask if there's a whole packet
  102442. waiting */
  102443. /* Gather the whole packet. We'll have no holes or a partial packet */
  102444. {
  102445. int size=os->lacing_vals[ptr]&0xff;
  102446. int bytes=size;
  102447. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  102448. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  102449. while(size==255){
  102450. int val=os->lacing_vals[++ptr];
  102451. size=val&0xff;
  102452. if(val&0x200)eos=0x200;
  102453. bytes+=size;
  102454. }
  102455. if(op){
  102456. op->e_o_s=eos;
  102457. op->b_o_s=bos;
  102458. op->packet=os->body_data+os->body_returned;
  102459. op->packetno=os->packetno;
  102460. op->granulepos=os->granule_vals[ptr];
  102461. op->bytes=bytes;
  102462. }
  102463. if(adv){
  102464. os->body_returned+=bytes;
  102465. os->lacing_returned=ptr+1;
  102466. os->packetno++;
  102467. }
  102468. }
  102469. return(1);
  102470. }
  102471. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  102472. return _packetout(os,op,1);
  102473. }
  102474. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  102475. return _packetout(os,op,0);
  102476. }
  102477. void ogg_packet_clear(ogg_packet *op) {
  102478. _ogg_free(op->packet);
  102479. memset(op, 0, sizeof(*op));
  102480. }
  102481. #ifdef _V_SELFTEST
  102482. #include <stdio.h>
  102483. ogg_stream_state os_en, os_de;
  102484. ogg_sync_state oy;
  102485. void checkpacket(ogg_packet *op,int len, int no, int pos){
  102486. long j;
  102487. static int sequence=0;
  102488. static int lastno=0;
  102489. if(op->bytes!=len){
  102490. fprintf(stderr,"incorrect packet length!\n");
  102491. exit(1);
  102492. }
  102493. if(op->granulepos!=pos){
  102494. fprintf(stderr,"incorrect packet position!\n");
  102495. exit(1);
  102496. }
  102497. /* packet number just follows sequence/gap; adjust the input number
  102498. for that */
  102499. if(no==0){
  102500. sequence=0;
  102501. }else{
  102502. sequence++;
  102503. if(no>lastno+1)
  102504. sequence++;
  102505. }
  102506. lastno=no;
  102507. if(op->packetno!=sequence){
  102508. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  102509. (long)(op->packetno),sequence);
  102510. exit(1);
  102511. }
  102512. /* Test data */
  102513. for(j=0;j<op->bytes;j++)
  102514. if(op->packet[j]!=((j+no)&0xff)){
  102515. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  102516. j,op->packet[j],(j+no)&0xff);
  102517. exit(1);
  102518. }
  102519. }
  102520. void check_page(unsigned char *data,const int *header,ogg_page *og){
  102521. long j;
  102522. /* Test data */
  102523. for(j=0;j<og->body_len;j++)
  102524. if(og->body[j]!=data[j]){
  102525. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  102526. j,data[j],og->body[j]);
  102527. exit(1);
  102528. }
  102529. /* Test header */
  102530. for(j=0;j<og->header_len;j++){
  102531. if(og->header[j]!=header[j]){
  102532. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  102533. for(j=0;j<header[26]+27;j++)
  102534. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  102535. fprintf(stderr,"\n");
  102536. exit(1);
  102537. }
  102538. }
  102539. if(og->header_len!=header[26]+27){
  102540. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  102541. og->header_len,header[26]+27);
  102542. exit(1);
  102543. }
  102544. }
  102545. void print_header(ogg_page *og){
  102546. int j;
  102547. fprintf(stderr,"\nHEADER:\n");
  102548. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  102549. og->header[0],og->header[1],og->header[2],og->header[3],
  102550. (int)og->header[4],(int)og->header[5]);
  102551. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  102552. (og->header[9]<<24)|(og->header[8]<<16)|
  102553. (og->header[7]<<8)|og->header[6],
  102554. (og->header[17]<<24)|(og->header[16]<<16)|
  102555. (og->header[15]<<8)|og->header[14],
  102556. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  102557. (og->header[19]<<8)|og->header[18]);
  102558. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  102559. (int)og->header[22],(int)og->header[23],
  102560. (int)og->header[24],(int)og->header[25],
  102561. (int)og->header[26]);
  102562. for(j=27;j<og->header_len;j++)
  102563. fprintf(stderr,"%d ",(int)og->header[j]);
  102564. fprintf(stderr,")\n\n");
  102565. }
  102566. void copy_page(ogg_page *og){
  102567. unsigned char *temp=_ogg_malloc(og->header_len);
  102568. memcpy(temp,og->header,og->header_len);
  102569. og->header=temp;
  102570. temp=_ogg_malloc(og->body_len);
  102571. memcpy(temp,og->body,og->body_len);
  102572. og->body=temp;
  102573. }
  102574. void free_page(ogg_page *og){
  102575. _ogg_free (og->header);
  102576. _ogg_free (og->body);
  102577. }
  102578. void error(void){
  102579. fprintf(stderr,"error!\n");
  102580. exit(1);
  102581. }
  102582. /* 17 only */
  102583. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  102584. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102585. 0x01,0x02,0x03,0x04,0,0,0,0,
  102586. 0x15,0xed,0xec,0x91,
  102587. 1,
  102588. 17};
  102589. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  102590. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102591. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102592. 0x01,0x02,0x03,0x04,0,0,0,0,
  102593. 0x59,0x10,0x6c,0x2c,
  102594. 1,
  102595. 17};
  102596. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102597. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  102598. 0x01,0x02,0x03,0x04,1,0,0,0,
  102599. 0x89,0x33,0x85,0xce,
  102600. 13,
  102601. 254,255,0,255,1,255,245,255,255,0,
  102602. 255,255,90};
  102603. /* nil packets; beginning,middle,end */
  102604. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102605. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102606. 0x01,0x02,0x03,0x04,0,0,0,0,
  102607. 0xff,0x7b,0x23,0x17,
  102608. 1,
  102609. 0};
  102610. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102611. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  102612. 0x01,0x02,0x03,0x04,1,0,0,0,
  102613. 0x5c,0x3f,0x66,0xcb,
  102614. 17,
  102615. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  102616. 255,255,90,0};
  102617. /* large initial packet */
  102618. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102619. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102620. 0x01,0x02,0x03,0x04,0,0,0,0,
  102621. 0x01,0x27,0x31,0xaa,
  102622. 18,
  102623. 255,255,255,255,255,255,255,255,
  102624. 255,255,255,255,255,255,255,255,255,10};
  102625. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102626. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  102627. 0x01,0x02,0x03,0x04,1,0,0,0,
  102628. 0x7f,0x4e,0x8a,0xd2,
  102629. 4,
  102630. 255,4,255,0};
  102631. /* continuing packet test */
  102632. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102633. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102634. 0x01,0x02,0x03,0x04,0,0,0,0,
  102635. 0xff,0x7b,0x23,0x17,
  102636. 1,
  102637. 0};
  102638. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102639. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  102640. 0x01,0x02,0x03,0x04,1,0,0,0,
  102641. 0x54,0x05,0x51,0xc8,
  102642. 17,
  102643. 255,255,255,255,255,255,255,255,
  102644. 255,255,255,255,255,255,255,255,255};
  102645. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102646. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  102647. 0x01,0x02,0x03,0x04,2,0,0,0,
  102648. 0xc8,0xc3,0xcb,0xed,
  102649. 5,
  102650. 10,255,4,255,0};
  102651. /* page with the 255 segment limit */
  102652. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102653. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102654. 0x01,0x02,0x03,0x04,0,0,0,0,
  102655. 0xff,0x7b,0x23,0x17,
  102656. 1,
  102657. 0};
  102658. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102659. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  102660. 0x01,0x02,0x03,0x04,1,0,0,0,
  102661. 0xed,0x2a,0x2e,0xa7,
  102662. 255,
  102663. 10,10,10,10,10,10,10,10,
  102664. 10,10,10,10,10,10,10,10,
  102665. 10,10,10,10,10,10,10,10,
  102666. 10,10,10,10,10,10,10,10,
  102667. 10,10,10,10,10,10,10,10,
  102668. 10,10,10,10,10,10,10,10,
  102669. 10,10,10,10,10,10,10,10,
  102670. 10,10,10,10,10,10,10,10,
  102671. 10,10,10,10,10,10,10,10,
  102672. 10,10,10,10,10,10,10,10,
  102673. 10,10,10,10,10,10,10,10,
  102674. 10,10,10,10,10,10,10,10,
  102675. 10,10,10,10,10,10,10,10,
  102676. 10,10,10,10,10,10,10,10,
  102677. 10,10,10,10,10,10,10,10,
  102678. 10,10,10,10,10,10,10,10,
  102679. 10,10,10,10,10,10,10,10,
  102680. 10,10,10,10,10,10,10,10,
  102681. 10,10,10,10,10,10,10,10,
  102682. 10,10,10,10,10,10,10,10,
  102683. 10,10,10,10,10,10,10,10,
  102684. 10,10,10,10,10,10,10,10,
  102685. 10,10,10,10,10,10,10,10,
  102686. 10,10,10,10,10,10,10,10,
  102687. 10,10,10,10,10,10,10,10,
  102688. 10,10,10,10,10,10,10,10,
  102689. 10,10,10,10,10,10,10,10,
  102690. 10,10,10,10,10,10,10,10,
  102691. 10,10,10,10,10,10,10,10,
  102692. 10,10,10,10,10,10,10,10,
  102693. 10,10,10,10,10,10,10,10,
  102694. 10,10,10,10,10,10,10};
  102695. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102696. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  102697. 0x01,0x02,0x03,0x04,2,0,0,0,
  102698. 0x6c,0x3b,0x82,0x3d,
  102699. 1,
  102700. 50};
  102701. /* packet that overspans over an entire page */
  102702. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102703. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102704. 0x01,0x02,0x03,0x04,0,0,0,0,
  102705. 0xff,0x7b,0x23,0x17,
  102706. 1,
  102707. 0};
  102708. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102709. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  102710. 0x01,0x02,0x03,0x04,1,0,0,0,
  102711. 0x3c,0xd9,0x4d,0x3f,
  102712. 17,
  102713. 100,255,255,255,255,255,255,255,255,
  102714. 255,255,255,255,255,255,255,255};
  102715. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  102716. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  102717. 0x01,0x02,0x03,0x04,2,0,0,0,
  102718. 0x01,0xd2,0xe5,0xe5,
  102719. 17,
  102720. 255,255,255,255,255,255,255,255,
  102721. 255,255,255,255,255,255,255,255,255};
  102722. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102723. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  102724. 0x01,0x02,0x03,0x04,3,0,0,0,
  102725. 0xef,0xdd,0x88,0xde,
  102726. 7,
  102727. 255,255,75,255,4,255,0};
  102728. /* packet that overspans over an entire page */
  102729. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102730. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102731. 0x01,0x02,0x03,0x04,0,0,0,0,
  102732. 0xff,0x7b,0x23,0x17,
  102733. 1,
  102734. 0};
  102735. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102736. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  102737. 0x01,0x02,0x03,0x04,1,0,0,0,
  102738. 0x3c,0xd9,0x4d,0x3f,
  102739. 17,
  102740. 100,255,255,255,255,255,255,255,255,
  102741. 255,255,255,255,255,255,255,255};
  102742. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102743. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  102744. 0x01,0x02,0x03,0x04,2,0,0,0,
  102745. 0xd4,0xe0,0x60,0xe5,
  102746. 1,0};
  102747. void test_pack(const int *pl, const int **headers, int byteskip,
  102748. int pageskip, int packetskip){
  102749. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  102750. long inptr=0;
  102751. long outptr=0;
  102752. long deptr=0;
  102753. long depacket=0;
  102754. long granule_pos=7,pageno=0;
  102755. int i,j,packets,pageout=pageskip;
  102756. int eosflag=0;
  102757. int bosflag=0;
  102758. int byteskipcount=0;
  102759. ogg_stream_reset(&os_en);
  102760. ogg_stream_reset(&os_de);
  102761. ogg_sync_reset(&oy);
  102762. for(packets=0;packets<packetskip;packets++)
  102763. depacket+=pl[packets];
  102764. for(packets=0;;packets++)if(pl[packets]==-1)break;
  102765. for(i=0;i<packets;i++){
  102766. /* construct a test packet */
  102767. ogg_packet op;
  102768. int len=pl[i];
  102769. op.packet=data+inptr;
  102770. op.bytes=len;
  102771. op.e_o_s=(pl[i+1]<0?1:0);
  102772. op.granulepos=granule_pos;
  102773. granule_pos+=1024;
  102774. for(j=0;j<len;j++)data[inptr++]=i+j;
  102775. /* submit the test packet */
  102776. ogg_stream_packetin(&os_en,&op);
  102777. /* retrieve any finished pages */
  102778. {
  102779. ogg_page og;
  102780. while(ogg_stream_pageout(&os_en,&og)){
  102781. /* We have a page. Check it carefully */
  102782. fprintf(stderr,"%ld, ",pageno);
  102783. if(headers[pageno]==NULL){
  102784. fprintf(stderr,"coded too many pages!\n");
  102785. exit(1);
  102786. }
  102787. check_page(data+outptr,headers[pageno],&og);
  102788. outptr+=og.body_len;
  102789. pageno++;
  102790. if(pageskip){
  102791. bosflag=1;
  102792. pageskip--;
  102793. deptr+=og.body_len;
  102794. }
  102795. /* have a complete page; submit it to sync/decode */
  102796. {
  102797. ogg_page og_de;
  102798. ogg_packet op_de,op_de2;
  102799. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  102800. char *next=buf;
  102801. byteskipcount+=og.header_len;
  102802. if(byteskipcount>byteskip){
  102803. memcpy(next,og.header,byteskipcount-byteskip);
  102804. next+=byteskipcount-byteskip;
  102805. byteskipcount=byteskip;
  102806. }
  102807. byteskipcount+=og.body_len;
  102808. if(byteskipcount>byteskip){
  102809. memcpy(next,og.body,byteskipcount-byteskip);
  102810. next+=byteskipcount-byteskip;
  102811. byteskipcount=byteskip;
  102812. }
  102813. ogg_sync_wrote(&oy,next-buf);
  102814. while(1){
  102815. int ret=ogg_sync_pageout(&oy,&og_de);
  102816. if(ret==0)break;
  102817. if(ret<0)continue;
  102818. /* got a page. Happy happy. Verify that it's good. */
  102819. fprintf(stderr,"(%ld), ",pageout);
  102820. check_page(data+deptr,headers[pageout],&og_de);
  102821. deptr+=og_de.body_len;
  102822. pageout++;
  102823. /* submit it to deconstitution */
  102824. ogg_stream_pagein(&os_de,&og_de);
  102825. /* packets out? */
  102826. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  102827. ogg_stream_packetpeek(&os_de,NULL);
  102828. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  102829. /* verify peek and out match */
  102830. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  102831. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  102832. depacket);
  102833. exit(1);
  102834. }
  102835. /* verify the packet! */
  102836. /* check data */
  102837. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  102838. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  102839. depacket);
  102840. exit(1);
  102841. }
  102842. /* check bos flag */
  102843. if(bosflag==0 && op_de.b_o_s==0){
  102844. fprintf(stderr,"b_o_s flag not set on packet!\n");
  102845. exit(1);
  102846. }
  102847. if(bosflag && op_de.b_o_s){
  102848. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  102849. exit(1);
  102850. }
  102851. bosflag=1;
  102852. depacket+=op_de.bytes;
  102853. /* check eos flag */
  102854. if(eosflag){
  102855. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  102856. exit(1);
  102857. }
  102858. if(op_de.e_o_s)eosflag=1;
  102859. /* check granulepos flag */
  102860. if(op_de.granulepos!=-1){
  102861. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  102862. }
  102863. }
  102864. }
  102865. }
  102866. }
  102867. }
  102868. }
  102869. _ogg_free(data);
  102870. if(headers[pageno]!=NULL){
  102871. fprintf(stderr,"did not write last page!\n");
  102872. exit(1);
  102873. }
  102874. if(headers[pageout]!=NULL){
  102875. fprintf(stderr,"did not decode last page!\n");
  102876. exit(1);
  102877. }
  102878. if(inptr!=outptr){
  102879. fprintf(stderr,"encoded page data incomplete!\n");
  102880. exit(1);
  102881. }
  102882. if(inptr!=deptr){
  102883. fprintf(stderr,"decoded page data incomplete!\n");
  102884. exit(1);
  102885. }
  102886. if(inptr!=depacket){
  102887. fprintf(stderr,"decoded packet data incomplete!\n");
  102888. exit(1);
  102889. }
  102890. if(!eosflag){
  102891. fprintf(stderr,"Never got a packet with EOS set!\n");
  102892. exit(1);
  102893. }
  102894. fprintf(stderr,"ok.\n");
  102895. }
  102896. int main(void){
  102897. ogg_stream_init(&os_en,0x04030201);
  102898. ogg_stream_init(&os_de,0x04030201);
  102899. ogg_sync_init(&oy);
  102900. /* Exercise each code path in the framing code. Also verify that
  102901. the checksums are working. */
  102902. {
  102903. /* 17 only */
  102904. const int packets[]={17, -1};
  102905. const int *headret[]={head1_0,NULL};
  102906. fprintf(stderr,"testing single page encoding... ");
  102907. test_pack(packets,headret,0,0,0);
  102908. }
  102909. {
  102910. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  102911. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  102912. const int *headret[]={head1_1,head2_1,NULL};
  102913. fprintf(stderr,"testing basic page encoding... ");
  102914. test_pack(packets,headret,0,0,0);
  102915. }
  102916. {
  102917. /* nil packets; beginning,middle,end */
  102918. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  102919. const int *headret[]={head1_2,head2_2,NULL};
  102920. fprintf(stderr,"testing basic nil packets... ");
  102921. test_pack(packets,headret,0,0,0);
  102922. }
  102923. {
  102924. /* large initial packet */
  102925. const int packets[]={4345,259,255,-1};
  102926. const int *headret[]={head1_3,head2_3,NULL};
  102927. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  102928. test_pack(packets,headret,0,0,0);
  102929. }
  102930. {
  102931. /* continuing packet test */
  102932. const int packets[]={0,4345,259,255,-1};
  102933. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  102934. fprintf(stderr,"testing single packet page span... ");
  102935. test_pack(packets,headret,0,0,0);
  102936. }
  102937. /* page with the 255 segment limit */
  102938. {
  102939. const int packets[]={0,10,10,10,10,10,10,10,10,
  102940. 10,10,10,10,10,10,10,10,
  102941. 10,10,10,10,10,10,10,10,
  102942. 10,10,10,10,10,10,10,10,
  102943. 10,10,10,10,10,10,10,10,
  102944. 10,10,10,10,10,10,10,10,
  102945. 10,10,10,10,10,10,10,10,
  102946. 10,10,10,10,10,10,10,10,
  102947. 10,10,10,10,10,10,10,10,
  102948. 10,10,10,10,10,10,10,10,
  102949. 10,10,10,10,10,10,10,10,
  102950. 10,10,10,10,10,10,10,10,
  102951. 10,10,10,10,10,10,10,10,
  102952. 10,10,10,10,10,10,10,10,
  102953. 10,10,10,10,10,10,10,10,
  102954. 10,10,10,10,10,10,10,10,
  102955. 10,10,10,10,10,10,10,10,
  102956. 10,10,10,10,10,10,10,10,
  102957. 10,10,10,10,10,10,10,10,
  102958. 10,10,10,10,10,10,10,10,
  102959. 10,10,10,10,10,10,10,10,
  102960. 10,10,10,10,10,10,10,10,
  102961. 10,10,10,10,10,10,10,10,
  102962. 10,10,10,10,10,10,10,10,
  102963. 10,10,10,10,10,10,10,10,
  102964. 10,10,10,10,10,10,10,10,
  102965. 10,10,10,10,10,10,10,10,
  102966. 10,10,10,10,10,10,10,10,
  102967. 10,10,10,10,10,10,10,10,
  102968. 10,10,10,10,10,10,10,10,
  102969. 10,10,10,10,10,10,10,10,
  102970. 10,10,10,10,10,10,10,50,-1};
  102971. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  102972. fprintf(stderr,"testing max packet segments... ");
  102973. test_pack(packets,headret,0,0,0);
  102974. }
  102975. {
  102976. /* packet that overspans over an entire page */
  102977. const int packets[]={0,100,9000,259,255,-1};
  102978. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  102979. fprintf(stderr,"testing very large packets... ");
  102980. test_pack(packets,headret,0,0,0);
  102981. }
  102982. {
  102983. /* test for the libogg 1.1.1 resync in large continuation bug
  102984. found by Josh Coalson) */
  102985. const int packets[]={0,100,9000,259,255,-1};
  102986. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  102987. fprintf(stderr,"testing continuation resync in very large packets... ");
  102988. test_pack(packets,headret,100,2,3);
  102989. }
  102990. {
  102991. /* term only page. why not? */
  102992. const int packets[]={0,100,4080,-1};
  102993. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  102994. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  102995. test_pack(packets,headret,0,0,0);
  102996. }
  102997. {
  102998. /* build a bunch of pages for testing */
  102999. unsigned char *data=_ogg_malloc(1024*1024);
  103000. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  103001. int inptr=0,i,j;
  103002. ogg_page og[5];
  103003. ogg_stream_reset(&os_en);
  103004. for(i=0;pl[i]!=-1;i++){
  103005. ogg_packet op;
  103006. int len=pl[i];
  103007. op.packet=data+inptr;
  103008. op.bytes=len;
  103009. op.e_o_s=(pl[i+1]<0?1:0);
  103010. op.granulepos=(i+1)*1000;
  103011. for(j=0;j<len;j++)data[inptr++]=i+j;
  103012. ogg_stream_packetin(&os_en,&op);
  103013. }
  103014. _ogg_free(data);
  103015. /* retrieve finished pages */
  103016. for(i=0;i<5;i++){
  103017. if(ogg_stream_pageout(&os_en,&og[i])==0){
  103018. fprintf(stderr,"Too few pages output building sync tests!\n");
  103019. exit(1);
  103020. }
  103021. copy_page(&og[i]);
  103022. }
  103023. /* Test lost pages on pagein/packetout: no rollback */
  103024. {
  103025. ogg_page temp;
  103026. ogg_packet test;
  103027. fprintf(stderr,"Testing loss of pages... ");
  103028. ogg_sync_reset(&oy);
  103029. ogg_stream_reset(&os_de);
  103030. for(i=0;i<5;i++){
  103031. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103032. og[i].header_len);
  103033. ogg_sync_wrote(&oy,og[i].header_len);
  103034. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103035. ogg_sync_wrote(&oy,og[i].body_len);
  103036. }
  103037. ogg_sync_pageout(&oy,&temp);
  103038. ogg_stream_pagein(&os_de,&temp);
  103039. ogg_sync_pageout(&oy,&temp);
  103040. ogg_stream_pagein(&os_de,&temp);
  103041. ogg_sync_pageout(&oy,&temp);
  103042. /* skip */
  103043. ogg_sync_pageout(&oy,&temp);
  103044. ogg_stream_pagein(&os_de,&temp);
  103045. /* do we get the expected results/packets? */
  103046. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103047. checkpacket(&test,0,0,0);
  103048. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103049. checkpacket(&test,100,1,-1);
  103050. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103051. checkpacket(&test,4079,2,3000);
  103052. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103053. fprintf(stderr,"Error: loss of page did not return error\n");
  103054. exit(1);
  103055. }
  103056. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103057. checkpacket(&test,76,5,-1);
  103058. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103059. checkpacket(&test,34,6,-1);
  103060. fprintf(stderr,"ok.\n");
  103061. }
  103062. /* Test lost pages on pagein/packetout: rollback with continuation */
  103063. {
  103064. ogg_page temp;
  103065. ogg_packet test;
  103066. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  103067. ogg_sync_reset(&oy);
  103068. ogg_stream_reset(&os_de);
  103069. for(i=0;i<5;i++){
  103070. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103071. og[i].header_len);
  103072. ogg_sync_wrote(&oy,og[i].header_len);
  103073. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103074. ogg_sync_wrote(&oy,og[i].body_len);
  103075. }
  103076. ogg_sync_pageout(&oy,&temp);
  103077. ogg_stream_pagein(&os_de,&temp);
  103078. ogg_sync_pageout(&oy,&temp);
  103079. ogg_stream_pagein(&os_de,&temp);
  103080. ogg_sync_pageout(&oy,&temp);
  103081. ogg_stream_pagein(&os_de,&temp);
  103082. ogg_sync_pageout(&oy,&temp);
  103083. /* skip */
  103084. ogg_sync_pageout(&oy,&temp);
  103085. ogg_stream_pagein(&os_de,&temp);
  103086. /* do we get the expected results/packets? */
  103087. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103088. checkpacket(&test,0,0,0);
  103089. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103090. checkpacket(&test,100,1,-1);
  103091. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103092. checkpacket(&test,4079,2,3000);
  103093. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103094. checkpacket(&test,2956,3,4000);
  103095. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103096. fprintf(stderr,"Error: loss of page did not return error\n");
  103097. exit(1);
  103098. }
  103099. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103100. checkpacket(&test,300,13,14000);
  103101. fprintf(stderr,"ok.\n");
  103102. }
  103103. /* the rest only test sync */
  103104. {
  103105. ogg_page og_de;
  103106. /* Test fractional page inputs: incomplete capture */
  103107. fprintf(stderr,"Testing sync on partial inputs... ");
  103108. ogg_sync_reset(&oy);
  103109. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103110. 3);
  103111. ogg_sync_wrote(&oy,3);
  103112. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103113. /* Test fractional page inputs: incomplete fixed header */
  103114. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  103115. 20);
  103116. ogg_sync_wrote(&oy,20);
  103117. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103118. /* Test fractional page inputs: incomplete header */
  103119. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  103120. 5);
  103121. ogg_sync_wrote(&oy,5);
  103122. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103123. /* Test fractional page inputs: incomplete body */
  103124. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  103125. og[1].header_len-28);
  103126. ogg_sync_wrote(&oy,og[1].header_len-28);
  103127. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103128. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  103129. ogg_sync_wrote(&oy,1000);
  103130. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103131. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  103132. og[1].body_len-1000);
  103133. ogg_sync_wrote(&oy,og[1].body_len-1000);
  103134. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103135. fprintf(stderr,"ok.\n");
  103136. }
  103137. /* Test fractional page inputs: page + incomplete capture */
  103138. {
  103139. ogg_page og_de;
  103140. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  103141. ogg_sync_reset(&oy);
  103142. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103143. og[1].header_len);
  103144. ogg_sync_wrote(&oy,og[1].header_len);
  103145. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103146. og[1].body_len);
  103147. ogg_sync_wrote(&oy,og[1].body_len);
  103148. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103149. 20);
  103150. ogg_sync_wrote(&oy,20);
  103151. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103152. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103153. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  103154. og[1].header_len-20);
  103155. ogg_sync_wrote(&oy,og[1].header_len-20);
  103156. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103157. og[1].body_len);
  103158. ogg_sync_wrote(&oy,og[1].body_len);
  103159. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103160. fprintf(stderr,"ok.\n");
  103161. }
  103162. /* Test recapture: garbage + page */
  103163. {
  103164. ogg_page og_de;
  103165. fprintf(stderr,"Testing search for capture... ");
  103166. ogg_sync_reset(&oy);
  103167. /* 'garbage' */
  103168. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103169. og[1].body_len);
  103170. ogg_sync_wrote(&oy,og[1].body_len);
  103171. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103172. og[1].header_len);
  103173. ogg_sync_wrote(&oy,og[1].header_len);
  103174. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103175. og[1].body_len);
  103176. ogg_sync_wrote(&oy,og[1].body_len);
  103177. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103178. 20);
  103179. ogg_sync_wrote(&oy,20);
  103180. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103181. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103182. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103183. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  103184. og[2].header_len-20);
  103185. ogg_sync_wrote(&oy,og[2].header_len-20);
  103186. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103187. og[2].body_len);
  103188. ogg_sync_wrote(&oy,og[2].body_len);
  103189. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103190. fprintf(stderr,"ok.\n");
  103191. }
  103192. /* Test recapture: page + garbage + page */
  103193. {
  103194. ogg_page og_de;
  103195. fprintf(stderr,"Testing recapture... ");
  103196. ogg_sync_reset(&oy);
  103197. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103198. og[1].header_len);
  103199. ogg_sync_wrote(&oy,og[1].header_len);
  103200. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103201. og[1].body_len);
  103202. ogg_sync_wrote(&oy,og[1].body_len);
  103203. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103204. og[2].header_len);
  103205. ogg_sync_wrote(&oy,og[2].header_len);
  103206. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103207. og[2].header_len);
  103208. ogg_sync_wrote(&oy,og[2].header_len);
  103209. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103210. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103211. og[2].body_len-5);
  103212. ogg_sync_wrote(&oy,og[2].body_len-5);
  103213. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  103214. og[3].header_len);
  103215. ogg_sync_wrote(&oy,og[3].header_len);
  103216. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  103217. og[3].body_len);
  103218. ogg_sync_wrote(&oy,og[3].body_len);
  103219. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103220. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103221. fprintf(stderr,"ok.\n");
  103222. }
  103223. /* Free page data that was previously copied */
  103224. {
  103225. for(i=0;i<5;i++){
  103226. free_page(&og[i]);
  103227. }
  103228. }
  103229. }
  103230. return(0);
  103231. }
  103232. #endif
  103233. #endif
  103234. /********* End of inlined file: framing.c *********/
  103235. /********* Start of inlined file: analysis.c *********/
  103236. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103237. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103238. // tasks..
  103239. #ifdef _MSC_VER
  103240. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103241. #endif
  103242. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103243. #if JUCE_USE_OGGVORBIS
  103244. #include <stdio.h>
  103245. #include <string.h>
  103246. #include <math.h>
  103247. /********* Start of inlined file: codec_internal.h *********/
  103248. #ifndef _V_CODECI_H_
  103249. #define _V_CODECI_H_
  103250. /********* Start of inlined file: envelope.h *********/
  103251. #ifndef _V_ENVELOPE_
  103252. #define _V_ENVELOPE_
  103253. /********* Start of inlined file: mdct.h *********/
  103254. #ifndef _OGG_mdct_H_
  103255. #define _OGG_mdct_H_
  103256. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  103257. #ifdef MDCT_INTEGERIZED
  103258. #define DATA_TYPE int
  103259. #define REG_TYPE register int
  103260. #define TRIGBITS 14
  103261. #define cPI3_8 6270
  103262. #define cPI2_8 11585
  103263. #define cPI1_8 15137
  103264. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  103265. #define MULT_NORM(x) ((x)>>TRIGBITS)
  103266. #define HALVE(x) ((x)>>1)
  103267. #else
  103268. #define DATA_TYPE float
  103269. #define REG_TYPE float
  103270. #define cPI3_8 .38268343236508977175F
  103271. #define cPI2_8 .70710678118654752441F
  103272. #define cPI1_8 .92387953251128675613F
  103273. #define FLOAT_CONV(x) (x)
  103274. #define MULT_NORM(x) (x)
  103275. #define HALVE(x) ((x)*.5f)
  103276. #endif
  103277. typedef struct {
  103278. int n;
  103279. int log2n;
  103280. DATA_TYPE *trig;
  103281. int *bitrev;
  103282. DATA_TYPE scale;
  103283. } mdct_lookup;
  103284. extern void mdct_init(mdct_lookup *lookup,int n);
  103285. extern void mdct_clear(mdct_lookup *l);
  103286. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103287. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103288. #endif
  103289. /********* End of inlined file: mdct.h *********/
  103290. #define VE_PRE 16
  103291. #define VE_WIN 4
  103292. #define VE_POST 2
  103293. #define VE_AMP (VE_PRE+VE_POST-1)
  103294. #define VE_BANDS 7
  103295. #define VE_NEARDC 15
  103296. #define VE_MINSTRETCH 2 /* a bit less than short block */
  103297. #define VE_MAXSTRETCH 12 /* one-third full block */
  103298. typedef struct {
  103299. float ampbuf[VE_AMP];
  103300. int ampptr;
  103301. float nearDC[VE_NEARDC];
  103302. float nearDC_acc;
  103303. float nearDC_partialacc;
  103304. int nearptr;
  103305. } envelope_filter_state;
  103306. typedef struct {
  103307. int begin;
  103308. int end;
  103309. float *window;
  103310. float total;
  103311. } envelope_band;
  103312. typedef struct {
  103313. int ch;
  103314. int winlength;
  103315. int searchstep;
  103316. float minenergy;
  103317. mdct_lookup mdct;
  103318. float *mdct_win;
  103319. envelope_band band[VE_BANDS];
  103320. envelope_filter_state *filter;
  103321. int stretch;
  103322. int *mark;
  103323. long storage;
  103324. long current;
  103325. long curmark;
  103326. long cursor;
  103327. } envelope_lookup;
  103328. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  103329. extern void _ve_envelope_clear(envelope_lookup *e);
  103330. extern long _ve_envelope_search(vorbis_dsp_state *v);
  103331. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  103332. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  103333. #endif
  103334. /********* End of inlined file: envelope.h *********/
  103335. /********* Start of inlined file: codebook.h *********/
  103336. #ifndef _V_CODEBOOK_H_
  103337. #define _V_CODEBOOK_H_
  103338. /* This structure encapsulates huffman and VQ style encoding books; it
  103339. doesn't do anything specific to either.
  103340. valuelist/quantlist are nonNULL (and q_* significant) only if
  103341. there's entry->value mapping to be done.
  103342. If encode-side mapping must be done (and thus the entry needs to be
  103343. hunted), the auxiliary encode pointer will point to a decision
  103344. tree. This is true of both VQ and huffman, but is mostly useful
  103345. with VQ.
  103346. */
  103347. typedef struct static_codebook{
  103348. long dim; /* codebook dimensions (elements per vector) */
  103349. long entries; /* codebook entries */
  103350. long *lengthlist; /* codeword lengths in bits */
  103351. /* mapping ***************************************************************/
  103352. int maptype; /* 0=none
  103353. 1=implicitly populated values from map column
  103354. 2=listed arbitrary values */
  103355. /* The below does a linear, single monotonic sequence mapping. */
  103356. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  103357. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  103358. int q_quant; /* bits: 0 < quant <= 16 */
  103359. int q_sequencep; /* bitflag */
  103360. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  103361. map == 2: list of dim*entries quantized entry vals
  103362. */
  103363. /* encode helpers ********************************************************/
  103364. struct encode_aux_nearestmatch *nearest_tree;
  103365. struct encode_aux_threshmatch *thresh_tree;
  103366. struct encode_aux_pigeonhole *pigeon_tree;
  103367. int allocedp;
  103368. } static_codebook;
  103369. /* this structures an arbitrary trained book to quickly find the
  103370. nearest cell match */
  103371. typedef struct encode_aux_nearestmatch{
  103372. /* pre-calculated partitioning tree */
  103373. long *ptr0;
  103374. long *ptr1;
  103375. long *p; /* decision points (each is an entry) */
  103376. long *q; /* decision points (each is an entry) */
  103377. long aux; /* number of tree entries */
  103378. long alloc;
  103379. } encode_aux_nearestmatch;
  103380. /* assumes a maptype of 1; encode side only, so that's OK */
  103381. typedef struct encode_aux_threshmatch{
  103382. float *quantthresh;
  103383. long *quantmap;
  103384. int quantvals;
  103385. int threshvals;
  103386. } encode_aux_threshmatch;
  103387. typedef struct encode_aux_pigeonhole{
  103388. float min;
  103389. float del;
  103390. int mapentries;
  103391. int quantvals;
  103392. long *pigeonmap;
  103393. long fittotal;
  103394. long *fitlist;
  103395. long *fitmap;
  103396. long *fitlength;
  103397. } encode_aux_pigeonhole;
  103398. typedef struct codebook{
  103399. long dim; /* codebook dimensions (elements per vector) */
  103400. long entries; /* codebook entries */
  103401. long used_entries; /* populated codebook entries */
  103402. const static_codebook *c;
  103403. /* for encode, the below are entry-ordered, fully populated */
  103404. /* for decode, the below are ordered by bitreversed codeword and only
  103405. used entries are populated */
  103406. float *valuelist; /* list of dim*entries actual entry values */
  103407. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  103408. int *dec_index; /* only used if sparseness collapsed */
  103409. char *dec_codelengths;
  103410. ogg_uint32_t *dec_firsttable;
  103411. int dec_firsttablen;
  103412. int dec_maxlength;
  103413. } codebook;
  103414. extern void vorbis_staticbook_clear(static_codebook *b);
  103415. extern void vorbis_staticbook_destroy(static_codebook *b);
  103416. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  103417. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  103418. extern void vorbis_book_clear(codebook *b);
  103419. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  103420. extern float *_book_logdist(const static_codebook *b,float *vals);
  103421. extern float _float32_unpack(long val);
  103422. extern long _float32_pack(float val);
  103423. extern int _best(codebook *book, float *a, int step);
  103424. extern int _ilog(unsigned int v);
  103425. extern long _book_maptype1_quantvals(const static_codebook *b);
  103426. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  103427. extern long vorbis_book_codeword(codebook *book,int entry);
  103428. extern long vorbis_book_codelen(codebook *book,int entry);
  103429. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  103430. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  103431. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  103432. extern int vorbis_book_errorv(codebook *book, float *a);
  103433. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  103434. oggpack_buffer *b);
  103435. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  103436. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  103437. oggpack_buffer *b,int n);
  103438. extern long vorbis_book_decodev_set(codebook *book, float *a,
  103439. oggpack_buffer *b,int n);
  103440. extern long vorbis_book_decodev_add(codebook *book, float *a,
  103441. oggpack_buffer *b,int n);
  103442. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  103443. long off,int ch,
  103444. oggpack_buffer *b,int n);
  103445. #endif
  103446. /********* End of inlined file: codebook.h *********/
  103447. #define BLOCKTYPE_IMPULSE 0
  103448. #define BLOCKTYPE_PADDING 1
  103449. #define BLOCKTYPE_TRANSITION 0
  103450. #define BLOCKTYPE_LONG 1
  103451. #define PACKETBLOBS 15
  103452. typedef struct vorbis_block_internal{
  103453. float **pcmdelay; /* this is a pointer into local storage */
  103454. float ampmax;
  103455. int blocktype;
  103456. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  103457. blob [PACKETBLOBS/2] points to
  103458. the oggpack_buffer in the
  103459. main vorbis_block */
  103460. } vorbis_block_internal;
  103461. typedef void vorbis_look_floor;
  103462. typedef void vorbis_look_residue;
  103463. typedef void vorbis_look_transform;
  103464. /* mode ************************************************************/
  103465. typedef struct {
  103466. int blockflag;
  103467. int windowtype;
  103468. int transformtype;
  103469. int mapping;
  103470. } vorbis_info_mode;
  103471. typedef void vorbis_info_floor;
  103472. typedef void vorbis_info_residue;
  103473. typedef void vorbis_info_mapping;
  103474. /********* Start of inlined file: psy.h *********/
  103475. #ifndef _V_PSY_H_
  103476. #define _V_PSY_H_
  103477. /********* Start of inlined file: smallft.h *********/
  103478. #ifndef _V_SMFT_H_
  103479. #define _V_SMFT_H_
  103480. typedef struct {
  103481. int n;
  103482. float *trigcache;
  103483. int *splitcache;
  103484. } drft_lookup;
  103485. extern void drft_forward(drft_lookup *l,float *data);
  103486. extern void drft_backward(drft_lookup *l,float *data);
  103487. extern void drft_init(drft_lookup *l,int n);
  103488. extern void drft_clear(drft_lookup *l);
  103489. #endif
  103490. /********* End of inlined file: smallft.h *********/
  103491. /********* Start of inlined file: backends.h *********/
  103492. /* this is exposed up here because we need it for static modes.
  103493. Lookups for each backend aren't exposed because there's no reason
  103494. to do so */
  103495. #ifndef _vorbis_backend_h_
  103496. #define _vorbis_backend_h_
  103497. /* this would all be simpler/shorter with templates, but.... */
  103498. /* Floor backend generic *****************************************/
  103499. typedef struct{
  103500. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  103501. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  103502. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  103503. void (*free_info) (vorbis_info_floor *);
  103504. void (*free_look) (vorbis_look_floor *);
  103505. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  103506. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  103507. void *buffer,float *);
  103508. } vorbis_func_floor;
  103509. typedef struct{
  103510. int order;
  103511. long rate;
  103512. long barkmap;
  103513. int ampbits;
  103514. int ampdB;
  103515. int numbooks; /* <= 16 */
  103516. int books[16];
  103517. float lessthan; /* encode-only config setting hacks for libvorbis */
  103518. float greaterthan; /* encode-only config setting hacks for libvorbis */
  103519. } vorbis_info_floor0;
  103520. #define VIF_POSIT 63
  103521. #define VIF_CLASS 16
  103522. #define VIF_PARTS 31
  103523. typedef struct{
  103524. int partitions; /* 0 to 31 */
  103525. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  103526. int class_dim[VIF_CLASS]; /* 1 to 8 */
  103527. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  103528. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  103529. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  103530. int mult; /* 1 2 3 or 4 */
  103531. int postlist[VIF_POSIT+2]; /* first two implicit */
  103532. /* encode side analysis parameters */
  103533. float maxover;
  103534. float maxunder;
  103535. float maxerr;
  103536. float twofitweight;
  103537. float twofitatten;
  103538. int n;
  103539. } vorbis_info_floor1;
  103540. /* Residue backend generic *****************************************/
  103541. typedef struct{
  103542. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  103543. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  103544. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  103545. vorbis_info_residue *);
  103546. void (*free_info) (vorbis_info_residue *);
  103547. void (*free_look) (vorbis_look_residue *);
  103548. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  103549. float **,int *,int);
  103550. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  103551. vorbis_look_residue *,
  103552. float **,float **,int *,int,long **);
  103553. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  103554. float **,int *,int);
  103555. } vorbis_func_residue;
  103556. typedef struct vorbis_info_residue0{
  103557. /* block-partitioned VQ coded straight residue */
  103558. long begin;
  103559. long end;
  103560. /* first stage (lossless partitioning) */
  103561. int grouping; /* group n vectors per partition */
  103562. int partitions; /* possible codebooks for a partition */
  103563. int groupbook; /* huffbook for partitioning */
  103564. int secondstages[64]; /* expanded out to pointers in lookup */
  103565. int booklist[256]; /* list of second stage books */
  103566. float classmetric1[64];
  103567. float classmetric2[64];
  103568. } vorbis_info_residue0;
  103569. /* Mapping backend generic *****************************************/
  103570. typedef struct{
  103571. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  103572. oggpack_buffer *);
  103573. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  103574. void (*free_info) (vorbis_info_mapping *);
  103575. int (*forward) (struct vorbis_block *vb);
  103576. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  103577. } vorbis_func_mapping;
  103578. typedef struct vorbis_info_mapping0{
  103579. int submaps; /* <= 16 */
  103580. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  103581. int floorsubmap[16]; /* [mux] submap to floors */
  103582. int residuesubmap[16]; /* [mux] submap to residue */
  103583. int coupling_steps;
  103584. int coupling_mag[256];
  103585. int coupling_ang[256];
  103586. } vorbis_info_mapping0;
  103587. #endif
  103588. /********* End of inlined file: backends.h *********/
  103589. #ifndef EHMER_MAX
  103590. #define EHMER_MAX 56
  103591. #endif
  103592. /* psychoacoustic setup ********************************************/
  103593. #define P_BANDS 17 /* 62Hz to 16kHz */
  103594. #define P_LEVELS 8 /* 30dB to 100dB */
  103595. #define P_LEVEL_0 30. /* 30 dB */
  103596. #define P_NOISECURVES 3
  103597. #define NOISE_COMPAND_LEVELS 40
  103598. typedef struct vorbis_info_psy{
  103599. int blockflag;
  103600. float ath_adjatt;
  103601. float ath_maxatt;
  103602. float tone_masteratt[P_NOISECURVES];
  103603. float tone_centerboost;
  103604. float tone_decay;
  103605. float tone_abs_limit;
  103606. float toneatt[P_BANDS];
  103607. int noisemaskp;
  103608. float noisemaxsupp;
  103609. float noisewindowlo;
  103610. float noisewindowhi;
  103611. int noisewindowlomin;
  103612. int noisewindowhimin;
  103613. int noisewindowfixed;
  103614. float noiseoff[P_NOISECURVES][P_BANDS];
  103615. float noisecompand[NOISE_COMPAND_LEVELS];
  103616. float max_curve_dB;
  103617. int normal_channel_p;
  103618. int normal_point_p;
  103619. int normal_start;
  103620. int normal_partition;
  103621. double normal_thresh;
  103622. } vorbis_info_psy;
  103623. typedef struct{
  103624. int eighth_octave_lines;
  103625. /* for block long/short tuning; encode only */
  103626. float preecho_thresh[VE_BANDS];
  103627. float postecho_thresh[VE_BANDS];
  103628. float stretch_penalty;
  103629. float preecho_minenergy;
  103630. float ampmax_att_per_sec;
  103631. /* channel coupling config */
  103632. int coupling_pkHz[PACKETBLOBS];
  103633. int coupling_pointlimit[2][PACKETBLOBS];
  103634. int coupling_prepointamp[PACKETBLOBS];
  103635. int coupling_postpointamp[PACKETBLOBS];
  103636. int sliding_lowpass[2][PACKETBLOBS];
  103637. } vorbis_info_psy_global;
  103638. typedef struct {
  103639. float ampmax;
  103640. int channels;
  103641. vorbis_info_psy_global *gi;
  103642. int coupling_pointlimit[2][P_NOISECURVES];
  103643. } vorbis_look_psy_global;
  103644. typedef struct {
  103645. int n;
  103646. struct vorbis_info_psy *vi;
  103647. float ***tonecurves;
  103648. float **noiseoffset;
  103649. float *ath;
  103650. long *octave; /* in n.ocshift format */
  103651. long *bark;
  103652. long firstoc;
  103653. long shiftoc;
  103654. int eighth_octave_lines; /* power of two, please */
  103655. int total_octave_lines;
  103656. long rate; /* cache it */
  103657. float m_val; /* Masking compensation value */
  103658. } vorbis_look_psy;
  103659. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  103660. vorbis_info_psy_global *gi,int n,long rate);
  103661. extern void _vp_psy_clear(vorbis_look_psy *p);
  103662. extern void *_vi_psy_dup(void *source);
  103663. extern void _vi_psy_free(vorbis_info_psy *i);
  103664. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  103665. extern void _vp_remove_floor(vorbis_look_psy *p,
  103666. float *mdct,
  103667. int *icodedflr,
  103668. float *residue,
  103669. int sliding_lowpass);
  103670. extern void _vp_noisemask(vorbis_look_psy *p,
  103671. float *logmdct,
  103672. float *logmask);
  103673. extern void _vp_tonemask(vorbis_look_psy *p,
  103674. float *logfft,
  103675. float *logmask,
  103676. float global_specmax,
  103677. float local_specmax);
  103678. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  103679. float *noise,
  103680. float *tone,
  103681. int offset_select,
  103682. float *logmask,
  103683. float *mdct,
  103684. float *logmdct);
  103685. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  103686. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  103687. vorbis_info_psy_global *g,
  103688. vorbis_look_psy *p,
  103689. vorbis_info_mapping0 *vi,
  103690. float **mdct);
  103691. extern void _vp_couple(int blobno,
  103692. vorbis_info_psy_global *g,
  103693. vorbis_look_psy *p,
  103694. vorbis_info_mapping0 *vi,
  103695. float **res,
  103696. float **mag_memo,
  103697. int **mag_sort,
  103698. int **ifloor,
  103699. int *nonzero,
  103700. int sliding_lowpass);
  103701. extern void _vp_noise_normalize(vorbis_look_psy *p,
  103702. float *in,float *out,int *sortedindex);
  103703. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  103704. float *magnitudes,int *sortedindex);
  103705. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  103706. vorbis_look_psy *p,
  103707. vorbis_info_mapping0 *vi,
  103708. float **mags);
  103709. extern void hf_reduction(vorbis_info_psy_global *g,
  103710. vorbis_look_psy *p,
  103711. vorbis_info_mapping0 *vi,
  103712. float **mdct);
  103713. #endif
  103714. /********* End of inlined file: psy.h *********/
  103715. /********* Start of inlined file: bitrate.h *********/
  103716. #ifndef _V_BITRATE_H_
  103717. #define _V_BITRATE_H_
  103718. /********* Start of inlined file: os.h *********/
  103719. #ifndef _OS_H
  103720. #define _OS_H
  103721. /********************************************************************
  103722. * *
  103723. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  103724. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  103725. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  103726. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  103727. * *
  103728. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  103729. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  103730. * *
  103731. ********************************************************************
  103732. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  103733. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  103734. ********************************************************************/
  103735. #ifdef HAVE_CONFIG_H
  103736. #include "config.h"
  103737. #endif
  103738. #include <math.h>
  103739. /********* Start of inlined file: misc.h *********/
  103740. #ifndef _V_RANDOM_H_
  103741. #define _V_RANDOM_H_
  103742. extern int analysis_noisy;
  103743. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  103744. extern void _vorbis_block_ripcord(vorbis_block *vb);
  103745. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  103746. ogg_int64_t off);
  103747. #ifdef DEBUG_MALLOC
  103748. #define _VDBG_GRAPHFILE "malloc.m"
  103749. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  103750. extern void _VDBG_free(void *ptr,char *file,long line);
  103751. #ifndef MISC_C
  103752. #undef _ogg_malloc
  103753. #undef _ogg_calloc
  103754. #undef _ogg_realloc
  103755. #undef _ogg_free
  103756. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  103757. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  103758. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  103759. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  103760. #endif
  103761. #endif
  103762. #endif
  103763. /********* End of inlined file: misc.h *********/
  103764. #ifndef _V_IFDEFJAIL_H_
  103765. # define _V_IFDEFJAIL_H_
  103766. # ifdef __GNUC__
  103767. # define STIN static __inline__
  103768. # elif _WIN32
  103769. # define STIN static __inline
  103770. # else
  103771. # define STIN static
  103772. # endif
  103773. #ifdef DJGPP
  103774. # define rint(x) (floor((x)+0.5f))
  103775. #endif
  103776. #ifndef M_PI
  103777. # define M_PI (3.1415926536f)
  103778. #endif
  103779. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  103780. # include <malloc.h>
  103781. # define rint(x) (floor((x)+0.5f))
  103782. # define NO_FLOAT_MATH_LIB
  103783. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  103784. #endif
  103785. #if defined(__SYMBIAN32__) && defined(__WINS__)
  103786. void *_alloca(size_t size);
  103787. # define alloca _alloca
  103788. #endif
  103789. #ifndef FAST_HYPOT
  103790. # define FAST_HYPOT hypot
  103791. #endif
  103792. #endif
  103793. #ifdef HAVE_ALLOCA_H
  103794. # include <alloca.h>
  103795. #endif
  103796. #ifdef USE_MEMORY_H
  103797. # include <memory.h>
  103798. #endif
  103799. #ifndef min
  103800. # define min(x,y) ((x)>(y)?(y):(x))
  103801. #endif
  103802. #ifndef max
  103803. # define max(x,y) ((x)<(y)?(y):(x))
  103804. #endif
  103805. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  103806. # define VORBIS_FPU_CONTROL
  103807. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  103808. Because of encapsulation constraints (GCC can't see inside the asm
  103809. block and so we end up doing stupid things like a store/load that
  103810. is collectively a noop), we do it this way */
  103811. /* we must set up the fpu before this works!! */
  103812. typedef ogg_int16_t vorbis_fpu_control;
  103813. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  103814. ogg_int16_t ret;
  103815. ogg_int16_t temp;
  103816. __asm__ __volatile__("fnstcw %0\n\t"
  103817. "movw %0,%%dx\n\t"
  103818. "orw $62463,%%dx\n\t"
  103819. "movw %%dx,%1\n\t"
  103820. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  103821. *fpu=ret;
  103822. }
  103823. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  103824. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  103825. }
  103826. /* assumes the FPU is in round mode! */
  103827. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  103828. we get extra fst/fld to
  103829. truncate precision */
  103830. int i;
  103831. __asm__("fistl %0": "=m"(i) : "t"(f));
  103832. return(i);
  103833. }
  103834. #endif
  103835. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  103836. # define VORBIS_FPU_CONTROL
  103837. typedef ogg_int16_t vorbis_fpu_control;
  103838. static __inline int vorbis_ftoi(double f){
  103839. int i;
  103840. __asm{
  103841. fld f
  103842. fistp i
  103843. }
  103844. return i;
  103845. }
  103846. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  103847. }
  103848. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  103849. }
  103850. #endif
  103851. #ifndef VORBIS_FPU_CONTROL
  103852. typedef int vorbis_fpu_control;
  103853. static int vorbis_ftoi(double f){
  103854. return (int)(f+.5);
  103855. }
  103856. /* We don't have special code for this compiler/arch, so do it the slow way */
  103857. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  103858. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  103859. #endif
  103860. #endif /* _OS_H */
  103861. /********* End of inlined file: os.h *********/
  103862. /* encode side bitrate tracking */
  103863. typedef struct bitrate_manager_state {
  103864. int managed;
  103865. long avg_reservoir;
  103866. long minmax_reservoir;
  103867. long avg_bitsper;
  103868. long min_bitsper;
  103869. long max_bitsper;
  103870. long short_per_long;
  103871. double avgfloat;
  103872. vorbis_block *vb;
  103873. int choice;
  103874. } bitrate_manager_state;
  103875. typedef struct bitrate_manager_info{
  103876. long avg_rate;
  103877. long min_rate;
  103878. long max_rate;
  103879. long reservoir_bits;
  103880. double reservoir_bias;
  103881. double slew_damp;
  103882. } bitrate_manager_info;
  103883. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  103884. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  103885. extern int vorbis_bitrate_managed(vorbis_block *vb);
  103886. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103887. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  103888. #endif
  103889. /********* End of inlined file: bitrate.h *********/
  103890. static int ilog(unsigned int v){
  103891. int ret=0;
  103892. while(v){
  103893. ret++;
  103894. v>>=1;
  103895. }
  103896. return(ret);
  103897. }
  103898. static int ilog2(unsigned int v){
  103899. int ret=0;
  103900. if(v)--v;
  103901. while(v){
  103902. ret++;
  103903. v>>=1;
  103904. }
  103905. return(ret);
  103906. }
  103907. typedef struct private_state {
  103908. /* local lookup storage */
  103909. envelope_lookup *ve; /* envelope lookup */
  103910. int window[2];
  103911. vorbis_look_transform **transform[2]; /* block, type */
  103912. drft_lookup fft_look[2];
  103913. int modebits;
  103914. vorbis_look_floor **flr;
  103915. vorbis_look_residue **residue;
  103916. vorbis_look_psy *psy;
  103917. vorbis_look_psy_global *psy_g_look;
  103918. /* local storage, only used on the encoding side. This way the
  103919. application does not need to worry about freeing some packets'
  103920. memory and not others'; packet storage is always tracked.
  103921. Cleared next call to a _dsp_ function */
  103922. unsigned char *header;
  103923. unsigned char *header1;
  103924. unsigned char *header2;
  103925. bitrate_manager_state bms;
  103926. ogg_int64_t sample_count;
  103927. } private_state;
  103928. /* codec_setup_info contains all the setup information specific to the
  103929. specific compression/decompression mode in progress (eg,
  103930. psychoacoustic settings, channel setup, options, codebook
  103931. etc).
  103932. *********************************************************************/
  103933. /********* Start of inlined file: highlevel.h *********/
  103934. typedef struct highlevel_byblocktype {
  103935. double tone_mask_setting;
  103936. double tone_peaklimit_setting;
  103937. double noise_bias_setting;
  103938. double noise_compand_setting;
  103939. } highlevel_byblocktype;
  103940. typedef struct highlevel_encode_setup {
  103941. void *setup;
  103942. int set_in_stone;
  103943. double base_setting;
  103944. double long_setting;
  103945. double short_setting;
  103946. double impulse_noisetune;
  103947. int managed;
  103948. long bitrate_min;
  103949. long bitrate_av;
  103950. double bitrate_av_damp;
  103951. long bitrate_max;
  103952. long bitrate_reservoir;
  103953. double bitrate_reservoir_bias;
  103954. int impulse_block_p;
  103955. int noise_normalize_p;
  103956. double stereo_point_setting;
  103957. double lowpass_kHz;
  103958. double ath_floating_dB;
  103959. double ath_absolute_dB;
  103960. double amplitude_track_dBpersec;
  103961. double trigger_setting;
  103962. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  103963. } highlevel_encode_setup;
  103964. /********* End of inlined file: highlevel.h *********/
  103965. typedef struct codec_setup_info {
  103966. /* Vorbis supports only short and long blocks, but allows the
  103967. encoder to choose the sizes */
  103968. long blocksizes[2];
  103969. /* modes are the primary means of supporting on-the-fly different
  103970. blocksizes, different channel mappings (LR or M/A),
  103971. different residue backends, etc. Each mode consists of a
  103972. blocksize flag and a mapping (along with the mapping setup */
  103973. int modes;
  103974. int maps;
  103975. int floors;
  103976. int residues;
  103977. int books;
  103978. int psys; /* encode only */
  103979. vorbis_info_mode *mode_param[64];
  103980. int map_type[64];
  103981. vorbis_info_mapping *map_param[64];
  103982. int floor_type[64];
  103983. vorbis_info_floor *floor_param[64];
  103984. int residue_type[64];
  103985. vorbis_info_residue *residue_param[64];
  103986. static_codebook *book_param[256];
  103987. codebook *fullbooks;
  103988. vorbis_info_psy *psy_param[4]; /* encode only */
  103989. vorbis_info_psy_global psy_g_param;
  103990. bitrate_manager_info bi;
  103991. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  103992. highly redundant structure, but
  103993. improves clarity of program flow. */
  103994. int halfrate_flag; /* painless downsample for decode */
  103995. } codec_setup_info;
  103996. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  103997. extern void _vp_global_free(vorbis_look_psy_global *look);
  103998. #endif
  103999. /********* End of inlined file: codec_internal.h *********/
  104000. /********* Start of inlined file: registry.h *********/
  104001. #ifndef _V_REG_H_
  104002. #define _V_REG_H_
  104003. #define VI_TRANSFORMB 1
  104004. #define VI_WINDOWB 1
  104005. #define VI_TIMEB 1
  104006. #define VI_FLOORB 2
  104007. #define VI_RESB 3
  104008. #define VI_MAPB 1
  104009. extern vorbis_func_floor *_floor_P[];
  104010. extern vorbis_func_residue *_residue_P[];
  104011. extern vorbis_func_mapping *_mapping_P[];
  104012. #endif
  104013. /********* End of inlined file: registry.h *********/
  104014. /********* Start of inlined file: scales.h *********/
  104015. #ifndef _V_SCALES_H_
  104016. #define _V_SCALES_H_
  104017. #include <math.h>
  104018. /* 20log10(x) */
  104019. #define VORBIS_IEEE_FLOAT32 1
  104020. #ifdef VORBIS_IEEE_FLOAT32
  104021. static float unitnorm(float x){
  104022. union {
  104023. ogg_uint32_t i;
  104024. float f;
  104025. } ix;
  104026. ix.f = x;
  104027. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  104028. return ix.f;
  104029. }
  104030. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  104031. static float todB(const float *x){
  104032. union {
  104033. ogg_uint32_t i;
  104034. float f;
  104035. } ix;
  104036. ix.f = *x;
  104037. ix.i = ix.i&0x7fffffff;
  104038. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  104039. }
  104040. #define todB_nn(x) todB(x)
  104041. #else
  104042. static float unitnorm(float x){
  104043. if(x<0)return(-1.f);
  104044. return(1.f);
  104045. }
  104046. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  104047. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  104048. #endif
  104049. #define fromdB(x) (exp((x)*.11512925f))
  104050. /* The bark scale equations are approximations, since the original
  104051. table was somewhat hand rolled. The below are chosen to have the
  104052. best possible fit to the rolled tables, thus their somewhat odd
  104053. appearance (these are more accurate and over a longer range than
  104054. the oft-quoted bark equations found in the texts I have). The
  104055. approximations are valid from 0 - 30kHz (nyquist) or so.
  104056. all f in Hz, z in Bark */
  104057. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  104058. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  104059. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  104060. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  104061. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  104062. 0.0 */
  104063. #define toOC(n) (log(n)*1.442695f-5.965784f)
  104064. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  104065. #endif
  104066. /********* End of inlined file: scales.h *********/
  104067. int analysis_noisy=1;
  104068. /* decides between modes, dispatches to the appropriate mapping. */
  104069. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  104070. int ret,i;
  104071. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104072. vb->glue_bits=0;
  104073. vb->time_bits=0;
  104074. vb->floor_bits=0;
  104075. vb->res_bits=0;
  104076. /* first things first. Make sure encode is ready */
  104077. for(i=0;i<PACKETBLOBS;i++)
  104078. oggpack_reset(vbi->packetblob[i]);
  104079. /* we only have one mapping type (0), and we let the mapping code
  104080. itself figure out what soft mode to use. This allows easier
  104081. bitrate management */
  104082. if((ret=_mapping_P[0]->forward(vb)))
  104083. return(ret);
  104084. if(op){
  104085. if(vorbis_bitrate_managed(vb))
  104086. /* The app is using a bitmanaged mode... but not using the
  104087. bitrate management interface. */
  104088. return(OV_EINVAL);
  104089. op->packet=oggpack_get_buffer(&vb->opb);
  104090. op->bytes=oggpack_bytes(&vb->opb);
  104091. op->b_o_s=0;
  104092. op->e_o_s=vb->eofflag;
  104093. op->granulepos=vb->granulepos;
  104094. op->packetno=vb->sequence; /* for sake of completeness */
  104095. }
  104096. return(0);
  104097. }
  104098. /* there was no great place to put this.... */
  104099. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  104100. int j;
  104101. FILE *of;
  104102. char buffer[80];
  104103. /* if(i==5870){*/
  104104. sprintf(buffer,"%s_%d.m",base,i);
  104105. of=fopen(buffer,"w");
  104106. if(!of)perror("failed to open data dump file");
  104107. for(j=0;j<n;j++){
  104108. if(bark){
  104109. float b=toBARK((4000.f*j/n)+.25);
  104110. fprintf(of,"%f ",b);
  104111. }else
  104112. if(off!=0)
  104113. fprintf(of,"%f ",(double)(j+off)/8000.);
  104114. else
  104115. fprintf(of,"%f ",(double)j);
  104116. if(dB){
  104117. float val;
  104118. if(v[j]==0.)
  104119. val=-140.;
  104120. else
  104121. val=todB(v+j);
  104122. fprintf(of,"%f\n",val);
  104123. }else{
  104124. fprintf(of,"%f\n",v[j]);
  104125. }
  104126. }
  104127. fclose(of);
  104128. /* } */
  104129. }
  104130. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104131. ogg_int64_t off){
  104132. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  104133. }
  104134. #endif
  104135. /********* End of inlined file: analysis.c *********/
  104136. /********* Start of inlined file: bitrate.c *********/
  104137. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104138. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104139. // tasks..
  104140. #ifdef _MSC_VER
  104141. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104142. #endif
  104143. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104144. #if JUCE_USE_OGGVORBIS
  104145. #include <stdlib.h>
  104146. #include <string.h>
  104147. #include <math.h>
  104148. /* compute bitrate tracking setup */
  104149. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  104150. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  104151. bitrate_manager_info *bi=&ci->bi;
  104152. memset(bm,0,sizeof(*bm));
  104153. if(bi && (bi->reservoir_bits>0)){
  104154. long ratesamples=vi->rate;
  104155. int halfsamples=ci->blocksizes[0]>>1;
  104156. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  104157. bm->managed=1;
  104158. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  104159. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  104160. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  104161. bm->avgfloat=PACKETBLOBS/2;
  104162. /* not a necessary fix, but one that leads to a more balanced
  104163. typical initialization */
  104164. {
  104165. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104166. bm->minmax_reservoir=desired_fill;
  104167. bm->avg_reservoir=desired_fill;
  104168. }
  104169. }
  104170. }
  104171. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  104172. memset(bm,0,sizeof(*bm));
  104173. return;
  104174. }
  104175. int vorbis_bitrate_managed(vorbis_block *vb){
  104176. vorbis_dsp_state *vd=vb->vd;
  104177. private_state *b=(private_state*)vd->backend_state;
  104178. bitrate_manager_state *bm=&b->bms;
  104179. if(bm && bm->managed)return(1);
  104180. return(0);
  104181. }
  104182. /* finish taking in the block we just processed */
  104183. int vorbis_bitrate_addblock(vorbis_block *vb){
  104184. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104185. vorbis_dsp_state *vd=vb->vd;
  104186. private_state *b=(private_state*)vd->backend_state;
  104187. bitrate_manager_state *bm=&b->bms;
  104188. vorbis_info *vi=vd->vi;
  104189. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104190. bitrate_manager_info *bi=&ci->bi;
  104191. int choice=rint(bm->avgfloat);
  104192. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104193. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  104194. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  104195. int samples=ci->blocksizes[vb->W]>>1;
  104196. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104197. if(!bm->managed){
  104198. /* not a bitrate managed stream, but for API simplicity, we'll
  104199. buffer the packet to keep the code path clean */
  104200. if(bm->vb)return(-1); /* one has been submitted without
  104201. being claimed */
  104202. bm->vb=vb;
  104203. return(0);
  104204. }
  104205. bm->vb=vb;
  104206. /* look ahead for avg floater */
  104207. if(bm->avg_bitsper>0){
  104208. double slew=0.;
  104209. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104210. double slewlimit= 15./bi->slew_damp;
  104211. /* choosing a new floater:
  104212. if we're over target, we slew down
  104213. if we're under target, we slew up
  104214. choose slew as follows: look through packetblobs of this frame
  104215. and set slew as the first in the appropriate direction that
  104216. gives us the slew we want. This may mean no slew if delta is
  104217. already favorable.
  104218. Then limit slew to slew max */
  104219. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104220. while(choice>0 && this_bits>avg_target_bits &&
  104221. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104222. choice--;
  104223. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104224. }
  104225. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104226. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  104227. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104228. choice++;
  104229. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104230. }
  104231. }
  104232. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  104233. if(slew<-slewlimit)slew=-slewlimit;
  104234. if(slew>slewlimit)slew=slewlimit;
  104235. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  104236. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104237. }
  104238. /* enforce min(if used) on the current floater (if used) */
  104239. if(bm->min_bitsper>0){
  104240. /* do we need to force the bitrate up? */
  104241. if(this_bits<min_target_bits){
  104242. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  104243. choice++;
  104244. if(choice>=PACKETBLOBS)break;
  104245. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104246. }
  104247. }
  104248. }
  104249. /* enforce max (if used) on the current floater (if used) */
  104250. if(bm->max_bitsper>0){
  104251. /* do we need to force the bitrate down? */
  104252. if(this_bits>max_target_bits){
  104253. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  104254. choice--;
  104255. if(choice<0)break;
  104256. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104257. }
  104258. }
  104259. }
  104260. /* Choice of packetblobs now made based on floater, and min/max
  104261. requirements. Now boundary check extreme choices */
  104262. if(choice<0){
  104263. /* choosing a smaller packetblob is insufficient to trim bitrate.
  104264. frame will need to be truncated */
  104265. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  104266. bm->choice=choice=0;
  104267. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  104268. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  104269. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104270. }
  104271. }else{
  104272. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  104273. if(choice>=PACKETBLOBS)
  104274. choice=PACKETBLOBS-1;
  104275. bm->choice=choice;
  104276. /* prop up bitrate according to demand. pad this frame out with zeroes */
  104277. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  104278. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  104279. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104280. }
  104281. /* now we have the final packet and the final packet size. Update statistics */
  104282. /* min and max reservoir */
  104283. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  104284. if(max_target_bits>0 && this_bits>max_target_bits){
  104285. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104286. }else if(min_target_bits>0 && this_bits<min_target_bits){
  104287. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104288. }else{
  104289. /* inbetween; we want to take reservoir toward but not past desired_fill */
  104290. if(bm->minmax_reservoir>desired_fill){
  104291. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  104292. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104293. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  104294. }else{
  104295. bm->minmax_reservoir=desired_fill;
  104296. }
  104297. }else{
  104298. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  104299. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104300. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  104301. }else{
  104302. bm->minmax_reservoir=desired_fill;
  104303. }
  104304. }
  104305. }
  104306. }
  104307. /* avg reservoir */
  104308. if(bm->avg_bitsper>0){
  104309. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104310. bm->avg_reservoir+=this_bits-avg_target_bits;
  104311. }
  104312. return(0);
  104313. }
  104314. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  104315. private_state *b=(private_state*)vd->backend_state;
  104316. bitrate_manager_state *bm=&b->bms;
  104317. vorbis_block *vb=bm->vb;
  104318. int choice=PACKETBLOBS/2;
  104319. if(!vb)return 0;
  104320. if(op){
  104321. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104322. if(vorbis_bitrate_managed(vb))
  104323. choice=bm->choice;
  104324. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  104325. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  104326. op->b_o_s=0;
  104327. op->e_o_s=vb->eofflag;
  104328. op->granulepos=vb->granulepos;
  104329. op->packetno=vb->sequence; /* for sake of completeness */
  104330. }
  104331. bm->vb=0;
  104332. return(1);
  104333. }
  104334. #endif
  104335. /********* End of inlined file: bitrate.c *********/
  104336. /********* Start of inlined file: block.c *********/
  104337. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104338. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104339. // tasks..
  104340. #ifdef _MSC_VER
  104341. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104342. #endif
  104343. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104344. #if JUCE_USE_OGGVORBIS
  104345. #include <stdio.h>
  104346. #include <stdlib.h>
  104347. #include <string.h>
  104348. /********* Start of inlined file: window.h *********/
  104349. #ifndef _V_WINDOW_
  104350. #define _V_WINDOW_
  104351. extern float *_vorbis_window_get(int n);
  104352. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  104353. int lW,int W,int nW);
  104354. #endif
  104355. /********* End of inlined file: window.h *********/
  104356. /********* Start of inlined file: lpc.h *********/
  104357. #ifndef _V_LPC_H_
  104358. #define _V_LPC_H_
  104359. /* simple linear scale LPC code */
  104360. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  104361. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  104362. float *data,long n);
  104363. #endif
  104364. /********* End of inlined file: lpc.h *********/
  104365. /* pcm accumulator examples (not exhaustive):
  104366. <-------------- lW ---------------->
  104367. <--------------- W ---------------->
  104368. : .....|..... _______________ |
  104369. : .''' | '''_--- | |\ |
  104370. :.....''' |_____--- '''......| | \_______|
  104371. :.................|__________________|_______|__|______|
  104372. |<------ Sl ------>| > Sr < |endW
  104373. |beginSl |endSl | |endSr
  104374. |beginW |endlW |beginSr
  104375. |< lW >|
  104376. <--------------- W ---------------->
  104377. | | .. ______________ |
  104378. | | ' `/ | ---_ |
  104379. |___.'___/`. | ---_____|
  104380. |_______|__|_______|_________________|
  104381. | >|Sl|< |<------ Sr ----->|endW
  104382. | | |endSl |beginSr |endSr
  104383. |beginW | |endlW
  104384. mult[0] |beginSl mult[n]
  104385. <-------------- lW ----------------->
  104386. |<--W-->|
  104387. : .............. ___ | |
  104388. : .''' |`/ \ | |
  104389. :.....''' |/`....\|...|
  104390. :.........................|___|___|___|
  104391. |Sl |Sr |endW
  104392. | | |endSr
  104393. | |beginSr
  104394. | |endSl
  104395. |beginSl
  104396. |beginW
  104397. */
  104398. /* block abstraction setup *********************************************/
  104399. #ifndef WORD_ALIGN
  104400. #define WORD_ALIGN 8
  104401. #endif
  104402. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  104403. int i;
  104404. memset(vb,0,sizeof(*vb));
  104405. vb->vd=v;
  104406. vb->localalloc=0;
  104407. vb->localstore=NULL;
  104408. if(v->analysisp){
  104409. vorbis_block_internal *vbi=(vorbis_block_internal*)
  104410. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  104411. vbi->ampmax=-9999;
  104412. for(i=0;i<PACKETBLOBS;i++){
  104413. if(i==PACKETBLOBS/2){
  104414. vbi->packetblob[i]=&vb->opb;
  104415. }else{
  104416. vbi->packetblob[i]=
  104417. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  104418. }
  104419. oggpack_writeinit(vbi->packetblob[i]);
  104420. }
  104421. }
  104422. return(0);
  104423. }
  104424. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  104425. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  104426. if(bytes+vb->localtop>vb->localalloc){
  104427. /* can't just _ogg_realloc... there are outstanding pointers */
  104428. if(vb->localstore){
  104429. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  104430. vb->totaluse+=vb->localtop;
  104431. link->next=vb->reap;
  104432. link->ptr=vb->localstore;
  104433. vb->reap=link;
  104434. }
  104435. /* highly conservative */
  104436. vb->localalloc=bytes;
  104437. vb->localstore=_ogg_malloc(vb->localalloc);
  104438. vb->localtop=0;
  104439. }
  104440. {
  104441. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  104442. vb->localtop+=bytes;
  104443. return ret;
  104444. }
  104445. }
  104446. /* reap the chain, pull the ripcord */
  104447. void _vorbis_block_ripcord(vorbis_block *vb){
  104448. /* reap the chain */
  104449. struct alloc_chain *reap=vb->reap;
  104450. while(reap){
  104451. struct alloc_chain *next=reap->next;
  104452. _ogg_free(reap->ptr);
  104453. memset(reap,0,sizeof(*reap));
  104454. _ogg_free(reap);
  104455. reap=next;
  104456. }
  104457. /* consolidate storage */
  104458. if(vb->totaluse){
  104459. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  104460. vb->localalloc+=vb->totaluse;
  104461. vb->totaluse=0;
  104462. }
  104463. /* pull the ripcord */
  104464. vb->localtop=0;
  104465. vb->reap=NULL;
  104466. }
  104467. int vorbis_block_clear(vorbis_block *vb){
  104468. int i;
  104469. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104470. _vorbis_block_ripcord(vb);
  104471. if(vb->localstore)_ogg_free(vb->localstore);
  104472. if(vbi){
  104473. for(i=0;i<PACKETBLOBS;i++){
  104474. oggpack_writeclear(vbi->packetblob[i]);
  104475. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  104476. }
  104477. _ogg_free(vbi);
  104478. }
  104479. memset(vb,0,sizeof(*vb));
  104480. return(0);
  104481. }
  104482. /* Analysis side code, but directly related to blocking. Thus it's
  104483. here and not in analysis.c (which is for analysis transforms only).
  104484. The init is here because some of it is shared */
  104485. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  104486. int i;
  104487. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104488. private_state *b=NULL;
  104489. int hs;
  104490. if(ci==NULL) return 1;
  104491. hs=ci->halfrate_flag;
  104492. memset(v,0,sizeof(*v));
  104493. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  104494. v->vi=vi;
  104495. b->modebits=ilog2(ci->modes);
  104496. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  104497. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  104498. /* MDCT is tranform 0 */
  104499. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  104500. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  104501. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  104502. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  104503. /* Vorbis I uses only window type 0 */
  104504. b->window[0]=ilog2(ci->blocksizes[0])-6;
  104505. b->window[1]=ilog2(ci->blocksizes[1])-6;
  104506. if(encp){ /* encode/decode differ here */
  104507. /* analysis always needs an fft */
  104508. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  104509. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  104510. /* finish the codebooks */
  104511. if(!ci->fullbooks){
  104512. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  104513. for(i=0;i<ci->books;i++)
  104514. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  104515. }
  104516. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  104517. for(i=0;i<ci->psys;i++){
  104518. _vp_psy_init(b->psy+i,
  104519. ci->psy_param[i],
  104520. &ci->psy_g_param,
  104521. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  104522. vi->rate);
  104523. }
  104524. v->analysisp=1;
  104525. }else{
  104526. /* finish the codebooks */
  104527. if(!ci->fullbooks){
  104528. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  104529. for(i=0;i<ci->books;i++){
  104530. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  104531. /* decode codebooks are now standalone after init */
  104532. vorbis_staticbook_destroy(ci->book_param[i]);
  104533. ci->book_param[i]=NULL;
  104534. }
  104535. }
  104536. }
  104537. /* initialize the storage vectors. blocksize[1] is small for encode,
  104538. but the correct size for decode */
  104539. v->pcm_storage=ci->blocksizes[1];
  104540. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  104541. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  104542. {
  104543. int i;
  104544. for(i=0;i<vi->channels;i++)
  104545. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  104546. }
  104547. /* all 1 (large block) or 0 (small block) */
  104548. /* explicitly set for the sake of clarity */
  104549. v->lW=0; /* previous window size */
  104550. v->W=0; /* current window size */
  104551. /* all vector indexes */
  104552. v->centerW=ci->blocksizes[1]/2;
  104553. v->pcm_current=v->centerW;
  104554. /* initialize all the backend lookups */
  104555. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  104556. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  104557. for(i=0;i<ci->floors;i++)
  104558. b->flr[i]=_floor_P[ci->floor_type[i]]->
  104559. look(v,ci->floor_param[i]);
  104560. for(i=0;i<ci->residues;i++)
  104561. b->residue[i]=_residue_P[ci->residue_type[i]]->
  104562. look(v,ci->residue_param[i]);
  104563. return 0;
  104564. }
  104565. /* arbitrary settings and spec-mandated numbers get filled in here */
  104566. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  104567. private_state *b=NULL;
  104568. if(_vds_shared_init(v,vi,1))return 1;
  104569. b=(private_state*)v->backend_state;
  104570. b->psy_g_look=_vp_global_look(vi);
  104571. /* Initialize the envelope state storage */
  104572. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  104573. _ve_envelope_init(b->ve,vi);
  104574. vorbis_bitrate_init(vi,&b->bms);
  104575. /* compressed audio packets start after the headers
  104576. with sequence number 3 */
  104577. v->sequence=3;
  104578. return(0);
  104579. }
  104580. void vorbis_dsp_clear(vorbis_dsp_state *v){
  104581. int i;
  104582. if(v){
  104583. vorbis_info *vi=v->vi;
  104584. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  104585. private_state *b=(private_state*)v->backend_state;
  104586. if(b){
  104587. if(b->ve){
  104588. _ve_envelope_clear(b->ve);
  104589. _ogg_free(b->ve);
  104590. }
  104591. if(b->transform[0]){
  104592. mdct_clear((mdct_lookup*) b->transform[0][0]);
  104593. _ogg_free(b->transform[0][0]);
  104594. _ogg_free(b->transform[0]);
  104595. }
  104596. if(b->transform[1]){
  104597. mdct_clear((mdct_lookup*) b->transform[1][0]);
  104598. _ogg_free(b->transform[1][0]);
  104599. _ogg_free(b->transform[1]);
  104600. }
  104601. if(b->flr){
  104602. for(i=0;i<ci->floors;i++)
  104603. _floor_P[ci->floor_type[i]]->
  104604. free_look(b->flr[i]);
  104605. _ogg_free(b->flr);
  104606. }
  104607. if(b->residue){
  104608. for(i=0;i<ci->residues;i++)
  104609. _residue_P[ci->residue_type[i]]->
  104610. free_look(b->residue[i]);
  104611. _ogg_free(b->residue);
  104612. }
  104613. if(b->psy){
  104614. for(i=0;i<ci->psys;i++)
  104615. _vp_psy_clear(b->psy+i);
  104616. _ogg_free(b->psy);
  104617. }
  104618. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  104619. vorbis_bitrate_clear(&b->bms);
  104620. drft_clear(&b->fft_look[0]);
  104621. drft_clear(&b->fft_look[1]);
  104622. }
  104623. if(v->pcm){
  104624. for(i=0;i<vi->channels;i++)
  104625. if(v->pcm[i])_ogg_free(v->pcm[i]);
  104626. _ogg_free(v->pcm);
  104627. if(v->pcmret)_ogg_free(v->pcmret);
  104628. }
  104629. if(b){
  104630. /* free header, header1, header2 */
  104631. if(b->header)_ogg_free(b->header);
  104632. if(b->header1)_ogg_free(b->header1);
  104633. if(b->header2)_ogg_free(b->header2);
  104634. _ogg_free(b);
  104635. }
  104636. memset(v,0,sizeof(*v));
  104637. }
  104638. }
  104639. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  104640. int i;
  104641. vorbis_info *vi=v->vi;
  104642. private_state *b=(private_state*)v->backend_state;
  104643. /* free header, header1, header2 */
  104644. if(b->header)_ogg_free(b->header);b->header=NULL;
  104645. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  104646. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  104647. /* Do we have enough storage space for the requested buffer? If not,
  104648. expand the PCM (and envelope) storage */
  104649. if(v->pcm_current+vals>=v->pcm_storage){
  104650. v->pcm_storage=v->pcm_current+vals*2;
  104651. for(i=0;i<vi->channels;i++){
  104652. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  104653. }
  104654. }
  104655. for(i=0;i<vi->channels;i++)
  104656. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  104657. return(v->pcmret);
  104658. }
  104659. static void _preextrapolate_helper(vorbis_dsp_state *v){
  104660. int i;
  104661. int order=32;
  104662. float *lpc=(float*)alloca(order*sizeof(*lpc));
  104663. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  104664. long j;
  104665. v->preextrapolate=1;
  104666. if(v->pcm_current-v->centerW>order*2){ /* safety */
  104667. for(i=0;i<v->vi->channels;i++){
  104668. /* need to run the extrapolation in reverse! */
  104669. for(j=0;j<v->pcm_current;j++)
  104670. work[j]=v->pcm[i][v->pcm_current-j-1];
  104671. /* prime as above */
  104672. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  104673. /* run the predictor filter */
  104674. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  104675. order,
  104676. work+v->pcm_current-v->centerW,
  104677. v->centerW);
  104678. for(j=0;j<v->pcm_current;j++)
  104679. v->pcm[i][v->pcm_current-j-1]=work[j];
  104680. }
  104681. }
  104682. }
  104683. /* call with val<=0 to set eof */
  104684. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  104685. vorbis_info *vi=v->vi;
  104686. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104687. if(vals<=0){
  104688. int order=32;
  104689. int i;
  104690. float *lpc=(float*) alloca(order*sizeof(*lpc));
  104691. /* if it wasn't done earlier (very short sample) */
  104692. if(!v->preextrapolate)
  104693. _preextrapolate_helper(v);
  104694. /* We're encoding the end of the stream. Just make sure we have
  104695. [at least] a few full blocks of zeroes at the end. */
  104696. /* actually, we don't want zeroes; that could drop a large
  104697. amplitude off a cliff, creating spread spectrum noise that will
  104698. suck to encode. Extrapolate for the sake of cleanliness. */
  104699. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  104700. v->eofflag=v->pcm_current;
  104701. v->pcm_current+=ci->blocksizes[1]*3;
  104702. for(i=0;i<vi->channels;i++){
  104703. if(v->eofflag>order*2){
  104704. /* extrapolate with LPC to fill in */
  104705. long n;
  104706. /* make a predictor filter */
  104707. n=v->eofflag;
  104708. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  104709. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  104710. /* run the predictor filter */
  104711. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  104712. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  104713. }else{
  104714. /* not enough data to extrapolate (unlikely to happen due to
  104715. guarding the overlap, but bulletproof in case that
  104716. assumtion goes away). zeroes will do. */
  104717. memset(v->pcm[i]+v->eofflag,0,
  104718. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  104719. }
  104720. }
  104721. }else{
  104722. if(v->pcm_current+vals>v->pcm_storage)
  104723. return(OV_EINVAL);
  104724. v->pcm_current+=vals;
  104725. /* we may want to reverse extrapolate the beginning of a stream
  104726. too... in case we're beginning on a cliff! */
  104727. /* clumsy, but simple. It only runs once, so simple is good. */
  104728. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  104729. _preextrapolate_helper(v);
  104730. }
  104731. return(0);
  104732. }
  104733. /* do the deltas, envelope shaping, pre-echo and determine the size of
  104734. the next block on which to continue analysis */
  104735. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  104736. int i;
  104737. vorbis_info *vi=v->vi;
  104738. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104739. private_state *b=(private_state*)v->backend_state;
  104740. vorbis_look_psy_global *g=b->psy_g_look;
  104741. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  104742. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104743. /* check to see if we're started... */
  104744. if(!v->preextrapolate)return(0);
  104745. /* check to see if we're done... */
  104746. if(v->eofflag==-1)return(0);
  104747. /* By our invariant, we have lW, W and centerW set. Search for
  104748. the next boundary so we can determine nW (the next window size)
  104749. which lets us compute the shape of the current block's window */
  104750. /* we do an envelope search even on a single blocksize; we may still
  104751. be throwing more bits at impulses, and envelope search handles
  104752. marking impulses too. */
  104753. {
  104754. long bp=_ve_envelope_search(v);
  104755. if(bp==-1){
  104756. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  104757. full long block */
  104758. v->nW=0;
  104759. }else{
  104760. if(ci->blocksizes[0]==ci->blocksizes[1])
  104761. v->nW=0;
  104762. else
  104763. v->nW=bp;
  104764. }
  104765. }
  104766. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  104767. {
  104768. /* center of next block + next block maximum right side. */
  104769. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  104770. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  104771. although this check is
  104772. less strict that the
  104773. _ve_envelope_search,
  104774. the search is not run
  104775. if we only use one
  104776. block size */
  104777. }
  104778. /* fill in the block. Note that for a short window, lW and nW are *short*
  104779. regardless of actual settings in the stream */
  104780. _vorbis_block_ripcord(vb);
  104781. vb->lW=v->lW;
  104782. vb->W=v->W;
  104783. vb->nW=v->nW;
  104784. if(v->W){
  104785. if(!v->lW || !v->nW){
  104786. vbi->blocktype=BLOCKTYPE_TRANSITION;
  104787. /*fprintf(stderr,"-");*/
  104788. }else{
  104789. vbi->blocktype=BLOCKTYPE_LONG;
  104790. /*fprintf(stderr,"_");*/
  104791. }
  104792. }else{
  104793. if(_ve_envelope_mark(v)){
  104794. vbi->blocktype=BLOCKTYPE_IMPULSE;
  104795. /*fprintf(stderr,"|");*/
  104796. }else{
  104797. vbi->blocktype=BLOCKTYPE_PADDING;
  104798. /*fprintf(stderr,".");*/
  104799. }
  104800. }
  104801. vb->vd=v;
  104802. vb->sequence=v->sequence++;
  104803. vb->granulepos=v->granulepos;
  104804. vb->pcmend=ci->blocksizes[v->W];
  104805. /* copy the vectors; this uses the local storage in vb */
  104806. /* this tracks 'strongest peak' for later psychoacoustics */
  104807. /* moved to the global psy state; clean this mess up */
  104808. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  104809. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  104810. vbi->ampmax=g->ampmax;
  104811. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  104812. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  104813. for(i=0;i<vi->channels;i++){
  104814. vbi->pcmdelay[i]=
  104815. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  104816. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  104817. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  104818. /* before we added the delay
  104819. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  104820. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  104821. */
  104822. }
  104823. /* handle eof detection: eof==0 means that we've not yet received EOF
  104824. eof>0 marks the last 'real' sample in pcm[]
  104825. eof<0 'no more to do'; doesn't get here */
  104826. if(v->eofflag){
  104827. if(v->centerW>=v->eofflag){
  104828. v->eofflag=-1;
  104829. vb->eofflag=1;
  104830. return(1);
  104831. }
  104832. }
  104833. /* advance storage vectors and clean up */
  104834. {
  104835. int new_centerNext=ci->blocksizes[1]/2;
  104836. int movementW=centerNext-new_centerNext;
  104837. if(movementW>0){
  104838. _ve_envelope_shift(b->ve,movementW);
  104839. v->pcm_current-=movementW;
  104840. for(i=0;i<vi->channels;i++)
  104841. memmove(v->pcm[i],v->pcm[i]+movementW,
  104842. v->pcm_current*sizeof(*v->pcm[i]));
  104843. v->lW=v->W;
  104844. v->W=v->nW;
  104845. v->centerW=new_centerNext;
  104846. if(v->eofflag){
  104847. v->eofflag-=movementW;
  104848. if(v->eofflag<=0)v->eofflag=-1;
  104849. /* do not add padding to end of stream! */
  104850. if(v->centerW>=v->eofflag){
  104851. v->granulepos+=movementW-(v->centerW-v->eofflag);
  104852. }else{
  104853. v->granulepos+=movementW;
  104854. }
  104855. }else{
  104856. v->granulepos+=movementW;
  104857. }
  104858. }
  104859. }
  104860. /* done */
  104861. return(1);
  104862. }
  104863. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  104864. vorbis_info *vi=v->vi;
  104865. codec_setup_info *ci;
  104866. int hs;
  104867. if(!v->backend_state)return -1;
  104868. if(!vi)return -1;
  104869. ci=(codec_setup_info*) vi->codec_setup;
  104870. if(!ci)return -1;
  104871. hs=ci->halfrate_flag;
  104872. v->centerW=ci->blocksizes[1]>>(hs+1);
  104873. v->pcm_current=v->centerW>>hs;
  104874. v->pcm_returned=-1;
  104875. v->granulepos=-1;
  104876. v->sequence=-1;
  104877. v->eofflag=0;
  104878. ((private_state *)(v->backend_state))->sample_count=-1;
  104879. return(0);
  104880. }
  104881. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  104882. if(_vds_shared_init(v,vi,0)) return 1;
  104883. vorbis_synthesis_restart(v);
  104884. return 0;
  104885. }
  104886. /* Unlike in analysis, the window is only partially applied for each
  104887. block. The time domain envelope is not yet handled at the point of
  104888. calling (as it relies on the previous block). */
  104889. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  104890. vorbis_info *vi=v->vi;
  104891. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104892. private_state *b=(private_state*)v->backend_state;
  104893. int hs=ci->halfrate_flag;
  104894. int i,j;
  104895. if(!vb)return(OV_EINVAL);
  104896. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  104897. v->lW=v->W;
  104898. v->W=vb->W;
  104899. v->nW=-1;
  104900. if((v->sequence==-1)||
  104901. (v->sequence+1 != vb->sequence)){
  104902. v->granulepos=-1; /* out of sequence; lose count */
  104903. b->sample_count=-1;
  104904. }
  104905. v->sequence=vb->sequence;
  104906. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  104907. was called on block */
  104908. int n=ci->blocksizes[v->W]>>(hs+1);
  104909. int n0=ci->blocksizes[0]>>(hs+1);
  104910. int n1=ci->blocksizes[1]>>(hs+1);
  104911. int thisCenter;
  104912. int prevCenter;
  104913. v->glue_bits+=vb->glue_bits;
  104914. v->time_bits+=vb->time_bits;
  104915. v->floor_bits+=vb->floor_bits;
  104916. v->res_bits+=vb->res_bits;
  104917. if(v->centerW){
  104918. thisCenter=n1;
  104919. prevCenter=0;
  104920. }else{
  104921. thisCenter=0;
  104922. prevCenter=n1;
  104923. }
  104924. /* v->pcm is now used like a two-stage double buffer. We don't want
  104925. to have to constantly shift *or* adjust memory usage. Don't
  104926. accept a new block until the old is shifted out */
  104927. for(j=0;j<vi->channels;j++){
  104928. /* the overlap/add section */
  104929. if(v->lW){
  104930. if(v->W){
  104931. /* large/large */
  104932. float *w=_vorbis_window_get(b->window[1]-hs);
  104933. float *pcm=v->pcm[j]+prevCenter;
  104934. float *p=vb->pcm[j];
  104935. for(i=0;i<n1;i++)
  104936. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  104937. }else{
  104938. /* large/small */
  104939. float *w=_vorbis_window_get(b->window[0]-hs);
  104940. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  104941. float *p=vb->pcm[j];
  104942. for(i=0;i<n0;i++)
  104943. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104944. }
  104945. }else{
  104946. if(v->W){
  104947. /* small/large */
  104948. float *w=_vorbis_window_get(b->window[0]-hs);
  104949. float *pcm=v->pcm[j]+prevCenter;
  104950. float *p=vb->pcm[j]+n1/2-n0/2;
  104951. for(i=0;i<n0;i++)
  104952. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104953. for(;i<n1/2+n0/2;i++)
  104954. pcm[i]=p[i];
  104955. }else{
  104956. /* small/small */
  104957. float *w=_vorbis_window_get(b->window[0]-hs);
  104958. float *pcm=v->pcm[j]+prevCenter;
  104959. float *p=vb->pcm[j];
  104960. for(i=0;i<n0;i++)
  104961. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104962. }
  104963. }
  104964. /* the copy section */
  104965. {
  104966. float *pcm=v->pcm[j]+thisCenter;
  104967. float *p=vb->pcm[j]+n;
  104968. for(i=0;i<n;i++)
  104969. pcm[i]=p[i];
  104970. }
  104971. }
  104972. if(v->centerW)
  104973. v->centerW=0;
  104974. else
  104975. v->centerW=n1;
  104976. /* deal with initial packet state; we do this using the explicit
  104977. pcm_returned==-1 flag otherwise we're sensitive to first block
  104978. being short or long */
  104979. if(v->pcm_returned==-1){
  104980. v->pcm_returned=thisCenter;
  104981. v->pcm_current=thisCenter;
  104982. }else{
  104983. v->pcm_returned=prevCenter;
  104984. v->pcm_current=prevCenter+
  104985. ((ci->blocksizes[v->lW]/4+
  104986. ci->blocksizes[v->W]/4)>>hs);
  104987. }
  104988. }
  104989. /* track the frame number... This is for convenience, but also
  104990. making sure our last packet doesn't end with added padding. If
  104991. the last packet is partial, the number of samples we'll have to
  104992. return will be past the vb->granulepos.
  104993. This is not foolproof! It will be confused if we begin
  104994. decoding at the last page after a seek or hole. In that case,
  104995. we don't have a starting point to judge where the last frame
  104996. is. For this reason, vorbisfile will always try to make sure
  104997. it reads the last two marked pages in proper sequence */
  104998. if(b->sample_count==-1){
  104999. b->sample_count=0;
  105000. }else{
  105001. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105002. }
  105003. if(v->granulepos==-1){
  105004. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  105005. v->granulepos=vb->granulepos;
  105006. /* is this a short page? */
  105007. if(b->sample_count>v->granulepos){
  105008. /* corner case; if this is both the first and last audio page,
  105009. then spec says the end is cut, not beginning */
  105010. if(vb->eofflag){
  105011. /* trim the end */
  105012. /* no preceeding granulepos; assume we started at zero (we'd
  105013. have to in a short single-page stream) */
  105014. /* granulepos could be -1 due to a seek, but that would result
  105015. in a long count, not short count */
  105016. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  105017. }else{
  105018. /* trim the beginning */
  105019. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  105020. if(v->pcm_returned>v->pcm_current)
  105021. v->pcm_returned=v->pcm_current;
  105022. }
  105023. }
  105024. }
  105025. }else{
  105026. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105027. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  105028. if(v->granulepos>vb->granulepos){
  105029. long extra=v->granulepos-vb->granulepos;
  105030. if(extra)
  105031. if(vb->eofflag){
  105032. /* partial last frame. Strip the extra samples off */
  105033. v->pcm_current-=extra>>hs;
  105034. } /* else {Shouldn't happen *unless* the bitstream is out of
  105035. spec. Either way, believe the bitstream } */
  105036. } /* else {Shouldn't happen *unless* the bitstream is out of
  105037. spec. Either way, believe the bitstream } */
  105038. v->granulepos=vb->granulepos;
  105039. }
  105040. }
  105041. /* Update, cleanup */
  105042. if(vb->eofflag)v->eofflag=1;
  105043. return(0);
  105044. }
  105045. /* pcm==NULL indicates we just want the pending samples, no more */
  105046. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  105047. vorbis_info *vi=v->vi;
  105048. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  105049. if(pcm){
  105050. int i;
  105051. for(i=0;i<vi->channels;i++)
  105052. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105053. *pcm=v->pcmret;
  105054. }
  105055. return(v->pcm_current-v->pcm_returned);
  105056. }
  105057. return(0);
  105058. }
  105059. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  105060. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  105061. v->pcm_returned+=n;
  105062. return(0);
  105063. }
  105064. /* intended for use with a specific vorbisfile feature; we want access
  105065. to the [usually synthetic/postextrapolated] buffer and lapping at
  105066. the end of a decode cycle, specifically, a half-short-block worth.
  105067. This funtion works like pcmout above, except it will also expose
  105068. this implicit buffer data not normally decoded. */
  105069. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  105070. vorbis_info *vi=v->vi;
  105071. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105072. int hs=ci->halfrate_flag;
  105073. int n=ci->blocksizes[v->W]>>(hs+1);
  105074. int n0=ci->blocksizes[0]>>(hs+1);
  105075. int n1=ci->blocksizes[1]>>(hs+1);
  105076. int i,j;
  105077. if(v->pcm_returned<0)return 0;
  105078. /* our returned data ends at pcm_returned; because the synthesis pcm
  105079. buffer is a two-fragment ring, that means our data block may be
  105080. fragmented by buffering, wrapping or a short block not filling
  105081. out a buffer. To simplify things, we unfragment if it's at all
  105082. possibly needed. Otherwise, we'd need to call lapout more than
  105083. once as well as hold additional dsp state. Opt for
  105084. simplicity. */
  105085. /* centerW was advanced by blockin; it would be the center of the
  105086. *next* block */
  105087. if(v->centerW==n1){
  105088. /* the data buffer wraps; swap the halves */
  105089. /* slow, sure, small */
  105090. for(j=0;j<vi->channels;j++){
  105091. float *p=v->pcm[j];
  105092. for(i=0;i<n1;i++){
  105093. float temp=p[i];
  105094. p[i]=p[i+n1];
  105095. p[i+n1]=temp;
  105096. }
  105097. }
  105098. v->pcm_current-=n1;
  105099. v->pcm_returned-=n1;
  105100. v->centerW=0;
  105101. }
  105102. /* solidify buffer into contiguous space */
  105103. if((v->lW^v->W)==1){
  105104. /* long/short or short/long */
  105105. for(j=0;j<vi->channels;j++){
  105106. float *s=v->pcm[j];
  105107. float *d=v->pcm[j]+(n1-n0)/2;
  105108. for(i=(n1+n0)/2-1;i>=0;--i)
  105109. d[i]=s[i];
  105110. }
  105111. v->pcm_returned+=(n1-n0)/2;
  105112. v->pcm_current+=(n1-n0)/2;
  105113. }else{
  105114. if(v->lW==0){
  105115. /* short/short */
  105116. for(j=0;j<vi->channels;j++){
  105117. float *s=v->pcm[j];
  105118. float *d=v->pcm[j]+n1-n0;
  105119. for(i=n0-1;i>=0;--i)
  105120. d[i]=s[i];
  105121. }
  105122. v->pcm_returned+=n1-n0;
  105123. v->pcm_current+=n1-n0;
  105124. }
  105125. }
  105126. if(pcm){
  105127. int i;
  105128. for(i=0;i<vi->channels;i++)
  105129. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105130. *pcm=v->pcmret;
  105131. }
  105132. return(n1+n-v->pcm_returned);
  105133. }
  105134. float *vorbis_window(vorbis_dsp_state *v,int W){
  105135. vorbis_info *vi=v->vi;
  105136. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  105137. int hs=ci->halfrate_flag;
  105138. private_state *b=(private_state*)v->backend_state;
  105139. if(b->window[W]-1<0)return NULL;
  105140. return _vorbis_window_get(b->window[W]-hs);
  105141. }
  105142. #endif
  105143. /********* End of inlined file: block.c *********/
  105144. /********* Start of inlined file: codebook.c *********/
  105145. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105146. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105147. // tasks..
  105148. #ifdef _MSC_VER
  105149. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105150. #endif
  105151. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105152. #if JUCE_USE_OGGVORBIS
  105153. #include <stdlib.h>
  105154. #include <string.h>
  105155. #include <math.h>
  105156. /* packs the given codebook into the bitstream **************************/
  105157. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  105158. long i,j;
  105159. int ordered=0;
  105160. /* first the basic parameters */
  105161. oggpack_write(opb,0x564342,24);
  105162. oggpack_write(opb,c->dim,16);
  105163. oggpack_write(opb,c->entries,24);
  105164. /* pack the codewords. There are two packings; length ordered and
  105165. length random. Decide between the two now. */
  105166. for(i=1;i<c->entries;i++)
  105167. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  105168. if(i==c->entries)ordered=1;
  105169. if(ordered){
  105170. /* length ordered. We only need to say how many codewords of
  105171. each length. The actual codewords are generated
  105172. deterministically */
  105173. long count=0;
  105174. oggpack_write(opb,1,1); /* ordered */
  105175. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  105176. for(i=1;i<c->entries;i++){
  105177. long thisx=c->lengthlist[i];
  105178. long last=c->lengthlist[i-1];
  105179. if(thisx>last){
  105180. for(j=last;j<thisx;j++){
  105181. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105182. count=i;
  105183. }
  105184. }
  105185. }
  105186. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105187. }else{
  105188. /* length random. Again, we don't code the codeword itself, just
  105189. the length. This time, though, we have to encode each length */
  105190. oggpack_write(opb,0,1); /* unordered */
  105191. /* algortihmic mapping has use for 'unused entries', which we tag
  105192. here. The algorithmic mapping happens as usual, but the unused
  105193. entry has no codeword. */
  105194. for(i=0;i<c->entries;i++)
  105195. if(c->lengthlist[i]==0)break;
  105196. if(i==c->entries){
  105197. oggpack_write(opb,0,1); /* no unused entries */
  105198. for(i=0;i<c->entries;i++)
  105199. oggpack_write(opb,c->lengthlist[i]-1,5);
  105200. }else{
  105201. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  105202. for(i=0;i<c->entries;i++){
  105203. if(c->lengthlist[i]==0){
  105204. oggpack_write(opb,0,1);
  105205. }else{
  105206. oggpack_write(opb,1,1);
  105207. oggpack_write(opb,c->lengthlist[i]-1,5);
  105208. }
  105209. }
  105210. }
  105211. }
  105212. /* is the entry number the desired return value, or do we have a
  105213. mapping? If we have a mapping, what type? */
  105214. oggpack_write(opb,c->maptype,4);
  105215. switch(c->maptype){
  105216. case 0:
  105217. /* no mapping */
  105218. break;
  105219. case 1:case 2:
  105220. /* implicitly populated value mapping */
  105221. /* explicitly populated value mapping */
  105222. if(!c->quantlist){
  105223. /* no quantlist? error */
  105224. return(-1);
  105225. }
  105226. /* values that define the dequantization */
  105227. oggpack_write(opb,c->q_min,32);
  105228. oggpack_write(opb,c->q_delta,32);
  105229. oggpack_write(opb,c->q_quant-1,4);
  105230. oggpack_write(opb,c->q_sequencep,1);
  105231. {
  105232. int quantvals;
  105233. switch(c->maptype){
  105234. case 1:
  105235. /* a single column of (c->entries/c->dim) quantized values for
  105236. building a full value list algorithmically (square lattice) */
  105237. quantvals=_book_maptype1_quantvals(c);
  105238. break;
  105239. case 2:
  105240. /* every value (c->entries*c->dim total) specified explicitly */
  105241. quantvals=c->entries*c->dim;
  105242. break;
  105243. default: /* NOT_REACHABLE */
  105244. quantvals=-1;
  105245. }
  105246. /* quantized values */
  105247. for(i=0;i<quantvals;i++)
  105248. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  105249. }
  105250. break;
  105251. default:
  105252. /* error case; we don't have any other map types now */
  105253. return(-1);
  105254. }
  105255. return(0);
  105256. }
  105257. /* unpacks a codebook from the packet buffer into the codebook struct,
  105258. readies the codebook auxiliary structures for decode *************/
  105259. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  105260. long i,j;
  105261. memset(s,0,sizeof(*s));
  105262. s->allocedp=1;
  105263. /* make sure alignment is correct */
  105264. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  105265. /* first the basic parameters */
  105266. s->dim=oggpack_read(opb,16);
  105267. s->entries=oggpack_read(opb,24);
  105268. if(s->entries==-1)goto _eofout;
  105269. /* codeword ordering.... length ordered or unordered? */
  105270. switch((int)oggpack_read(opb,1)){
  105271. case 0:
  105272. /* unordered */
  105273. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105274. /* allocated but unused entries? */
  105275. if(oggpack_read(opb,1)){
  105276. /* yes, unused entries */
  105277. for(i=0;i<s->entries;i++){
  105278. if(oggpack_read(opb,1)){
  105279. long num=oggpack_read(opb,5);
  105280. if(num==-1)goto _eofout;
  105281. s->lengthlist[i]=num+1;
  105282. }else
  105283. s->lengthlist[i]=0;
  105284. }
  105285. }else{
  105286. /* all entries used; no tagging */
  105287. for(i=0;i<s->entries;i++){
  105288. long num=oggpack_read(opb,5);
  105289. if(num==-1)goto _eofout;
  105290. s->lengthlist[i]=num+1;
  105291. }
  105292. }
  105293. break;
  105294. case 1:
  105295. /* ordered */
  105296. {
  105297. long length=oggpack_read(opb,5)+1;
  105298. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105299. for(i=0;i<s->entries;){
  105300. long num=oggpack_read(opb,_ilog(s->entries-i));
  105301. if(num==-1)goto _eofout;
  105302. for(j=0;j<num && i<s->entries;j++,i++)
  105303. s->lengthlist[i]=length;
  105304. length++;
  105305. }
  105306. }
  105307. break;
  105308. default:
  105309. /* EOF */
  105310. return(-1);
  105311. }
  105312. /* Do we have a mapping to unpack? */
  105313. switch((s->maptype=oggpack_read(opb,4))){
  105314. case 0:
  105315. /* no mapping */
  105316. break;
  105317. case 1: case 2:
  105318. /* implicitly populated value mapping */
  105319. /* explicitly populated value mapping */
  105320. s->q_min=oggpack_read(opb,32);
  105321. s->q_delta=oggpack_read(opb,32);
  105322. s->q_quant=oggpack_read(opb,4)+1;
  105323. s->q_sequencep=oggpack_read(opb,1);
  105324. {
  105325. int quantvals=0;
  105326. switch(s->maptype){
  105327. case 1:
  105328. quantvals=_book_maptype1_quantvals(s);
  105329. break;
  105330. case 2:
  105331. quantvals=s->entries*s->dim;
  105332. break;
  105333. }
  105334. /* quantized values */
  105335. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  105336. for(i=0;i<quantvals;i++)
  105337. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  105338. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  105339. }
  105340. break;
  105341. default:
  105342. goto _errout;
  105343. }
  105344. /* all set */
  105345. return(0);
  105346. _errout:
  105347. _eofout:
  105348. vorbis_staticbook_clear(s);
  105349. return(-1);
  105350. }
  105351. /* returns the number of bits ************************************************/
  105352. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  105353. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  105354. return(book->c->lengthlist[a]);
  105355. }
  105356. /* One the encode side, our vector writers are each designed for a
  105357. specific purpose, and the encoder is not flexible without modification:
  105358. The LSP vector coder uses a single stage nearest-match with no
  105359. interleave, so no step and no error return. This is specced by floor0
  105360. and doesn't change.
  105361. Residue0 encoding interleaves, uses multiple stages, and each stage
  105362. peels of a specific amount of resolution from a lattice (thus we want
  105363. to match by threshold, not nearest match). Residue doesn't *have* to
  105364. be encoded that way, but to change it, one will need to add more
  105365. infrastructure on the encode side (decode side is specced and simpler) */
  105366. /* floor0 LSP (single stage, non interleaved, nearest match) */
  105367. /* returns entry number and *modifies a* to the quantization value *****/
  105368. int vorbis_book_errorv(codebook *book,float *a){
  105369. int dim=book->dim,k;
  105370. int best=_best(book,a,1);
  105371. for(k=0;k<dim;k++)
  105372. a[k]=(book->valuelist+best*dim)[k];
  105373. return(best);
  105374. }
  105375. /* returns the number of bits and *modifies a* to the quantization value *****/
  105376. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  105377. int k,dim=book->dim;
  105378. for(k=0;k<dim;k++)
  105379. a[k]=(book->valuelist+best*dim)[k];
  105380. return(vorbis_book_encode(book,best,b));
  105381. }
  105382. /* the 'eliminate the decode tree' optimization actually requires the
  105383. codewords to be MSb first, not LSb. This is an annoying inelegancy
  105384. (and one of the first places where carefully thought out design
  105385. turned out to be wrong; Vorbis II and future Ogg codecs should go
  105386. to an MSb bitpacker), but not actually the huge hit it appears to
  105387. be. The first-stage decode table catches most words so that
  105388. bitreverse is not in the main execution path. */
  105389. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  105390. int read=book->dec_maxlength;
  105391. long lo,hi;
  105392. long lok = oggpack_look(b,book->dec_firsttablen);
  105393. if (lok >= 0) {
  105394. long entry = book->dec_firsttable[lok];
  105395. if(entry&0x80000000UL){
  105396. lo=(entry>>15)&0x7fff;
  105397. hi=book->used_entries-(entry&0x7fff);
  105398. }else{
  105399. oggpack_adv(b, book->dec_codelengths[entry-1]);
  105400. return(entry-1);
  105401. }
  105402. }else{
  105403. lo=0;
  105404. hi=book->used_entries;
  105405. }
  105406. lok = oggpack_look(b, read);
  105407. while(lok<0 && read>1)
  105408. lok = oggpack_look(b, --read);
  105409. if(lok<0)return -1;
  105410. /* bisect search for the codeword in the ordered list */
  105411. {
  105412. ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
  105413. while(hi-lo>1){
  105414. long p=(hi-lo)>>1;
  105415. long test=book->codelist[lo+p]>testword;
  105416. lo+=p&(test-1);
  105417. hi-=p&(-test);
  105418. }
  105419. if(book->dec_codelengths[lo]<=read){
  105420. oggpack_adv(b, book->dec_codelengths[lo]);
  105421. return(lo);
  105422. }
  105423. }
  105424. oggpack_adv(b, read);
  105425. return(-1);
  105426. }
  105427. /* Decode side is specced and easier, because we don't need to find
  105428. matches using different criteria; we simply read and map. There are
  105429. two things we need to do 'depending':
  105430. We may need to support interleave. We don't really, but it's
  105431. convenient to do it here rather than rebuild the vector later.
  105432. Cascades may be additive or multiplicitive; this is not inherent in
  105433. the codebook, but set in the code using the codebook. Like
  105434. interleaving, it's easiest to do it here.
  105435. addmul==0 -> declarative (set the value)
  105436. addmul==1 -> additive
  105437. addmul==2 -> multiplicitive */
  105438. /* returns the [original, not compacted] entry number or -1 on eof *********/
  105439. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  105440. long packed_entry=decode_packed_entry_number(book,b);
  105441. if(packed_entry>=0)
  105442. return(book->dec_index[packed_entry]);
  105443. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  105444. return(packed_entry);
  105445. }
  105446. /* returns 0 on OK or -1 on eof *************************************/
  105447. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  105448. int step=n/book->dim;
  105449. long *entry = (long*)alloca(sizeof(*entry)*step);
  105450. float **t = (float**)alloca(sizeof(*t)*step);
  105451. int i,j,o;
  105452. for (i = 0; i < step; i++) {
  105453. entry[i]=decode_packed_entry_number(book,b);
  105454. if(entry[i]==-1)return(-1);
  105455. t[i] = book->valuelist+entry[i]*book->dim;
  105456. }
  105457. for(i=0,o=0;i<book->dim;i++,o+=step)
  105458. for (j=0;j<step;j++)
  105459. a[o+j]+=t[j][i];
  105460. return(0);
  105461. }
  105462. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  105463. int i,j,entry;
  105464. float *t;
  105465. if(book->dim>8){
  105466. for(i=0;i<n;){
  105467. entry = decode_packed_entry_number(book,b);
  105468. if(entry==-1)return(-1);
  105469. t = book->valuelist+entry*book->dim;
  105470. for (j=0;j<book->dim;)
  105471. a[i++]+=t[j++];
  105472. }
  105473. }else{
  105474. for(i=0;i<n;){
  105475. entry = decode_packed_entry_number(book,b);
  105476. if(entry==-1)return(-1);
  105477. t = book->valuelist+entry*book->dim;
  105478. j=0;
  105479. switch((int)book->dim){
  105480. case 8:
  105481. a[i++]+=t[j++];
  105482. case 7:
  105483. a[i++]+=t[j++];
  105484. case 6:
  105485. a[i++]+=t[j++];
  105486. case 5:
  105487. a[i++]+=t[j++];
  105488. case 4:
  105489. a[i++]+=t[j++];
  105490. case 3:
  105491. a[i++]+=t[j++];
  105492. case 2:
  105493. a[i++]+=t[j++];
  105494. case 1:
  105495. a[i++]+=t[j++];
  105496. case 0:
  105497. break;
  105498. }
  105499. }
  105500. }
  105501. return(0);
  105502. }
  105503. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  105504. int i,j,entry;
  105505. float *t;
  105506. for(i=0;i<n;){
  105507. entry = decode_packed_entry_number(book,b);
  105508. if(entry==-1)return(-1);
  105509. t = book->valuelist+entry*book->dim;
  105510. for (j=0;j<book->dim;)
  105511. a[i++]=t[j++];
  105512. }
  105513. return(0);
  105514. }
  105515. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  105516. oggpack_buffer *b,int n){
  105517. long i,j,entry;
  105518. int chptr=0;
  105519. for(i=offset/ch;i<(offset+n)/ch;){
  105520. entry = decode_packed_entry_number(book,b);
  105521. if(entry==-1)return(-1);
  105522. {
  105523. const float *t = book->valuelist+entry*book->dim;
  105524. for (j=0;j<book->dim;j++){
  105525. a[chptr++][i]+=t[j];
  105526. if(chptr==ch){
  105527. chptr=0;
  105528. i++;
  105529. }
  105530. }
  105531. }
  105532. }
  105533. return(0);
  105534. }
  105535. #ifdef _V_SELFTEST
  105536. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  105537. number of vectors through (keeping track of the quantized values),
  105538. and decode using the unpacked book. quantized version of in should
  105539. exactly equal out */
  105540. #include <stdio.h>
  105541. #include "vorbis/book/lsp20_0.vqh"
  105542. #include "vorbis/book/res0a_13.vqh"
  105543. #define TESTSIZE 40
  105544. float test1[TESTSIZE]={
  105545. 0.105939f,
  105546. 0.215373f,
  105547. 0.429117f,
  105548. 0.587974f,
  105549. 0.181173f,
  105550. 0.296583f,
  105551. 0.515707f,
  105552. 0.715261f,
  105553. 0.162327f,
  105554. 0.263834f,
  105555. 0.342876f,
  105556. 0.406025f,
  105557. 0.103571f,
  105558. 0.223561f,
  105559. 0.368513f,
  105560. 0.540313f,
  105561. 0.136672f,
  105562. 0.395882f,
  105563. 0.587183f,
  105564. 0.652476f,
  105565. 0.114338f,
  105566. 0.417300f,
  105567. 0.525486f,
  105568. 0.698679f,
  105569. 0.147492f,
  105570. 0.324481f,
  105571. 0.643089f,
  105572. 0.757582f,
  105573. 0.139556f,
  105574. 0.215795f,
  105575. 0.324559f,
  105576. 0.399387f,
  105577. 0.120236f,
  105578. 0.267420f,
  105579. 0.446940f,
  105580. 0.608760f,
  105581. 0.115587f,
  105582. 0.287234f,
  105583. 0.571081f,
  105584. 0.708603f,
  105585. };
  105586. float test3[TESTSIZE]={
  105587. 0,1,-2,3,4,-5,6,7,8,9,
  105588. 8,-2,7,-1,4,6,8,3,1,-9,
  105589. 10,11,12,13,14,15,26,17,18,19,
  105590. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  105591. static_codebook *testlist[]={&_vq_book_lsp20_0,
  105592. &_vq_book_res0a_13,NULL};
  105593. float *testvec[]={test1,test3};
  105594. int main(){
  105595. oggpack_buffer write;
  105596. oggpack_buffer read;
  105597. long ptr=0,i;
  105598. oggpack_writeinit(&write);
  105599. fprintf(stderr,"Testing codebook abstraction...:\n");
  105600. while(testlist[ptr]){
  105601. codebook c;
  105602. static_codebook s;
  105603. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  105604. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  105605. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  105606. memset(iv,0,sizeof(*iv)*TESTSIZE);
  105607. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  105608. /* pack the codebook, write the testvector */
  105609. oggpack_reset(&write);
  105610. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  105611. we can write */
  105612. vorbis_staticbook_pack(testlist[ptr],&write);
  105613. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  105614. for(i=0;i<TESTSIZE;i+=c.dim){
  105615. int best=_best(&c,qv+i,1);
  105616. vorbis_book_encodev(&c,best,qv+i,&write);
  105617. }
  105618. vorbis_book_clear(&c);
  105619. fprintf(stderr,"OK.\n");
  105620. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  105621. /* transfer the write data to a read buffer and unpack/read */
  105622. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  105623. if(vorbis_staticbook_unpack(&read,&s)){
  105624. fprintf(stderr,"Error unpacking codebook.\n");
  105625. exit(1);
  105626. }
  105627. if(vorbis_book_init_decode(&c,&s)){
  105628. fprintf(stderr,"Error initializing codebook.\n");
  105629. exit(1);
  105630. }
  105631. for(i=0;i<TESTSIZE;i+=c.dim)
  105632. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  105633. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  105634. exit(1);
  105635. }
  105636. for(i=0;i<TESTSIZE;i++)
  105637. if(fabs(qv[i]-iv[i])>.000001){
  105638. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  105639. iv[i],qv[i],i);
  105640. exit(1);
  105641. }
  105642. fprintf(stderr,"OK\n");
  105643. ptr++;
  105644. }
  105645. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  105646. exit(0);
  105647. }
  105648. #endif
  105649. #endif
  105650. /********* End of inlined file: codebook.c *********/
  105651. /********* Start of inlined file: envelope.c *********/
  105652. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105653. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105654. // tasks..
  105655. #ifdef _MSC_VER
  105656. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105657. #endif
  105658. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105659. #if JUCE_USE_OGGVORBIS
  105660. #include <stdlib.h>
  105661. #include <string.h>
  105662. #include <stdio.h>
  105663. #include <math.h>
  105664. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  105665. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105666. vorbis_info_psy_global *gi=&ci->psy_g_param;
  105667. int ch=vi->channels;
  105668. int i,j;
  105669. int n=e->winlength=128;
  105670. e->searchstep=64; /* not random */
  105671. e->minenergy=gi->preecho_minenergy;
  105672. e->ch=ch;
  105673. e->storage=128;
  105674. e->cursor=ci->blocksizes[1]/2;
  105675. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  105676. mdct_init(&e->mdct,n);
  105677. for(i=0;i<n;i++){
  105678. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  105679. e->mdct_win[i]*=e->mdct_win[i];
  105680. }
  105681. /* magic follows */
  105682. e->band[0].begin=2; e->band[0].end=4;
  105683. e->band[1].begin=4; e->band[1].end=5;
  105684. e->band[2].begin=6; e->band[2].end=6;
  105685. e->band[3].begin=9; e->band[3].end=8;
  105686. e->band[4].begin=13; e->band[4].end=8;
  105687. e->band[5].begin=17; e->band[5].end=8;
  105688. e->band[6].begin=22; e->band[6].end=8;
  105689. for(j=0;j<VE_BANDS;j++){
  105690. n=e->band[j].end;
  105691. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  105692. for(i=0;i<n;i++){
  105693. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  105694. e->band[j].total+=e->band[j].window[i];
  105695. }
  105696. e->band[j].total=1./e->band[j].total;
  105697. }
  105698. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  105699. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  105700. }
  105701. void _ve_envelope_clear(envelope_lookup *e){
  105702. int i;
  105703. mdct_clear(&e->mdct);
  105704. for(i=0;i<VE_BANDS;i++)
  105705. _ogg_free(e->band[i].window);
  105706. _ogg_free(e->mdct_win);
  105707. _ogg_free(e->filter);
  105708. _ogg_free(e->mark);
  105709. memset(e,0,sizeof(*e));
  105710. }
  105711. /* fairly straight threshhold-by-band based until we find something
  105712. that works better and isn't patented. */
  105713. static int _ve_amp(envelope_lookup *ve,
  105714. vorbis_info_psy_global *gi,
  105715. float *data,
  105716. envelope_band *bands,
  105717. envelope_filter_state *filters,
  105718. long pos){
  105719. long n=ve->winlength;
  105720. int ret=0;
  105721. long i,j;
  105722. float decay;
  105723. /* we want to have a 'minimum bar' for energy, else we're just
  105724. basing blocks on quantization noise that outweighs the signal
  105725. itself (for low power signals) */
  105726. float minV=ve->minenergy;
  105727. float *vec=(float*) alloca(n*sizeof(*vec));
  105728. /* stretch is used to gradually lengthen the number of windows
  105729. considered prevoius-to-potential-trigger */
  105730. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  105731. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  105732. if(penalty<0.f)penalty=0.f;
  105733. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  105734. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  105735. totalshift+pos*ve->searchstep);*/
  105736. /* window and transform */
  105737. for(i=0;i<n;i++)
  105738. vec[i]=data[i]*ve->mdct_win[i];
  105739. mdct_forward(&ve->mdct,vec,vec);
  105740. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  105741. /* near-DC spreading function; this has nothing to do with
  105742. psychoacoustics, just sidelobe leakage and window size */
  105743. {
  105744. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  105745. int ptr=filters->nearptr;
  105746. /* the accumulation is regularly refreshed from scratch to avoid
  105747. floating point creep */
  105748. if(ptr==0){
  105749. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  105750. filters->nearDC_partialacc=temp;
  105751. }else{
  105752. decay=filters->nearDC_acc+=temp;
  105753. filters->nearDC_partialacc+=temp;
  105754. }
  105755. filters->nearDC_acc-=filters->nearDC[ptr];
  105756. filters->nearDC[ptr]=temp;
  105757. decay*=(1./(VE_NEARDC+1));
  105758. filters->nearptr++;
  105759. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  105760. decay=todB(&decay)*.5-15.f;
  105761. }
  105762. /* perform spreading and limiting, also smooth the spectrum. yes,
  105763. the MDCT results in all real coefficients, but it still *behaves*
  105764. like real/imaginary pairs */
  105765. for(i=0;i<n/2;i+=2){
  105766. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  105767. val=todB(&val)*.5f;
  105768. if(val<decay)val=decay;
  105769. if(val<minV)val=minV;
  105770. vec[i>>1]=val;
  105771. decay-=8.;
  105772. }
  105773. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  105774. /* perform preecho/postecho triggering by band */
  105775. for(j=0;j<VE_BANDS;j++){
  105776. float acc=0.;
  105777. float valmax,valmin;
  105778. /* accumulate amplitude */
  105779. for(i=0;i<bands[j].end;i++)
  105780. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  105781. acc*=bands[j].total;
  105782. /* convert amplitude to delta */
  105783. {
  105784. int p,thisx=filters[j].ampptr;
  105785. float postmax,postmin,premax=-99999.f,premin=99999.f;
  105786. p=thisx;
  105787. p--;
  105788. if(p<0)p+=VE_AMP;
  105789. postmax=max(acc,filters[j].ampbuf[p]);
  105790. postmin=min(acc,filters[j].ampbuf[p]);
  105791. for(i=0;i<stretch;i++){
  105792. p--;
  105793. if(p<0)p+=VE_AMP;
  105794. premax=max(premax,filters[j].ampbuf[p]);
  105795. premin=min(premin,filters[j].ampbuf[p]);
  105796. }
  105797. valmin=postmin-premin;
  105798. valmax=postmax-premax;
  105799. /*filters[j].markers[pos]=valmax;*/
  105800. filters[j].ampbuf[thisx]=acc;
  105801. filters[j].ampptr++;
  105802. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  105803. }
  105804. /* look at min/max, decide trigger */
  105805. if(valmax>gi->preecho_thresh[j]+penalty){
  105806. ret|=1;
  105807. ret|=4;
  105808. }
  105809. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  105810. }
  105811. return(ret);
  105812. }
  105813. #if 0
  105814. static int seq=0;
  105815. static ogg_int64_t totalshift=-1024;
  105816. #endif
  105817. long _ve_envelope_search(vorbis_dsp_state *v){
  105818. vorbis_info *vi=v->vi;
  105819. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105820. vorbis_info_psy_global *gi=&ci->psy_g_param;
  105821. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  105822. long i,j;
  105823. int first=ve->current/ve->searchstep;
  105824. int last=v->pcm_current/ve->searchstep-VE_WIN;
  105825. if(first<0)first=0;
  105826. /* make sure we have enough storage to match the PCM */
  105827. if(last+VE_WIN+VE_POST>ve->storage){
  105828. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  105829. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  105830. }
  105831. for(j=first;j<last;j++){
  105832. int ret=0;
  105833. ve->stretch++;
  105834. if(ve->stretch>VE_MAXSTRETCH*2)
  105835. ve->stretch=VE_MAXSTRETCH*2;
  105836. for(i=0;i<ve->ch;i++){
  105837. float *pcm=v->pcm[i]+ve->searchstep*(j);
  105838. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  105839. }
  105840. ve->mark[j+VE_POST]=0;
  105841. if(ret&1){
  105842. ve->mark[j]=1;
  105843. ve->mark[j+1]=1;
  105844. }
  105845. if(ret&2){
  105846. ve->mark[j]=1;
  105847. if(j>0)ve->mark[j-1]=1;
  105848. }
  105849. if(ret&4)ve->stretch=-1;
  105850. }
  105851. ve->current=last*ve->searchstep;
  105852. {
  105853. long centerW=v->centerW;
  105854. long testW=
  105855. centerW+
  105856. ci->blocksizes[v->W]/4+
  105857. ci->blocksizes[1]/2+
  105858. ci->blocksizes[0]/4;
  105859. j=ve->cursor;
  105860. while(j<ve->current-(ve->searchstep)){/* account for postecho
  105861. working back one window */
  105862. if(j>=testW)return(1);
  105863. ve->cursor=j;
  105864. if(ve->mark[j/ve->searchstep]){
  105865. if(j>centerW){
  105866. #if 0
  105867. if(j>ve->curmark){
  105868. float *marker=alloca(v->pcm_current*sizeof(*marker));
  105869. int l,m;
  105870. memset(marker,0,sizeof(*marker)*v->pcm_current);
  105871. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  105872. seq,
  105873. (totalshift+ve->cursor)/44100.,
  105874. (totalshift+j)/44100.);
  105875. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  105876. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  105877. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  105878. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  105879. for(m=0;m<VE_BANDS;m++){
  105880. char buf[80];
  105881. sprintf(buf,"delL%d",m);
  105882. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  105883. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  105884. }
  105885. for(m=0;m<VE_BANDS;m++){
  105886. char buf[80];
  105887. sprintf(buf,"delR%d",m);
  105888. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  105889. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  105890. }
  105891. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  105892. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  105893. seq++;
  105894. }
  105895. #endif
  105896. ve->curmark=j;
  105897. if(j>=testW)return(1);
  105898. return(0);
  105899. }
  105900. }
  105901. j+=ve->searchstep;
  105902. }
  105903. }
  105904. return(-1);
  105905. }
  105906. int _ve_envelope_mark(vorbis_dsp_state *v){
  105907. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  105908. vorbis_info *vi=v->vi;
  105909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105910. long centerW=v->centerW;
  105911. long beginW=centerW-ci->blocksizes[v->W]/4;
  105912. long endW=centerW+ci->blocksizes[v->W]/4;
  105913. if(v->W){
  105914. beginW-=ci->blocksizes[v->lW]/4;
  105915. endW+=ci->blocksizes[v->nW]/4;
  105916. }else{
  105917. beginW-=ci->blocksizes[0]/4;
  105918. endW+=ci->blocksizes[0]/4;
  105919. }
  105920. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  105921. {
  105922. long first=beginW/ve->searchstep;
  105923. long last=endW/ve->searchstep;
  105924. long i;
  105925. for(i=first;i<last;i++)
  105926. if(ve->mark[i])return(1);
  105927. }
  105928. return(0);
  105929. }
  105930. void _ve_envelope_shift(envelope_lookup *e,long shift){
  105931. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  105932. ahead of ve->current */
  105933. int smallshift=shift/e->searchstep;
  105934. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  105935. #if 0
  105936. for(i=0;i<VE_BANDS*e->ch;i++)
  105937. memmove(e->filter[i].markers,
  105938. e->filter[i].markers+smallshift,
  105939. (1024-smallshift)*sizeof(*(*e->filter).markers));
  105940. totalshift+=shift;
  105941. #endif
  105942. e->current-=shift;
  105943. if(e->curmark>=0)
  105944. e->curmark-=shift;
  105945. e->cursor-=shift;
  105946. }
  105947. #endif
  105948. /********* End of inlined file: envelope.c *********/
  105949. /********* Start of inlined file: floor0.c *********/
  105950. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105951. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105952. // tasks..
  105953. #ifdef _MSC_VER
  105954. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105955. #endif
  105956. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105957. #if JUCE_USE_OGGVORBIS
  105958. #include <stdlib.h>
  105959. #include <string.h>
  105960. #include <math.h>
  105961. /********* Start of inlined file: lsp.h *********/
  105962. #ifndef _V_LSP_H_
  105963. #define _V_LSP_H_
  105964. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  105965. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  105966. float *lsp,int m,
  105967. float amp,float ampoffset);
  105968. #endif
  105969. /********* End of inlined file: lsp.h *********/
  105970. #include <stdio.h>
  105971. typedef struct {
  105972. int ln;
  105973. int m;
  105974. int **linearmap;
  105975. int n[2];
  105976. vorbis_info_floor0 *vi;
  105977. long bits;
  105978. long frames;
  105979. } vorbis_look_floor0;
  105980. /***********************************************/
  105981. static void floor0_free_info(vorbis_info_floor *i){
  105982. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  105983. if(info){
  105984. memset(info,0,sizeof(*info));
  105985. _ogg_free(info);
  105986. }
  105987. }
  105988. static void floor0_free_look(vorbis_look_floor *i){
  105989. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  105990. if(look){
  105991. if(look->linearmap){
  105992. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  105993. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  105994. _ogg_free(look->linearmap);
  105995. }
  105996. memset(look,0,sizeof(*look));
  105997. _ogg_free(look);
  105998. }
  105999. }
  106000. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106001. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106002. int j;
  106003. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  106004. info->order=oggpack_read(opb,8);
  106005. info->rate=oggpack_read(opb,16);
  106006. info->barkmap=oggpack_read(opb,16);
  106007. info->ampbits=oggpack_read(opb,6);
  106008. info->ampdB=oggpack_read(opb,8);
  106009. info->numbooks=oggpack_read(opb,4)+1;
  106010. if(info->order<1)goto err_out;
  106011. if(info->rate<1)goto err_out;
  106012. if(info->barkmap<1)goto err_out;
  106013. if(info->numbooks<1)goto err_out;
  106014. for(j=0;j<info->numbooks;j++){
  106015. info->books[j]=oggpack_read(opb,8);
  106016. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  106017. }
  106018. return(info);
  106019. err_out:
  106020. floor0_free_info(info);
  106021. return(NULL);
  106022. }
  106023. /* initialize Bark scale and normalization lookups. We could do this
  106024. with static tables, but Vorbis allows a number of possible
  106025. combinations, so it's best to do it computationally.
  106026. The below is authoritative in terms of defining scale mapping.
  106027. Note that the scale depends on the sampling rate as well as the
  106028. linear block and mapping sizes */
  106029. static void floor0_map_lazy_init(vorbis_block *vb,
  106030. vorbis_info_floor *infoX,
  106031. vorbis_look_floor0 *look){
  106032. if(!look->linearmap[vb->W]){
  106033. vorbis_dsp_state *vd=vb->vd;
  106034. vorbis_info *vi=vd->vi;
  106035. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106036. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  106037. int W=vb->W;
  106038. int n=ci->blocksizes[W]/2,j;
  106039. /* we choose a scaling constant so that:
  106040. floor(bark(rate/2-1)*C)=mapped-1
  106041. floor(bark(rate/2)*C)=mapped */
  106042. float scale=look->ln/toBARK(info->rate/2.f);
  106043. /* the mapping from a linear scale to a smaller bark scale is
  106044. straightforward. We do *not* make sure that the linear mapping
  106045. does not skip bark-scale bins; the decoder simply skips them and
  106046. the encoder may do what it wishes in filling them. They're
  106047. necessary in some mapping combinations to keep the scale spacing
  106048. accurate */
  106049. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  106050. for(j=0;j<n;j++){
  106051. int val=floor( toBARK((info->rate/2.f)/n*j)
  106052. *scale); /* bark numbers represent band edges */
  106053. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  106054. look->linearmap[W][j]=val;
  106055. }
  106056. look->linearmap[W][j]=-1;
  106057. look->n[W]=n;
  106058. }
  106059. }
  106060. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  106061. vorbis_info_floor *i){
  106062. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  106063. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  106064. look->m=info->order;
  106065. look->ln=info->barkmap;
  106066. look->vi=info;
  106067. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  106068. return look;
  106069. }
  106070. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  106071. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106072. vorbis_info_floor0 *info=look->vi;
  106073. int j,k;
  106074. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  106075. if(ampraw>0){ /* also handles the -1 out of data case */
  106076. long maxval=(1<<info->ampbits)-1;
  106077. float amp=(float)ampraw/maxval*info->ampdB;
  106078. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  106079. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  106080. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  106081. codebook *b=ci->fullbooks+info->books[booknum];
  106082. float last=0.f;
  106083. /* the additional b->dim is a guard against any possible stack
  106084. smash; b->dim is provably more than we can overflow the
  106085. vector */
  106086. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  106087. for(j=0;j<look->m;j+=b->dim)
  106088. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  106089. for(j=0;j<look->m;){
  106090. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  106091. last=lsp[j-1];
  106092. }
  106093. lsp[look->m]=amp;
  106094. return(lsp);
  106095. }
  106096. }
  106097. eop:
  106098. return(NULL);
  106099. }
  106100. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  106101. void *memo,float *out){
  106102. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106103. vorbis_info_floor0 *info=look->vi;
  106104. floor0_map_lazy_init(vb,info,look);
  106105. if(memo){
  106106. float *lsp=(float *)memo;
  106107. float amp=lsp[look->m];
  106108. /* take the coefficients back to a spectral envelope curve */
  106109. vorbis_lsp_to_curve(out,
  106110. look->linearmap[vb->W],
  106111. look->n[vb->W],
  106112. look->ln,
  106113. lsp,look->m,amp,(float)info->ampdB);
  106114. return(1);
  106115. }
  106116. memset(out,0,sizeof(*out)*look->n[vb->W]);
  106117. return(0);
  106118. }
  106119. /* export hooks */
  106120. vorbis_func_floor floor0_exportbundle={
  106121. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  106122. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  106123. };
  106124. #endif
  106125. /********* End of inlined file: floor0.c *********/
  106126. /********* Start of inlined file: floor1.c *********/
  106127. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106128. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106129. // tasks..
  106130. #ifdef _MSC_VER
  106131. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106132. #endif
  106133. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106134. #if JUCE_USE_OGGVORBIS
  106135. #include <stdlib.h>
  106136. #include <string.h>
  106137. #include <math.h>
  106138. #include <stdio.h>
  106139. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  106140. typedef struct {
  106141. int sorted_index[VIF_POSIT+2];
  106142. int forward_index[VIF_POSIT+2];
  106143. int reverse_index[VIF_POSIT+2];
  106144. int hineighbor[VIF_POSIT];
  106145. int loneighbor[VIF_POSIT];
  106146. int posts;
  106147. int n;
  106148. int quant_q;
  106149. vorbis_info_floor1 *vi;
  106150. long phrasebits;
  106151. long postbits;
  106152. long frames;
  106153. } vorbis_look_floor1;
  106154. typedef struct lsfit_acc{
  106155. long x0;
  106156. long x1;
  106157. long xa;
  106158. long ya;
  106159. long x2a;
  106160. long y2a;
  106161. long xya;
  106162. long an;
  106163. } lsfit_acc;
  106164. /***********************************************/
  106165. static void floor1_free_info(vorbis_info_floor *i){
  106166. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106167. if(info){
  106168. memset(info,0,sizeof(*info));
  106169. _ogg_free(info);
  106170. }
  106171. }
  106172. static void floor1_free_look(vorbis_look_floor *i){
  106173. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  106174. if(look){
  106175. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  106176. (float)look->phrasebits/look->frames,
  106177. (float)look->postbits/look->frames,
  106178. (float)(look->postbits+look->phrasebits)/look->frames);*/
  106179. memset(look,0,sizeof(*look));
  106180. _ogg_free(look);
  106181. }
  106182. }
  106183. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  106184. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106185. int j,k;
  106186. int count=0;
  106187. int rangebits;
  106188. int maxposit=info->postlist[1];
  106189. int maxclass=-1;
  106190. /* save out partitions */
  106191. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  106192. for(j=0;j<info->partitions;j++){
  106193. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  106194. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106195. }
  106196. /* save out partition classes */
  106197. for(j=0;j<maxclass+1;j++){
  106198. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  106199. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  106200. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  106201. for(k=0;k<(1<<info->class_subs[j]);k++)
  106202. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  106203. }
  106204. /* save out the post list */
  106205. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  106206. oggpack_write(opb,ilog2(maxposit),4);
  106207. rangebits=ilog2(maxposit);
  106208. for(j=0,k=0;j<info->partitions;j++){
  106209. count+=info->class_dim[info->partitionclass[j]];
  106210. for(;k<count;k++)
  106211. oggpack_write(opb,info->postlist[k+2],rangebits);
  106212. }
  106213. }
  106214. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106215. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106216. int j,k,count=0,maxclass=-1,rangebits;
  106217. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  106218. /* read partitions */
  106219. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  106220. for(j=0;j<info->partitions;j++){
  106221. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  106222. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106223. }
  106224. /* read partition classes */
  106225. for(j=0;j<maxclass+1;j++){
  106226. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  106227. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  106228. if(info->class_subs[j]<0)
  106229. goto err_out;
  106230. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  106231. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  106232. goto err_out;
  106233. for(k=0;k<(1<<info->class_subs[j]);k++){
  106234. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  106235. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  106236. goto err_out;
  106237. }
  106238. }
  106239. /* read the post list */
  106240. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  106241. rangebits=oggpack_read(opb,4);
  106242. for(j=0,k=0;j<info->partitions;j++){
  106243. count+=info->class_dim[info->partitionclass[j]];
  106244. for(;k<count;k++){
  106245. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  106246. if(t<0 || t>=(1<<rangebits))
  106247. goto err_out;
  106248. }
  106249. }
  106250. info->postlist[0]=0;
  106251. info->postlist[1]=1<<rangebits;
  106252. return(info);
  106253. err_out:
  106254. floor1_free_info(info);
  106255. return(NULL);
  106256. }
  106257. static int icomp(const void *a,const void *b){
  106258. return(**(int **)a-**(int **)b);
  106259. }
  106260. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  106261. vorbis_info_floor *in){
  106262. int *sortpointer[VIF_POSIT+2];
  106263. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  106264. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  106265. int i,j,n=0;
  106266. look->vi=info;
  106267. look->n=info->postlist[1];
  106268. /* we drop each position value in-between already decoded values,
  106269. and use linear interpolation to predict each new value past the
  106270. edges. The positions are read in the order of the position
  106271. list... we precompute the bounding positions in the lookup. Of
  106272. course, the neighbors can change (if a position is declined), but
  106273. this is an initial mapping */
  106274. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  106275. n+=2;
  106276. look->posts=n;
  106277. /* also store a sorted position index */
  106278. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  106279. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  106280. /* points from sort order back to range number */
  106281. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  106282. /* points from range order to sorted position */
  106283. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  106284. /* we actually need the post values too */
  106285. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  106286. /* quantize values to multiplier spec */
  106287. switch(info->mult){
  106288. case 1: /* 1024 -> 256 */
  106289. look->quant_q=256;
  106290. break;
  106291. case 2: /* 1024 -> 128 */
  106292. look->quant_q=128;
  106293. break;
  106294. case 3: /* 1024 -> 86 */
  106295. look->quant_q=86;
  106296. break;
  106297. case 4: /* 1024 -> 64 */
  106298. look->quant_q=64;
  106299. break;
  106300. }
  106301. /* discover our neighbors for decode where we don't use fit flags
  106302. (that would push the neighbors outward) */
  106303. for(i=0;i<n-2;i++){
  106304. int lo=0;
  106305. int hi=1;
  106306. int lx=0;
  106307. int hx=look->n;
  106308. int currentx=info->postlist[i+2];
  106309. for(j=0;j<i+2;j++){
  106310. int x=info->postlist[j];
  106311. if(x>lx && x<currentx){
  106312. lo=j;
  106313. lx=x;
  106314. }
  106315. if(x<hx && x>currentx){
  106316. hi=j;
  106317. hx=x;
  106318. }
  106319. }
  106320. look->loneighbor[i]=lo;
  106321. look->hineighbor[i]=hi;
  106322. }
  106323. return(look);
  106324. }
  106325. static int render_point(int x0,int x1,int y0,int y1,int x){
  106326. y0&=0x7fff; /* mask off flag */
  106327. y1&=0x7fff;
  106328. {
  106329. int dy=y1-y0;
  106330. int adx=x1-x0;
  106331. int ady=abs(dy);
  106332. int err=ady*(x-x0);
  106333. int off=err/adx;
  106334. if(dy<0)return(y0-off);
  106335. return(y0+off);
  106336. }
  106337. }
  106338. static int vorbis_dBquant(const float *x){
  106339. int i= *x*7.3142857f+1023.5f;
  106340. if(i>1023)return(1023);
  106341. if(i<0)return(0);
  106342. return i;
  106343. }
  106344. static float FLOOR1_fromdB_LOOKUP[256]={
  106345. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  106346. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  106347. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  106348. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  106349. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  106350. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  106351. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  106352. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  106353. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  106354. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  106355. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  106356. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  106357. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  106358. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  106359. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  106360. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  106361. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  106362. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  106363. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  106364. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  106365. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  106366. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  106367. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  106368. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  106369. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  106370. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  106371. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  106372. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  106373. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  106374. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  106375. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  106376. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  106377. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  106378. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  106379. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  106380. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  106381. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  106382. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  106383. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  106384. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  106385. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  106386. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  106387. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  106388. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  106389. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  106390. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  106391. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  106392. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  106393. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  106394. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  106395. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  106396. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  106397. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  106398. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  106399. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  106400. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  106401. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  106402. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  106403. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  106404. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  106405. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  106406. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  106407. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  106408. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  106409. };
  106410. static void render_line(int x0,int x1,int y0,int y1,float *d){
  106411. int dy=y1-y0;
  106412. int adx=x1-x0;
  106413. int ady=abs(dy);
  106414. int base=dy/adx;
  106415. int sy=(dy<0?base-1:base+1);
  106416. int x=x0;
  106417. int y=y0;
  106418. int err=0;
  106419. ady-=abs(base*adx);
  106420. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  106421. while(++x<x1){
  106422. err=err+ady;
  106423. if(err>=adx){
  106424. err-=adx;
  106425. y+=sy;
  106426. }else{
  106427. y+=base;
  106428. }
  106429. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  106430. }
  106431. }
  106432. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  106433. int dy=y1-y0;
  106434. int adx=x1-x0;
  106435. int ady=abs(dy);
  106436. int base=dy/adx;
  106437. int sy=(dy<0?base-1:base+1);
  106438. int x=x0;
  106439. int y=y0;
  106440. int err=0;
  106441. ady-=abs(base*adx);
  106442. d[x]=y;
  106443. while(++x<x1){
  106444. err=err+ady;
  106445. if(err>=adx){
  106446. err-=adx;
  106447. y+=sy;
  106448. }else{
  106449. y+=base;
  106450. }
  106451. d[x]=y;
  106452. }
  106453. }
  106454. /* the floor has already been filtered to only include relevant sections */
  106455. static int accumulate_fit(const float *flr,const float *mdct,
  106456. int x0, int x1,lsfit_acc *a,
  106457. int n,vorbis_info_floor1 *info){
  106458. long i;
  106459. long xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
  106460. memset(a,0,sizeof(*a));
  106461. a->x0=x0;
  106462. a->x1=x1;
  106463. if(x1>=n)x1=n-1;
  106464. for(i=x0;i<=x1;i++){
  106465. int quantized=vorbis_dBquant(flr+i);
  106466. if(quantized){
  106467. if(mdct[i]+info->twofitatten>=flr[i]){
  106468. xa += i;
  106469. ya += quantized;
  106470. x2a += i*i;
  106471. y2a += quantized*quantized;
  106472. xya += i*quantized;
  106473. na++;
  106474. }else{
  106475. xb += i;
  106476. yb += quantized;
  106477. x2b += i*i;
  106478. y2b += quantized*quantized;
  106479. xyb += i*quantized;
  106480. nb++;
  106481. }
  106482. }
  106483. }
  106484. xb+=xa;
  106485. yb+=ya;
  106486. x2b+=x2a;
  106487. y2b+=y2a;
  106488. xyb+=xya;
  106489. nb+=na;
  106490. /* weight toward the actually used frequencies if we meet the threshhold */
  106491. {
  106492. int weight=nb*info->twofitweight/(na+1);
  106493. a->xa=xa*weight+xb;
  106494. a->ya=ya*weight+yb;
  106495. a->x2a=x2a*weight+x2b;
  106496. a->y2a=y2a*weight+y2b;
  106497. a->xya=xya*weight+xyb;
  106498. a->an=na*weight+nb;
  106499. }
  106500. return(na);
  106501. }
  106502. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  106503. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  106504. long x0=a[0].x0;
  106505. long x1=a[fits-1].x1;
  106506. for(i=0;i<fits;i++){
  106507. x+=a[i].xa;
  106508. y+=a[i].ya;
  106509. x2+=a[i].x2a;
  106510. y2+=a[i].y2a;
  106511. xy+=a[i].xya;
  106512. an+=a[i].an;
  106513. }
  106514. if(*y0>=0){
  106515. x+= x0;
  106516. y+= *y0;
  106517. x2+= x0 * x0;
  106518. y2+= *y0 * *y0;
  106519. xy+= *y0 * x0;
  106520. an++;
  106521. }
  106522. if(*y1>=0){
  106523. x+= x1;
  106524. y+= *y1;
  106525. x2+= x1 * x1;
  106526. y2+= *y1 * *y1;
  106527. xy+= *y1 * x1;
  106528. an++;
  106529. }
  106530. if(an){
  106531. /* need 64 bit multiplies, which C doesn't give portably as int */
  106532. double fx=x;
  106533. double fy=y;
  106534. double fx2=x2;
  106535. double fxy=xy;
  106536. double denom=1./(an*fx2-fx*fx);
  106537. double a=(fy*fx2-fxy*fx)*denom;
  106538. double b=(an*fxy-fx*fy)*denom;
  106539. *y0=rint(a+b*x0);
  106540. *y1=rint(a+b*x1);
  106541. /* limit to our range! */
  106542. if(*y0>1023)*y0=1023;
  106543. if(*y1>1023)*y1=1023;
  106544. if(*y0<0)*y0=0;
  106545. if(*y1<0)*y1=0;
  106546. }else{
  106547. *y0=0;
  106548. *y1=0;
  106549. }
  106550. }
  106551. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  106552. long y=0;
  106553. int i;
  106554. for(i=0;i<fits && y==0;i++)
  106555. y+=a[i].ya;
  106556. *y0=*y1=y;
  106557. }*/
  106558. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  106559. const float *mdct,
  106560. vorbis_info_floor1 *info){
  106561. int dy=y1-y0;
  106562. int adx=x1-x0;
  106563. int ady=abs(dy);
  106564. int base=dy/adx;
  106565. int sy=(dy<0?base-1:base+1);
  106566. int x=x0;
  106567. int y=y0;
  106568. int err=0;
  106569. int val=vorbis_dBquant(mask+x);
  106570. int mse=0;
  106571. int n=0;
  106572. ady-=abs(base*adx);
  106573. mse=(y-val);
  106574. mse*=mse;
  106575. n++;
  106576. if(mdct[x]+info->twofitatten>=mask[x]){
  106577. if(y+info->maxover<val)return(1);
  106578. if(y-info->maxunder>val)return(1);
  106579. }
  106580. while(++x<x1){
  106581. err=err+ady;
  106582. if(err>=adx){
  106583. err-=adx;
  106584. y+=sy;
  106585. }else{
  106586. y+=base;
  106587. }
  106588. val=vorbis_dBquant(mask+x);
  106589. mse+=((y-val)*(y-val));
  106590. n++;
  106591. if(mdct[x]+info->twofitatten>=mask[x]){
  106592. if(val){
  106593. if(y+info->maxover<val)return(1);
  106594. if(y-info->maxunder>val)return(1);
  106595. }
  106596. }
  106597. }
  106598. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  106599. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  106600. if(mse/n>info->maxerr)return(1);
  106601. return(0);
  106602. }
  106603. static int post_Y(int *A,int *B,int pos){
  106604. if(A[pos]<0)
  106605. return B[pos];
  106606. if(B[pos]<0)
  106607. return A[pos];
  106608. return (A[pos]+B[pos])>>1;
  106609. }
  106610. int *floor1_fit(vorbis_block *vb,void *look_,
  106611. const float *logmdct, /* in */
  106612. const float *logmask){
  106613. long i,j;
  106614. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  106615. vorbis_info_floor1 *info=look->vi;
  106616. long n=look->n;
  106617. long posts=look->posts;
  106618. long nonzero=0;
  106619. lsfit_acc fits[VIF_POSIT+1];
  106620. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  106621. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  106622. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  106623. int hineighbor[VIF_POSIT+2];
  106624. int *output=NULL;
  106625. int memo[VIF_POSIT+2];
  106626. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  106627. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  106628. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  106629. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  106630. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  106631. /* quantize the relevant floor points and collect them into line fit
  106632. structures (one per minimal division) at the same time */
  106633. if(posts==0){
  106634. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  106635. }else{
  106636. for(i=0;i<posts-1;i++)
  106637. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  106638. look->sorted_index[i+1],fits+i,
  106639. n,info);
  106640. }
  106641. if(nonzero){
  106642. /* start by fitting the implicit base case.... */
  106643. int y0=-200;
  106644. int y1=-200;
  106645. fit_line(fits,posts-1,&y0,&y1);
  106646. fit_valueA[0]=y0;
  106647. fit_valueB[0]=y0;
  106648. fit_valueB[1]=y1;
  106649. fit_valueA[1]=y1;
  106650. /* Non degenerate case */
  106651. /* start progressive splitting. This is a greedy, non-optimal
  106652. algorithm, but simple and close enough to the best
  106653. answer. */
  106654. for(i=2;i<posts;i++){
  106655. int sortpos=look->reverse_index[i];
  106656. int ln=loneighbor[sortpos];
  106657. int hn=hineighbor[sortpos];
  106658. /* eliminate repeat searches of a particular range with a memo */
  106659. if(memo[ln]!=hn){
  106660. /* haven't performed this error search yet */
  106661. int lsortpos=look->reverse_index[ln];
  106662. int hsortpos=look->reverse_index[hn];
  106663. memo[ln]=hn;
  106664. {
  106665. /* A note: we want to bound/minimize *local*, not global, error */
  106666. int lx=info->postlist[ln];
  106667. int hx=info->postlist[hn];
  106668. int ly=post_Y(fit_valueA,fit_valueB,ln);
  106669. int hy=post_Y(fit_valueA,fit_valueB,hn);
  106670. if(ly==-1 || hy==-1){
  106671. exit(1);
  106672. }
  106673. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  106674. /* outside error bounds/begin search area. Split it. */
  106675. int ly0=-200;
  106676. int ly1=-200;
  106677. int hy0=-200;
  106678. int hy1=-200;
  106679. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  106680. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  106681. /* store new edge values */
  106682. fit_valueB[ln]=ly0;
  106683. if(ln==0)fit_valueA[ln]=ly0;
  106684. fit_valueA[i]=ly1;
  106685. fit_valueB[i]=hy0;
  106686. fit_valueA[hn]=hy1;
  106687. if(hn==1)fit_valueB[hn]=hy1;
  106688. if(ly1>=0 || hy0>=0){
  106689. /* store new neighbor values */
  106690. for(j=sortpos-1;j>=0;j--)
  106691. if(hineighbor[j]==hn)
  106692. hineighbor[j]=i;
  106693. else
  106694. break;
  106695. for(j=sortpos+1;j<posts;j++)
  106696. if(loneighbor[j]==ln)
  106697. loneighbor[j]=i;
  106698. else
  106699. break;
  106700. }
  106701. }else{
  106702. fit_valueA[i]=-200;
  106703. fit_valueB[i]=-200;
  106704. }
  106705. }
  106706. }
  106707. }
  106708. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  106709. output[0]=post_Y(fit_valueA,fit_valueB,0);
  106710. output[1]=post_Y(fit_valueA,fit_valueB,1);
  106711. /* fill in posts marked as not using a fit; we will zero
  106712. back out to 'unused' when encoding them so long as curve
  106713. interpolation doesn't force them into use */
  106714. for(i=2;i<posts;i++){
  106715. int ln=look->loneighbor[i-2];
  106716. int hn=look->hineighbor[i-2];
  106717. int x0=info->postlist[ln];
  106718. int x1=info->postlist[hn];
  106719. int y0=output[ln];
  106720. int y1=output[hn];
  106721. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  106722. int vx=post_Y(fit_valueA,fit_valueB,i);
  106723. if(vx>=0 && predicted!=vx){
  106724. output[i]=vx;
  106725. }else{
  106726. output[i]= predicted|0x8000;
  106727. }
  106728. }
  106729. }
  106730. return(output);
  106731. }
  106732. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  106733. int *A,int *B,
  106734. int del){
  106735. long i;
  106736. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  106737. long posts=look->posts;
  106738. int *output=NULL;
  106739. if(A && B){
  106740. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  106741. for(i=0;i<posts;i++){
  106742. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  106743. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  106744. }
  106745. }
  106746. return(output);
  106747. }
  106748. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  106749. void*look_,
  106750. int *post,int *ilogmask){
  106751. long i,j;
  106752. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  106753. vorbis_info_floor1 *info=look->vi;
  106754. long posts=look->posts;
  106755. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  106756. int out[VIF_POSIT+2];
  106757. static_codebook **sbooks=ci->book_param;
  106758. codebook *books=ci->fullbooks;
  106759. static long seq=0;
  106760. /* quantize values to multiplier spec */
  106761. if(post){
  106762. for(i=0;i<posts;i++){
  106763. int val=post[i]&0x7fff;
  106764. switch(info->mult){
  106765. case 1: /* 1024 -> 256 */
  106766. val>>=2;
  106767. break;
  106768. case 2: /* 1024 -> 128 */
  106769. val>>=3;
  106770. break;
  106771. case 3: /* 1024 -> 86 */
  106772. val/=12;
  106773. break;
  106774. case 4: /* 1024 -> 64 */
  106775. val>>=4;
  106776. break;
  106777. }
  106778. post[i]=val | (post[i]&0x8000);
  106779. }
  106780. out[0]=post[0];
  106781. out[1]=post[1];
  106782. /* find prediction values for each post and subtract them */
  106783. for(i=2;i<posts;i++){
  106784. int ln=look->loneighbor[i-2];
  106785. int hn=look->hineighbor[i-2];
  106786. int x0=info->postlist[ln];
  106787. int x1=info->postlist[hn];
  106788. int y0=post[ln];
  106789. int y1=post[hn];
  106790. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  106791. if((post[i]&0x8000) || (predicted==post[i])){
  106792. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  106793. in interpolation */
  106794. out[i]=0;
  106795. }else{
  106796. int headroom=(look->quant_q-predicted<predicted?
  106797. look->quant_q-predicted:predicted);
  106798. int val=post[i]-predicted;
  106799. /* at this point the 'deviation' value is in the range +/- max
  106800. range, but the real, unique range can always be mapped to
  106801. only [0-maxrange). So we want to wrap the deviation into
  106802. this limited range, but do it in the way that least screws
  106803. an essentially gaussian probability distribution. */
  106804. if(val<0)
  106805. if(val<-headroom)
  106806. val=headroom-val-1;
  106807. else
  106808. val=-1-(val<<1);
  106809. else
  106810. if(val>=headroom)
  106811. val= val+headroom;
  106812. else
  106813. val<<=1;
  106814. out[i]=val;
  106815. post[ln]&=0x7fff;
  106816. post[hn]&=0x7fff;
  106817. }
  106818. }
  106819. /* we have everything we need. pack it out */
  106820. /* mark nontrivial floor */
  106821. oggpack_write(opb,1,1);
  106822. /* beginning/end post */
  106823. look->frames++;
  106824. look->postbits+=ilog(look->quant_q-1)*2;
  106825. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  106826. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  106827. /* partition by partition */
  106828. for(i=0,j=2;i<info->partitions;i++){
  106829. int classx=info->partitionclass[i];
  106830. int cdim=info->class_dim[classx];
  106831. int csubbits=info->class_subs[classx];
  106832. int csub=1<<csubbits;
  106833. int bookas[8]={0,0,0,0,0,0,0,0};
  106834. int cval=0;
  106835. int cshift=0;
  106836. int k,l;
  106837. /* generate the partition's first stage cascade value */
  106838. if(csubbits){
  106839. int maxval[8];
  106840. for(k=0;k<csub;k++){
  106841. int booknum=info->class_subbook[classx][k];
  106842. if(booknum<0){
  106843. maxval[k]=1;
  106844. }else{
  106845. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  106846. }
  106847. }
  106848. for(k=0;k<cdim;k++){
  106849. for(l=0;l<csub;l++){
  106850. int val=out[j+k];
  106851. if(val<maxval[l]){
  106852. bookas[k]=l;
  106853. break;
  106854. }
  106855. }
  106856. cval|= bookas[k]<<cshift;
  106857. cshift+=csubbits;
  106858. }
  106859. /* write it */
  106860. look->phrasebits+=
  106861. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  106862. #ifdef TRAIN_FLOOR1
  106863. {
  106864. FILE *of;
  106865. char buffer[80];
  106866. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  106867. vb->pcmend/2,posts-2,class);
  106868. of=fopen(buffer,"a");
  106869. fprintf(of,"%d\n",cval);
  106870. fclose(of);
  106871. }
  106872. #endif
  106873. }
  106874. /* write post values */
  106875. for(k=0;k<cdim;k++){
  106876. int book=info->class_subbook[classx][bookas[k]];
  106877. if(book>=0){
  106878. /* hack to allow training with 'bad' books */
  106879. if(out[j+k]<(books+book)->entries)
  106880. look->postbits+=vorbis_book_encode(books+book,
  106881. out[j+k],opb);
  106882. /*else
  106883. fprintf(stderr,"+!");*/
  106884. #ifdef TRAIN_FLOOR1
  106885. {
  106886. FILE *of;
  106887. char buffer[80];
  106888. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  106889. vb->pcmend/2,posts-2,class,bookas[k]);
  106890. of=fopen(buffer,"a");
  106891. fprintf(of,"%d\n",out[j+k]);
  106892. fclose(of);
  106893. }
  106894. #endif
  106895. }
  106896. }
  106897. j+=cdim;
  106898. }
  106899. {
  106900. /* generate quantized floor equivalent to what we'd unpack in decode */
  106901. /* render the lines */
  106902. int hx=0;
  106903. int lx=0;
  106904. int ly=post[0]*info->mult;
  106905. for(j=1;j<look->posts;j++){
  106906. int current=look->forward_index[j];
  106907. int hy=post[current]&0x7fff;
  106908. if(hy==post[current]){
  106909. hy*=info->mult;
  106910. hx=info->postlist[current];
  106911. render_line0(lx,hx,ly,hy,ilogmask);
  106912. lx=hx;
  106913. ly=hy;
  106914. }
  106915. }
  106916. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  106917. seq++;
  106918. return(1);
  106919. }
  106920. }else{
  106921. oggpack_write(opb,0,1);
  106922. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  106923. seq++;
  106924. return(0);
  106925. }
  106926. }
  106927. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  106928. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  106929. vorbis_info_floor1 *info=look->vi;
  106930. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  106931. int i,j,k;
  106932. codebook *books=ci->fullbooks;
  106933. /* unpack wrapped/predicted values from stream */
  106934. if(oggpack_read(&vb->opb,1)==1){
  106935. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  106936. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  106937. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  106938. /* partition by partition */
  106939. for(i=0,j=2;i<info->partitions;i++){
  106940. int classx=info->partitionclass[i];
  106941. int cdim=info->class_dim[classx];
  106942. int csubbits=info->class_subs[classx];
  106943. int csub=1<<csubbits;
  106944. int cval=0;
  106945. /* decode the partition's first stage cascade value */
  106946. if(csubbits){
  106947. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  106948. if(cval==-1)goto eop;
  106949. }
  106950. for(k=0;k<cdim;k++){
  106951. int book=info->class_subbook[classx][cval&(csub-1)];
  106952. cval>>=csubbits;
  106953. if(book>=0){
  106954. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  106955. goto eop;
  106956. }else{
  106957. fit_value[j+k]=0;
  106958. }
  106959. }
  106960. j+=cdim;
  106961. }
  106962. /* unwrap positive values and reconsitute via linear interpolation */
  106963. for(i=2;i<look->posts;i++){
  106964. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  106965. info->postlist[look->hineighbor[i-2]],
  106966. fit_value[look->loneighbor[i-2]],
  106967. fit_value[look->hineighbor[i-2]],
  106968. info->postlist[i]);
  106969. int hiroom=look->quant_q-predicted;
  106970. int loroom=predicted;
  106971. int room=(hiroom<loroom?hiroom:loroom)<<1;
  106972. int val=fit_value[i];
  106973. if(val){
  106974. if(val>=room){
  106975. if(hiroom>loroom){
  106976. val = val-loroom;
  106977. }else{
  106978. val = -1-(val-hiroom);
  106979. }
  106980. }else{
  106981. if(val&1){
  106982. val= -((val+1)>>1);
  106983. }else{
  106984. val>>=1;
  106985. }
  106986. }
  106987. fit_value[i]=val+predicted;
  106988. fit_value[look->loneighbor[i-2]]&=0x7fff;
  106989. fit_value[look->hineighbor[i-2]]&=0x7fff;
  106990. }else{
  106991. fit_value[i]=predicted|0x8000;
  106992. }
  106993. }
  106994. return(fit_value);
  106995. }
  106996. eop:
  106997. return(NULL);
  106998. }
  106999. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  107000. float *out){
  107001. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107002. vorbis_info_floor1 *info=look->vi;
  107003. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107004. int n=ci->blocksizes[vb->W]/2;
  107005. int j;
  107006. if(memo){
  107007. /* render the lines */
  107008. int *fit_value=(int *)memo;
  107009. int hx=0;
  107010. int lx=0;
  107011. int ly=fit_value[0]*info->mult;
  107012. for(j=1;j<look->posts;j++){
  107013. int current=look->forward_index[j];
  107014. int hy=fit_value[current]&0x7fff;
  107015. if(hy==fit_value[current]){
  107016. hy*=info->mult;
  107017. hx=info->postlist[current];
  107018. render_line(lx,hx,ly,hy,out);
  107019. lx=hx;
  107020. ly=hy;
  107021. }
  107022. }
  107023. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  107024. return(1);
  107025. }
  107026. memset(out,0,sizeof(*out)*n);
  107027. return(0);
  107028. }
  107029. /* export hooks */
  107030. vorbis_func_floor floor1_exportbundle={
  107031. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  107032. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  107033. };
  107034. #endif
  107035. /********* End of inlined file: floor1.c *********/
  107036. /********* Start of inlined file: info.c *********/
  107037. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107038. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107039. // tasks..
  107040. #ifdef _MSC_VER
  107041. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107042. #endif
  107043. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107044. #if JUCE_USE_OGGVORBIS
  107045. /* general handling of the header and the vorbis_info structure (and
  107046. substructures) */
  107047. #include <stdlib.h>
  107048. #include <string.h>
  107049. #include <ctype.h>
  107050. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  107051. while(bytes--){
  107052. oggpack_write(o,*s++,8);
  107053. }
  107054. }
  107055. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  107056. while(bytes--){
  107057. *buf++=oggpack_read(o,8);
  107058. }
  107059. }
  107060. void vorbis_comment_init(vorbis_comment *vc){
  107061. memset(vc,0,sizeof(*vc));
  107062. }
  107063. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  107064. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  107065. (vc->comments+2)*sizeof(*vc->user_comments));
  107066. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  107067. (vc->comments+2)*sizeof(*vc->comment_lengths));
  107068. vc->comment_lengths[vc->comments]=strlen(comment);
  107069. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  107070. strcpy(vc->user_comments[vc->comments], comment);
  107071. vc->comments++;
  107072. vc->user_comments[vc->comments]=NULL;
  107073. }
  107074. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  107075. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  107076. strcpy(comment, tag);
  107077. strcat(comment, "=");
  107078. strcat(comment, contents);
  107079. vorbis_comment_add(vc, comment);
  107080. }
  107081. /* This is more or less the same as strncasecmp - but that doesn't exist
  107082. * everywhere, and this is a fairly trivial function, so we include it */
  107083. static int tagcompare(const char *s1, const char *s2, int n){
  107084. int c=0;
  107085. while(c < n){
  107086. if(toupper(s1[c]) != toupper(s2[c]))
  107087. return !0;
  107088. c++;
  107089. }
  107090. return 0;
  107091. }
  107092. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  107093. long i;
  107094. int found = 0;
  107095. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107096. char *fulltag = (char*)alloca(taglen+ 1);
  107097. strcpy(fulltag, tag);
  107098. strcat(fulltag, "=");
  107099. for(i=0;i<vc->comments;i++){
  107100. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  107101. if(count == found)
  107102. /* We return a pointer to the data, not a copy */
  107103. return vc->user_comments[i] + taglen;
  107104. else
  107105. found++;
  107106. }
  107107. }
  107108. return NULL; /* didn't find anything */
  107109. }
  107110. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  107111. int i,count=0;
  107112. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107113. char *fulltag = (char*)alloca(taglen+1);
  107114. strcpy(fulltag,tag);
  107115. strcat(fulltag, "=");
  107116. for(i=0;i<vc->comments;i++){
  107117. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  107118. count++;
  107119. }
  107120. return count;
  107121. }
  107122. void vorbis_comment_clear(vorbis_comment *vc){
  107123. if(vc){
  107124. long i;
  107125. for(i=0;i<vc->comments;i++)
  107126. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  107127. if(vc->user_comments)_ogg_free(vc->user_comments);
  107128. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  107129. if(vc->vendor)_ogg_free(vc->vendor);
  107130. }
  107131. memset(vc,0,sizeof(*vc));
  107132. }
  107133. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  107134. They may be equal, but short will never ge greater than long */
  107135. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  107136. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  107137. return ci ? ci->blocksizes[zo] : -1;
  107138. }
  107139. /* used by synthesis, which has a full, alloced vi */
  107140. void vorbis_info_init(vorbis_info *vi){
  107141. memset(vi,0,sizeof(*vi));
  107142. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  107143. }
  107144. void vorbis_info_clear(vorbis_info *vi){
  107145. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107146. int i;
  107147. if(ci){
  107148. for(i=0;i<ci->modes;i++)
  107149. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  107150. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  107151. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  107152. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  107153. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  107154. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  107155. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  107156. for(i=0;i<ci->books;i++){
  107157. if(ci->book_param[i]){
  107158. /* knows if the book was not alloced */
  107159. vorbis_staticbook_destroy(ci->book_param[i]);
  107160. }
  107161. if(ci->fullbooks)
  107162. vorbis_book_clear(ci->fullbooks+i);
  107163. }
  107164. if(ci->fullbooks)
  107165. _ogg_free(ci->fullbooks);
  107166. for(i=0;i<ci->psys;i++)
  107167. _vi_psy_free(ci->psy_param[i]);
  107168. _ogg_free(ci);
  107169. }
  107170. memset(vi,0,sizeof(*vi));
  107171. }
  107172. /* Header packing/unpacking ********************************************/
  107173. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  107174. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107175. if(!ci)return(OV_EFAULT);
  107176. vi->version=oggpack_read(opb,32);
  107177. if(vi->version!=0)return(OV_EVERSION);
  107178. vi->channels=oggpack_read(opb,8);
  107179. vi->rate=oggpack_read(opb,32);
  107180. vi->bitrate_upper=oggpack_read(opb,32);
  107181. vi->bitrate_nominal=oggpack_read(opb,32);
  107182. vi->bitrate_lower=oggpack_read(opb,32);
  107183. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  107184. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  107185. if(vi->rate<1)goto err_out;
  107186. if(vi->channels<1)goto err_out;
  107187. if(ci->blocksizes[0]<8)goto err_out;
  107188. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  107189. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107190. return(0);
  107191. err_out:
  107192. vorbis_info_clear(vi);
  107193. return(OV_EBADHEADER);
  107194. }
  107195. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  107196. int i;
  107197. int vendorlen=oggpack_read(opb,32);
  107198. if(vendorlen<0)goto err_out;
  107199. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  107200. _v_readstring(opb,vc->vendor,vendorlen);
  107201. vc->comments=oggpack_read(opb,32);
  107202. if(vc->comments<0)goto err_out;
  107203. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  107204. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  107205. for(i=0;i<vc->comments;i++){
  107206. int len=oggpack_read(opb,32);
  107207. if(len<0)goto err_out;
  107208. vc->comment_lengths[i]=len;
  107209. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  107210. _v_readstring(opb,vc->user_comments[i],len);
  107211. }
  107212. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107213. return(0);
  107214. err_out:
  107215. vorbis_comment_clear(vc);
  107216. return(OV_EBADHEADER);
  107217. }
  107218. /* all of the real encoding details are here. The modes, books,
  107219. everything */
  107220. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  107221. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107222. int i;
  107223. if(!ci)return(OV_EFAULT);
  107224. /* codebooks */
  107225. ci->books=oggpack_read(opb,8)+1;
  107226. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  107227. for(i=0;i<ci->books;i++){
  107228. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  107229. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  107230. }
  107231. /* time backend settings; hooks are unused */
  107232. {
  107233. int times=oggpack_read(opb,6)+1;
  107234. for(i=0;i<times;i++){
  107235. int test=oggpack_read(opb,16);
  107236. if(test<0 || test>=VI_TIMEB)goto err_out;
  107237. }
  107238. }
  107239. /* floor backend settings */
  107240. ci->floors=oggpack_read(opb,6)+1;
  107241. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  107242. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  107243. for(i=0;i<ci->floors;i++){
  107244. ci->floor_type[i]=oggpack_read(opb,16);
  107245. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  107246. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  107247. if(!ci->floor_param[i])goto err_out;
  107248. }
  107249. /* residue backend settings */
  107250. ci->residues=oggpack_read(opb,6)+1;
  107251. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  107252. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  107253. for(i=0;i<ci->residues;i++){
  107254. ci->residue_type[i]=oggpack_read(opb,16);
  107255. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  107256. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  107257. if(!ci->residue_param[i])goto err_out;
  107258. }
  107259. /* map backend settings */
  107260. ci->maps=oggpack_read(opb,6)+1;
  107261. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  107262. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  107263. for(i=0;i<ci->maps;i++){
  107264. ci->map_type[i]=oggpack_read(opb,16);
  107265. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  107266. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  107267. if(!ci->map_param[i])goto err_out;
  107268. }
  107269. /* mode settings */
  107270. ci->modes=oggpack_read(opb,6)+1;
  107271. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  107272. for(i=0;i<ci->modes;i++){
  107273. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  107274. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  107275. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  107276. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  107277. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  107278. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  107279. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  107280. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  107281. }
  107282. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  107283. return(0);
  107284. err_out:
  107285. vorbis_info_clear(vi);
  107286. return(OV_EBADHEADER);
  107287. }
  107288. /* The Vorbis header is in three packets; the initial small packet in
  107289. the first page that identifies basic parameters, a second packet
  107290. with bitstream comments and a third packet that holds the
  107291. codebook. */
  107292. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  107293. oggpack_buffer opb;
  107294. if(op){
  107295. oggpack_readinit(&opb,op->packet,op->bytes);
  107296. /* Which of the three types of header is this? */
  107297. /* Also verify header-ness, vorbis */
  107298. {
  107299. char buffer[6];
  107300. int packtype=oggpack_read(&opb,8);
  107301. memset(buffer,0,6);
  107302. _v_readstring(&opb,buffer,6);
  107303. if(memcmp(buffer,"vorbis",6)){
  107304. /* not a vorbis header */
  107305. return(OV_ENOTVORBIS);
  107306. }
  107307. switch(packtype){
  107308. case 0x01: /* least significant *bit* is read first */
  107309. if(!op->b_o_s){
  107310. /* Not the initial packet */
  107311. return(OV_EBADHEADER);
  107312. }
  107313. if(vi->rate!=0){
  107314. /* previously initialized info header */
  107315. return(OV_EBADHEADER);
  107316. }
  107317. return(_vorbis_unpack_info(vi,&opb));
  107318. case 0x03: /* least significant *bit* is read first */
  107319. if(vi->rate==0){
  107320. /* um... we didn't get the initial header */
  107321. return(OV_EBADHEADER);
  107322. }
  107323. return(_vorbis_unpack_comment(vc,&opb));
  107324. case 0x05: /* least significant *bit* is read first */
  107325. if(vi->rate==0 || vc->vendor==NULL){
  107326. /* um... we didn;t get the initial header or comments yet */
  107327. return(OV_EBADHEADER);
  107328. }
  107329. return(_vorbis_unpack_books(vi,&opb));
  107330. default:
  107331. /* Not a valid vorbis header type */
  107332. return(OV_EBADHEADER);
  107333. break;
  107334. }
  107335. }
  107336. }
  107337. return(OV_EBADHEADER);
  107338. }
  107339. /* pack side **********************************************************/
  107340. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  107341. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107342. if(!ci)return(OV_EFAULT);
  107343. /* preamble */
  107344. oggpack_write(opb,0x01,8);
  107345. _v_writestring(opb,"vorbis", 6);
  107346. /* basic information about the stream */
  107347. oggpack_write(opb,0x00,32);
  107348. oggpack_write(opb,vi->channels,8);
  107349. oggpack_write(opb,vi->rate,32);
  107350. oggpack_write(opb,vi->bitrate_upper,32);
  107351. oggpack_write(opb,vi->bitrate_nominal,32);
  107352. oggpack_write(opb,vi->bitrate_lower,32);
  107353. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  107354. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  107355. oggpack_write(opb,1,1);
  107356. return(0);
  107357. }
  107358. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  107359. char temp[]="Xiph.Org libVorbis I 20050304";
  107360. int bytes = strlen(temp);
  107361. /* preamble */
  107362. oggpack_write(opb,0x03,8);
  107363. _v_writestring(opb,"vorbis", 6);
  107364. /* vendor */
  107365. oggpack_write(opb,bytes,32);
  107366. _v_writestring(opb,temp, bytes);
  107367. /* comments */
  107368. oggpack_write(opb,vc->comments,32);
  107369. if(vc->comments){
  107370. int i;
  107371. for(i=0;i<vc->comments;i++){
  107372. if(vc->user_comments[i]){
  107373. oggpack_write(opb,vc->comment_lengths[i],32);
  107374. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  107375. }else{
  107376. oggpack_write(opb,0,32);
  107377. }
  107378. }
  107379. }
  107380. oggpack_write(opb,1,1);
  107381. return(0);
  107382. }
  107383. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  107384. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107385. int i;
  107386. if(!ci)return(OV_EFAULT);
  107387. oggpack_write(opb,0x05,8);
  107388. _v_writestring(opb,"vorbis", 6);
  107389. /* books */
  107390. oggpack_write(opb,ci->books-1,8);
  107391. for(i=0;i<ci->books;i++)
  107392. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  107393. /* times; hook placeholders */
  107394. oggpack_write(opb,0,6);
  107395. oggpack_write(opb,0,16);
  107396. /* floors */
  107397. oggpack_write(opb,ci->floors-1,6);
  107398. for(i=0;i<ci->floors;i++){
  107399. oggpack_write(opb,ci->floor_type[i],16);
  107400. if(_floor_P[ci->floor_type[i]]->pack)
  107401. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  107402. else
  107403. goto err_out;
  107404. }
  107405. /* residues */
  107406. oggpack_write(opb,ci->residues-1,6);
  107407. for(i=0;i<ci->residues;i++){
  107408. oggpack_write(opb,ci->residue_type[i],16);
  107409. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  107410. }
  107411. /* maps */
  107412. oggpack_write(opb,ci->maps-1,6);
  107413. for(i=0;i<ci->maps;i++){
  107414. oggpack_write(opb,ci->map_type[i],16);
  107415. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  107416. }
  107417. /* modes */
  107418. oggpack_write(opb,ci->modes-1,6);
  107419. for(i=0;i<ci->modes;i++){
  107420. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  107421. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  107422. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  107423. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  107424. }
  107425. oggpack_write(opb,1,1);
  107426. return(0);
  107427. err_out:
  107428. return(-1);
  107429. }
  107430. int vorbis_commentheader_out(vorbis_comment *vc,
  107431. ogg_packet *op){
  107432. oggpack_buffer opb;
  107433. oggpack_writeinit(&opb);
  107434. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  107435. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107436. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  107437. op->bytes=oggpack_bytes(&opb);
  107438. op->b_o_s=0;
  107439. op->e_o_s=0;
  107440. op->granulepos=0;
  107441. op->packetno=1;
  107442. return 0;
  107443. }
  107444. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107445. vorbis_comment *vc,
  107446. ogg_packet *op,
  107447. ogg_packet *op_comm,
  107448. ogg_packet *op_code){
  107449. int ret=OV_EIMPL;
  107450. vorbis_info *vi=v->vi;
  107451. oggpack_buffer opb;
  107452. private_state *b=(private_state*)v->backend_state;
  107453. if(!b){
  107454. ret=OV_EFAULT;
  107455. goto err_out;
  107456. }
  107457. /* first header packet **********************************************/
  107458. oggpack_writeinit(&opb);
  107459. if(_vorbis_pack_info(&opb,vi))goto err_out;
  107460. /* build the packet */
  107461. if(b->header)_ogg_free(b->header);
  107462. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107463. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  107464. op->packet=b->header;
  107465. op->bytes=oggpack_bytes(&opb);
  107466. op->b_o_s=1;
  107467. op->e_o_s=0;
  107468. op->granulepos=0;
  107469. op->packetno=0;
  107470. /* second header packet (comments) **********************************/
  107471. oggpack_reset(&opb);
  107472. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  107473. if(b->header1)_ogg_free(b->header1);
  107474. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107475. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  107476. op_comm->packet=b->header1;
  107477. op_comm->bytes=oggpack_bytes(&opb);
  107478. op_comm->b_o_s=0;
  107479. op_comm->e_o_s=0;
  107480. op_comm->granulepos=0;
  107481. op_comm->packetno=1;
  107482. /* third header packet (modes/codebooks) ****************************/
  107483. oggpack_reset(&opb);
  107484. if(_vorbis_pack_books(&opb,vi))goto err_out;
  107485. if(b->header2)_ogg_free(b->header2);
  107486. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107487. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  107488. op_code->packet=b->header2;
  107489. op_code->bytes=oggpack_bytes(&opb);
  107490. op_code->b_o_s=0;
  107491. op_code->e_o_s=0;
  107492. op_code->granulepos=0;
  107493. op_code->packetno=2;
  107494. oggpack_writeclear(&opb);
  107495. return(0);
  107496. err_out:
  107497. oggpack_writeclear(&opb);
  107498. memset(op,0,sizeof(*op));
  107499. memset(op_comm,0,sizeof(*op_comm));
  107500. memset(op_code,0,sizeof(*op_code));
  107501. if(b->header)_ogg_free(b->header);
  107502. if(b->header1)_ogg_free(b->header1);
  107503. if(b->header2)_ogg_free(b->header2);
  107504. b->header=NULL;
  107505. b->header1=NULL;
  107506. b->header2=NULL;
  107507. return(ret);
  107508. }
  107509. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  107510. if(granulepos>=0)
  107511. return((double)granulepos/v->vi->rate);
  107512. return(-1);
  107513. }
  107514. #endif
  107515. /********* End of inlined file: info.c *********/
  107516. /********* Start of inlined file: lpc.c *********/
  107517. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  107518. are derived from code written by Jutta Degener and Carsten Bormann;
  107519. thus we include their copyright below. The entirety of this file
  107520. is freely redistributable on the condition that both of these
  107521. copyright notices are preserved without modification. */
  107522. /* Preserved Copyright: *********************************************/
  107523. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  107524. Technische Universita"t Berlin
  107525. Any use of this software is permitted provided that this notice is not
  107526. removed and that neither the authors nor the Technische Universita"t
  107527. Berlin are deemed to have made any representations as to the
  107528. suitability of this software for any purpose nor are held responsible
  107529. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  107530. THIS SOFTWARE.
  107531. As a matter of courtesy, the authors request to be informed about uses
  107532. this software has found, about bugs in this software, and about any
  107533. improvements that may be of general interest.
  107534. Berlin, 28.11.1994
  107535. Jutta Degener
  107536. Carsten Bormann
  107537. *********************************************************************/
  107538. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107539. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107540. // tasks..
  107541. #ifdef _MSC_VER
  107542. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107543. #endif
  107544. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107545. #if JUCE_USE_OGGVORBIS
  107546. #include <stdlib.h>
  107547. #include <string.h>
  107548. #include <math.h>
  107549. /* Autocorrelation LPC coeff generation algorithm invented by
  107550. N. Levinson in 1947, modified by J. Durbin in 1959. */
  107551. /* Input : n elements of time doamin data
  107552. Output: m lpc coefficients, excitation energy */
  107553. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  107554. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  107555. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  107556. double error;
  107557. int i,j;
  107558. /* autocorrelation, p+1 lag coefficients */
  107559. j=m+1;
  107560. while(j--){
  107561. double d=0; /* double needed for accumulator depth */
  107562. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  107563. aut[j]=d;
  107564. }
  107565. /* Generate lpc coefficients from autocorr values */
  107566. error=aut[0];
  107567. for(i=0;i<m;i++){
  107568. double r= -aut[i+1];
  107569. if(error==0){
  107570. memset(lpci,0,m*sizeof(*lpci));
  107571. return 0;
  107572. }
  107573. /* Sum up this iteration's reflection coefficient; note that in
  107574. Vorbis we don't save it. If anyone wants to recycle this code
  107575. and needs reflection coefficients, save the results of 'r' from
  107576. each iteration. */
  107577. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  107578. r/=error;
  107579. /* Update LPC coefficients and total error */
  107580. lpc[i]=r;
  107581. for(j=0;j<i/2;j++){
  107582. double tmp=lpc[j];
  107583. lpc[j]+=r*lpc[i-1-j];
  107584. lpc[i-1-j]+=r*tmp;
  107585. }
  107586. if(i%2)lpc[j]+=lpc[j]*r;
  107587. error*=1.f-r*r;
  107588. }
  107589. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  107590. /* we need the error value to know how big an impulse to hit the
  107591. filter with later */
  107592. return error;
  107593. }
  107594. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  107595. float *data,long n){
  107596. /* in: coeff[0...m-1] LPC coefficients
  107597. prime[0...m-1] initial values (allocated size of n+m-1)
  107598. out: data[0...n-1] data samples */
  107599. long i,j,o,p;
  107600. float y;
  107601. float *work=(float*)alloca(sizeof(*work)*(m+n));
  107602. if(!prime)
  107603. for(i=0;i<m;i++)
  107604. work[i]=0.f;
  107605. else
  107606. for(i=0;i<m;i++)
  107607. work[i]=prime[i];
  107608. for(i=0;i<n;i++){
  107609. y=0;
  107610. o=i;
  107611. p=m;
  107612. for(j=0;j<m;j++)
  107613. y-=work[o++]*coeff[--p];
  107614. data[i]=work[o]=y;
  107615. }
  107616. }
  107617. #endif
  107618. /********* End of inlined file: lpc.c *********/
  107619. /********* Start of inlined file: lsp.c *********/
  107620. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  107621. an iterative root polisher (CACM algorithm 283). It *is* possible
  107622. to confuse this algorithm into not converging; that should only
  107623. happen with absurdly closely spaced roots (very sharp peaks in the
  107624. LPC f response) which in turn should be impossible in our use of
  107625. the code. If this *does* happen anyway, it's a bug in the floor
  107626. finder; find the cause of the confusion (probably a single bin
  107627. spike or accidental near-float-limit resolution problems) and
  107628. correct it. */
  107629. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107630. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107631. // tasks..
  107632. #ifdef _MSC_VER
  107633. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107634. #endif
  107635. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107636. #if JUCE_USE_OGGVORBIS
  107637. #include <math.h>
  107638. #include <string.h>
  107639. #include <stdlib.h>
  107640. /********* Start of inlined file: lookup.h *********/
  107641. #ifndef _V_LOOKUP_H_
  107642. #ifdef FLOAT_LOOKUP
  107643. extern float vorbis_coslook(float a);
  107644. extern float vorbis_invsqlook(float a);
  107645. extern float vorbis_invsq2explook(int a);
  107646. extern float vorbis_fromdBlook(float a);
  107647. #endif
  107648. #ifdef INT_LOOKUP
  107649. extern long vorbis_invsqlook_i(long a,long e);
  107650. extern long vorbis_coslook_i(long a);
  107651. extern float vorbis_fromdBlook_i(long a);
  107652. #endif
  107653. #endif
  107654. /********* End of inlined file: lookup.h *********/
  107655. /* three possible LSP to f curve functions; the exact computation
  107656. (float), a lookup based float implementation, and an integer
  107657. implementation. The float lookup is likely the optimal choice on
  107658. any machine with an FPU. The integer implementation is *not* fixed
  107659. point (due to the need for a large dynamic range and thus a
  107660. seperately tracked exponent) and thus much more complex than the
  107661. relatively simple float implementations. It's mostly for future
  107662. work on a fully fixed point implementation for processors like the
  107663. ARM family. */
  107664. /* undefine both for the 'old' but more precise implementation */
  107665. #define FLOAT_LOOKUP
  107666. #undef INT_LOOKUP
  107667. #ifdef FLOAT_LOOKUP
  107668. /********* Start of inlined file: lookup.c *********/
  107669. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107670. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107671. // tasks..
  107672. #ifdef _MSC_VER
  107673. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107674. #endif
  107675. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107676. #if JUCE_USE_OGGVORBIS
  107677. #include <math.h>
  107678. /********* Start of inlined file: lookup.h *********/
  107679. #ifndef _V_LOOKUP_H_
  107680. #ifdef FLOAT_LOOKUP
  107681. extern float vorbis_coslook(float a);
  107682. extern float vorbis_invsqlook(float a);
  107683. extern float vorbis_invsq2explook(int a);
  107684. extern float vorbis_fromdBlook(float a);
  107685. #endif
  107686. #ifdef INT_LOOKUP
  107687. extern long vorbis_invsqlook_i(long a,long e);
  107688. extern long vorbis_coslook_i(long a);
  107689. extern float vorbis_fromdBlook_i(long a);
  107690. #endif
  107691. #endif
  107692. /********* End of inlined file: lookup.h *********/
  107693. /********* Start of inlined file: lookup_data.h *********/
  107694. #ifndef _V_LOOKUP_DATA_H_
  107695. #ifdef FLOAT_LOOKUP
  107696. #define COS_LOOKUP_SZ 128
  107697. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  107698. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  107699. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  107700. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  107701. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  107702. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  107703. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  107704. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  107705. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  107706. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  107707. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  107708. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  107709. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  107710. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  107711. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  107712. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  107713. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  107714. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  107715. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  107716. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  107717. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  107718. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  107719. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  107720. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  107721. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  107722. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  107723. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  107724. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  107725. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  107726. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  107727. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  107728. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  107729. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  107730. -1.0000000000000f,
  107731. };
  107732. #define INVSQ_LOOKUP_SZ 32
  107733. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  107734. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  107735. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  107736. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  107737. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  107738. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  107739. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  107740. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  107741. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  107742. 1.000000000000f,
  107743. };
  107744. #define INVSQ2EXP_LOOKUP_MIN (-32)
  107745. #define INVSQ2EXP_LOOKUP_MAX 32
  107746. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  107747. INVSQ2EXP_LOOKUP_MIN+1]={
  107748. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  107749. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  107750. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  107751. 1024.f, 724.0773439f, 512.f, 362.038672f,
  107752. 256.f, 181.019336f, 128.f, 90.50966799f,
  107753. 64.f, 45.254834f, 32.f, 22.627417f,
  107754. 16.f, 11.3137085f, 8.f, 5.656854249f,
  107755. 4.f, 2.828427125f, 2.f, 1.414213562f,
  107756. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  107757. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  107758. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  107759. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  107760. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  107761. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  107762. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  107763. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  107764. 1.525878906e-05f,
  107765. };
  107766. #endif
  107767. #define FROMdB_LOOKUP_SZ 35
  107768. #define FROMdB2_LOOKUP_SZ 32
  107769. #define FROMdB_SHIFT 5
  107770. #define FROMdB2_SHIFT 3
  107771. #define FROMdB2_MASK 31
  107772. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  107773. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  107774. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  107775. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  107776. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  107777. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  107778. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  107779. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  107780. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  107781. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  107782. };
  107783. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  107784. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  107785. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  107786. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  107787. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  107788. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  107789. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  107790. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  107791. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  107792. };
  107793. #ifdef INT_LOOKUP
  107794. #define INVSQ_LOOKUP_I_SHIFT 10
  107795. #define INVSQ_LOOKUP_I_MASK 1023
  107796. static long INVSQ_LOOKUP_I[64+1]={
  107797. 92682l, 91966l, 91267l, 90583l,
  107798. 89915l, 89261l, 88621l, 87995l,
  107799. 87381l, 86781l, 86192l, 85616l,
  107800. 85051l, 84497l, 83953l, 83420l,
  107801. 82897l, 82384l, 81880l, 81385l,
  107802. 80899l, 80422l, 79953l, 79492l,
  107803. 79039l, 78594l, 78156l, 77726l,
  107804. 77302l, 76885l, 76475l, 76072l,
  107805. 75674l, 75283l, 74898l, 74519l,
  107806. 74146l, 73778l, 73415l, 73058l,
  107807. 72706l, 72359l, 72016l, 71679l,
  107808. 71347l, 71019l, 70695l, 70376l,
  107809. 70061l, 69750l, 69444l, 69141l,
  107810. 68842l, 68548l, 68256l, 67969l,
  107811. 67685l, 67405l, 67128l, 66855l,
  107812. 66585l, 66318l, 66054l, 65794l,
  107813. 65536l,
  107814. };
  107815. #define COS_LOOKUP_I_SHIFT 9
  107816. #define COS_LOOKUP_I_MASK 511
  107817. #define COS_LOOKUP_I_SZ 128
  107818. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  107819. 16384l, 16379l, 16364l, 16340l,
  107820. 16305l, 16261l, 16207l, 16143l,
  107821. 16069l, 15986l, 15893l, 15791l,
  107822. 15679l, 15557l, 15426l, 15286l,
  107823. 15137l, 14978l, 14811l, 14635l,
  107824. 14449l, 14256l, 14053l, 13842l,
  107825. 13623l, 13395l, 13160l, 12916l,
  107826. 12665l, 12406l, 12140l, 11866l,
  107827. 11585l, 11297l, 11003l, 10702l,
  107828. 10394l, 10080l, 9760l, 9434l,
  107829. 9102l, 8765l, 8423l, 8076l,
  107830. 7723l, 7366l, 7005l, 6639l,
  107831. 6270l, 5897l, 5520l, 5139l,
  107832. 4756l, 4370l, 3981l, 3590l,
  107833. 3196l, 2801l, 2404l, 2006l,
  107834. 1606l, 1205l, 804l, 402l,
  107835. 0l, -401l, -803l, -1204l,
  107836. -1605l, -2005l, -2403l, -2800l,
  107837. -3195l, -3589l, -3980l, -4369l,
  107838. -4755l, -5138l, -5519l, -5896l,
  107839. -6269l, -6638l, -7004l, -7365l,
  107840. -7722l, -8075l, -8422l, -8764l,
  107841. -9101l, -9433l, -9759l, -10079l,
  107842. -10393l, -10701l, -11002l, -11296l,
  107843. -11584l, -11865l, -12139l, -12405l,
  107844. -12664l, -12915l, -13159l, -13394l,
  107845. -13622l, -13841l, -14052l, -14255l,
  107846. -14448l, -14634l, -14810l, -14977l,
  107847. -15136l, -15285l, -15425l, -15556l,
  107848. -15678l, -15790l, -15892l, -15985l,
  107849. -16068l, -16142l, -16206l, -16260l,
  107850. -16304l, -16339l, -16363l, -16378l,
  107851. -16383l,
  107852. };
  107853. #endif
  107854. #endif
  107855. /********* End of inlined file: lookup_data.h *********/
  107856. #ifdef FLOAT_LOOKUP
  107857. /* interpolated lookup based cos function, domain 0 to PI only */
  107858. float vorbis_coslook(float a){
  107859. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  107860. int i=vorbis_ftoi(d-.5);
  107861. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  107862. }
  107863. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  107864. float vorbis_invsqlook(float a){
  107865. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  107866. int i=vorbis_ftoi(d-.5f);
  107867. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  107868. }
  107869. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  107870. float vorbis_invsq2explook(int a){
  107871. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  107872. }
  107873. #include <stdio.h>
  107874. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  107875. float vorbis_fromdBlook(float a){
  107876. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  107877. return (i<0)?1.f:
  107878. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  107879. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  107880. }
  107881. #endif
  107882. #ifdef INT_LOOKUP
  107883. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  107884. 16.16 format
  107885. returns in m.8 format */
  107886. long vorbis_invsqlook_i(long a,long e){
  107887. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  107888. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  107889. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  107890. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  107891. d)>>16); /* result 1.16 */
  107892. e+=32;
  107893. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  107894. e=(e>>1)-8;
  107895. return(val>>e);
  107896. }
  107897. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  107898. /* a is in n.12 format */
  107899. float vorbis_fromdBlook_i(long a){
  107900. int i=(-a)>>(12-FROMdB2_SHIFT);
  107901. return (i<0)?1.f:
  107902. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  107903. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  107904. }
  107905. /* interpolated lookup based cos function, domain 0 to PI only */
  107906. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  107907. long vorbis_coslook_i(long a){
  107908. int i=a>>COS_LOOKUP_I_SHIFT;
  107909. int d=a&COS_LOOKUP_I_MASK;
  107910. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  107911. COS_LOOKUP_I_SHIFT);
  107912. }
  107913. #endif
  107914. #endif
  107915. /********* End of inlined file: lookup.c *********/
  107916. /* catch this in the build system; we #include for
  107917. compilers (like gcc) that can't inline across
  107918. modules */
  107919. /* side effect: changes *lsp to cosines of lsp */
  107920. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  107921. float amp,float ampoffset){
  107922. int i;
  107923. float wdel=M_PI/ln;
  107924. vorbis_fpu_control fpu;
  107925. (void) fpu; // to avoid an unused variable warning
  107926. vorbis_fpu_setround(&fpu);
  107927. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  107928. i=0;
  107929. while(i<n){
  107930. int k=map[i];
  107931. int qexp;
  107932. float p=.7071067812f;
  107933. float q=.7071067812f;
  107934. float w=vorbis_coslook(wdel*k);
  107935. float *ftmp=lsp;
  107936. int c=m>>1;
  107937. do{
  107938. q*=ftmp[0]-w;
  107939. p*=ftmp[1]-w;
  107940. ftmp+=2;
  107941. }while(--c);
  107942. if(m&1){
  107943. /* odd order filter; slightly assymetric */
  107944. /* the last coefficient */
  107945. q*=ftmp[0]-w;
  107946. q*=q;
  107947. p*=p*(1.f-w*w);
  107948. }else{
  107949. /* even order filter; still symmetric */
  107950. q*=q*(1.f+w);
  107951. p*=p*(1.f-w);
  107952. }
  107953. q=frexp(p+q,&qexp);
  107954. q=vorbis_fromdBlook(amp*
  107955. vorbis_invsqlook(q)*
  107956. vorbis_invsq2explook(qexp+m)-
  107957. ampoffset);
  107958. do{
  107959. curve[i++]*=q;
  107960. }while(map[i]==k);
  107961. }
  107962. vorbis_fpu_restore(fpu);
  107963. }
  107964. #else
  107965. #ifdef INT_LOOKUP
  107966. /********* Start of inlined file: lookup.c *********/
  107967. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107968. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107969. // tasks..
  107970. #ifdef _MSC_VER
  107971. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107972. #endif
  107973. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107974. #if JUCE_USE_OGGVORBIS
  107975. #include <math.h>
  107976. /********* Start of inlined file: lookup.h *********/
  107977. #ifndef _V_LOOKUP_H_
  107978. #ifdef FLOAT_LOOKUP
  107979. extern float vorbis_coslook(float a);
  107980. extern float vorbis_invsqlook(float a);
  107981. extern float vorbis_invsq2explook(int a);
  107982. extern float vorbis_fromdBlook(float a);
  107983. #endif
  107984. #ifdef INT_LOOKUP
  107985. extern long vorbis_invsqlook_i(long a,long e);
  107986. extern long vorbis_coslook_i(long a);
  107987. extern float vorbis_fromdBlook_i(long a);
  107988. #endif
  107989. #endif
  107990. /********* End of inlined file: lookup.h *********/
  107991. /********* Start of inlined file: lookup_data.h *********/
  107992. #ifndef _V_LOOKUP_DATA_H_
  107993. #ifdef FLOAT_LOOKUP
  107994. #define COS_LOOKUP_SZ 128
  107995. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  107996. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  107997. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  107998. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  107999. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108000. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108001. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108002. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108003. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108004. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108005. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108006. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108007. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108008. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108009. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108010. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108011. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108012. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108013. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108014. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108015. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108016. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108017. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108018. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108019. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108020. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108021. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108022. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108023. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108024. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108025. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108026. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108027. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108028. -1.0000000000000f,
  108029. };
  108030. #define INVSQ_LOOKUP_SZ 32
  108031. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108032. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108033. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108034. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108035. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108036. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108037. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108038. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108039. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108040. 1.000000000000f,
  108041. };
  108042. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108043. #define INVSQ2EXP_LOOKUP_MAX 32
  108044. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108045. INVSQ2EXP_LOOKUP_MIN+1]={
  108046. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108047. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108048. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108049. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108050. 256.f, 181.019336f, 128.f, 90.50966799f,
  108051. 64.f, 45.254834f, 32.f, 22.627417f,
  108052. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108053. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108054. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108055. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108056. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108057. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108058. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108059. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108060. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108061. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108062. 1.525878906e-05f,
  108063. };
  108064. #endif
  108065. #define FROMdB_LOOKUP_SZ 35
  108066. #define FROMdB2_LOOKUP_SZ 32
  108067. #define FROMdB_SHIFT 5
  108068. #define FROMdB2_SHIFT 3
  108069. #define FROMdB2_MASK 31
  108070. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108071. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108072. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108073. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108074. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108075. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108076. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108077. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108078. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108079. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108080. };
  108081. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108082. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108083. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108084. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108085. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108086. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108087. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108088. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108089. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108090. };
  108091. #ifdef INT_LOOKUP
  108092. #define INVSQ_LOOKUP_I_SHIFT 10
  108093. #define INVSQ_LOOKUP_I_MASK 1023
  108094. static long INVSQ_LOOKUP_I[64+1]={
  108095. 92682l, 91966l, 91267l, 90583l,
  108096. 89915l, 89261l, 88621l, 87995l,
  108097. 87381l, 86781l, 86192l, 85616l,
  108098. 85051l, 84497l, 83953l, 83420l,
  108099. 82897l, 82384l, 81880l, 81385l,
  108100. 80899l, 80422l, 79953l, 79492l,
  108101. 79039l, 78594l, 78156l, 77726l,
  108102. 77302l, 76885l, 76475l, 76072l,
  108103. 75674l, 75283l, 74898l, 74519l,
  108104. 74146l, 73778l, 73415l, 73058l,
  108105. 72706l, 72359l, 72016l, 71679l,
  108106. 71347l, 71019l, 70695l, 70376l,
  108107. 70061l, 69750l, 69444l, 69141l,
  108108. 68842l, 68548l, 68256l, 67969l,
  108109. 67685l, 67405l, 67128l, 66855l,
  108110. 66585l, 66318l, 66054l, 65794l,
  108111. 65536l,
  108112. };
  108113. #define COS_LOOKUP_I_SHIFT 9
  108114. #define COS_LOOKUP_I_MASK 511
  108115. #define COS_LOOKUP_I_SZ 128
  108116. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108117. 16384l, 16379l, 16364l, 16340l,
  108118. 16305l, 16261l, 16207l, 16143l,
  108119. 16069l, 15986l, 15893l, 15791l,
  108120. 15679l, 15557l, 15426l, 15286l,
  108121. 15137l, 14978l, 14811l, 14635l,
  108122. 14449l, 14256l, 14053l, 13842l,
  108123. 13623l, 13395l, 13160l, 12916l,
  108124. 12665l, 12406l, 12140l, 11866l,
  108125. 11585l, 11297l, 11003l, 10702l,
  108126. 10394l, 10080l, 9760l, 9434l,
  108127. 9102l, 8765l, 8423l, 8076l,
  108128. 7723l, 7366l, 7005l, 6639l,
  108129. 6270l, 5897l, 5520l, 5139l,
  108130. 4756l, 4370l, 3981l, 3590l,
  108131. 3196l, 2801l, 2404l, 2006l,
  108132. 1606l, 1205l, 804l, 402l,
  108133. 0l, -401l, -803l, -1204l,
  108134. -1605l, -2005l, -2403l, -2800l,
  108135. -3195l, -3589l, -3980l, -4369l,
  108136. -4755l, -5138l, -5519l, -5896l,
  108137. -6269l, -6638l, -7004l, -7365l,
  108138. -7722l, -8075l, -8422l, -8764l,
  108139. -9101l, -9433l, -9759l, -10079l,
  108140. -10393l, -10701l, -11002l, -11296l,
  108141. -11584l, -11865l, -12139l, -12405l,
  108142. -12664l, -12915l, -13159l, -13394l,
  108143. -13622l, -13841l, -14052l, -14255l,
  108144. -14448l, -14634l, -14810l, -14977l,
  108145. -15136l, -15285l, -15425l, -15556l,
  108146. -15678l, -15790l, -15892l, -15985l,
  108147. -16068l, -16142l, -16206l, -16260l,
  108148. -16304l, -16339l, -16363l, -16378l,
  108149. -16383l,
  108150. };
  108151. #endif
  108152. #endif
  108153. /********* End of inlined file: lookup_data.h *********/
  108154. #ifdef FLOAT_LOOKUP
  108155. /* interpolated lookup based cos function, domain 0 to PI only */
  108156. float vorbis_coslook(float a){
  108157. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108158. int i=vorbis_ftoi(d-.5);
  108159. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108160. }
  108161. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108162. float vorbis_invsqlook(float a){
  108163. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108164. int i=vorbis_ftoi(d-.5f);
  108165. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108166. }
  108167. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108168. float vorbis_invsq2explook(int a){
  108169. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108170. }
  108171. #include <stdio.h>
  108172. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108173. float vorbis_fromdBlook(float a){
  108174. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108175. return (i<0)?1.f:
  108176. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108177. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108178. }
  108179. #endif
  108180. #ifdef INT_LOOKUP
  108181. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108182. 16.16 format
  108183. returns in m.8 format */
  108184. long vorbis_invsqlook_i(long a,long e){
  108185. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108186. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108187. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108188. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108189. d)>>16); /* result 1.16 */
  108190. e+=32;
  108191. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108192. e=(e>>1)-8;
  108193. return(val>>e);
  108194. }
  108195. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108196. /* a is in n.12 format */
  108197. float vorbis_fromdBlook_i(long a){
  108198. int i=(-a)>>(12-FROMdB2_SHIFT);
  108199. return (i<0)?1.f:
  108200. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108201. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108202. }
  108203. /* interpolated lookup based cos function, domain 0 to PI only */
  108204. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108205. long vorbis_coslook_i(long a){
  108206. int i=a>>COS_LOOKUP_I_SHIFT;
  108207. int d=a&COS_LOOKUP_I_MASK;
  108208. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108209. COS_LOOKUP_I_SHIFT);
  108210. }
  108211. #endif
  108212. #endif
  108213. /********* End of inlined file: lookup.c *********/
  108214. /* catch this in the build system; we #include for
  108215. compilers (like gcc) that can't inline across
  108216. modules */
  108217. static int MLOOP_1[64]={
  108218. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  108219. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  108220. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108221. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108222. };
  108223. static int MLOOP_2[64]={
  108224. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  108225. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  108226. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108227. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108228. };
  108229. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  108230. /* side effect: changes *lsp to cosines of lsp */
  108231. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108232. float amp,float ampoffset){
  108233. /* 0 <= m < 256 */
  108234. /* set up for using all int later */
  108235. int i;
  108236. int ampoffseti=rint(ampoffset*4096.f);
  108237. int ampi=rint(amp*16.f);
  108238. long *ilsp=alloca(m*sizeof(*ilsp));
  108239. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  108240. i=0;
  108241. while(i<n){
  108242. int j,k=map[i];
  108243. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  108244. unsigned long qi=46341;
  108245. int qexp=0,shift;
  108246. long wi=vorbis_coslook_i(k*65536/ln);
  108247. qi*=labs(ilsp[0]-wi);
  108248. pi*=labs(ilsp[1]-wi);
  108249. for(j=3;j<m;j+=2){
  108250. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108251. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108252. shift=MLOOP_3[(pi|qi)>>16];
  108253. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108254. pi=(pi>>shift)*labs(ilsp[j]-wi);
  108255. qexp+=shift;
  108256. }
  108257. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108258. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108259. shift=MLOOP_3[(pi|qi)>>16];
  108260. /* pi,qi normalized collectively, both tracked using qexp */
  108261. if(m&1){
  108262. /* odd order filter; slightly assymetric */
  108263. /* the last coefficient */
  108264. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108265. pi=(pi>>shift)<<14;
  108266. qexp+=shift;
  108267. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108268. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108269. shift=MLOOP_3[(pi|qi)>>16];
  108270. pi>>=shift;
  108271. qi>>=shift;
  108272. qexp+=shift-14*((m+1)>>1);
  108273. pi=((pi*pi)>>16);
  108274. qi=((qi*qi)>>16);
  108275. qexp=qexp*2+m;
  108276. pi*=(1<<14)-((wi*wi)>>14);
  108277. qi+=pi>>14;
  108278. }else{
  108279. /* even order filter; still symmetric */
  108280. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  108281. worth tracking step by step */
  108282. pi>>=shift;
  108283. qi>>=shift;
  108284. qexp+=shift-7*m;
  108285. pi=((pi*pi)>>16);
  108286. qi=((qi*qi)>>16);
  108287. qexp=qexp*2+m;
  108288. pi*=(1<<14)-wi;
  108289. qi*=(1<<14)+wi;
  108290. qi=(qi+pi)>>14;
  108291. }
  108292. /* we've let the normalization drift because it wasn't important;
  108293. however, for the lookup, things must be normalized again. We
  108294. need at most one right shift or a number of left shifts */
  108295. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  108296. qi>>=1; qexp++;
  108297. }else
  108298. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  108299. qi<<=1; qexp--;
  108300. }
  108301. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  108302. vorbis_invsqlook_i(qi,qexp)-
  108303. /* m.8, m+n<=8 */
  108304. ampoffseti); /* 8.12[0] */
  108305. curve[i]*=amp;
  108306. while(map[++i]==k)curve[i]*=amp;
  108307. }
  108308. }
  108309. #else
  108310. /* old, nonoptimized but simple version for any poor sap who needs to
  108311. figure out what the hell this code does, or wants the other
  108312. fraction of a dB precision */
  108313. /* side effect: changes *lsp to cosines of lsp */
  108314. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108315. float amp,float ampoffset){
  108316. int i;
  108317. float wdel=M_PI/ln;
  108318. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  108319. i=0;
  108320. while(i<n){
  108321. int j,k=map[i];
  108322. float p=.5f;
  108323. float q=.5f;
  108324. float w=2.f*cos(wdel*k);
  108325. for(j=1;j<m;j+=2){
  108326. q *= w-lsp[j-1];
  108327. p *= w-lsp[j];
  108328. }
  108329. if(j==m){
  108330. /* odd order filter; slightly assymetric */
  108331. /* the last coefficient */
  108332. q*=w-lsp[j-1];
  108333. p*=p*(4.f-w*w);
  108334. q*=q;
  108335. }else{
  108336. /* even order filter; still symmetric */
  108337. p*=p*(2.f-w);
  108338. q*=q*(2.f+w);
  108339. }
  108340. q=fromdB(amp/sqrt(p+q)-ampoffset);
  108341. curve[i]*=q;
  108342. while(map[++i]==k)curve[i]*=q;
  108343. }
  108344. }
  108345. #endif
  108346. #endif
  108347. static void cheby(float *g, int ord) {
  108348. int i, j;
  108349. g[0] *= .5f;
  108350. for(i=2; i<= ord; i++) {
  108351. for(j=ord; j >= i; j--) {
  108352. g[j-2] -= g[j];
  108353. g[j] += g[j];
  108354. }
  108355. }
  108356. }
  108357. static int comp(const void *a,const void *b){
  108358. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  108359. }
  108360. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  108361. but there are root sets for which it gets into limit cycles
  108362. (exacerbated by zero suppression) and fails. We can't afford to
  108363. fail, even if the failure is 1 in 100,000,000, so we now use
  108364. Laguerre and later polish with Newton-Raphson (which can then
  108365. afford to fail) */
  108366. #define EPSILON 10e-7
  108367. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  108368. int i,m;
  108369. double lastdelta=0.f;
  108370. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  108371. for(i=0;i<=ord;i++)defl[i]=a[i];
  108372. for(m=ord;m>0;m--){
  108373. double newx=0.f,delta;
  108374. /* iterate a root */
  108375. while(1){
  108376. double p=defl[m],pp=0.f,ppp=0.f,denom;
  108377. /* eval the polynomial and its first two derivatives */
  108378. for(i=m;i>0;i--){
  108379. ppp = newx*ppp + pp;
  108380. pp = newx*pp + p;
  108381. p = newx*p + defl[i-1];
  108382. }
  108383. /* Laguerre's method */
  108384. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  108385. if(denom<0)
  108386. return(-1); /* complex root! The LPC generator handed us a bad filter */
  108387. if(pp>0){
  108388. denom = pp + sqrt(denom);
  108389. if(denom<EPSILON)denom=EPSILON;
  108390. }else{
  108391. denom = pp - sqrt(denom);
  108392. if(denom>-(EPSILON))denom=-(EPSILON);
  108393. }
  108394. delta = m*p/denom;
  108395. newx -= delta;
  108396. if(delta<0.f)delta*=-1;
  108397. if(fabs(delta/newx)<10e-12)break;
  108398. lastdelta=delta;
  108399. }
  108400. r[m-1]=newx;
  108401. /* forward deflation */
  108402. for(i=m;i>0;i--)
  108403. defl[i-1]+=newx*defl[i];
  108404. defl++;
  108405. }
  108406. return(0);
  108407. }
  108408. /* for spit-and-polish only */
  108409. static int Newton_Raphson(float *a,int ord,float *r){
  108410. int i, k, count=0;
  108411. double error=1.f;
  108412. double *root=(double*)alloca(ord*sizeof(*root));
  108413. for(i=0; i<ord;i++) root[i] = r[i];
  108414. while(error>1e-20){
  108415. error=0;
  108416. for(i=0; i<ord; i++) { /* Update each point. */
  108417. double pp=0.,delta;
  108418. double rooti=root[i];
  108419. double p=a[ord];
  108420. for(k=ord-1; k>= 0; k--) {
  108421. pp= pp* rooti + p;
  108422. p = p * rooti + a[k];
  108423. }
  108424. delta = p/pp;
  108425. root[i] -= delta;
  108426. error+= delta*delta;
  108427. }
  108428. if(count>40)return(-1);
  108429. count++;
  108430. }
  108431. /* Replaced the original bubble sort with a real sort. With your
  108432. help, we can eliminate the bubble sort in our lifetime. --Monty */
  108433. for(i=0; i<ord;i++) r[i] = root[i];
  108434. return(0);
  108435. }
  108436. /* Convert lpc coefficients to lsp coefficients */
  108437. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  108438. int order2=(m+1)>>1;
  108439. int g1_order,g2_order;
  108440. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  108441. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  108442. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  108443. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  108444. int i;
  108445. /* even and odd are slightly different base cases */
  108446. g1_order=(m+1)>>1;
  108447. g2_order=(m) >>1;
  108448. /* Compute the lengths of the x polynomials. */
  108449. /* Compute the first half of K & R F1 & F2 polynomials. */
  108450. /* Compute half of the symmetric and antisymmetric polynomials. */
  108451. /* Remove the roots at +1 and -1. */
  108452. g1[g1_order] = 1.f;
  108453. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  108454. g2[g2_order] = 1.f;
  108455. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  108456. if(g1_order>g2_order){
  108457. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  108458. }else{
  108459. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  108460. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  108461. }
  108462. /* Convert into polynomials in cos(alpha) */
  108463. cheby(g1,g1_order);
  108464. cheby(g2,g2_order);
  108465. /* Find the roots of the 2 even polynomials.*/
  108466. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  108467. Laguerre_With_Deflation(g2,g2_order,g2r))
  108468. return(-1);
  108469. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  108470. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  108471. qsort(g1r,g1_order,sizeof(*g1r),comp);
  108472. qsort(g2r,g2_order,sizeof(*g2r),comp);
  108473. for(i=0;i<g1_order;i++)
  108474. lsp[i*2] = acos(g1r[i]);
  108475. for(i=0;i<g2_order;i++)
  108476. lsp[i*2+1] = acos(g2r[i]);
  108477. return(0);
  108478. }
  108479. #endif
  108480. /********* End of inlined file: lsp.c *********/
  108481. /********* Start of inlined file: mapping0.c *********/
  108482. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108483. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108484. // tasks..
  108485. #ifdef _MSC_VER
  108486. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108487. #endif
  108488. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108489. #if JUCE_USE_OGGVORBIS
  108490. #include <stdlib.h>
  108491. #include <stdio.h>
  108492. #include <string.h>
  108493. #include <math.h>
  108494. /* simplistic, wasteful way of doing this (unique lookup for each
  108495. mode/submapping); there should be a central repository for
  108496. identical lookups. That will require minor work, so I'm putting it
  108497. off as low priority.
  108498. Why a lookup for each backend in a given mode? Because the
  108499. blocksize is set by the mode, and low backend lookups may require
  108500. parameters from other areas of the mode/mapping */
  108501. static void mapping0_free_info(vorbis_info_mapping *i){
  108502. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  108503. if(info){
  108504. memset(info,0,sizeof(*info));
  108505. _ogg_free(info);
  108506. }
  108507. }
  108508. static int ilog3(unsigned int v){
  108509. int ret=0;
  108510. if(v)--v;
  108511. while(v){
  108512. ret++;
  108513. v>>=1;
  108514. }
  108515. return(ret);
  108516. }
  108517. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  108518. oggpack_buffer *opb){
  108519. int i;
  108520. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  108521. /* another 'we meant to do it this way' hack... up to beta 4, we
  108522. packed 4 binary zeros here to signify one submapping in use. We
  108523. now redefine that to mean four bitflags that indicate use of
  108524. deeper features; bit0:submappings, bit1:coupling,
  108525. bit2,3:reserved. This is backward compatable with all actual uses
  108526. of the beta code. */
  108527. if(info->submaps>1){
  108528. oggpack_write(opb,1,1);
  108529. oggpack_write(opb,info->submaps-1,4);
  108530. }else
  108531. oggpack_write(opb,0,1);
  108532. if(info->coupling_steps>0){
  108533. oggpack_write(opb,1,1);
  108534. oggpack_write(opb,info->coupling_steps-1,8);
  108535. for(i=0;i<info->coupling_steps;i++){
  108536. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  108537. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  108538. }
  108539. }else
  108540. oggpack_write(opb,0,1);
  108541. oggpack_write(opb,0,2); /* 2,3:reserved */
  108542. /* we don't write the channel submappings if we only have one... */
  108543. if(info->submaps>1){
  108544. for(i=0;i<vi->channels;i++)
  108545. oggpack_write(opb,info->chmuxlist[i],4);
  108546. }
  108547. for(i=0;i<info->submaps;i++){
  108548. oggpack_write(opb,0,8); /* time submap unused */
  108549. oggpack_write(opb,info->floorsubmap[i],8);
  108550. oggpack_write(opb,info->residuesubmap[i],8);
  108551. }
  108552. }
  108553. /* also responsible for range checking */
  108554. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  108555. int i;
  108556. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  108557. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108558. memset(info,0,sizeof(*info));
  108559. if(oggpack_read(opb,1))
  108560. info->submaps=oggpack_read(opb,4)+1;
  108561. else
  108562. info->submaps=1;
  108563. if(oggpack_read(opb,1)){
  108564. info->coupling_steps=oggpack_read(opb,8)+1;
  108565. for(i=0;i<info->coupling_steps;i++){
  108566. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  108567. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  108568. if(testM<0 ||
  108569. testA<0 ||
  108570. testM==testA ||
  108571. testM>=vi->channels ||
  108572. testA>=vi->channels) goto err_out;
  108573. }
  108574. }
  108575. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  108576. if(info->submaps>1){
  108577. for(i=0;i<vi->channels;i++){
  108578. info->chmuxlist[i]=oggpack_read(opb,4);
  108579. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  108580. }
  108581. }
  108582. for(i=0;i<info->submaps;i++){
  108583. oggpack_read(opb,8); /* time submap unused */
  108584. info->floorsubmap[i]=oggpack_read(opb,8);
  108585. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  108586. info->residuesubmap[i]=oggpack_read(opb,8);
  108587. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  108588. }
  108589. return info;
  108590. err_out:
  108591. mapping0_free_info(info);
  108592. return(NULL);
  108593. }
  108594. #if 0
  108595. static long seq=0;
  108596. static ogg_int64_t total=0;
  108597. static float FLOOR1_fromdB_LOOKUP[256]={
  108598. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108599. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108600. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108601. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108602. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108603. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108604. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108605. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108606. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108607. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108608. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108609. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108610. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108611. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108612. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108613. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108614. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108615. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108616. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108617. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108618. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108619. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108620. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108621. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108622. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108623. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108624. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108625. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108626. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108627. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108628. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108629. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108630. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108631. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108632. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108633. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108634. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108635. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108636. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108637. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108638. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108639. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108640. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108641. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108642. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108643. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108644. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108645. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108646. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108647. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108648. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108649. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108650. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108651. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108652. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108653. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108654. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108655. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108656. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108657. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108658. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108659. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108660. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108661. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108662. };
  108663. #endif
  108664. extern int *floor1_fit(vorbis_block *vb,void *look,
  108665. const float *logmdct, /* in */
  108666. const float *logmask);
  108667. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  108668. int *A,int *B,
  108669. int del);
  108670. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108671. void*look,
  108672. int *post,int *ilogmask);
  108673. static int mapping0_forward(vorbis_block *vb){
  108674. vorbis_dsp_state *vd=vb->vd;
  108675. vorbis_info *vi=vd->vi;
  108676. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108677. private_state *b=(private_state*)vb->vd->backend_state;
  108678. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  108679. int n=vb->pcmend;
  108680. int i,j,k;
  108681. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  108682. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  108683. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  108684. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  108685. float global_ampmax=vbi->ampmax;
  108686. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  108687. int blocktype=vbi->blocktype;
  108688. int modenumber=vb->W;
  108689. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  108690. vorbis_look_psy *psy_look=
  108691. b->psy+blocktype+(vb->W?2:0);
  108692. vb->mode=modenumber;
  108693. for(i=0;i<vi->channels;i++){
  108694. float scale=4.f/n;
  108695. float scale_dB;
  108696. float *pcm =vb->pcm[i];
  108697. float *logfft =pcm;
  108698. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  108699. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  108700. todB estimation used on IEEE 754
  108701. compliant machines had a bug that
  108702. returned dB values about a third
  108703. of a decibel too high. The bug
  108704. was harmless because tunings
  108705. implicitly took that into
  108706. account. However, fixing the bug
  108707. in the estimator requires
  108708. changing all the tunings as well.
  108709. For now, it's easier to sync
  108710. things back up here, and
  108711. recalibrate the tunings in the
  108712. next major model upgrade. */
  108713. #if 0
  108714. if(vi->channels==2)
  108715. if(i==0)
  108716. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  108717. else
  108718. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  108719. #endif
  108720. /* window the PCM data */
  108721. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  108722. #if 0
  108723. if(vi->channels==2)
  108724. if(i==0)
  108725. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  108726. else
  108727. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  108728. #endif
  108729. /* transform the PCM data */
  108730. /* only MDCT right now.... */
  108731. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  108732. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  108733. drft_forward(&b->fft_look[vb->W],pcm);
  108734. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  108735. original todB estimation used on
  108736. IEEE 754 compliant machines had a
  108737. bug that returned dB values about
  108738. a third of a decibel too high.
  108739. The bug was harmless because
  108740. tunings implicitly took that into
  108741. account. However, fixing the bug
  108742. in the estimator requires
  108743. changing all the tunings as well.
  108744. For now, it's easier to sync
  108745. things back up here, and
  108746. recalibrate the tunings in the
  108747. next major model upgrade. */
  108748. local_ampmax[i]=logfft[0];
  108749. for(j=1;j<n-1;j+=2){
  108750. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  108751. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  108752. .345 is a hack; the original todB
  108753. estimation used on IEEE 754
  108754. compliant machines had a bug that
  108755. returned dB values about a third
  108756. of a decibel too high. The bug
  108757. was harmless because tunings
  108758. implicitly took that into
  108759. account. However, fixing the bug
  108760. in the estimator requires
  108761. changing all the tunings as well.
  108762. For now, it's easier to sync
  108763. things back up here, and
  108764. recalibrate the tunings in the
  108765. next major model upgrade. */
  108766. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  108767. }
  108768. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  108769. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  108770. #if 0
  108771. if(vi->channels==2){
  108772. if(i==0){
  108773. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  108774. }else{
  108775. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  108776. }
  108777. }
  108778. #endif
  108779. }
  108780. {
  108781. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  108782. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  108783. for(i=0;i<vi->channels;i++){
  108784. /* the encoder setup assumes that all the modes used by any
  108785. specific bitrate tweaking use the same floor */
  108786. int submap=info->chmuxlist[i];
  108787. /* the following makes things clearer to *me* anyway */
  108788. float *mdct =gmdct[i];
  108789. float *logfft =vb->pcm[i];
  108790. float *logmdct =logfft+n/2;
  108791. float *logmask =logfft;
  108792. vb->mode=modenumber;
  108793. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  108794. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  108795. for(j=0;j<n/2;j++)
  108796. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  108797. todB estimation used on IEEE 754
  108798. compliant machines had a bug that
  108799. returned dB values about a third
  108800. of a decibel too high. The bug
  108801. was harmless because tunings
  108802. implicitly took that into
  108803. account. However, fixing the bug
  108804. in the estimator requires
  108805. changing all the tunings as well.
  108806. For now, it's easier to sync
  108807. things back up here, and
  108808. recalibrate the tunings in the
  108809. next major model upgrade. */
  108810. #if 0
  108811. if(vi->channels==2){
  108812. if(i==0)
  108813. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  108814. else
  108815. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  108816. }else{
  108817. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  108818. }
  108819. #endif
  108820. /* first step; noise masking. Not only does 'noise masking'
  108821. give us curves from which we can decide how much resolution
  108822. to give noise parts of the spectrum, it also implicitly hands
  108823. us a tonality estimate (the larger the value in the
  108824. 'noise_depth' vector, the more tonal that area is) */
  108825. _vp_noisemask(psy_look,
  108826. logmdct,
  108827. noise); /* noise does not have by-frequency offset
  108828. bias applied yet */
  108829. #if 0
  108830. if(vi->channels==2){
  108831. if(i==0)
  108832. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  108833. else
  108834. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  108835. }
  108836. #endif
  108837. /* second step: 'all the other crap'; all the stuff that isn't
  108838. computed/fit for bitrate management goes in the second psy
  108839. vector. This includes tone masking, peak limiting and ATH */
  108840. _vp_tonemask(psy_look,
  108841. logfft,
  108842. tone,
  108843. global_ampmax,
  108844. local_ampmax[i]);
  108845. #if 0
  108846. if(vi->channels==2){
  108847. if(i==0)
  108848. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  108849. else
  108850. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  108851. }
  108852. #endif
  108853. /* third step; we offset the noise vectors, overlay tone
  108854. masking. We then do a floor1-specific line fit. If we're
  108855. performing bitrate management, the line fit is performed
  108856. multiple times for up/down tweakage on demand. */
  108857. #if 0
  108858. {
  108859. float aotuv[psy_look->n];
  108860. #endif
  108861. _vp_offset_and_mix(psy_look,
  108862. noise,
  108863. tone,
  108864. 1,
  108865. logmask,
  108866. mdct,
  108867. logmdct);
  108868. #if 0
  108869. if(vi->channels==2){
  108870. if(i==0)
  108871. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  108872. else
  108873. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  108874. }
  108875. }
  108876. #endif
  108877. #if 0
  108878. if(vi->channels==2){
  108879. if(i==0)
  108880. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  108881. else
  108882. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  108883. }
  108884. #endif
  108885. /* this algorithm is hardwired to floor 1 for now; abort out if
  108886. we're *not* floor1. This won't happen unless someone has
  108887. broken the encode setup lib. Guard it anyway. */
  108888. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  108889. floor_posts[i][PACKETBLOBS/2]=
  108890. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108891. logmdct,
  108892. logmask);
  108893. /* are we managing bitrate? If so, perform two more fits for
  108894. later rate tweaking (fits represent hi/lo) */
  108895. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  108896. /* higher rate by way of lower noise curve */
  108897. _vp_offset_and_mix(psy_look,
  108898. noise,
  108899. tone,
  108900. 2,
  108901. logmask,
  108902. mdct,
  108903. logmdct);
  108904. #if 0
  108905. if(vi->channels==2){
  108906. if(i==0)
  108907. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  108908. else
  108909. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  108910. }
  108911. #endif
  108912. floor_posts[i][PACKETBLOBS-1]=
  108913. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108914. logmdct,
  108915. logmask);
  108916. /* lower rate by way of higher noise curve */
  108917. _vp_offset_and_mix(psy_look,
  108918. noise,
  108919. tone,
  108920. 0,
  108921. logmask,
  108922. mdct,
  108923. logmdct);
  108924. #if 0
  108925. if(vi->channels==2)
  108926. if(i==0)
  108927. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  108928. else
  108929. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  108930. #endif
  108931. floor_posts[i][0]=
  108932. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108933. logmdct,
  108934. logmask);
  108935. /* we also interpolate a range of intermediate curves for
  108936. intermediate rates */
  108937. for(k=1;k<PACKETBLOBS/2;k++)
  108938. floor_posts[i][k]=
  108939. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  108940. floor_posts[i][0],
  108941. floor_posts[i][PACKETBLOBS/2],
  108942. k*65536/(PACKETBLOBS/2));
  108943. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  108944. floor_posts[i][k]=
  108945. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  108946. floor_posts[i][PACKETBLOBS/2],
  108947. floor_posts[i][PACKETBLOBS-1],
  108948. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  108949. }
  108950. }
  108951. }
  108952. vbi->ampmax=global_ampmax;
  108953. /*
  108954. the next phases are performed once for vbr-only and PACKETBLOB
  108955. times for bitrate managed modes.
  108956. 1) encode actual mode being used
  108957. 2) encode the floor for each channel, compute coded mask curve/res
  108958. 3) normalize and couple.
  108959. 4) encode residue
  108960. 5) save packet bytes to the packetblob vector
  108961. */
  108962. /* iterate over the many masking curve fits we've created */
  108963. {
  108964. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  108965. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  108966. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  108967. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  108968. float **mag_memo;
  108969. int **mag_sort;
  108970. if(info->coupling_steps){
  108971. mag_memo=_vp_quantize_couple_memo(vb,
  108972. &ci->psy_g_param,
  108973. psy_look,
  108974. info,
  108975. gmdct);
  108976. mag_sort=_vp_quantize_couple_sort(vb,
  108977. psy_look,
  108978. info,
  108979. mag_memo);
  108980. hf_reduction(&ci->psy_g_param,
  108981. psy_look,
  108982. info,
  108983. mag_memo);
  108984. }
  108985. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  108986. if(psy_look->vi->normal_channel_p){
  108987. for(i=0;i<vi->channels;i++){
  108988. float *mdct =gmdct[i];
  108989. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  108990. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  108991. }
  108992. }
  108993. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  108994. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  108995. k++){
  108996. oggpack_buffer *opb=vbi->packetblob[k];
  108997. /* start out our new packet blob with packet type and mode */
  108998. /* Encode the packet type */
  108999. oggpack_write(opb,0,1);
  109000. /* Encode the modenumber */
  109001. /* Encode frame mode, pre,post windowsize, then dispatch */
  109002. oggpack_write(opb,modenumber,b->modebits);
  109003. if(vb->W){
  109004. oggpack_write(opb,vb->lW,1);
  109005. oggpack_write(opb,vb->nW,1);
  109006. }
  109007. /* encode floor, compute masking curve, sep out residue */
  109008. for(i=0;i<vi->channels;i++){
  109009. int submap=info->chmuxlist[i];
  109010. float *mdct =gmdct[i];
  109011. float *res =vb->pcm[i];
  109012. int *ilogmask=ilogmaskch[i]=
  109013. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109014. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  109015. floor_posts[i][k],
  109016. ilogmask);
  109017. #if 0
  109018. {
  109019. char buf[80];
  109020. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  109021. float work[n/2];
  109022. for(j=0;j<n/2;j++)
  109023. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  109024. _analysis_output(buf,seq,work,n/2,1,1,0);
  109025. }
  109026. #endif
  109027. _vp_remove_floor(psy_look,
  109028. mdct,
  109029. ilogmask,
  109030. res,
  109031. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109032. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  109033. #if 0
  109034. {
  109035. char buf[80];
  109036. float work[n/2];
  109037. for(j=0;j<n/2;j++)
  109038. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  109039. sprintf(buf,"resI%c%d",i?'R':'L',k);
  109040. _analysis_output(buf,seq,work,n/2,1,1,0);
  109041. }
  109042. #endif
  109043. }
  109044. /* our iteration is now based on masking curve, not prequant and
  109045. coupling. Only one prequant/coupling step */
  109046. /* quantize/couple */
  109047. /* incomplete implementation that assumes the tree is all depth
  109048. one, or no tree at all */
  109049. if(info->coupling_steps){
  109050. _vp_couple(k,
  109051. &ci->psy_g_param,
  109052. psy_look,
  109053. info,
  109054. vb->pcm,
  109055. mag_memo,
  109056. mag_sort,
  109057. ilogmaskch,
  109058. nonzero,
  109059. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109060. }
  109061. /* classify and encode by submap */
  109062. for(i=0;i<info->submaps;i++){
  109063. int ch_in_bundle=0;
  109064. long **classifications;
  109065. int resnum=info->residuesubmap[i];
  109066. for(j=0;j<vi->channels;j++){
  109067. if(info->chmuxlist[j]==i){
  109068. zerobundle[ch_in_bundle]=0;
  109069. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  109070. res_bundle[ch_in_bundle]=vb->pcm[j];
  109071. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  109072. }
  109073. }
  109074. classifications=_residue_P[ci->residue_type[resnum]]->
  109075. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  109076. _residue_P[ci->residue_type[resnum]]->
  109077. forward(opb,vb,b->residue[resnum],
  109078. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  109079. }
  109080. /* ok, done encoding. Next protopacket. */
  109081. }
  109082. }
  109083. #if 0
  109084. seq++;
  109085. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  109086. #endif
  109087. return(0);
  109088. }
  109089. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  109090. vorbis_dsp_state *vd=vb->vd;
  109091. vorbis_info *vi=vd->vi;
  109092. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109093. private_state *b=(private_state*)vd->backend_state;
  109094. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  109095. int i,j;
  109096. long n=vb->pcmend=ci->blocksizes[vb->W];
  109097. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  109098. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109099. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  109100. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  109101. /* recover the spectral envelope; store it in the PCM vector for now */
  109102. for(i=0;i<vi->channels;i++){
  109103. int submap=info->chmuxlist[i];
  109104. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109105. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  109106. if(floormemo[i])
  109107. nonzero[i]=1;
  109108. else
  109109. nonzero[i]=0;
  109110. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  109111. }
  109112. /* channel coupling can 'dirty' the nonzero listing */
  109113. for(i=0;i<info->coupling_steps;i++){
  109114. if(nonzero[info->coupling_mag[i]] ||
  109115. nonzero[info->coupling_ang[i]]){
  109116. nonzero[info->coupling_mag[i]]=1;
  109117. nonzero[info->coupling_ang[i]]=1;
  109118. }
  109119. }
  109120. /* recover the residue into our working vectors */
  109121. for(i=0;i<info->submaps;i++){
  109122. int ch_in_bundle=0;
  109123. for(j=0;j<vi->channels;j++){
  109124. if(info->chmuxlist[j]==i){
  109125. if(nonzero[j])
  109126. zerobundle[ch_in_bundle]=1;
  109127. else
  109128. zerobundle[ch_in_bundle]=0;
  109129. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  109130. }
  109131. }
  109132. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  109133. inverse(vb,b->residue[info->residuesubmap[i]],
  109134. pcmbundle,zerobundle,ch_in_bundle);
  109135. }
  109136. /* channel coupling */
  109137. for(i=info->coupling_steps-1;i>=0;i--){
  109138. float *pcmM=vb->pcm[info->coupling_mag[i]];
  109139. float *pcmA=vb->pcm[info->coupling_ang[i]];
  109140. for(j=0;j<n/2;j++){
  109141. float mag=pcmM[j];
  109142. float ang=pcmA[j];
  109143. if(mag>0)
  109144. if(ang>0){
  109145. pcmM[j]=mag;
  109146. pcmA[j]=mag-ang;
  109147. }else{
  109148. pcmA[j]=mag;
  109149. pcmM[j]=mag+ang;
  109150. }
  109151. else
  109152. if(ang>0){
  109153. pcmM[j]=mag;
  109154. pcmA[j]=mag+ang;
  109155. }else{
  109156. pcmA[j]=mag;
  109157. pcmM[j]=mag-ang;
  109158. }
  109159. }
  109160. }
  109161. /* compute and apply spectral envelope */
  109162. for(i=0;i<vi->channels;i++){
  109163. float *pcm=vb->pcm[i];
  109164. int submap=info->chmuxlist[i];
  109165. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109166. inverse2(vb,b->flr[info->floorsubmap[submap]],
  109167. floormemo[i],pcm);
  109168. }
  109169. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  109170. /* only MDCT right now.... */
  109171. for(i=0;i<vi->channels;i++){
  109172. float *pcm=vb->pcm[i];
  109173. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  109174. }
  109175. /* all done! */
  109176. return(0);
  109177. }
  109178. /* export hooks */
  109179. vorbis_func_mapping mapping0_exportbundle={
  109180. &mapping0_pack,
  109181. &mapping0_unpack,
  109182. &mapping0_free_info,
  109183. &mapping0_forward,
  109184. &mapping0_inverse
  109185. };
  109186. #endif
  109187. /********* End of inlined file: mapping0.c *********/
  109188. /********* Start of inlined file: mdct.c *********/
  109189. /* this can also be run as an integer transform by uncommenting a
  109190. define in mdct.h; the integerization is a first pass and although
  109191. it's likely stable for Vorbis, the dynamic range is constrained and
  109192. roundoff isn't done (so it's noisy). Consider it functional, but
  109193. only a starting point. There's no point on a machine with an FPU */
  109194. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109195. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109196. // tasks..
  109197. #ifdef _MSC_VER
  109198. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109199. #endif
  109200. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109201. #if JUCE_USE_OGGVORBIS
  109202. #include <stdio.h>
  109203. #include <stdlib.h>
  109204. #include <string.h>
  109205. #include <math.h>
  109206. /* build lookups for trig functions; also pre-figure scaling and
  109207. some window function algebra. */
  109208. void mdct_init(mdct_lookup *lookup,int n){
  109209. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  109210. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  109211. int i;
  109212. int n2=n>>1;
  109213. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  109214. lookup->n=n;
  109215. lookup->trig=T;
  109216. lookup->bitrev=bitrev;
  109217. /* trig lookups... */
  109218. for(i=0;i<n/4;i++){
  109219. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  109220. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  109221. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  109222. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  109223. }
  109224. for(i=0;i<n/8;i++){
  109225. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  109226. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  109227. }
  109228. /* bitreverse lookup... */
  109229. {
  109230. int mask=(1<<(log2n-1))-1,i,j;
  109231. int msb=1<<(log2n-2);
  109232. for(i=0;i<n/8;i++){
  109233. int acc=0;
  109234. for(j=0;msb>>j;j++)
  109235. if((msb>>j)&i)acc|=1<<j;
  109236. bitrev[i*2]=((~acc)&mask)-1;
  109237. bitrev[i*2+1]=acc;
  109238. }
  109239. }
  109240. lookup->scale=FLOAT_CONV(4.f/n);
  109241. }
  109242. /* 8 point butterfly (in place, 4 register) */
  109243. STIN void mdct_butterfly_8(DATA_TYPE *x){
  109244. REG_TYPE r0 = x[6] + x[2];
  109245. REG_TYPE r1 = x[6] - x[2];
  109246. REG_TYPE r2 = x[4] + x[0];
  109247. REG_TYPE r3 = x[4] - x[0];
  109248. x[6] = r0 + r2;
  109249. x[4] = r0 - r2;
  109250. r0 = x[5] - x[1];
  109251. r2 = x[7] - x[3];
  109252. x[0] = r1 + r0;
  109253. x[2] = r1 - r0;
  109254. r0 = x[5] + x[1];
  109255. r1 = x[7] + x[3];
  109256. x[3] = r2 + r3;
  109257. x[1] = r2 - r3;
  109258. x[7] = r1 + r0;
  109259. x[5] = r1 - r0;
  109260. }
  109261. /* 16 point butterfly (in place, 4 register) */
  109262. STIN void mdct_butterfly_16(DATA_TYPE *x){
  109263. REG_TYPE r0 = x[1] - x[9];
  109264. REG_TYPE r1 = x[0] - x[8];
  109265. x[8] += x[0];
  109266. x[9] += x[1];
  109267. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  109268. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  109269. r0 = x[3] - x[11];
  109270. r1 = x[10] - x[2];
  109271. x[10] += x[2];
  109272. x[11] += x[3];
  109273. x[2] = r0;
  109274. x[3] = r1;
  109275. r0 = x[12] - x[4];
  109276. r1 = x[13] - x[5];
  109277. x[12] += x[4];
  109278. x[13] += x[5];
  109279. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  109280. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  109281. r0 = x[14] - x[6];
  109282. r1 = x[15] - x[7];
  109283. x[14] += x[6];
  109284. x[15] += x[7];
  109285. x[6] = r0;
  109286. x[7] = r1;
  109287. mdct_butterfly_8(x);
  109288. mdct_butterfly_8(x+8);
  109289. }
  109290. /* 32 point butterfly (in place, 4 register) */
  109291. STIN void mdct_butterfly_32(DATA_TYPE *x){
  109292. REG_TYPE r0 = x[30] - x[14];
  109293. REG_TYPE r1 = x[31] - x[15];
  109294. x[30] += x[14];
  109295. x[31] += x[15];
  109296. x[14] = r0;
  109297. x[15] = r1;
  109298. r0 = x[28] - x[12];
  109299. r1 = x[29] - x[13];
  109300. x[28] += x[12];
  109301. x[29] += x[13];
  109302. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  109303. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  109304. r0 = x[26] - x[10];
  109305. r1 = x[27] - x[11];
  109306. x[26] += x[10];
  109307. x[27] += x[11];
  109308. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  109309. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  109310. r0 = x[24] - x[8];
  109311. r1 = x[25] - x[9];
  109312. x[24] += x[8];
  109313. x[25] += x[9];
  109314. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  109315. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  109316. r0 = x[22] - x[6];
  109317. r1 = x[7] - x[23];
  109318. x[22] += x[6];
  109319. x[23] += x[7];
  109320. x[6] = r1;
  109321. x[7] = r0;
  109322. r0 = x[4] - x[20];
  109323. r1 = x[5] - x[21];
  109324. x[20] += x[4];
  109325. x[21] += x[5];
  109326. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  109327. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  109328. r0 = x[2] - x[18];
  109329. r1 = x[3] - x[19];
  109330. x[18] += x[2];
  109331. x[19] += x[3];
  109332. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  109333. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  109334. r0 = x[0] - x[16];
  109335. r1 = x[1] - x[17];
  109336. x[16] += x[0];
  109337. x[17] += x[1];
  109338. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  109339. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  109340. mdct_butterfly_16(x);
  109341. mdct_butterfly_16(x+16);
  109342. }
  109343. /* N point first stage butterfly (in place, 2 register) */
  109344. STIN void mdct_butterfly_first(DATA_TYPE *T,
  109345. DATA_TYPE *x,
  109346. int points){
  109347. DATA_TYPE *x1 = x + points - 8;
  109348. DATA_TYPE *x2 = x + (points>>1) - 8;
  109349. REG_TYPE r0;
  109350. REG_TYPE r1;
  109351. do{
  109352. r0 = x1[6] - x2[6];
  109353. r1 = x1[7] - x2[7];
  109354. x1[6] += x2[6];
  109355. x1[7] += x2[7];
  109356. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109357. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109358. r0 = x1[4] - x2[4];
  109359. r1 = x1[5] - x2[5];
  109360. x1[4] += x2[4];
  109361. x1[5] += x2[5];
  109362. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  109363. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  109364. r0 = x1[2] - x2[2];
  109365. r1 = x1[3] - x2[3];
  109366. x1[2] += x2[2];
  109367. x1[3] += x2[3];
  109368. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  109369. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  109370. r0 = x1[0] - x2[0];
  109371. r1 = x1[1] - x2[1];
  109372. x1[0] += x2[0];
  109373. x1[1] += x2[1];
  109374. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  109375. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  109376. x1-=8;
  109377. x2-=8;
  109378. T+=16;
  109379. }while(x2>=x);
  109380. }
  109381. /* N/stage point generic N stage butterfly (in place, 2 register) */
  109382. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  109383. DATA_TYPE *x,
  109384. int points,
  109385. int trigint){
  109386. DATA_TYPE *x1 = x + points - 8;
  109387. DATA_TYPE *x2 = x + (points>>1) - 8;
  109388. REG_TYPE r0;
  109389. REG_TYPE r1;
  109390. do{
  109391. r0 = x1[6] - x2[6];
  109392. r1 = x1[7] - x2[7];
  109393. x1[6] += x2[6];
  109394. x1[7] += x2[7];
  109395. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109396. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109397. T+=trigint;
  109398. r0 = x1[4] - x2[4];
  109399. r1 = x1[5] - x2[5];
  109400. x1[4] += x2[4];
  109401. x1[5] += x2[5];
  109402. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109403. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109404. T+=trigint;
  109405. r0 = x1[2] - x2[2];
  109406. r1 = x1[3] - x2[3];
  109407. x1[2] += x2[2];
  109408. x1[3] += x2[3];
  109409. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109410. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109411. T+=trigint;
  109412. r0 = x1[0] - x2[0];
  109413. r1 = x1[1] - x2[1];
  109414. x1[0] += x2[0];
  109415. x1[1] += x2[1];
  109416. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109417. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109418. T+=trigint;
  109419. x1-=8;
  109420. x2-=8;
  109421. }while(x2>=x);
  109422. }
  109423. STIN void mdct_butterflies(mdct_lookup *init,
  109424. DATA_TYPE *x,
  109425. int points){
  109426. DATA_TYPE *T=init->trig;
  109427. int stages=init->log2n-5;
  109428. int i,j;
  109429. if(--stages>0){
  109430. mdct_butterfly_first(T,x,points);
  109431. }
  109432. for(i=1;--stages>0;i++){
  109433. for(j=0;j<(1<<i);j++)
  109434. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  109435. }
  109436. for(j=0;j<points;j+=32)
  109437. mdct_butterfly_32(x+j);
  109438. }
  109439. void mdct_clear(mdct_lookup *l){
  109440. if(l){
  109441. if(l->trig)_ogg_free(l->trig);
  109442. if(l->bitrev)_ogg_free(l->bitrev);
  109443. memset(l,0,sizeof(*l));
  109444. }
  109445. }
  109446. STIN void mdct_bitreverse(mdct_lookup *init,
  109447. DATA_TYPE *x){
  109448. int n = init->n;
  109449. int *bit = init->bitrev;
  109450. DATA_TYPE *w0 = x;
  109451. DATA_TYPE *w1 = x = w0+(n>>1);
  109452. DATA_TYPE *T = init->trig+n;
  109453. do{
  109454. DATA_TYPE *x0 = x+bit[0];
  109455. DATA_TYPE *x1 = x+bit[1];
  109456. REG_TYPE r0 = x0[1] - x1[1];
  109457. REG_TYPE r1 = x0[0] + x1[0];
  109458. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  109459. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  109460. w1 -= 4;
  109461. r0 = HALVE(x0[1] + x1[1]);
  109462. r1 = HALVE(x0[0] - x1[0]);
  109463. w0[0] = r0 + r2;
  109464. w1[2] = r0 - r2;
  109465. w0[1] = r1 + r3;
  109466. w1[3] = r3 - r1;
  109467. x0 = x+bit[2];
  109468. x1 = x+bit[3];
  109469. r0 = x0[1] - x1[1];
  109470. r1 = x0[0] + x1[0];
  109471. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  109472. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  109473. r0 = HALVE(x0[1] + x1[1]);
  109474. r1 = HALVE(x0[0] - x1[0]);
  109475. w0[2] = r0 + r2;
  109476. w1[0] = r0 - r2;
  109477. w0[3] = r1 + r3;
  109478. w1[1] = r3 - r1;
  109479. T += 4;
  109480. bit += 4;
  109481. w0 += 4;
  109482. }while(w0<w1);
  109483. }
  109484. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  109485. int n=init->n;
  109486. int n2=n>>1;
  109487. int n4=n>>2;
  109488. /* rotate */
  109489. DATA_TYPE *iX = in+n2-7;
  109490. DATA_TYPE *oX = out+n2+n4;
  109491. DATA_TYPE *T = init->trig+n4;
  109492. do{
  109493. oX -= 4;
  109494. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  109495. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  109496. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  109497. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  109498. iX -= 8;
  109499. T += 4;
  109500. }while(iX>=in);
  109501. iX = in+n2-8;
  109502. oX = out+n2+n4;
  109503. T = init->trig+n4;
  109504. do{
  109505. T -= 4;
  109506. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  109507. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  109508. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  109509. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  109510. iX -= 8;
  109511. oX += 4;
  109512. }while(iX>=in);
  109513. mdct_butterflies(init,out+n2,n2);
  109514. mdct_bitreverse(init,out);
  109515. /* roatate + window */
  109516. {
  109517. DATA_TYPE *oX1=out+n2+n4;
  109518. DATA_TYPE *oX2=out+n2+n4;
  109519. DATA_TYPE *iX =out;
  109520. T =init->trig+n2;
  109521. do{
  109522. oX1-=4;
  109523. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  109524. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  109525. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  109526. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  109527. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  109528. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  109529. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  109530. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  109531. oX2+=4;
  109532. iX += 8;
  109533. T += 8;
  109534. }while(iX<oX1);
  109535. iX=out+n2+n4;
  109536. oX1=out+n4;
  109537. oX2=oX1;
  109538. do{
  109539. oX1-=4;
  109540. iX-=4;
  109541. oX2[0] = -(oX1[3] = iX[3]);
  109542. oX2[1] = -(oX1[2] = iX[2]);
  109543. oX2[2] = -(oX1[1] = iX[1]);
  109544. oX2[3] = -(oX1[0] = iX[0]);
  109545. oX2+=4;
  109546. }while(oX2<iX);
  109547. iX=out+n2+n4;
  109548. oX1=out+n2+n4;
  109549. oX2=out+n2;
  109550. do{
  109551. oX1-=4;
  109552. oX1[0]= iX[3];
  109553. oX1[1]= iX[2];
  109554. oX1[2]= iX[1];
  109555. oX1[3]= iX[0];
  109556. iX+=4;
  109557. }while(oX1>oX2);
  109558. }
  109559. }
  109560. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  109561. int n=init->n;
  109562. int n2=n>>1;
  109563. int n4=n>>2;
  109564. int n8=n>>3;
  109565. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  109566. DATA_TYPE *w2=w+n2;
  109567. /* rotate */
  109568. /* window + rotate + step 1 */
  109569. REG_TYPE r0;
  109570. REG_TYPE r1;
  109571. DATA_TYPE *x0=in+n2+n4;
  109572. DATA_TYPE *x1=x0+1;
  109573. DATA_TYPE *T=init->trig+n2;
  109574. int i=0;
  109575. for(i=0;i<n8;i+=2){
  109576. x0 -=4;
  109577. T-=2;
  109578. r0= x0[2] + x1[0];
  109579. r1= x0[0] + x1[2];
  109580. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109581. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109582. x1 +=4;
  109583. }
  109584. x1=in+1;
  109585. for(;i<n2-n8;i+=2){
  109586. T-=2;
  109587. x0 -=4;
  109588. r0= x0[2] - x1[0];
  109589. r1= x0[0] - x1[2];
  109590. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109591. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109592. x1 +=4;
  109593. }
  109594. x0=in+n;
  109595. for(;i<n2;i+=2){
  109596. T-=2;
  109597. x0 -=4;
  109598. r0= -x0[2] - x1[0];
  109599. r1= -x0[0] - x1[2];
  109600. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109601. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109602. x1 +=4;
  109603. }
  109604. mdct_butterflies(init,w+n2,n2);
  109605. mdct_bitreverse(init,w);
  109606. /* roatate + window */
  109607. T=init->trig+n2;
  109608. x0=out+n2;
  109609. for(i=0;i<n4;i++){
  109610. x0--;
  109611. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  109612. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  109613. w+=2;
  109614. T+=2;
  109615. }
  109616. }
  109617. #endif
  109618. /********* End of inlined file: mdct.c *********/
  109619. /********* Start of inlined file: psy.c *********/
  109620. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109621. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109622. // tasks..
  109623. #ifdef _MSC_VER
  109624. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109625. #endif
  109626. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109627. #if JUCE_USE_OGGVORBIS
  109628. #include <stdlib.h>
  109629. #include <math.h>
  109630. #include <string.h>
  109631. /********* Start of inlined file: masking.h *********/
  109632. #ifndef _V_MASKING_H_
  109633. #define _V_MASKING_H_
  109634. /* more detailed ATH; the bass if flat to save stressing the floor
  109635. overly for only a bin or two of savings. */
  109636. #define MAX_ATH 88
  109637. static float ATH[]={
  109638. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  109639. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  109640. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  109641. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  109642. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  109643. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  109644. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  109645. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  109646. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  109647. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  109648. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  109649. };
  109650. /* The tone masking curves from Ehmer's and Fielder's papers have been
  109651. replaced by an empirically collected data set. The previously
  109652. published values were, far too often, simply on crack. */
  109653. #define EHMER_OFFSET 16
  109654. #define EHMER_MAX 56
  109655. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  109656. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  109657. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  109658. for collection of these curves) */
  109659. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  109660. /* 62.5 Hz */
  109661. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  109662. -60, -60, -60, -60, -62, -62, -65, -73,
  109663. -69, -68, -68, -67, -70, -70, -72, -74,
  109664. -75, -79, -79, -80, -83, -88, -93, -100,
  109665. -110, -999, -999, -999, -999, -999, -999, -999,
  109666. -999, -999, -999, -999, -999, -999, -999, -999,
  109667. -999, -999, -999, -999, -999, -999, -999, -999},
  109668. { -48, -48, -48, -48, -48, -48, -48, -48,
  109669. -48, -48, -48, -48, -48, -53, -61, -66,
  109670. -66, -68, -67, -70, -76, -76, -72, -73,
  109671. -75, -76, -78, -79, -83, -88, -93, -100,
  109672. -110, -999, -999, -999, -999, -999, -999, -999,
  109673. -999, -999, -999, -999, -999, -999, -999, -999,
  109674. -999, -999, -999, -999, -999, -999, -999, -999},
  109675. { -37, -37, -37, -37, -37, -37, -37, -37,
  109676. -38, -40, -42, -46, -48, -53, -55, -62,
  109677. -65, -58, -56, -56, -61, -60, -65, -67,
  109678. -69, -71, -77, -77, -78, -80, -82, -84,
  109679. -88, -93, -98, -106, -112, -999, -999, -999,
  109680. -999, -999, -999, -999, -999, -999, -999, -999,
  109681. -999, -999, -999, -999, -999, -999, -999, -999},
  109682. { -25, -25, -25, -25, -25, -25, -25, -25,
  109683. -25, -26, -27, -29, -32, -38, -48, -52,
  109684. -52, -50, -48, -48, -51, -52, -54, -60,
  109685. -67, -67, -66, -68, -69, -73, -73, -76,
  109686. -80, -81, -81, -85, -85, -86, -88, -93,
  109687. -100, -110, -999, -999, -999, -999, -999, -999,
  109688. -999, -999, -999, -999, -999, -999, -999, -999},
  109689. { -16, -16, -16, -16, -16, -16, -16, -16,
  109690. -17, -19, -20, -22, -26, -28, -31, -40,
  109691. -47, -39, -39, -40, -42, -43, -47, -51,
  109692. -57, -52, -55, -55, -60, -58, -62, -63,
  109693. -70, -67, -69, -72, -73, -77, -80, -82,
  109694. -83, -87, -90, -94, -98, -104, -115, -999,
  109695. -999, -999, -999, -999, -999, -999, -999, -999},
  109696. { -8, -8, -8, -8, -8, -8, -8, -8,
  109697. -8, -8, -10, -11, -15, -19, -25, -30,
  109698. -34, -31, -30, -31, -29, -32, -35, -42,
  109699. -48, -42, -44, -46, -50, -50, -51, -52,
  109700. -59, -54, -55, -55, -58, -62, -63, -66,
  109701. -72, -73, -76, -75, -78, -80, -80, -81,
  109702. -84, -88, -90, -94, -98, -101, -106, -110}},
  109703. /* 88Hz */
  109704. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  109705. -66, -66, -66, -66, -66, -67, -67, -67,
  109706. -76, -72, -71, -74, -76, -76, -75, -78,
  109707. -79, -79, -81, -83, -86, -89, -93, -97,
  109708. -100, -105, -110, -999, -999, -999, -999, -999,
  109709. -999, -999, -999, -999, -999, -999, -999, -999,
  109710. -999, -999, -999, -999, -999, -999, -999, -999},
  109711. { -47, -47, -47, -47, -47, -47, -47, -47,
  109712. -47, -47, -47, -48, -51, -55, -59, -66,
  109713. -66, -66, -67, -66, -68, -69, -70, -74,
  109714. -79, -77, -77, -78, -80, -81, -82, -84,
  109715. -86, -88, -91, -95, -100, -108, -116, -999,
  109716. -999, -999, -999, -999, -999, -999, -999, -999,
  109717. -999, -999, -999, -999, -999, -999, -999, -999},
  109718. { -36, -36, -36, -36, -36, -36, -36, -36,
  109719. -36, -37, -37, -41, -44, -48, -51, -58,
  109720. -62, -60, -57, -59, -59, -60, -63, -65,
  109721. -72, -71, -70, -72, -74, -77, -76, -78,
  109722. -81, -81, -80, -83, -86, -91, -96, -100,
  109723. -105, -110, -999, -999, -999, -999, -999, -999,
  109724. -999, -999, -999, -999, -999, -999, -999, -999},
  109725. { -28, -28, -28, -28, -28, -28, -28, -28,
  109726. -28, -30, -32, -32, -33, -35, -41, -49,
  109727. -50, -49, -47, -48, -48, -52, -51, -57,
  109728. -65, -61, -59, -61, -64, -69, -70, -74,
  109729. -77, -77, -78, -81, -84, -85, -87, -90,
  109730. -92, -96, -100, -107, -112, -999, -999, -999,
  109731. -999, -999, -999, -999, -999, -999, -999, -999},
  109732. { -19, -19, -19, -19, -19, -19, -19, -19,
  109733. -20, -21, -23, -27, -30, -35, -36, -41,
  109734. -46, -44, -42, -40, -41, -41, -43, -48,
  109735. -55, -53, -52, -53, -56, -59, -58, -60,
  109736. -67, -66, -69, -71, -72, -75, -79, -81,
  109737. -84, -87, -90, -93, -97, -101, -107, -114,
  109738. -999, -999, -999, -999, -999, -999, -999, -999},
  109739. { -9, -9, -9, -9, -9, -9, -9, -9,
  109740. -11, -12, -12, -15, -16, -20, -23, -30,
  109741. -37, -34, -33, -34, -31, -32, -32, -38,
  109742. -47, -44, -41, -40, -47, -49, -46, -46,
  109743. -58, -50, -50, -54, -58, -62, -64, -67,
  109744. -67, -70, -72, -76, -79, -83, -87, -91,
  109745. -96, -100, -104, -110, -999, -999, -999, -999}},
  109746. /* 125 Hz */
  109747. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  109748. -62, -62, -63, -64, -66, -67, -66, -68,
  109749. -75, -72, -76, -75, -76, -78, -79, -82,
  109750. -84, -85, -90, -94, -101, -110, -999, -999,
  109751. -999, -999, -999, -999, -999, -999, -999, -999,
  109752. -999, -999, -999, -999, -999, -999, -999, -999,
  109753. -999, -999, -999, -999, -999, -999, -999, -999},
  109754. { -59, -59, -59, -59, -59, -59, -59, -59,
  109755. -59, -59, -59, -60, -60, -61, -63, -66,
  109756. -71, -68, -70, -70, -71, -72, -72, -75,
  109757. -81, -78, -79, -82, -83, -86, -90, -97,
  109758. -103, -113, -999, -999, -999, -999, -999, -999,
  109759. -999, -999, -999, -999, -999, -999, -999, -999,
  109760. -999, -999, -999, -999, -999, -999, -999, -999},
  109761. { -53, -53, -53, -53, -53, -53, -53, -53,
  109762. -53, -54, -55, -57, -56, -57, -55, -61,
  109763. -65, -60, -60, -62, -63, -63, -66, -68,
  109764. -74, -73, -75, -75, -78, -80, -80, -82,
  109765. -85, -90, -96, -101, -108, -999, -999, -999,
  109766. -999, -999, -999, -999, -999, -999, -999, -999,
  109767. -999, -999, -999, -999, -999, -999, -999, -999},
  109768. { -46, -46, -46, -46, -46, -46, -46, -46,
  109769. -46, -46, -47, -47, -47, -47, -48, -51,
  109770. -57, -51, -49, -50, -51, -53, -54, -59,
  109771. -66, -60, -62, -67, -67, -70, -72, -75,
  109772. -76, -78, -81, -85, -88, -94, -97, -104,
  109773. -112, -999, -999, -999, -999, -999, -999, -999,
  109774. -999, -999, -999, -999, -999, -999, -999, -999},
  109775. { -36, -36, -36, -36, -36, -36, -36, -36,
  109776. -39, -41, -42, -42, -39, -38, -41, -43,
  109777. -52, -44, -40, -39, -37, -37, -40, -47,
  109778. -54, -50, -48, -50, -55, -61, -59, -62,
  109779. -66, -66, -66, -69, -69, -73, -74, -74,
  109780. -75, -77, -79, -82, -87, -91, -95, -100,
  109781. -108, -115, -999, -999, -999, -999, -999, -999},
  109782. { -28, -26, -24, -22, -20, -20, -23, -29,
  109783. -30, -31, -28, -27, -28, -28, -28, -35,
  109784. -40, -33, -32, -29, -30, -30, -30, -37,
  109785. -45, -41, -37, -38, -45, -47, -47, -48,
  109786. -53, -49, -48, -50, -49, -49, -51, -52,
  109787. -58, -56, -57, -56, -60, -61, -62, -70,
  109788. -72, -74, -78, -83, -88, -93, -100, -106}},
  109789. /* 177 Hz */
  109790. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109791. -999, -110, -105, -100, -95, -91, -87, -83,
  109792. -80, -78, -76, -78, -78, -81, -83, -85,
  109793. -86, -85, -86, -87, -90, -97, -107, -999,
  109794. -999, -999, -999, -999, -999, -999, -999, -999,
  109795. -999, -999, -999, -999, -999, -999, -999, -999,
  109796. -999, -999, -999, -999, -999, -999, -999, -999},
  109797. {-999, -999, -999, -110, -105, -100, -95, -90,
  109798. -85, -81, -77, -73, -70, -67, -67, -68,
  109799. -75, -73, -70, -69, -70, -72, -75, -79,
  109800. -84, -83, -84, -86, -88, -89, -89, -93,
  109801. -98, -105, -112, -999, -999, -999, -999, -999,
  109802. -999, -999, -999, -999, -999, -999, -999, -999,
  109803. -999, -999, -999, -999, -999, -999, -999, -999},
  109804. {-105, -100, -95, -90, -85, -80, -76, -71,
  109805. -68, -68, -65, -63, -63, -62, -62, -64,
  109806. -65, -64, -61, -62, -63, -64, -66, -68,
  109807. -73, -73, -74, -75, -76, -81, -83, -85,
  109808. -88, -89, -92, -95, -100, -108, -999, -999,
  109809. -999, -999, -999, -999, -999, -999, -999, -999,
  109810. -999, -999, -999, -999, -999, -999, -999, -999},
  109811. { -80, -75, -71, -68, -65, -63, -62, -61,
  109812. -61, -61, -61, -59, -56, -57, -53, -50,
  109813. -58, -52, -50, -50, -52, -53, -54, -58,
  109814. -67, -63, -67, -68, -72, -75, -78, -80,
  109815. -81, -81, -82, -85, -89, -90, -93, -97,
  109816. -101, -107, -114, -999, -999, -999, -999, -999,
  109817. -999, -999, -999, -999, -999, -999, -999, -999},
  109818. { -65, -61, -59, -57, -56, -55, -55, -56,
  109819. -56, -57, -55, -53, -52, -47, -44, -44,
  109820. -50, -44, -41, -39, -39, -42, -40, -46,
  109821. -51, -49, -50, -53, -54, -63, -60, -61,
  109822. -62, -66, -66, -66, -70, -73, -74, -75,
  109823. -76, -75, -79, -85, -89, -91, -96, -102,
  109824. -110, -999, -999, -999, -999, -999, -999, -999},
  109825. { -52, -50, -49, -49, -48, -48, -48, -49,
  109826. -50, -50, -49, -46, -43, -39, -35, -33,
  109827. -38, -36, -32, -29, -32, -32, -32, -35,
  109828. -44, -39, -38, -38, -46, -50, -45, -46,
  109829. -53, -50, -50, -50, -54, -54, -53, -53,
  109830. -56, -57, -59, -66, -70, -72, -74, -79,
  109831. -83, -85, -90, -97, -114, -999, -999, -999}},
  109832. /* 250 Hz */
  109833. {{-999, -999, -999, -999, -999, -999, -110, -105,
  109834. -100, -95, -90, -86, -80, -75, -75, -79,
  109835. -80, -79, -80, -81, -82, -88, -95, -103,
  109836. -110, -999, -999, -999, -999, -999, -999, -999,
  109837. -999, -999, -999, -999, -999, -999, -999, -999,
  109838. -999, -999, -999, -999, -999, -999, -999, -999,
  109839. -999, -999, -999, -999, -999, -999, -999, -999},
  109840. {-999, -999, -999, -999, -108, -103, -98, -93,
  109841. -88, -83, -79, -78, -75, -71, -67, -68,
  109842. -73, -73, -72, -73, -75, -77, -80, -82,
  109843. -88, -93, -100, -107, -114, -999, -999, -999,
  109844. -999, -999, -999, -999, -999, -999, -999, -999,
  109845. -999, -999, -999, -999, -999, -999, -999, -999,
  109846. -999, -999, -999, -999, -999, -999, -999, -999},
  109847. {-999, -999, -999, -110, -105, -101, -96, -90,
  109848. -86, -81, -77, -73, -69, -66, -61, -62,
  109849. -66, -64, -62, -65, -66, -70, -72, -76,
  109850. -81, -80, -84, -90, -95, -102, -110, -999,
  109851. -999, -999, -999, -999, -999, -999, -999, -999,
  109852. -999, -999, -999, -999, -999, -999, -999, -999,
  109853. -999, -999, -999, -999, -999, -999, -999, -999},
  109854. {-999, -999, -999, -107, -103, -97, -92, -88,
  109855. -83, -79, -74, -70, -66, -59, -53, -58,
  109856. -62, -55, -54, -54, -54, -58, -61, -62,
  109857. -72, -70, -72, -75, -78, -80, -81, -80,
  109858. -83, -83, -88, -93, -100, -107, -115, -999,
  109859. -999, -999, -999, -999, -999, -999, -999, -999,
  109860. -999, -999, -999, -999, -999, -999, -999, -999},
  109861. {-999, -999, -999, -105, -100, -95, -90, -85,
  109862. -80, -75, -70, -66, -62, -56, -48, -44,
  109863. -48, -46, -46, -43, -46, -48, -48, -51,
  109864. -58, -58, -59, -60, -62, -62, -61, -61,
  109865. -65, -64, -65, -68, -70, -74, -75, -78,
  109866. -81, -86, -95, -110, -999, -999, -999, -999,
  109867. -999, -999, -999, -999, -999, -999, -999, -999},
  109868. {-999, -999, -105, -100, -95, -90, -85, -80,
  109869. -75, -70, -65, -61, -55, -49, -39, -33,
  109870. -40, -35, -32, -38, -40, -33, -35, -37,
  109871. -46, -41, -45, -44, -46, -42, -45, -46,
  109872. -52, -50, -50, -50, -54, -54, -55, -57,
  109873. -62, -64, -66, -68, -70, -76, -81, -90,
  109874. -100, -110, -999, -999, -999, -999, -999, -999}},
  109875. /* 354 hz */
  109876. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109877. -105, -98, -90, -85, -82, -83, -80, -78,
  109878. -84, -79, -80, -83, -87, -89, -91, -93,
  109879. -99, -106, -117, -999, -999, -999, -999, -999,
  109880. -999, -999, -999, -999, -999, -999, -999, -999,
  109881. -999, -999, -999, -999, -999, -999, -999, -999,
  109882. -999, -999, -999, -999, -999, -999, -999, -999},
  109883. {-999, -999, -999, -999, -999, -999, -999, -999,
  109884. -105, -98, -90, -85, -80, -75, -70, -68,
  109885. -74, -72, -74, -77, -80, -82, -85, -87,
  109886. -92, -89, -91, -95, -100, -106, -112, -999,
  109887. -999, -999, -999, -999, -999, -999, -999, -999,
  109888. -999, -999, -999, -999, -999, -999, -999, -999,
  109889. -999, -999, -999, -999, -999, -999, -999, -999},
  109890. {-999, -999, -999, -999, -999, -999, -999, -999,
  109891. -105, -98, -90, -83, -75, -71, -63, -64,
  109892. -67, -62, -64, -67, -70, -73, -77, -81,
  109893. -84, -83, -85, -89, -90, -93, -98, -104,
  109894. -109, -114, -999, -999, -999, -999, -999, -999,
  109895. -999, -999, -999, -999, -999, -999, -999, -999,
  109896. -999, -999, -999, -999, -999, -999, -999, -999},
  109897. {-999, -999, -999, -999, -999, -999, -999, -999,
  109898. -103, -96, -88, -81, -75, -68, -58, -54,
  109899. -56, -54, -56, -56, -58, -60, -63, -66,
  109900. -74, -69, -72, -72, -75, -74, -77, -81,
  109901. -81, -82, -84, -87, -93, -96, -99, -104,
  109902. -110, -999, -999, -999, -999, -999, -999, -999,
  109903. -999, -999, -999, -999, -999, -999, -999, -999},
  109904. {-999, -999, -999, -999, -999, -108, -102, -96,
  109905. -91, -85, -80, -74, -68, -60, -51, -46,
  109906. -48, -46, -43, -45, -47, -47, -49, -48,
  109907. -56, -53, -55, -58, -57, -63, -58, -60,
  109908. -66, -64, -67, -70, -70, -74, -77, -84,
  109909. -86, -89, -91, -93, -94, -101, -109, -118,
  109910. -999, -999, -999, -999, -999, -999, -999, -999},
  109911. {-999, -999, -999, -108, -103, -98, -93, -88,
  109912. -83, -78, -73, -68, -60, -53, -44, -35,
  109913. -38, -38, -34, -34, -36, -40, -41, -44,
  109914. -51, -45, -46, -47, -46, -54, -50, -49,
  109915. -50, -50, -50, -51, -54, -57, -58, -60,
  109916. -66, -66, -66, -64, -65, -68, -77, -82,
  109917. -87, -95, -110, -999, -999, -999, -999, -999}},
  109918. /* 500 Hz */
  109919. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109920. -107, -102, -97, -92, -87, -83, -78, -75,
  109921. -82, -79, -83, -85, -89, -92, -95, -98,
  109922. -101, -105, -109, -113, -999, -999, -999, -999,
  109923. -999, -999, -999, -999, -999, -999, -999, -999,
  109924. -999, -999, -999, -999, -999, -999, -999, -999,
  109925. -999, -999, -999, -999, -999, -999, -999, -999},
  109926. {-999, -999, -999, -999, -999, -999, -999, -106,
  109927. -100, -95, -90, -86, -81, -78, -74, -69,
  109928. -74, -74, -76, -79, -83, -84, -86, -89,
  109929. -92, -97, -93, -100, -103, -107, -110, -999,
  109930. -999, -999, -999, -999, -999, -999, -999, -999,
  109931. -999, -999, -999, -999, -999, -999, -999, -999,
  109932. -999, -999, -999, -999, -999, -999, -999, -999},
  109933. {-999, -999, -999, -999, -999, -999, -106, -100,
  109934. -95, -90, -87, -83, -80, -75, -69, -60,
  109935. -66, -66, -68, -70, -74, -78, -79, -81,
  109936. -81, -83, -84, -87, -93, -96, -99, -103,
  109937. -107, -110, -999, -999, -999, -999, -999, -999,
  109938. -999, -999, -999, -999, -999, -999, -999, -999,
  109939. -999, -999, -999, -999, -999, -999, -999, -999},
  109940. {-999, -999, -999, -999, -999, -108, -103, -98,
  109941. -93, -89, -85, -82, -78, -71, -62, -55,
  109942. -58, -58, -54, -54, -55, -59, -61, -62,
  109943. -70, -66, -66, -67, -70, -72, -75, -78,
  109944. -84, -84, -84, -88, -91, -90, -95, -98,
  109945. -102, -103, -106, -110, -999, -999, -999, -999,
  109946. -999, -999, -999, -999, -999, -999, -999, -999},
  109947. {-999, -999, -999, -999, -108, -103, -98, -94,
  109948. -90, -87, -82, -79, -73, -67, -58, -47,
  109949. -50, -45, -41, -45, -48, -44, -44, -49,
  109950. -54, -51, -48, -47, -49, -50, -51, -57,
  109951. -58, -60, -63, -69, -70, -69, -71, -74,
  109952. -78, -82, -90, -95, -101, -105, -110, -999,
  109953. -999, -999, -999, -999, -999, -999, -999, -999},
  109954. {-999, -999, -999, -105, -101, -97, -93, -90,
  109955. -85, -80, -77, -72, -65, -56, -48, -37,
  109956. -40, -36, -34, -40, -50, -47, -38, -41,
  109957. -47, -38, -35, -39, -38, -43, -40, -45,
  109958. -50, -45, -44, -47, -50, -55, -48, -48,
  109959. -52, -66, -70, -76, -82, -90, -97, -105,
  109960. -110, -999, -999, -999, -999, -999, -999, -999}},
  109961. /* 707 Hz */
  109962. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109963. -999, -108, -103, -98, -93, -86, -79, -76,
  109964. -83, -81, -85, -87, -89, -93, -98, -102,
  109965. -107, -112, -999, -999, -999, -999, -999, -999,
  109966. -999, -999, -999, -999, -999, -999, -999, -999,
  109967. -999, -999, -999, -999, -999, -999, -999, -999,
  109968. -999, -999, -999, -999, -999, -999, -999, -999},
  109969. {-999, -999, -999, -999, -999, -999, -999, -999,
  109970. -999, -108, -103, -98, -93, -86, -79, -71,
  109971. -77, -74, -77, -79, -81, -84, -85, -90,
  109972. -92, -93, -92, -98, -101, -108, -112, -999,
  109973. -999, -999, -999, -999, -999, -999, -999, -999,
  109974. -999, -999, -999, -999, -999, -999, -999, -999,
  109975. -999, -999, -999, -999, -999, -999, -999, -999},
  109976. {-999, -999, -999, -999, -999, -999, -999, -999,
  109977. -108, -103, -98, -93, -87, -78, -68, -65,
  109978. -66, -62, -65, -67, -70, -73, -75, -78,
  109979. -82, -82, -83, -84, -91, -93, -98, -102,
  109980. -106, -110, -999, -999, -999, -999, -999, -999,
  109981. -999, -999, -999, -999, -999, -999, -999, -999,
  109982. -999, -999, -999, -999, -999, -999, -999, -999},
  109983. {-999, -999, -999, -999, -999, -999, -999, -999,
  109984. -105, -100, -95, -90, -82, -74, -62, -57,
  109985. -58, -56, -51, -52, -52, -54, -54, -58,
  109986. -66, -59, -60, -63, -66, -69, -73, -79,
  109987. -83, -84, -80, -81, -81, -82, -88, -92,
  109988. -98, -105, -113, -999, -999, -999, -999, -999,
  109989. -999, -999, -999, -999, -999, -999, -999, -999},
  109990. {-999, -999, -999, -999, -999, -999, -999, -107,
  109991. -102, -97, -92, -84, -79, -69, -57, -47,
  109992. -52, -47, -44, -45, -50, -52, -42, -42,
  109993. -53, -43, -43, -48, -51, -56, -55, -52,
  109994. -57, -59, -61, -62, -67, -71, -78, -83,
  109995. -86, -94, -98, -103, -110, -999, -999, -999,
  109996. -999, -999, -999, -999, -999, -999, -999, -999},
  109997. {-999, -999, -999, -999, -999, -999, -105, -100,
  109998. -95, -90, -84, -78, -70, -61, -51, -41,
  109999. -40, -38, -40, -46, -52, -51, -41, -40,
  110000. -46, -40, -38, -38, -41, -46, -41, -46,
  110001. -47, -43, -43, -45, -41, -45, -56, -67,
  110002. -68, -83, -87, -90, -95, -102, -107, -113,
  110003. -999, -999, -999, -999, -999, -999, -999, -999}},
  110004. /* 1000 Hz */
  110005. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110006. -999, -109, -105, -101, -96, -91, -84, -77,
  110007. -82, -82, -85, -89, -94, -100, -106, -110,
  110008. -999, -999, -999, -999, -999, -999, -999, -999,
  110009. -999, -999, -999, -999, -999, -999, -999, -999,
  110010. -999, -999, -999, -999, -999, -999, -999, -999,
  110011. -999, -999, -999, -999, -999, -999, -999, -999},
  110012. {-999, -999, -999, -999, -999, -999, -999, -999,
  110013. -999, -106, -103, -98, -92, -85, -80, -71,
  110014. -75, -72, -76, -80, -84, -86, -89, -93,
  110015. -100, -107, -113, -999, -999, -999, -999, -999,
  110016. -999, -999, -999, -999, -999, -999, -999, -999,
  110017. -999, -999, -999, -999, -999, -999, -999, -999,
  110018. -999, -999, -999, -999, -999, -999, -999, -999},
  110019. {-999, -999, -999, -999, -999, -999, -999, -107,
  110020. -104, -101, -97, -92, -88, -84, -80, -64,
  110021. -66, -63, -64, -66, -69, -73, -77, -83,
  110022. -83, -86, -91, -98, -104, -111, -999, -999,
  110023. -999, -999, -999, -999, -999, -999, -999, -999,
  110024. -999, -999, -999, -999, -999, -999, -999, -999,
  110025. -999, -999, -999, -999, -999, -999, -999, -999},
  110026. {-999, -999, -999, -999, -999, -999, -999, -107,
  110027. -104, -101, -97, -92, -90, -84, -74, -57,
  110028. -58, -52, -55, -54, -50, -52, -50, -52,
  110029. -63, -62, -69, -76, -77, -78, -78, -79,
  110030. -82, -88, -94, -100, -106, -111, -999, -999,
  110031. -999, -999, -999, -999, -999, -999, -999, -999,
  110032. -999, -999, -999, -999, -999, -999, -999, -999},
  110033. {-999, -999, -999, -999, -999, -999, -106, -102,
  110034. -98, -95, -90, -85, -83, -78, -70, -50,
  110035. -50, -41, -44, -49, -47, -50, -50, -44,
  110036. -55, -46, -47, -48, -48, -54, -49, -49,
  110037. -58, -62, -71, -81, -87, -92, -97, -102,
  110038. -108, -114, -999, -999, -999, -999, -999, -999,
  110039. -999, -999, -999, -999, -999, -999, -999, -999},
  110040. {-999, -999, -999, -999, -999, -999, -106, -102,
  110041. -98, -95, -90, -85, -83, -78, -70, -45,
  110042. -43, -41, -47, -50, -51, -50, -49, -45,
  110043. -47, -41, -44, -41, -39, -43, -38, -37,
  110044. -40, -41, -44, -50, -58, -65, -73, -79,
  110045. -85, -92, -97, -101, -105, -109, -113, -999,
  110046. -999, -999, -999, -999, -999, -999, -999, -999}},
  110047. /* 1414 Hz */
  110048. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110049. -999, -999, -999, -107, -100, -95, -87, -81,
  110050. -85, -83, -88, -93, -100, -107, -114, -999,
  110051. -999, -999, -999, -999, -999, -999, -999, -999,
  110052. -999, -999, -999, -999, -999, -999, -999, -999,
  110053. -999, -999, -999, -999, -999, -999, -999, -999,
  110054. -999, -999, -999, -999, -999, -999, -999, -999},
  110055. {-999, -999, -999, -999, -999, -999, -999, -999,
  110056. -999, -999, -107, -101, -95, -88, -83, -76,
  110057. -73, -72, -79, -84, -90, -95, -100, -105,
  110058. -110, -115, -999, -999, -999, -999, -999, -999,
  110059. -999, -999, -999, -999, -999, -999, -999, -999,
  110060. -999, -999, -999, -999, -999, -999, -999, -999,
  110061. -999, -999, -999, -999, -999, -999, -999, -999},
  110062. {-999, -999, -999, -999, -999, -999, -999, -999,
  110063. -999, -999, -104, -98, -92, -87, -81, -70,
  110064. -65, -62, -67, -71, -74, -80, -85, -91,
  110065. -95, -99, -103, -108, -111, -114, -999, -999,
  110066. -999, -999, -999, -999, -999, -999, -999, -999,
  110067. -999, -999, -999, -999, -999, -999, -999, -999,
  110068. -999, -999, -999, -999, -999, -999, -999, -999},
  110069. {-999, -999, -999, -999, -999, -999, -999, -999,
  110070. -999, -999, -103, -97, -90, -85, -76, -60,
  110071. -56, -54, -60, -62, -61, -56, -63, -65,
  110072. -73, -74, -77, -75, -78, -81, -86, -87,
  110073. -88, -91, -94, -98, -103, -110, -999, -999,
  110074. -999, -999, -999, -999, -999, -999, -999, -999,
  110075. -999, -999, -999, -999, -999, -999, -999, -999},
  110076. {-999, -999, -999, -999, -999, -999, -999, -105,
  110077. -100, -97, -92, -86, -81, -79, -70, -57,
  110078. -51, -47, -51, -58, -60, -56, -53, -50,
  110079. -58, -52, -50, -50, -53, -55, -64, -69,
  110080. -71, -85, -82, -78, -81, -85, -95, -102,
  110081. -112, -999, -999, -999, -999, -999, -999, -999,
  110082. -999, -999, -999, -999, -999, -999, -999, -999},
  110083. {-999, -999, -999, -999, -999, -999, -999, -105,
  110084. -100, -97, -92, -85, -83, -79, -72, -49,
  110085. -40, -43, -43, -54, -56, -51, -50, -40,
  110086. -43, -38, -36, -35, -37, -38, -37, -44,
  110087. -54, -60, -57, -60, -70, -75, -84, -92,
  110088. -103, -112, -999, -999, -999, -999, -999, -999,
  110089. -999, -999, -999, -999, -999, -999, -999, -999}},
  110090. /* 2000 Hz */
  110091. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110092. -999, -999, -999, -110, -102, -95, -89, -82,
  110093. -83, -84, -90, -92, -99, -107, -113, -999,
  110094. -999, -999, -999, -999, -999, -999, -999, -999,
  110095. -999, -999, -999, -999, -999, -999, -999, -999,
  110096. -999, -999, -999, -999, -999, -999, -999, -999,
  110097. -999, -999, -999, -999, -999, -999, -999, -999},
  110098. {-999, -999, -999, -999, -999, -999, -999, -999,
  110099. -999, -999, -107, -101, -95, -89, -83, -72,
  110100. -74, -78, -85, -88, -88, -90, -92, -98,
  110101. -105, -111, -999, -999, -999, -999, -999, -999,
  110102. -999, -999, -999, -999, -999, -999, -999, -999,
  110103. -999, -999, -999, -999, -999, -999, -999, -999,
  110104. -999, -999, -999, -999, -999, -999, -999, -999},
  110105. {-999, -999, -999, -999, -999, -999, -999, -999,
  110106. -999, -109, -103, -97, -93, -87, -81, -70,
  110107. -70, -67, -75, -73, -76, -79, -81, -83,
  110108. -88, -89, -97, -103, -110, -999, -999, -999,
  110109. -999, -999, -999, -999, -999, -999, -999, -999,
  110110. -999, -999, -999, -999, -999, -999, -999, -999,
  110111. -999, -999, -999, -999, -999, -999, -999, -999},
  110112. {-999, -999, -999, -999, -999, -999, -999, -999,
  110113. -999, -107, -100, -94, -88, -83, -75, -63,
  110114. -59, -59, -63, -66, -60, -62, -67, -67,
  110115. -77, -76, -81, -88, -86, -92, -96, -102,
  110116. -109, -116, -999, -999, -999, -999, -999, -999,
  110117. -999, -999, -999, -999, -999, -999, -999, -999,
  110118. -999, -999, -999, -999, -999, -999, -999, -999},
  110119. {-999, -999, -999, -999, -999, -999, -999, -999,
  110120. -999, -105, -98, -92, -86, -81, -73, -56,
  110121. -52, -47, -55, -60, -58, -52, -51, -45,
  110122. -49, -50, -53, -54, -61, -71, -70, -69,
  110123. -78, -79, -87, -90, -96, -104, -112, -999,
  110124. -999, -999, -999, -999, -999, -999, -999, -999,
  110125. -999, -999, -999, -999, -999, -999, -999, -999},
  110126. {-999, -999, -999, -999, -999, -999, -999, -999,
  110127. -999, -103, -96, -90, -86, -78, -70, -51,
  110128. -42, -47, -48, -55, -54, -54, -53, -42,
  110129. -35, -28, -33, -38, -37, -44, -47, -49,
  110130. -54, -63, -68, -78, -82, -89, -94, -99,
  110131. -104, -109, -114, -999, -999, -999, -999, -999,
  110132. -999, -999, -999, -999, -999, -999, -999, -999}},
  110133. /* 2828 Hz */
  110134. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110135. -999, -999, -999, -999, -110, -100, -90, -79,
  110136. -85, -81, -82, -82, -89, -94, -99, -103,
  110137. -109, -115, -999, -999, -999, -999, -999, -999,
  110138. -999, -999, -999, -999, -999, -999, -999, -999,
  110139. -999, -999, -999, -999, -999, -999, -999, -999,
  110140. -999, -999, -999, -999, -999, -999, -999, -999},
  110141. {-999, -999, -999, -999, -999, -999, -999, -999,
  110142. -999, -999, -999, -999, -105, -97, -85, -72,
  110143. -74, -70, -70, -70, -76, -85, -91, -93,
  110144. -97, -103, -109, -115, -999, -999, -999, -999,
  110145. -999, -999, -999, -999, -999, -999, -999, -999,
  110146. -999, -999, -999, -999, -999, -999, -999, -999,
  110147. -999, -999, -999, -999, -999, -999, -999, -999},
  110148. {-999, -999, -999, -999, -999, -999, -999, -999,
  110149. -999, -999, -999, -999, -112, -93, -81, -68,
  110150. -62, -60, -60, -57, -63, -70, -77, -82,
  110151. -90, -93, -98, -104, -109, -113, -999, -999,
  110152. -999, -999, -999, -999, -999, -999, -999, -999,
  110153. -999, -999, -999, -999, -999, -999, -999, -999,
  110154. -999, -999, -999, -999, -999, -999, -999, -999},
  110155. {-999, -999, -999, -999, -999, -999, -999, -999,
  110156. -999, -999, -999, -113, -100, -93, -84, -63,
  110157. -58, -48, -53, -54, -52, -52, -57, -64,
  110158. -66, -76, -83, -81, -85, -85, -90, -95,
  110159. -98, -101, -103, -106, -108, -111, -999, -999,
  110160. -999, -999, -999, -999, -999, -999, -999, -999,
  110161. -999, -999, -999, -999, -999, -999, -999, -999},
  110162. {-999, -999, -999, -999, -999, -999, -999, -999,
  110163. -999, -999, -999, -105, -95, -86, -74, -53,
  110164. -50, -38, -43, -49, -43, -42, -39, -39,
  110165. -46, -52, -57, -56, -72, -69, -74, -81,
  110166. -87, -92, -94, -97, -99, -102, -105, -108,
  110167. -999, -999, -999, -999, -999, -999, -999, -999,
  110168. -999, -999, -999, -999, -999, -999, -999, -999},
  110169. {-999, -999, -999, -999, -999, -999, -999, -999,
  110170. -999, -999, -108, -99, -90, -76, -66, -45,
  110171. -43, -41, -44, -47, -43, -47, -40, -30,
  110172. -31, -31, -39, -33, -40, -41, -43, -53,
  110173. -59, -70, -73, -77, -79, -82, -84, -87,
  110174. -999, -999, -999, -999, -999, -999, -999, -999,
  110175. -999, -999, -999, -999, -999, -999, -999, -999}},
  110176. /* 4000 Hz */
  110177. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110178. -999, -999, -999, -999, -999, -110, -91, -76,
  110179. -75, -85, -93, -98, -104, -110, -999, -999,
  110180. -999, -999, -999, -999, -999, -999, -999, -999,
  110181. -999, -999, -999, -999, -999, -999, -999, -999,
  110182. -999, -999, -999, -999, -999, -999, -999, -999,
  110183. -999, -999, -999, -999, -999, -999, -999, -999},
  110184. {-999, -999, -999, -999, -999, -999, -999, -999,
  110185. -999, -999, -999, -999, -999, -110, -91, -70,
  110186. -70, -75, -86, -89, -94, -98, -101, -106,
  110187. -110, -999, -999, -999, -999, -999, -999, -999,
  110188. -999, -999, -999, -999, -999, -999, -999, -999,
  110189. -999, -999, -999, -999, -999, -999, -999, -999,
  110190. -999, -999, -999, -999, -999, -999, -999, -999},
  110191. {-999, -999, -999, -999, -999, -999, -999, -999,
  110192. -999, -999, -999, -999, -110, -95, -80, -60,
  110193. -65, -64, -74, -83, -88, -91, -95, -99,
  110194. -103, -107, -110, -999, -999, -999, -999, -999,
  110195. -999, -999, -999, -999, -999, -999, -999, -999,
  110196. -999, -999, -999, -999, -999, -999, -999, -999,
  110197. -999, -999, -999, -999, -999, -999, -999, -999},
  110198. {-999, -999, -999, -999, -999, -999, -999, -999,
  110199. -999, -999, -999, -999, -110, -95, -80, -58,
  110200. -55, -49, -66, -68, -71, -78, -78, -80,
  110201. -88, -85, -89, -97, -100, -105, -110, -999,
  110202. -999, -999, -999, -999, -999, -999, -999, -999,
  110203. -999, -999, -999, -999, -999, -999, -999, -999,
  110204. -999, -999, -999, -999, -999, -999, -999, -999},
  110205. {-999, -999, -999, -999, -999, -999, -999, -999,
  110206. -999, -999, -999, -999, -110, -95, -80, -53,
  110207. -52, -41, -59, -59, -49, -58, -56, -63,
  110208. -86, -79, -90, -93, -98, -103, -107, -112,
  110209. -999, -999, -999, -999, -999, -999, -999, -999,
  110210. -999, -999, -999, -999, -999, -999, -999, -999,
  110211. -999, -999, -999, -999, -999, -999, -999, -999},
  110212. {-999, -999, -999, -999, -999, -999, -999, -999,
  110213. -999, -999, -999, -110, -97, -91, -73, -45,
  110214. -40, -33, -53, -61, -49, -54, -50, -50,
  110215. -60, -52, -67, -74, -81, -92, -96, -100,
  110216. -105, -110, -999, -999, -999, -999, -999, -999,
  110217. -999, -999, -999, -999, -999, -999, -999, -999,
  110218. -999, -999, -999, -999, -999, -999, -999, -999}},
  110219. /* 5657 Hz */
  110220. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110221. -999, -999, -999, -113, -106, -99, -92, -77,
  110222. -80, -88, -97, -106, -115, -999, -999, -999,
  110223. -999, -999, -999, -999, -999, -999, -999, -999,
  110224. -999, -999, -999, -999, -999, -999, -999, -999,
  110225. -999, -999, -999, -999, -999, -999, -999, -999,
  110226. -999, -999, -999, -999, -999, -999, -999, -999},
  110227. {-999, -999, -999, -999, -999, -999, -999, -999,
  110228. -999, -999, -116, -109, -102, -95, -89, -74,
  110229. -72, -88, -87, -95, -102, -109, -116, -999,
  110230. -999, -999, -999, -999, -999, -999, -999, -999,
  110231. -999, -999, -999, -999, -999, -999, -999, -999,
  110232. -999, -999, -999, -999, -999, -999, -999, -999,
  110233. -999, -999, -999, -999, -999, -999, -999, -999},
  110234. {-999, -999, -999, -999, -999, -999, -999, -999,
  110235. -999, -999, -116, -109, -102, -95, -89, -75,
  110236. -66, -74, -77, -78, -86, -87, -90, -96,
  110237. -105, -115, -999, -999, -999, -999, -999, -999,
  110238. -999, -999, -999, -999, -999, -999, -999, -999,
  110239. -999, -999, -999, -999, -999, -999, -999, -999,
  110240. -999, -999, -999, -999, -999, -999, -999, -999},
  110241. {-999, -999, -999, -999, -999, -999, -999, -999,
  110242. -999, -999, -115, -108, -101, -94, -88, -66,
  110243. -56, -61, -70, -65, -78, -72, -83, -84,
  110244. -93, -98, -105, -110, -999, -999, -999, -999,
  110245. -999, -999, -999, -999, -999, -999, -999, -999,
  110246. -999, -999, -999, -999, -999, -999, -999, -999,
  110247. -999, -999, -999, -999, -999, -999, -999, -999},
  110248. {-999, -999, -999, -999, -999, -999, -999, -999,
  110249. -999, -999, -110, -105, -95, -89, -82, -57,
  110250. -52, -52, -59, -56, -59, -58, -69, -67,
  110251. -88, -82, -82, -89, -94, -100, -108, -999,
  110252. -999, -999, -999, -999, -999, -999, -999, -999,
  110253. -999, -999, -999, -999, -999, -999, -999, -999,
  110254. -999, -999, -999, -999, -999, -999, -999, -999},
  110255. {-999, -999, -999, -999, -999, -999, -999, -999,
  110256. -999, -110, -101, -96, -90, -83, -77, -54,
  110257. -43, -38, -50, -48, -52, -48, -42, -42,
  110258. -51, -52, -53, -59, -65, -71, -78, -85,
  110259. -95, -999, -999, -999, -999, -999, -999, -999,
  110260. -999, -999, -999, -999, -999, -999, -999, -999,
  110261. -999, -999, -999, -999, -999, -999, -999, -999}},
  110262. /* 8000 Hz */
  110263. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110264. -999, -999, -999, -999, -120, -105, -86, -68,
  110265. -78, -79, -90, -100, -110, -999, -999, -999,
  110266. -999, -999, -999, -999, -999, -999, -999, -999,
  110267. -999, -999, -999, -999, -999, -999, -999, -999,
  110268. -999, -999, -999, -999, -999, -999, -999, -999,
  110269. -999, -999, -999, -999, -999, -999, -999, -999},
  110270. {-999, -999, -999, -999, -999, -999, -999, -999,
  110271. -999, -999, -999, -999, -120, -105, -86, -66,
  110272. -73, -77, -88, -96, -105, -115, -999, -999,
  110273. -999, -999, -999, -999, -999, -999, -999, -999,
  110274. -999, -999, -999, -999, -999, -999, -999, -999,
  110275. -999, -999, -999, -999, -999, -999, -999, -999,
  110276. -999, -999, -999, -999, -999, -999, -999, -999},
  110277. {-999, -999, -999, -999, -999, -999, -999, -999,
  110278. -999, -999, -999, -120, -105, -92, -80, -61,
  110279. -64, -68, -80, -87, -92, -100, -110, -999,
  110280. -999, -999, -999, -999, -999, -999, -999, -999,
  110281. -999, -999, -999, -999, -999, -999, -999, -999,
  110282. -999, -999, -999, -999, -999, -999, -999, -999,
  110283. -999, -999, -999, -999, -999, -999, -999, -999},
  110284. {-999, -999, -999, -999, -999, -999, -999, -999,
  110285. -999, -999, -999, -120, -104, -91, -79, -52,
  110286. -60, -54, -64, -69, -77, -80, -82, -84,
  110287. -85, -87, -88, -90, -999, -999, -999, -999,
  110288. -999, -999, -999, -999, -999, -999, -999, -999,
  110289. -999, -999, -999, -999, -999, -999, -999, -999,
  110290. -999, -999, -999, -999, -999, -999, -999, -999},
  110291. {-999, -999, -999, -999, -999, -999, -999, -999,
  110292. -999, -999, -999, -118, -100, -87, -77, -49,
  110293. -50, -44, -58, -61, -61, -67, -65, -62,
  110294. -62, -62, -65, -68, -999, -999, -999, -999,
  110295. -999, -999, -999, -999, -999, -999, -999, -999,
  110296. -999, -999, -999, -999, -999, -999, -999, -999,
  110297. -999, -999, -999, -999, -999, -999, -999, -999},
  110298. {-999, -999, -999, -999, -999, -999, -999, -999,
  110299. -999, -999, -999, -115, -98, -84, -62, -49,
  110300. -44, -38, -46, -49, -49, -46, -39, -37,
  110301. -39, -40, -42, -43, -999, -999, -999, -999,
  110302. -999, -999, -999, -999, -999, -999, -999, -999,
  110303. -999, -999, -999, -999, -999, -999, -999, -999,
  110304. -999, -999, -999, -999, -999, -999, -999, -999}},
  110305. /* 11314 Hz */
  110306. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110307. -999, -999, -999, -999, -999, -110, -88, -74,
  110308. -77, -82, -82, -85, -90, -94, -99, -104,
  110309. -999, -999, -999, -999, -999, -999, -999, -999,
  110310. -999, -999, -999, -999, -999, -999, -999, -999,
  110311. -999, -999, -999, -999, -999, -999, -999, -999,
  110312. -999, -999, -999, -999, -999, -999, -999, -999},
  110313. {-999, -999, -999, -999, -999, -999, -999, -999,
  110314. -999, -999, -999, -999, -999, -110, -88, -66,
  110315. -70, -81, -80, -81, -84, -88, -91, -93,
  110316. -999, -999, -999, -999, -999, -999, -999, -999,
  110317. -999, -999, -999, -999, -999, -999, -999, -999,
  110318. -999, -999, -999, -999, -999, -999, -999, -999,
  110319. -999, -999, -999, -999, -999, -999, -999, -999},
  110320. {-999, -999, -999, -999, -999, -999, -999, -999,
  110321. -999, -999, -999, -999, -999, -110, -88, -61,
  110322. -63, -70, -71, -74, -77, -80, -83, -85,
  110323. -999, -999, -999, -999, -999, -999, -999, -999,
  110324. -999, -999, -999, -999, -999, -999, -999, -999,
  110325. -999, -999, -999, -999, -999, -999, -999, -999,
  110326. -999, -999, -999, -999, -999, -999, -999, -999},
  110327. {-999, -999, -999, -999, -999, -999, -999, -999,
  110328. -999, -999, -999, -999, -999, -110, -86, -62,
  110329. -63, -62, -62, -58, -52, -50, -50, -52,
  110330. -54, -999, -999, -999, -999, -999, -999, -999,
  110331. -999, -999, -999, -999, -999, -999, -999, -999,
  110332. -999, -999, -999, -999, -999, -999, -999, -999,
  110333. -999, -999, -999, -999, -999, -999, -999, -999},
  110334. {-999, -999, -999, -999, -999, -999, -999, -999,
  110335. -999, -999, -999, -999, -118, -108, -84, -53,
  110336. -50, -50, -50, -55, -47, -45, -40, -40,
  110337. -40, -999, -999, -999, -999, -999, -999, -999,
  110338. -999, -999, -999, -999, -999, -999, -999, -999,
  110339. -999, -999, -999, -999, -999, -999, -999, -999,
  110340. -999, -999, -999, -999, -999, -999, -999, -999},
  110341. {-999, -999, -999, -999, -999, -999, -999, -999,
  110342. -999, -999, -999, -999, -118, -100, -73, -43,
  110343. -37, -42, -43, -53, -38, -37, -35, -35,
  110344. -38, -999, -999, -999, -999, -999, -999, -999,
  110345. -999, -999, -999, -999, -999, -999, -999, -999,
  110346. -999, -999, -999, -999, -999, -999, -999, -999,
  110347. -999, -999, -999, -999, -999, -999, -999, -999}},
  110348. /* 16000 Hz */
  110349. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110350. -999, -999, -999, -110, -100, -91, -84, -74,
  110351. -80, -80, -80, -80, -80, -999, -999, -999,
  110352. -999, -999, -999, -999, -999, -999, -999, -999,
  110353. -999, -999, -999, -999, -999, -999, -999, -999,
  110354. -999, -999, -999, -999, -999, -999, -999, -999,
  110355. -999, -999, -999, -999, -999, -999, -999, -999},
  110356. {-999, -999, -999, -999, -999, -999, -999, -999,
  110357. -999, -999, -999, -110, -100, -91, -84, -74,
  110358. -68, -68, -68, -68, -68, -999, -999, -999,
  110359. -999, -999, -999, -999, -999, -999, -999, -999,
  110360. -999, -999, -999, -999, -999, -999, -999, -999,
  110361. -999, -999, -999, -999, -999, -999, -999, -999,
  110362. -999, -999, -999, -999, -999, -999, -999, -999},
  110363. {-999, -999, -999, -999, -999, -999, -999, -999,
  110364. -999, -999, -999, -110, -100, -86, -78, -70,
  110365. -60, -45, -30, -21, -999, -999, -999, -999,
  110366. -999, -999, -999, -999, -999, -999, -999, -999,
  110367. -999, -999, -999, -999, -999, -999, -999, -999,
  110368. -999, -999, -999, -999, -999, -999, -999, -999,
  110369. -999, -999, -999, -999, -999, -999, -999, -999},
  110370. {-999, -999, -999, -999, -999, -999, -999, -999,
  110371. -999, -999, -999, -110, -100, -87, -78, -67,
  110372. -48, -38, -29, -21, -999, -999, -999, -999,
  110373. -999, -999, -999, -999, -999, -999, -999, -999,
  110374. -999, -999, -999, -999, -999, -999, -999, -999,
  110375. -999, -999, -999, -999, -999, -999, -999, -999,
  110376. -999, -999, -999, -999, -999, -999, -999, -999},
  110377. {-999, -999, -999, -999, -999, -999, -999, -999,
  110378. -999, -999, -999, -110, -100, -86, -69, -56,
  110379. -45, -35, -33, -29, -999, -999, -999, -999,
  110380. -999, -999, -999, -999, -999, -999, -999, -999,
  110381. -999, -999, -999, -999, -999, -999, -999, -999,
  110382. -999, -999, -999, -999, -999, -999, -999, -999,
  110383. -999, -999, -999, -999, -999, -999, -999, -999},
  110384. {-999, -999, -999, -999, -999, -999, -999, -999,
  110385. -999, -999, -999, -110, -100, -83, -71, -48,
  110386. -27, -38, -37, -34, -999, -999, -999, -999,
  110387. -999, -999, -999, -999, -999, -999, -999, -999,
  110388. -999, -999, -999, -999, -999, -999, -999, -999,
  110389. -999, -999, -999, -999, -999, -999, -999, -999,
  110390. -999, -999, -999, -999, -999, -999, -999, -999}}
  110391. };
  110392. #endif
  110393. /********* End of inlined file: masking.h *********/
  110394. #define NEGINF -9999.f
  110395. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  110396. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  110397. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  110398. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110399. vorbis_info_psy_global *gi=&ci->psy_g_param;
  110400. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  110401. look->channels=vi->channels;
  110402. look->ampmax=-9999.;
  110403. look->gi=gi;
  110404. return(look);
  110405. }
  110406. void _vp_global_free(vorbis_look_psy_global *look){
  110407. if(look){
  110408. memset(look,0,sizeof(*look));
  110409. _ogg_free(look);
  110410. }
  110411. }
  110412. void _vi_gpsy_free(vorbis_info_psy_global *i){
  110413. if(i){
  110414. memset(i,0,sizeof(*i));
  110415. _ogg_free(i);
  110416. }
  110417. }
  110418. void _vi_psy_free(vorbis_info_psy *i){
  110419. if(i){
  110420. memset(i,0,sizeof(*i));
  110421. _ogg_free(i);
  110422. }
  110423. }
  110424. static void min_curve(float *c,
  110425. float *c2){
  110426. int i;
  110427. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  110428. }
  110429. static void max_curve(float *c,
  110430. float *c2){
  110431. int i;
  110432. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  110433. }
  110434. static void attenuate_curve(float *c,float att){
  110435. int i;
  110436. for(i=0;i<EHMER_MAX;i++)
  110437. c[i]+=att;
  110438. }
  110439. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  110440. float center_boost, float center_decay_rate){
  110441. int i,j,k,m;
  110442. float ath[EHMER_MAX];
  110443. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  110444. float athc[P_LEVELS][EHMER_MAX];
  110445. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  110446. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  110447. memset(workc,0,sizeof(workc));
  110448. for(i=0;i<P_BANDS;i++){
  110449. /* we add back in the ATH to avoid low level curves falling off to
  110450. -infinity and unnecessarily cutting off high level curves in the
  110451. curve limiting (last step). */
  110452. /* A half-band's settings must be valid over the whole band, and
  110453. it's better to mask too little than too much */
  110454. int ath_offset=i*4;
  110455. for(j=0;j<EHMER_MAX;j++){
  110456. float min=999.;
  110457. for(k=0;k<4;k++)
  110458. if(j+k+ath_offset<MAX_ATH){
  110459. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  110460. }else{
  110461. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  110462. }
  110463. ath[j]=min;
  110464. }
  110465. /* copy curves into working space, replicate the 50dB curve to 30
  110466. and 40, replicate the 100dB curve to 110 */
  110467. for(j=0;j<6;j++)
  110468. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  110469. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  110470. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  110471. /* apply centered curve boost/decay */
  110472. for(j=0;j<P_LEVELS;j++){
  110473. for(k=0;k<EHMER_MAX;k++){
  110474. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  110475. if(adj<0. && center_boost>0)adj=0.;
  110476. if(adj>0. && center_boost<0)adj=0.;
  110477. workc[i][j][k]+=adj;
  110478. }
  110479. }
  110480. /* normalize curves so the driving amplitude is 0dB */
  110481. /* make temp curves with the ATH overlayed */
  110482. for(j=0;j<P_LEVELS;j++){
  110483. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  110484. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  110485. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  110486. max_curve(athc[j],workc[i][j]);
  110487. }
  110488. /* Now limit the louder curves.
  110489. the idea is this: We don't know what the playback attenuation
  110490. will be; 0dB SL moves every time the user twiddles the volume
  110491. knob. So that means we have to use a single 'most pessimal' curve
  110492. for all masking amplitudes, right? Wrong. The *loudest* sound
  110493. can be in (we assume) a range of ...+100dB] SL. However, sounds
  110494. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  110495. etc... */
  110496. for(j=1;j<P_LEVELS;j++){
  110497. min_curve(athc[j],athc[j-1]);
  110498. min_curve(workc[i][j],athc[j]);
  110499. }
  110500. }
  110501. for(i=0;i<P_BANDS;i++){
  110502. int hi_curve,lo_curve,bin;
  110503. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  110504. /* low frequency curves are measured with greater resolution than
  110505. the MDCT/FFT will actually give us; we want the curve applied
  110506. to the tone data to be pessimistic and thus apply the minimum
  110507. masking possible for a given bin. That means that a single bin
  110508. could span more than one octave and that the curve will be a
  110509. composite of multiple octaves. It also may mean that a single
  110510. bin may span > an eighth of an octave and that the eighth
  110511. octave values may also be composited. */
  110512. /* which octave curves will we be compositing? */
  110513. bin=floor(fromOC(i*.5)/binHz);
  110514. lo_curve= ceil(toOC(bin*binHz+1)*2);
  110515. hi_curve= floor(toOC((bin+1)*binHz)*2);
  110516. if(lo_curve>i)lo_curve=i;
  110517. if(lo_curve<0)lo_curve=0;
  110518. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  110519. for(m=0;m<P_LEVELS;m++){
  110520. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  110521. for(j=0;j<n;j++)brute_buffer[j]=999.;
  110522. /* render the curve into bins, then pull values back into curve.
  110523. The point is that any inherent subsampling aliasing results in
  110524. a safe minimum */
  110525. for(k=lo_curve;k<=hi_curve;k++){
  110526. int l=0;
  110527. for(j=0;j<EHMER_MAX;j++){
  110528. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  110529. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  110530. if(lo_bin<0)lo_bin=0;
  110531. if(lo_bin>n)lo_bin=n;
  110532. if(lo_bin<l)l=lo_bin;
  110533. if(hi_bin<0)hi_bin=0;
  110534. if(hi_bin>n)hi_bin=n;
  110535. for(;l<hi_bin && l<n;l++)
  110536. if(brute_buffer[l]>workc[k][m][j])
  110537. brute_buffer[l]=workc[k][m][j];
  110538. }
  110539. for(;l<n;l++)
  110540. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  110541. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  110542. }
  110543. /* be equally paranoid about being valid up to next half ocatve */
  110544. if(i+1<P_BANDS){
  110545. int l=0;
  110546. k=i+1;
  110547. for(j=0;j<EHMER_MAX;j++){
  110548. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  110549. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  110550. if(lo_bin<0)lo_bin=0;
  110551. if(lo_bin>n)lo_bin=n;
  110552. if(lo_bin<l)l=lo_bin;
  110553. if(hi_bin<0)hi_bin=0;
  110554. if(hi_bin>n)hi_bin=n;
  110555. for(;l<hi_bin && l<n;l++)
  110556. if(brute_buffer[l]>workc[k][m][j])
  110557. brute_buffer[l]=workc[k][m][j];
  110558. }
  110559. for(;l<n;l++)
  110560. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  110561. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  110562. }
  110563. for(j=0;j<EHMER_MAX;j++){
  110564. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  110565. if(bin<0){
  110566. ret[i][m][j+2]=-999.;
  110567. }else{
  110568. if(bin>=n){
  110569. ret[i][m][j+2]=-999.;
  110570. }else{
  110571. ret[i][m][j+2]=brute_buffer[bin];
  110572. }
  110573. }
  110574. }
  110575. /* add fenceposts */
  110576. for(j=0;j<EHMER_OFFSET;j++)
  110577. if(ret[i][m][j+2]>-200.f)break;
  110578. ret[i][m][0]=j;
  110579. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  110580. if(ret[i][m][j+2]>-200.f)
  110581. break;
  110582. ret[i][m][1]=j;
  110583. }
  110584. }
  110585. return(ret);
  110586. }
  110587. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110588. vorbis_info_psy_global *gi,int n,long rate){
  110589. long i,j,lo=-99,hi=1;
  110590. long maxoc;
  110591. memset(p,0,sizeof(*p));
  110592. p->eighth_octave_lines=gi->eighth_octave_lines;
  110593. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  110594. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  110595. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  110596. p->total_octave_lines=maxoc-p->firstoc+1;
  110597. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  110598. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  110599. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  110600. p->vi=vi;
  110601. p->n=n;
  110602. p->rate=rate;
  110603. /* AoTuV HF weighting */
  110604. p->m_val = 1.;
  110605. if(rate < 26000) p->m_val = 0;
  110606. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  110607. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  110608. /* set up the lookups for a given blocksize and sample rate */
  110609. for(i=0,j=0;i<MAX_ATH-1;i++){
  110610. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  110611. float base=ATH[i];
  110612. if(j<endpos){
  110613. float delta=(ATH[i+1]-base)/(endpos-j);
  110614. for(;j<endpos && j<n;j++){
  110615. p->ath[j]=base+100.;
  110616. base+=delta;
  110617. }
  110618. }
  110619. }
  110620. for(i=0;i<n;i++){
  110621. float bark=toBARK(rate/(2*n)*i);
  110622. for(;lo+vi->noisewindowlomin<i &&
  110623. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  110624. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  110625. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  110626. p->bark[i]=((lo-1)<<16)+(hi-1);
  110627. }
  110628. for(i=0;i<n;i++)
  110629. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  110630. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  110631. vi->tone_centerboost,vi->tone_decay);
  110632. /* set up rolling noise median */
  110633. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  110634. for(i=0;i<P_NOISECURVES;i++)
  110635. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  110636. for(i=0;i<n;i++){
  110637. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  110638. int inthalfoc;
  110639. float del;
  110640. if(halfoc<0)halfoc=0;
  110641. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  110642. inthalfoc=(int)halfoc;
  110643. del=halfoc-inthalfoc;
  110644. for(j=0;j<P_NOISECURVES;j++)
  110645. p->noiseoffset[j][i]=
  110646. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  110647. p->vi->noiseoff[j][inthalfoc+1]*del;
  110648. }
  110649. #if 0
  110650. {
  110651. static int ls=0;
  110652. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  110653. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  110654. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  110655. }
  110656. #endif
  110657. }
  110658. void _vp_psy_clear(vorbis_look_psy *p){
  110659. int i,j;
  110660. if(p){
  110661. if(p->ath)_ogg_free(p->ath);
  110662. if(p->octave)_ogg_free(p->octave);
  110663. if(p->bark)_ogg_free(p->bark);
  110664. if(p->tonecurves){
  110665. for(i=0;i<P_BANDS;i++){
  110666. for(j=0;j<P_LEVELS;j++){
  110667. _ogg_free(p->tonecurves[i][j]);
  110668. }
  110669. _ogg_free(p->tonecurves[i]);
  110670. }
  110671. _ogg_free(p->tonecurves);
  110672. }
  110673. if(p->noiseoffset){
  110674. for(i=0;i<P_NOISECURVES;i++){
  110675. _ogg_free(p->noiseoffset[i]);
  110676. }
  110677. _ogg_free(p->noiseoffset);
  110678. }
  110679. memset(p,0,sizeof(*p));
  110680. }
  110681. }
  110682. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  110683. static void seed_curve(float *seed,
  110684. const float **curves,
  110685. float amp,
  110686. int oc, int n,
  110687. int linesper,float dBoffset){
  110688. int i,post1;
  110689. int seedptr;
  110690. const float *posts,*curve;
  110691. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  110692. choice=max(choice,0);
  110693. choice=min(choice,P_LEVELS-1);
  110694. posts=curves[choice];
  110695. curve=posts+2;
  110696. post1=(int)posts[1];
  110697. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  110698. for(i=posts[0];i<post1;i++){
  110699. if(seedptr>0){
  110700. float lin=amp+curve[i];
  110701. if(seed[seedptr]<lin)seed[seedptr]=lin;
  110702. }
  110703. seedptr+=linesper;
  110704. if(seedptr>=n)break;
  110705. }
  110706. }
  110707. static void seed_loop(vorbis_look_psy *p,
  110708. const float ***curves,
  110709. const float *f,
  110710. const float *flr,
  110711. float *seed,
  110712. float specmax){
  110713. vorbis_info_psy *vi=p->vi;
  110714. long n=p->n,i;
  110715. float dBoffset=vi->max_curve_dB-specmax;
  110716. /* prime the working vector with peak values */
  110717. for(i=0;i<n;i++){
  110718. float max=f[i];
  110719. long oc=p->octave[i];
  110720. while(i+1<n && p->octave[i+1]==oc){
  110721. i++;
  110722. if(f[i]>max)max=f[i];
  110723. }
  110724. if(max+6.f>flr[i]){
  110725. oc=oc>>p->shiftoc;
  110726. if(oc>=P_BANDS)oc=P_BANDS-1;
  110727. if(oc<0)oc=0;
  110728. seed_curve(seed,
  110729. curves[oc],
  110730. max,
  110731. p->octave[i]-p->firstoc,
  110732. p->total_octave_lines,
  110733. p->eighth_octave_lines,
  110734. dBoffset);
  110735. }
  110736. }
  110737. }
  110738. static void seed_chase(float *seeds, int linesper, long n){
  110739. long *posstack=(long*)alloca(n*sizeof(*posstack));
  110740. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  110741. long stack=0;
  110742. long pos=0;
  110743. long i;
  110744. for(i=0;i<n;i++){
  110745. if(stack<2){
  110746. posstack[stack]=i;
  110747. ampstack[stack++]=seeds[i];
  110748. }else{
  110749. while(1){
  110750. if(seeds[i]<ampstack[stack-1]){
  110751. posstack[stack]=i;
  110752. ampstack[stack++]=seeds[i];
  110753. break;
  110754. }else{
  110755. if(i<posstack[stack-1]+linesper){
  110756. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  110757. i<posstack[stack-2]+linesper){
  110758. /* we completely overlap, making stack-1 irrelevant. pop it */
  110759. stack--;
  110760. continue;
  110761. }
  110762. }
  110763. posstack[stack]=i;
  110764. ampstack[stack++]=seeds[i];
  110765. break;
  110766. }
  110767. }
  110768. }
  110769. }
  110770. /* the stack now contains only the positions that are relevant. Scan
  110771. 'em straight through */
  110772. for(i=0;i<stack;i++){
  110773. long endpos;
  110774. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  110775. endpos=posstack[i+1];
  110776. }else{
  110777. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  110778. discarded in short frames */
  110779. }
  110780. if(endpos>n)endpos=n;
  110781. for(;pos<endpos;pos++)
  110782. seeds[pos]=ampstack[i];
  110783. }
  110784. /* there. Linear time. I now remember this was on a problem set I
  110785. had in Grad Skool... I didn't solve it at the time ;-) */
  110786. }
  110787. /* bleaugh, this is more complicated than it needs to be */
  110788. #include<stdio.h>
  110789. static void max_seeds(vorbis_look_psy *p,
  110790. float *seed,
  110791. float *flr){
  110792. long n=p->total_octave_lines;
  110793. int linesper=p->eighth_octave_lines;
  110794. long linpos=0;
  110795. long pos;
  110796. seed_chase(seed,linesper,n); /* for masking */
  110797. pos=p->octave[0]-p->firstoc-(linesper>>1);
  110798. while(linpos+1<p->n){
  110799. float minV=seed[pos];
  110800. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  110801. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  110802. while(pos+1<=end){
  110803. pos++;
  110804. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  110805. minV=seed[pos];
  110806. }
  110807. end=pos+p->firstoc;
  110808. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  110809. if(flr[linpos]<minV)flr[linpos]=minV;
  110810. }
  110811. {
  110812. float minV=seed[p->total_octave_lines-1];
  110813. for(;linpos<p->n;linpos++)
  110814. if(flr[linpos]<minV)flr[linpos]=minV;
  110815. }
  110816. }
  110817. static void bark_noise_hybridmp(int n,const long *b,
  110818. const float *f,
  110819. float *noise,
  110820. const float offset,
  110821. const int fixed){
  110822. float *N=(float*) alloca(n*sizeof(*N));
  110823. float *X=(float*) alloca(n*sizeof(*N));
  110824. float *XX=(float*) alloca(n*sizeof(*N));
  110825. float *Y=(float*) alloca(n*sizeof(*N));
  110826. float *XY=(float*) alloca(n*sizeof(*N));
  110827. float tN, tX, tXX, tY, tXY;
  110828. int i;
  110829. int lo, hi;
  110830. float R, A, B, D;
  110831. float w, x, y;
  110832. tN = tX = tXX = tY = tXY = 0.f;
  110833. y = f[0] + offset;
  110834. if (y < 1.f) y = 1.f;
  110835. w = y * y * .5;
  110836. tN += w;
  110837. tX += w;
  110838. tY += w * y;
  110839. N[0] = tN;
  110840. X[0] = tX;
  110841. XX[0] = tXX;
  110842. Y[0] = tY;
  110843. XY[0] = tXY;
  110844. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  110845. y = f[i] + offset;
  110846. if (y < 1.f) y = 1.f;
  110847. w = y * y;
  110848. tN += w;
  110849. tX += w * x;
  110850. tXX += w * x * x;
  110851. tY += w * y;
  110852. tXY += w * x * y;
  110853. N[i] = tN;
  110854. X[i] = tX;
  110855. XX[i] = tXX;
  110856. Y[i] = tY;
  110857. XY[i] = tXY;
  110858. }
  110859. for (i = 0, x = 0.f;; i++, x += 1.f) {
  110860. lo = b[i] >> 16;
  110861. if( lo>=0 ) break;
  110862. hi = b[i] & 0xffff;
  110863. tN = N[hi] + N[-lo];
  110864. tX = X[hi] - X[-lo];
  110865. tXX = XX[hi] + XX[-lo];
  110866. tY = Y[hi] + Y[-lo];
  110867. tXY = XY[hi] - XY[-lo];
  110868. A = tY * tXX - tX * tXY;
  110869. B = tN * tXY - tX * tY;
  110870. D = tN * tXX - tX * tX;
  110871. R = (A + x * B) / D;
  110872. if (R < 0.f)
  110873. R = 0.f;
  110874. noise[i] = R - offset;
  110875. }
  110876. for ( ;; i++, x += 1.f) {
  110877. lo = b[i] >> 16;
  110878. hi = b[i] & 0xffff;
  110879. if(hi>=n)break;
  110880. tN = N[hi] - N[lo];
  110881. tX = X[hi] - X[lo];
  110882. tXX = XX[hi] - XX[lo];
  110883. tY = Y[hi] - Y[lo];
  110884. tXY = XY[hi] - XY[lo];
  110885. A = tY * tXX - tX * tXY;
  110886. B = tN * tXY - tX * tY;
  110887. D = tN * tXX - tX * tX;
  110888. R = (A + x * B) / D;
  110889. if (R < 0.f) R = 0.f;
  110890. noise[i] = R - offset;
  110891. }
  110892. for ( ; i < n; i++, x += 1.f) {
  110893. R = (A + x * B) / D;
  110894. if (R < 0.f) R = 0.f;
  110895. noise[i] = R - offset;
  110896. }
  110897. if (fixed <= 0) return;
  110898. for (i = 0, x = 0.f;; i++, x += 1.f) {
  110899. hi = i + fixed / 2;
  110900. lo = hi - fixed;
  110901. if(lo>=0)break;
  110902. tN = N[hi] + N[-lo];
  110903. tX = X[hi] - X[-lo];
  110904. tXX = XX[hi] + XX[-lo];
  110905. tY = Y[hi] + Y[-lo];
  110906. tXY = XY[hi] - XY[-lo];
  110907. A = tY * tXX - tX * tXY;
  110908. B = tN * tXY - tX * tY;
  110909. D = tN * tXX - tX * tX;
  110910. R = (A + x * B) / D;
  110911. if (R - offset < noise[i]) noise[i] = R - offset;
  110912. }
  110913. for ( ;; i++, x += 1.f) {
  110914. hi = i + fixed / 2;
  110915. lo = hi - fixed;
  110916. if(hi>=n)break;
  110917. tN = N[hi] - N[lo];
  110918. tX = X[hi] - X[lo];
  110919. tXX = XX[hi] - XX[lo];
  110920. tY = Y[hi] - Y[lo];
  110921. tXY = XY[hi] - XY[lo];
  110922. A = tY * tXX - tX * tXY;
  110923. B = tN * tXY - tX * tY;
  110924. D = tN * tXX - tX * tX;
  110925. R = (A + x * B) / D;
  110926. if (R - offset < noise[i]) noise[i] = R - offset;
  110927. }
  110928. for ( ; i < n; i++, x += 1.f) {
  110929. R = (A + x * B) / D;
  110930. if (R - offset < noise[i]) noise[i] = R - offset;
  110931. }
  110932. }
  110933. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  110934. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  110935. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  110936. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  110937. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  110938. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  110939. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  110940. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  110941. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  110942. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  110943. 973377.F, 913981.F, 858210.F, 805842.F,
  110944. 756669.F, 710497.F, 667142.F, 626433.F,
  110945. 588208.F, 552316.F, 518613.F, 486967.F,
  110946. 457252.F, 429351.F, 403152.F, 378551.F,
  110947. 355452.F, 333762.F, 313396.F, 294273.F,
  110948. 276316.F, 259455.F, 243623.F, 228757.F,
  110949. 214798.F, 201691.F, 189384.F, 177828.F,
  110950. 166977.F, 156788.F, 147221.F, 138237.F,
  110951. 129802.F, 121881.F, 114444.F, 107461.F,
  110952. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  110953. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  110954. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  110955. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  110956. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  110957. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  110958. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  110959. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  110960. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  110961. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  110962. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  110963. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  110964. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  110965. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  110966. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  110967. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  110968. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  110969. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  110970. 1084.32F, 1018.15F, 956.024F, 897.687F,
  110971. 842.910F, 791.475F, 743.179F, 697.830F,
  110972. 655.249F, 615.265F, 577.722F, 542.469F,
  110973. 509.367F, 478.286F, 449.101F, 421.696F,
  110974. 395.964F, 371.803F, 349.115F, 327.812F,
  110975. 307.809F, 289.026F, 271.390F, 254.830F,
  110976. 239.280F, 224.679F, 210.969F, 198.096F,
  110977. 186.008F, 174.658F, 164.000F, 153.993F,
  110978. 144.596F, 135.773F, 127.488F, 119.708F,
  110979. 112.404F, 105.545F, 99.1046F, 93.0572F,
  110980. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  110981. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  110982. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  110983. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  110984. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  110985. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  110986. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  110987. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  110988. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  110989. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  110990. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  110991. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  110992. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  110993. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  110994. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  110995. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  110996. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  110997. 1.20790F, 1.13419F, 1.06499F, 1.F
  110998. };
  110999. void _vp_remove_floor(vorbis_look_psy *p,
  111000. float *mdct,
  111001. int *codedflr,
  111002. float *residue,
  111003. int sliding_lowpass){
  111004. int i,n=p->n;
  111005. if(sliding_lowpass>n)sliding_lowpass=n;
  111006. for(i=0;i<sliding_lowpass;i++){
  111007. residue[i]=
  111008. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  111009. }
  111010. for(;i<n;i++)
  111011. residue[i]=0.;
  111012. }
  111013. void _vp_noisemask(vorbis_look_psy *p,
  111014. float *logmdct,
  111015. float *logmask){
  111016. int i,n=p->n;
  111017. float *work=(float*) alloca(n*sizeof(*work));
  111018. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  111019. 140.,-1);
  111020. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  111021. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  111022. p->vi->noisewindowfixed);
  111023. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  111024. #if 0
  111025. {
  111026. static int seq=0;
  111027. float work2[n];
  111028. for(i=0;i<n;i++){
  111029. work2[i]=logmask[i]+work[i];
  111030. }
  111031. if(seq&1)
  111032. _analysis_output("median2R",seq/2,work,n,1,0,0);
  111033. else
  111034. _analysis_output("median2L",seq/2,work,n,1,0,0);
  111035. if(seq&1)
  111036. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  111037. else
  111038. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  111039. seq++;
  111040. }
  111041. #endif
  111042. for(i=0;i<n;i++){
  111043. int dB=logmask[i]+.5;
  111044. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  111045. if(dB<0)dB=0;
  111046. logmask[i]= work[i]+p->vi->noisecompand[dB];
  111047. }
  111048. }
  111049. void _vp_tonemask(vorbis_look_psy *p,
  111050. float *logfft,
  111051. float *logmask,
  111052. float global_specmax,
  111053. float local_specmax){
  111054. int i,n=p->n;
  111055. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  111056. float att=local_specmax+p->vi->ath_adjatt;
  111057. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  111058. /* set the ATH (floating below localmax, not global max by a
  111059. specified att) */
  111060. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  111061. for(i=0;i<n;i++)
  111062. logmask[i]=p->ath[i]+att;
  111063. /* tone masking */
  111064. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  111065. max_seeds(p,seed,logmask);
  111066. }
  111067. void _vp_offset_and_mix(vorbis_look_psy *p,
  111068. float *noise,
  111069. float *tone,
  111070. int offset_select,
  111071. float *logmask,
  111072. float *mdct,
  111073. float *logmdct){
  111074. int i,n=p->n;
  111075. float de, coeffi, cx;/* AoTuV */
  111076. float toneatt=p->vi->tone_masteratt[offset_select];
  111077. cx = p->m_val;
  111078. for(i=0;i<n;i++){
  111079. float val= noise[i]+p->noiseoffset[offset_select][i];
  111080. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  111081. logmask[i]=max(val,tone[i]+toneatt);
  111082. /* AoTuV */
  111083. /** @ M1 **
  111084. The following codes improve a noise problem.
  111085. A fundamental idea uses the value of masking and carries out
  111086. the relative compensation of the MDCT.
  111087. However, this code is not perfect and all noise problems cannot be solved.
  111088. by Aoyumi @ 2004/04/18
  111089. */
  111090. if(offset_select == 1) {
  111091. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  111092. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  111093. if(val > coeffi){
  111094. /* mdct value is > -17.2 dB below floor */
  111095. de = 1.0-((val-coeffi)*0.005*cx);
  111096. /* pro-rated attenuation:
  111097. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  111098. -0.77 dB boost if mdct value is 0dB (relative to floor)
  111099. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  111100. etc... */
  111101. if(de < 0) de = 0.0001;
  111102. }else
  111103. /* mdct value is <= -17.2 dB below floor */
  111104. de = 1.0-((val-coeffi)*0.0003*cx);
  111105. /* pro-rated attenuation:
  111106. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  111107. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  111108. etc... */
  111109. mdct[i] *= de;
  111110. }
  111111. }
  111112. }
  111113. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  111114. vorbis_info *vi=vd->vi;
  111115. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111116. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111117. int n=ci->blocksizes[vd->W]/2;
  111118. float secs=(float)n/vi->rate;
  111119. amp+=secs*gi->ampmax_att_per_sec;
  111120. if(amp<-9999)amp=-9999;
  111121. return(amp);
  111122. }
  111123. static void couple_lossless(float A, float B,
  111124. float *qA, float *qB){
  111125. int test1=fabs(*qA)>fabs(*qB);
  111126. test1-= fabs(*qA)<fabs(*qB);
  111127. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  111128. if(test1==1){
  111129. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  111130. }else{
  111131. float temp=*qB;
  111132. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  111133. *qA=temp;
  111134. }
  111135. if(*qB>fabs(*qA)*1.9999f){
  111136. *qB= -fabs(*qA)*2.f;
  111137. *qA= -*qA;
  111138. }
  111139. }
  111140. static float hypot_lookup[32]={
  111141. -0.009935, -0.011245, -0.012726, -0.014397,
  111142. -0.016282, -0.018407, -0.020800, -0.023494,
  111143. -0.026522, -0.029923, -0.033737, -0.038010,
  111144. -0.042787, -0.048121, -0.054064, -0.060671,
  111145. -0.068000, -0.076109, -0.085054, -0.094892,
  111146. -0.105675, -0.117451, -0.130260, -0.144134,
  111147. -0.159093, -0.175146, -0.192286, -0.210490,
  111148. -0.229718, -0.249913, -0.271001, -0.292893};
  111149. static void precomputed_couple_point(float premag,
  111150. int floorA,int floorB,
  111151. float *mag, float *ang){
  111152. int test=(floorA>floorB)-1;
  111153. int offset=31-abs(floorA-floorB);
  111154. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  111155. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  111156. *mag=premag*floormag;
  111157. *ang=0.f;
  111158. }
  111159. /* just like below, this is currently set up to only do
  111160. single-step-depth coupling. Otherwise, we'd have to do more
  111161. copying (which will be inevitable later) */
  111162. /* doing the real circular magnitude calculation is audibly superior
  111163. to (A+B)/sqrt(2) */
  111164. static float dipole_hypot(float a, float b){
  111165. if(a>0.){
  111166. if(b>0.)return sqrt(a*a+b*b);
  111167. if(a>-b)return sqrt(a*a-b*b);
  111168. return -sqrt(b*b-a*a);
  111169. }
  111170. if(b<0.)return -sqrt(a*a+b*b);
  111171. if(-a>b)return -sqrt(a*a-b*b);
  111172. return sqrt(b*b-a*a);
  111173. }
  111174. static float round_hypot(float a, float b){
  111175. if(a>0.){
  111176. if(b>0.)return sqrt(a*a+b*b);
  111177. if(a>-b)return sqrt(a*a+b*b);
  111178. return -sqrt(b*b+a*a);
  111179. }
  111180. if(b<0.)return -sqrt(a*a+b*b);
  111181. if(-a>b)return -sqrt(a*a+b*b);
  111182. return sqrt(b*b+a*a);
  111183. }
  111184. /* revert to round hypot for now */
  111185. float **_vp_quantize_couple_memo(vorbis_block *vb,
  111186. vorbis_info_psy_global *g,
  111187. vorbis_look_psy *p,
  111188. vorbis_info_mapping0 *vi,
  111189. float **mdct){
  111190. int i,j,n=p->n;
  111191. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111192. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111193. for(i=0;i<vi->coupling_steps;i++){
  111194. float *mdctM=mdct[vi->coupling_mag[i]];
  111195. float *mdctA=mdct[vi->coupling_ang[i]];
  111196. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111197. for(j=0;j<limit;j++)
  111198. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  111199. for(;j<n;j++)
  111200. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  111201. }
  111202. return(ret);
  111203. }
  111204. /* this is for per-channel noise normalization */
  111205. static int apsort(const void *a, const void *b){
  111206. float f1=fabs(**(float**)a);
  111207. float f2=fabs(**(float**)b);
  111208. return (f1<f2)-(f1>f2);
  111209. }
  111210. int **_vp_quantize_couple_sort(vorbis_block *vb,
  111211. vorbis_look_psy *p,
  111212. vorbis_info_mapping0 *vi,
  111213. float **mags){
  111214. if(p->vi->normal_point_p){
  111215. int i,j,k,n=p->n;
  111216. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111217. int partition=p->vi->normal_partition;
  111218. float **work=(float**) alloca(sizeof(*work)*partition);
  111219. for(i=0;i<vi->coupling_steps;i++){
  111220. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111221. for(j=0;j<n;j+=partition){
  111222. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  111223. qsort(work,partition,sizeof(*work),apsort);
  111224. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  111225. }
  111226. }
  111227. return(ret);
  111228. }
  111229. return(NULL);
  111230. }
  111231. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  111232. float *magnitudes,int *sortedindex){
  111233. int i,j,n=p->n;
  111234. vorbis_info_psy *vi=p->vi;
  111235. int partition=vi->normal_partition;
  111236. float **work=(float**) alloca(sizeof(*work)*partition);
  111237. int start=vi->normal_start;
  111238. for(j=start;j<n;j+=partition){
  111239. if(j+partition>n)partition=n-j;
  111240. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  111241. qsort(work,partition,sizeof(*work),apsort);
  111242. for(i=0;i<partition;i++){
  111243. sortedindex[i+j-start]=work[i]-magnitudes;
  111244. }
  111245. }
  111246. }
  111247. void _vp_noise_normalize(vorbis_look_psy *p,
  111248. float *in,float *out,int *sortedindex){
  111249. int flag=0,i,j=0,n=p->n;
  111250. vorbis_info_psy *vi=p->vi;
  111251. int partition=vi->normal_partition;
  111252. int start=vi->normal_start;
  111253. if(start>n)start=n;
  111254. if(vi->normal_channel_p){
  111255. for(;j<start;j++)
  111256. out[j]=rint(in[j]);
  111257. for(;j+partition<=n;j+=partition){
  111258. float acc=0.;
  111259. int k;
  111260. for(i=j;i<j+partition;i++)
  111261. acc+=in[i]*in[i];
  111262. for(i=0;i<partition;i++){
  111263. k=sortedindex[i+j-start];
  111264. if(in[k]*in[k]>=.25f){
  111265. out[k]=rint(in[k]);
  111266. acc-=in[k]*in[k];
  111267. flag=1;
  111268. }else{
  111269. if(acc<vi->normal_thresh)break;
  111270. out[k]=unitnorm(in[k]);
  111271. acc-=1.;
  111272. }
  111273. }
  111274. for(;i<partition;i++){
  111275. k=sortedindex[i+j-start];
  111276. out[k]=0.;
  111277. }
  111278. }
  111279. }
  111280. for(;j<n;j++)
  111281. out[j]=rint(in[j]);
  111282. }
  111283. void _vp_couple(int blobno,
  111284. vorbis_info_psy_global *g,
  111285. vorbis_look_psy *p,
  111286. vorbis_info_mapping0 *vi,
  111287. float **res,
  111288. float **mag_memo,
  111289. int **mag_sort,
  111290. int **ifloor,
  111291. int *nonzero,
  111292. int sliding_lowpass){
  111293. int i,j,k,n=p->n;
  111294. /* perform any requested channel coupling */
  111295. /* point stereo can only be used in a first stage (in this encoder)
  111296. because of the dependency on floor lookups */
  111297. for(i=0;i<vi->coupling_steps;i++){
  111298. /* once we're doing multistage coupling in which a channel goes
  111299. through more than one coupling step, the floor vector
  111300. magnitudes will also have to be recalculated an propogated
  111301. along with PCM. Right now, we're not (that will wait until 5.1
  111302. most likely), so the code isn't here yet. The memory management
  111303. here is all assuming single depth couplings anyway. */
  111304. /* make sure coupling a zero and a nonzero channel results in two
  111305. nonzero channels. */
  111306. if(nonzero[vi->coupling_mag[i]] ||
  111307. nonzero[vi->coupling_ang[i]]){
  111308. float *rM=res[vi->coupling_mag[i]];
  111309. float *rA=res[vi->coupling_ang[i]];
  111310. float *qM=rM+n;
  111311. float *qA=rA+n;
  111312. int *floorM=ifloor[vi->coupling_mag[i]];
  111313. int *floorA=ifloor[vi->coupling_ang[i]];
  111314. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  111315. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  111316. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  111317. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  111318. int pointlimit=limit;
  111319. nonzero[vi->coupling_mag[i]]=1;
  111320. nonzero[vi->coupling_ang[i]]=1;
  111321. /* The threshold of a stereo is changed with the size of n */
  111322. if(n > 1000)
  111323. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  111324. for(j=0;j<p->n;j+=partition){
  111325. float acc=0.f;
  111326. for(k=0;k<partition;k++){
  111327. int l=k+j;
  111328. if(l<sliding_lowpass){
  111329. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  111330. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  111331. precomputed_couple_point(mag_memo[i][l],
  111332. floorM[l],floorA[l],
  111333. qM+l,qA+l);
  111334. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  111335. }else{
  111336. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  111337. }
  111338. }else{
  111339. qM[l]=0.;
  111340. qA[l]=0.;
  111341. }
  111342. }
  111343. if(p->vi->normal_point_p){
  111344. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  111345. int l=mag_sort[i][j+k];
  111346. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  111347. qM[l]=unitnorm(qM[l]);
  111348. acc-=1.f;
  111349. }
  111350. }
  111351. }
  111352. }
  111353. }
  111354. }
  111355. }
  111356. /* AoTuV */
  111357. /** @ M2 **
  111358. The boost problem by the combination of noise normalization and point stereo is eased.
  111359. However, this is a temporary patch.
  111360. by Aoyumi @ 2004/04/18
  111361. */
  111362. void hf_reduction(vorbis_info_psy_global *g,
  111363. vorbis_look_psy *p,
  111364. vorbis_info_mapping0 *vi,
  111365. float **mdct){
  111366. int i,j,n=p->n, de=0.3*p->m_val;
  111367. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111368. for(i=0; i<vi->coupling_steps; i++){
  111369. /* for(j=start; j<limit; j++){} // ???*/
  111370. for(j=limit; j<n; j++)
  111371. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  111372. }
  111373. }
  111374. #endif
  111375. /********* End of inlined file: psy.c *********/
  111376. /********* Start of inlined file: registry.c *********/
  111377. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111378. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111379. // tasks..
  111380. #ifdef _MSC_VER
  111381. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111382. #endif
  111383. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111384. #if JUCE_USE_OGGVORBIS
  111385. /* seems like major overkill now; the backend numbers will grow into
  111386. the infrastructure soon enough */
  111387. extern vorbis_func_floor floor0_exportbundle;
  111388. extern vorbis_func_floor floor1_exportbundle;
  111389. extern vorbis_func_residue residue0_exportbundle;
  111390. extern vorbis_func_residue residue1_exportbundle;
  111391. extern vorbis_func_residue residue2_exportbundle;
  111392. extern vorbis_func_mapping mapping0_exportbundle;
  111393. vorbis_func_floor *_floor_P[]={
  111394. &floor0_exportbundle,
  111395. &floor1_exportbundle,
  111396. };
  111397. vorbis_func_residue *_residue_P[]={
  111398. &residue0_exportbundle,
  111399. &residue1_exportbundle,
  111400. &residue2_exportbundle,
  111401. };
  111402. vorbis_func_mapping *_mapping_P[]={
  111403. &mapping0_exportbundle,
  111404. };
  111405. #endif
  111406. /********* End of inlined file: registry.c *********/
  111407. /********* Start of inlined file: res0.c *********/
  111408. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  111409. encode/decode loops are coded for clarity and performance is not
  111410. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  111411. it's slow. */
  111412. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111413. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111414. // tasks..
  111415. #ifdef _MSC_VER
  111416. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111417. #endif
  111418. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111419. #if JUCE_USE_OGGVORBIS
  111420. #include <stdlib.h>
  111421. #include <string.h>
  111422. #include <math.h>
  111423. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111424. #include <stdio.h>
  111425. #endif
  111426. typedef struct {
  111427. vorbis_info_residue0 *info;
  111428. int parts;
  111429. int stages;
  111430. codebook *fullbooks;
  111431. codebook *phrasebook;
  111432. codebook ***partbooks;
  111433. int partvals;
  111434. int **decodemap;
  111435. long postbits;
  111436. long phrasebits;
  111437. long frames;
  111438. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  111439. int train_seq;
  111440. long *training_data[8][64];
  111441. float training_max[8][64];
  111442. float training_min[8][64];
  111443. float tmin;
  111444. float tmax;
  111445. #endif
  111446. } vorbis_look_residue0;
  111447. void res0_free_info(vorbis_info_residue *i){
  111448. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  111449. if(info){
  111450. memset(info,0,sizeof(*info));
  111451. _ogg_free(info);
  111452. }
  111453. }
  111454. void res0_free_look(vorbis_look_residue *i){
  111455. int j;
  111456. if(i){
  111457. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  111458. #ifdef TRAIN_RES
  111459. {
  111460. int j,k,l;
  111461. for(j=0;j<look->parts;j++){
  111462. /*fprintf(stderr,"partition %d: ",j);*/
  111463. for(k=0;k<8;k++)
  111464. if(look->training_data[k][j]){
  111465. char buffer[80];
  111466. FILE *of;
  111467. codebook *statebook=look->partbooks[j][k];
  111468. /* long and short into the same bucket by current convention */
  111469. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  111470. of=fopen(buffer,"a");
  111471. for(l=0;l<statebook->entries;l++)
  111472. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  111473. fclose(of);
  111474. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  111475. look->training_min[k][j],look->training_max[k][j]);*/
  111476. _ogg_free(look->training_data[k][j]);
  111477. look->training_data[k][j]=NULL;
  111478. }
  111479. /*fprintf(stderr,"\n");*/
  111480. }
  111481. }
  111482. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  111483. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  111484. (float)look->phrasebits/look->frames,
  111485. (float)look->postbits/look->frames,
  111486. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111487. #endif
  111488. /*vorbis_info_residue0 *info=look->info;
  111489. fprintf(stderr,
  111490. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  111491. "(%g/frame) \n",look->frames,look->phrasebits,
  111492. look->resbitsflat,
  111493. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  111494. for(j=0;j<look->parts;j++){
  111495. long acc=0;
  111496. fprintf(stderr,"\t[%d] == ",j);
  111497. for(k=0;k<look->stages;k++)
  111498. if((info->secondstages[j]>>k)&1){
  111499. fprintf(stderr,"%ld,",look->resbits[j][k]);
  111500. acc+=look->resbits[j][k];
  111501. }
  111502. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  111503. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  111504. }
  111505. fprintf(stderr,"\n");*/
  111506. for(j=0;j<look->parts;j++)
  111507. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  111508. _ogg_free(look->partbooks);
  111509. for(j=0;j<look->partvals;j++)
  111510. _ogg_free(look->decodemap[j]);
  111511. _ogg_free(look->decodemap);
  111512. memset(look,0,sizeof(*look));
  111513. _ogg_free(look);
  111514. }
  111515. }
  111516. static int icount(unsigned int v){
  111517. int ret=0;
  111518. while(v){
  111519. ret+=v&1;
  111520. v>>=1;
  111521. }
  111522. return(ret);
  111523. }
  111524. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  111525. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  111526. int j,acc=0;
  111527. oggpack_write(opb,info->begin,24);
  111528. oggpack_write(opb,info->end,24);
  111529. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  111530. code with a partitioned book */
  111531. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  111532. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  111533. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  111534. bitmask of one indicates this partition class has bits to write
  111535. this pass */
  111536. for(j=0;j<info->partitions;j++){
  111537. if(ilog(info->secondstages[j])>3){
  111538. /* yes, this is a minor hack due to not thinking ahead */
  111539. oggpack_write(opb,info->secondstages[j],3);
  111540. oggpack_write(opb,1,1);
  111541. oggpack_write(opb,info->secondstages[j]>>3,5);
  111542. }else
  111543. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  111544. acc+=icount(info->secondstages[j]);
  111545. }
  111546. for(j=0;j<acc;j++)
  111547. oggpack_write(opb,info->booklist[j],8);
  111548. }
  111549. /* vorbis_info is for range checking */
  111550. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  111551. int j,acc=0;
  111552. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  111553. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111554. info->begin=oggpack_read(opb,24);
  111555. info->end=oggpack_read(opb,24);
  111556. info->grouping=oggpack_read(opb,24)+1;
  111557. info->partitions=oggpack_read(opb,6)+1;
  111558. info->groupbook=oggpack_read(opb,8);
  111559. for(j=0;j<info->partitions;j++){
  111560. int cascade=oggpack_read(opb,3);
  111561. if(oggpack_read(opb,1))
  111562. cascade|=(oggpack_read(opb,5)<<3);
  111563. info->secondstages[j]=cascade;
  111564. acc+=icount(cascade);
  111565. }
  111566. for(j=0;j<acc;j++)
  111567. info->booklist[j]=oggpack_read(opb,8);
  111568. if(info->groupbook>=ci->books)goto errout;
  111569. for(j=0;j<acc;j++)
  111570. if(info->booklist[j]>=ci->books)goto errout;
  111571. return(info);
  111572. errout:
  111573. res0_free_info(info);
  111574. return(NULL);
  111575. }
  111576. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  111577. vorbis_info_residue *vr){
  111578. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  111579. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  111580. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  111581. int j,k,acc=0;
  111582. int dim;
  111583. int maxstage=0;
  111584. look->info=info;
  111585. look->parts=info->partitions;
  111586. look->fullbooks=ci->fullbooks;
  111587. look->phrasebook=ci->fullbooks+info->groupbook;
  111588. dim=look->phrasebook->dim;
  111589. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  111590. for(j=0;j<look->parts;j++){
  111591. int stages=ilog(info->secondstages[j]);
  111592. if(stages){
  111593. if(stages>maxstage)maxstage=stages;
  111594. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  111595. for(k=0;k<stages;k++)
  111596. if(info->secondstages[j]&(1<<k)){
  111597. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  111598. #ifdef TRAIN_RES
  111599. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  111600. sizeof(***look->training_data));
  111601. #endif
  111602. }
  111603. }
  111604. }
  111605. look->partvals=rint(pow((float)look->parts,(float)dim));
  111606. look->stages=maxstage;
  111607. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  111608. for(j=0;j<look->partvals;j++){
  111609. long val=j;
  111610. long mult=look->partvals/look->parts;
  111611. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  111612. for(k=0;k<dim;k++){
  111613. long deco=val/mult;
  111614. val-=deco*mult;
  111615. mult/=look->parts;
  111616. look->decodemap[j][k]=deco;
  111617. }
  111618. }
  111619. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111620. {
  111621. static int train_seq=0;
  111622. look->train_seq=train_seq++;
  111623. }
  111624. #endif
  111625. return(look);
  111626. }
  111627. /* break an abstraction and copy some code for performance purposes */
  111628. static int local_book_besterror(codebook *book,float *a){
  111629. int dim=book->dim,i,k,o;
  111630. int best=0;
  111631. encode_aux_threshmatch *tt=book->c->thresh_tree;
  111632. /* find the quant val of each scalar */
  111633. for(k=0,o=dim;k<dim;++k){
  111634. float val=a[--o];
  111635. i=tt->threshvals>>1;
  111636. if(val<tt->quantthresh[i]){
  111637. if(val<tt->quantthresh[i-1]){
  111638. for(--i;i>0;--i)
  111639. if(val>=tt->quantthresh[i-1])
  111640. break;
  111641. }
  111642. }else{
  111643. for(++i;i<tt->threshvals-1;++i)
  111644. if(val<tt->quantthresh[i])break;
  111645. }
  111646. best=(best*tt->quantvals)+tt->quantmap[i];
  111647. }
  111648. /* regular lattices are easy :-) */
  111649. if(book->c->lengthlist[best]<=0){
  111650. const static_codebook *c=book->c;
  111651. int i,j;
  111652. float bestf=0.f;
  111653. float *e=book->valuelist;
  111654. best=-1;
  111655. for(i=0;i<book->entries;i++){
  111656. if(c->lengthlist[i]>0){
  111657. float thisx=0.f;
  111658. for(j=0;j<dim;j++){
  111659. float val=(e[j]-a[j]);
  111660. thisx+=val*val;
  111661. }
  111662. if(best==-1 || thisx<bestf){
  111663. bestf=thisx;
  111664. best=i;
  111665. }
  111666. }
  111667. e+=dim;
  111668. }
  111669. }
  111670. {
  111671. float *ptr=book->valuelist+best*dim;
  111672. for(i=0;i<dim;i++)
  111673. *a++ -= *ptr++;
  111674. }
  111675. return(best);
  111676. }
  111677. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  111678. codebook *book,long *acc){
  111679. int i,bits=0;
  111680. int dim=book->dim;
  111681. int step=n/dim;
  111682. for(i=0;i<step;i++){
  111683. int entry=local_book_besterror(book,vec+i*dim);
  111684. #ifdef TRAIN_RES
  111685. acc[entry]++;
  111686. #endif
  111687. bits+=vorbis_book_encode(book,entry,opb);
  111688. }
  111689. return(bits);
  111690. }
  111691. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  111692. float **in,int ch){
  111693. long i,j,k;
  111694. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111695. vorbis_info_residue0 *info=look->info;
  111696. /* move all this setup out later */
  111697. int samples_per_partition=info->grouping;
  111698. int possible_partitions=info->partitions;
  111699. int n=info->end-info->begin;
  111700. int partvals=n/samples_per_partition;
  111701. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  111702. float scale=100./samples_per_partition;
  111703. /* we find the partition type for each partition of each
  111704. channel. We'll go back and do the interleaved encoding in a
  111705. bit. For now, clarity */
  111706. for(i=0;i<ch;i++){
  111707. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  111708. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  111709. }
  111710. for(i=0;i<partvals;i++){
  111711. int offset=i*samples_per_partition+info->begin;
  111712. for(j=0;j<ch;j++){
  111713. float max=0.;
  111714. float ent=0.;
  111715. for(k=0;k<samples_per_partition;k++){
  111716. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  111717. ent+=fabs(rint(in[j][offset+k]));
  111718. }
  111719. ent*=scale;
  111720. for(k=0;k<possible_partitions-1;k++)
  111721. if(max<=info->classmetric1[k] &&
  111722. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  111723. break;
  111724. partword[j][i]=k;
  111725. }
  111726. }
  111727. #ifdef TRAIN_RESAUX
  111728. {
  111729. FILE *of;
  111730. char buffer[80];
  111731. for(i=0;i<ch;i++){
  111732. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  111733. of=fopen(buffer,"a");
  111734. for(j=0;j<partvals;j++)
  111735. fprintf(of,"%ld, ",partword[i][j]);
  111736. fprintf(of,"\n");
  111737. fclose(of);
  111738. }
  111739. }
  111740. #endif
  111741. look->frames++;
  111742. return(partword);
  111743. }
  111744. /* designed for stereo or other modes where the partition size is an
  111745. integer multiple of the number of channels encoded in the current
  111746. submap */
  111747. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  111748. int ch){
  111749. long i,j,k,l;
  111750. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111751. vorbis_info_residue0 *info=look->info;
  111752. /* move all this setup out later */
  111753. int samples_per_partition=info->grouping;
  111754. int possible_partitions=info->partitions;
  111755. int n=info->end-info->begin;
  111756. int partvals=n/samples_per_partition;
  111757. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  111758. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111759. FILE *of;
  111760. char buffer[80];
  111761. #endif
  111762. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  111763. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  111764. for(i=0,l=info->begin/ch;i<partvals;i++){
  111765. float magmax=0.f;
  111766. float angmax=0.f;
  111767. for(j=0;j<samples_per_partition;j+=ch){
  111768. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  111769. for(k=1;k<ch;k++)
  111770. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  111771. l++;
  111772. }
  111773. for(j=0;j<possible_partitions-1;j++)
  111774. if(magmax<=info->classmetric1[j] &&
  111775. angmax<=info->classmetric2[j])
  111776. break;
  111777. partword[0][i]=j;
  111778. }
  111779. #ifdef TRAIN_RESAUX
  111780. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  111781. of=fopen(buffer,"a");
  111782. for(i=0;i<partvals;i++)
  111783. fprintf(of,"%ld, ",partword[0][i]);
  111784. fprintf(of,"\n");
  111785. fclose(of);
  111786. #endif
  111787. look->frames++;
  111788. return(partword);
  111789. }
  111790. static int _01forward(oggpack_buffer *opb,
  111791. vorbis_block *vb,vorbis_look_residue *vl,
  111792. float **in,int ch,
  111793. long **partword,
  111794. int (*encode)(oggpack_buffer *,float *,int,
  111795. codebook *,long *)){
  111796. long i,j,k,s;
  111797. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111798. vorbis_info_residue0 *info=look->info;
  111799. /* move all this setup out later */
  111800. int samples_per_partition=info->grouping;
  111801. int possible_partitions=info->partitions;
  111802. int partitions_per_word=look->phrasebook->dim;
  111803. int n=info->end-info->begin;
  111804. int partvals=n/samples_per_partition;
  111805. long resbits[128];
  111806. long resvals[128];
  111807. #ifdef TRAIN_RES
  111808. for(i=0;i<ch;i++)
  111809. for(j=info->begin;j<info->end;j++){
  111810. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  111811. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  111812. }
  111813. #endif
  111814. memset(resbits,0,sizeof(resbits));
  111815. memset(resvals,0,sizeof(resvals));
  111816. /* we code the partition words for each channel, then the residual
  111817. words for a partition per channel until we've written all the
  111818. residual words for that partition word. Then write the next
  111819. partition channel words... */
  111820. for(s=0;s<look->stages;s++){
  111821. for(i=0;i<partvals;){
  111822. /* first we encode a partition codeword for each channel */
  111823. if(s==0){
  111824. for(j=0;j<ch;j++){
  111825. long val=partword[j][i];
  111826. for(k=1;k<partitions_per_word;k++){
  111827. val*=possible_partitions;
  111828. if(i+k<partvals)
  111829. val+=partword[j][i+k];
  111830. }
  111831. /* training hack */
  111832. if(val<look->phrasebook->entries)
  111833. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  111834. #if 0 /*def TRAIN_RES*/
  111835. else
  111836. fprintf(stderr,"!");
  111837. #endif
  111838. }
  111839. }
  111840. /* now we encode interleaved residual values for the partitions */
  111841. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  111842. long offset=i*samples_per_partition+info->begin;
  111843. for(j=0;j<ch;j++){
  111844. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  111845. if(info->secondstages[partword[j][i]]&(1<<s)){
  111846. codebook *statebook=look->partbooks[partword[j][i]][s];
  111847. if(statebook){
  111848. int ret;
  111849. long *accumulator=NULL;
  111850. #ifdef TRAIN_RES
  111851. accumulator=look->training_data[s][partword[j][i]];
  111852. {
  111853. int l;
  111854. float *samples=in[j]+offset;
  111855. for(l=0;l<samples_per_partition;l++){
  111856. if(samples[l]<look->training_min[s][partword[j][i]])
  111857. look->training_min[s][partword[j][i]]=samples[l];
  111858. if(samples[l]>look->training_max[s][partword[j][i]])
  111859. look->training_max[s][partword[j][i]]=samples[l];
  111860. }
  111861. }
  111862. #endif
  111863. ret=encode(opb,in[j]+offset,samples_per_partition,
  111864. statebook,accumulator);
  111865. look->postbits+=ret;
  111866. resbits[partword[j][i]]+=ret;
  111867. }
  111868. }
  111869. }
  111870. }
  111871. }
  111872. }
  111873. /*{
  111874. long total=0;
  111875. long totalbits=0;
  111876. fprintf(stderr,"%d :: ",vb->mode);
  111877. for(k=0;k<possible_partitions;k++){
  111878. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  111879. total+=resvals[k];
  111880. totalbits+=resbits[k];
  111881. }
  111882. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  111883. }*/
  111884. return(0);
  111885. }
  111886. /* a truncated packet here just means 'stop working'; it's not an error */
  111887. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  111888. float **in,int ch,
  111889. long (*decodepart)(codebook *, float *,
  111890. oggpack_buffer *,int)){
  111891. long i,j,k,l,s;
  111892. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111893. vorbis_info_residue0 *info=look->info;
  111894. /* move all this setup out later */
  111895. int samples_per_partition=info->grouping;
  111896. int partitions_per_word=look->phrasebook->dim;
  111897. int n=info->end-info->begin;
  111898. int partvals=n/samples_per_partition;
  111899. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  111900. int ***partword=(int***)alloca(ch*sizeof(*partword));
  111901. for(j=0;j<ch;j++)
  111902. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  111903. for(s=0;s<look->stages;s++){
  111904. /* each loop decodes on partition codeword containing
  111905. partitions_pre_word partitions */
  111906. for(i=0,l=0;i<partvals;l++){
  111907. if(s==0){
  111908. /* fetch the partition word for each channel */
  111909. for(j=0;j<ch;j++){
  111910. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  111911. if(temp==-1)goto eopbreak;
  111912. partword[j][l]=look->decodemap[temp];
  111913. if(partword[j][l]==NULL)goto errout;
  111914. }
  111915. }
  111916. /* now we decode residual values for the partitions */
  111917. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  111918. for(j=0;j<ch;j++){
  111919. long offset=info->begin+i*samples_per_partition;
  111920. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  111921. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  111922. if(stagebook){
  111923. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  111924. samples_per_partition)==-1)goto eopbreak;
  111925. }
  111926. }
  111927. }
  111928. }
  111929. }
  111930. errout:
  111931. eopbreak:
  111932. return(0);
  111933. }
  111934. #if 0
  111935. /* residue 0 and 1 are just slight variants of one another. 0 is
  111936. interleaved, 1 is not */
  111937. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  111938. float **in,int *nonzero,int ch){
  111939. /* we encode only the nonzero parts of a bundle */
  111940. int i,used=0;
  111941. for(i=0;i<ch;i++)
  111942. if(nonzero[i])
  111943. in[used++]=in[i];
  111944. if(used)
  111945. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  111946. return(_01class(vb,vl,in,used));
  111947. else
  111948. return(0);
  111949. }
  111950. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  111951. float **in,float **out,int *nonzero,int ch,
  111952. long **partword){
  111953. /* we encode only the nonzero parts of a bundle */
  111954. int i,j,used=0,n=vb->pcmend/2;
  111955. for(i=0;i<ch;i++)
  111956. if(nonzero[i]){
  111957. if(out)
  111958. for(j=0;j<n;j++)
  111959. out[i][j]+=in[i][j];
  111960. in[used++]=in[i];
  111961. }
  111962. if(used){
  111963. int ret=_01forward(vb,vl,in,used,partword,
  111964. _interleaved_encodepart);
  111965. if(out){
  111966. used=0;
  111967. for(i=0;i<ch;i++)
  111968. if(nonzero[i]){
  111969. for(j=0;j<n;j++)
  111970. out[i][j]-=in[used][j];
  111971. used++;
  111972. }
  111973. }
  111974. return(ret);
  111975. }else{
  111976. return(0);
  111977. }
  111978. }
  111979. #endif
  111980. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  111981. float **in,int *nonzero,int ch){
  111982. int i,used=0;
  111983. for(i=0;i<ch;i++)
  111984. if(nonzero[i])
  111985. in[used++]=in[i];
  111986. if(used)
  111987. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  111988. else
  111989. return(0);
  111990. }
  111991. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  111992. float **in,float **out,int *nonzero,int ch,
  111993. long **partword){
  111994. int i,j,used=0,n=vb->pcmend/2;
  111995. for(i=0;i<ch;i++)
  111996. if(nonzero[i]){
  111997. if(out)
  111998. for(j=0;j<n;j++)
  111999. out[i][j]+=in[i][j];
  112000. in[used++]=in[i];
  112001. }
  112002. if(used){
  112003. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  112004. if(out){
  112005. used=0;
  112006. for(i=0;i<ch;i++)
  112007. if(nonzero[i]){
  112008. for(j=0;j<n;j++)
  112009. out[i][j]-=in[used][j];
  112010. used++;
  112011. }
  112012. }
  112013. return(ret);
  112014. }else{
  112015. return(0);
  112016. }
  112017. }
  112018. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  112019. float **in,int *nonzero,int ch){
  112020. int i,used=0;
  112021. for(i=0;i<ch;i++)
  112022. if(nonzero[i])
  112023. in[used++]=in[i];
  112024. if(used)
  112025. return(_01class(vb,vl,in,used));
  112026. else
  112027. return(0);
  112028. }
  112029. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112030. float **in,int *nonzero,int ch){
  112031. int i,used=0;
  112032. for(i=0;i<ch;i++)
  112033. if(nonzero[i])
  112034. in[used++]=in[i];
  112035. if(used)
  112036. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  112037. else
  112038. return(0);
  112039. }
  112040. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  112041. float **in,int *nonzero,int ch){
  112042. int i,used=0;
  112043. for(i=0;i<ch;i++)
  112044. if(nonzero[i])used++;
  112045. if(used)
  112046. return(_2class(vb,vl,in,ch));
  112047. else
  112048. return(0);
  112049. }
  112050. /* res2 is slightly more different; all the channels are interleaved
  112051. into a single vector and encoded. */
  112052. int res2_forward(oggpack_buffer *opb,
  112053. vorbis_block *vb,vorbis_look_residue *vl,
  112054. float **in,float **out,int *nonzero,int ch,
  112055. long **partword){
  112056. long i,j,k,n=vb->pcmend/2,used=0;
  112057. /* don't duplicate the code; use a working vector hack for now and
  112058. reshape ourselves into a single channel res1 */
  112059. /* ugly; reallocs for each coupling pass :-( */
  112060. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  112061. for(i=0;i<ch;i++){
  112062. float *pcm=in[i];
  112063. if(nonzero[i])used++;
  112064. for(j=0,k=i;j<n;j++,k+=ch)
  112065. work[k]=pcm[j];
  112066. }
  112067. if(used){
  112068. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  112069. /* update the sofar vector */
  112070. if(out){
  112071. for(i=0;i<ch;i++){
  112072. float *pcm=in[i];
  112073. float *sofar=out[i];
  112074. for(j=0,k=i;j<n;j++,k+=ch)
  112075. sofar[j]+=pcm[j]-work[k];
  112076. }
  112077. }
  112078. return(ret);
  112079. }else{
  112080. return(0);
  112081. }
  112082. }
  112083. /* duplicate code here as speed is somewhat more important */
  112084. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112085. float **in,int *nonzero,int ch){
  112086. long i,k,l,s;
  112087. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112088. vorbis_info_residue0 *info=look->info;
  112089. /* move all this setup out later */
  112090. int samples_per_partition=info->grouping;
  112091. int partitions_per_word=look->phrasebook->dim;
  112092. int n=info->end-info->begin;
  112093. int partvals=n/samples_per_partition;
  112094. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112095. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  112096. for(i=0;i<ch;i++)if(nonzero[i])break;
  112097. if(i==ch)return(0); /* no nonzero vectors */
  112098. for(s=0;s<look->stages;s++){
  112099. for(i=0,l=0;i<partvals;l++){
  112100. if(s==0){
  112101. /* fetch the partition word */
  112102. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112103. if(temp==-1)goto eopbreak;
  112104. partword[l]=look->decodemap[temp];
  112105. if(partword[l]==NULL)goto errout;
  112106. }
  112107. /* now we decode residual values for the partitions */
  112108. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112109. if(info->secondstages[partword[l][k]]&(1<<s)){
  112110. codebook *stagebook=look->partbooks[partword[l][k]][s];
  112111. if(stagebook){
  112112. if(vorbis_book_decodevv_add(stagebook,in,
  112113. i*samples_per_partition+info->begin,ch,
  112114. &vb->opb,samples_per_partition)==-1)
  112115. goto eopbreak;
  112116. }
  112117. }
  112118. }
  112119. }
  112120. errout:
  112121. eopbreak:
  112122. return(0);
  112123. }
  112124. vorbis_func_residue residue0_exportbundle={
  112125. NULL,
  112126. &res0_unpack,
  112127. &res0_look,
  112128. &res0_free_info,
  112129. &res0_free_look,
  112130. NULL,
  112131. NULL,
  112132. &res0_inverse
  112133. };
  112134. vorbis_func_residue residue1_exportbundle={
  112135. &res0_pack,
  112136. &res0_unpack,
  112137. &res0_look,
  112138. &res0_free_info,
  112139. &res0_free_look,
  112140. &res1_class,
  112141. &res1_forward,
  112142. &res1_inverse
  112143. };
  112144. vorbis_func_residue residue2_exportbundle={
  112145. &res0_pack,
  112146. &res0_unpack,
  112147. &res0_look,
  112148. &res0_free_info,
  112149. &res0_free_look,
  112150. &res2_class,
  112151. &res2_forward,
  112152. &res2_inverse
  112153. };
  112154. #endif
  112155. /********* End of inlined file: res0.c *********/
  112156. /********* Start of inlined file: sharedbook.c *********/
  112157. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112158. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112159. // tasks..
  112160. #ifdef _MSC_VER
  112161. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112162. #endif
  112163. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112164. #if JUCE_USE_OGGVORBIS
  112165. #include <stdlib.h>
  112166. #include <math.h>
  112167. #include <string.h>
  112168. /**** pack/unpack helpers ******************************************/
  112169. int _ilog(unsigned int v){
  112170. int ret=0;
  112171. while(v){
  112172. ret++;
  112173. v>>=1;
  112174. }
  112175. return(ret);
  112176. }
  112177. /* 32 bit float (not IEEE; nonnormalized mantissa +
  112178. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  112179. Why not IEEE? It's just not that important here. */
  112180. #define VQ_FEXP 10
  112181. #define VQ_FMAN 21
  112182. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  112183. /* doesn't currently guard under/overflow */
  112184. long _float32_pack(float val){
  112185. int sign=0;
  112186. long exp;
  112187. long mant;
  112188. if(val<0){
  112189. sign=0x80000000;
  112190. val= -val;
  112191. }
  112192. exp= floor(log(val)/log(2.f));
  112193. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  112194. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  112195. return(sign|exp|mant);
  112196. }
  112197. float _float32_unpack(long val){
  112198. double mant=val&0x1fffff;
  112199. int sign=val&0x80000000;
  112200. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  112201. if(sign)mant= -mant;
  112202. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  112203. }
  112204. /* given a list of word lengths, generate a list of codewords. Works
  112205. for length ordered or unordered, always assigns the lowest valued
  112206. codewords first. Extended to handle unused entries (length 0) */
  112207. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  112208. long i,j,count=0;
  112209. ogg_uint32_t marker[33];
  112210. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  112211. memset(marker,0,sizeof(marker));
  112212. for(i=0;i<n;i++){
  112213. long length=l[i];
  112214. if(length>0){
  112215. ogg_uint32_t entry=marker[length];
  112216. /* when we claim a node for an entry, we also claim the nodes
  112217. below it (pruning off the imagined tree that may have dangled
  112218. from it) as well as blocking the use of any nodes directly
  112219. above for leaves */
  112220. /* update ourself */
  112221. if(length<32 && (entry>>length)){
  112222. /* error condition; the lengths must specify an overpopulated tree */
  112223. _ogg_free(r);
  112224. return(NULL);
  112225. }
  112226. r[count++]=entry;
  112227. /* Look to see if the next shorter marker points to the node
  112228. above. if so, update it and repeat. */
  112229. {
  112230. for(j=length;j>0;j--){
  112231. if(marker[j]&1){
  112232. /* have to jump branches */
  112233. if(j==1)
  112234. marker[1]++;
  112235. else
  112236. marker[j]=marker[j-1]<<1;
  112237. break; /* invariant says next upper marker would already
  112238. have been moved if it was on the same path */
  112239. }
  112240. marker[j]++;
  112241. }
  112242. }
  112243. /* prune the tree; the implicit invariant says all the longer
  112244. markers were dangling from our just-taken node. Dangle them
  112245. from our *new* node. */
  112246. for(j=length+1;j<33;j++)
  112247. if((marker[j]>>1) == entry){
  112248. entry=marker[j];
  112249. marker[j]=marker[j-1]<<1;
  112250. }else
  112251. break;
  112252. }else
  112253. if(sparsecount==0)count++;
  112254. }
  112255. /* bitreverse the words because our bitwise packer/unpacker is LSb
  112256. endian */
  112257. for(i=0,count=0;i<n;i++){
  112258. ogg_uint32_t temp=0;
  112259. for(j=0;j<l[i];j++){
  112260. temp<<=1;
  112261. temp|=(r[count]>>j)&1;
  112262. }
  112263. if(sparsecount){
  112264. if(l[i])
  112265. r[count++]=temp;
  112266. }else
  112267. r[count++]=temp;
  112268. }
  112269. return(r);
  112270. }
  112271. /* there might be a straightforward one-line way to do the below
  112272. that's portable and totally safe against roundoff, but I haven't
  112273. thought of it. Therefore, we opt on the side of caution */
  112274. long _book_maptype1_quantvals(const static_codebook *b){
  112275. long vals=floor(pow((float)b->entries,1.f/b->dim));
  112276. /* the above *should* be reliable, but we'll not assume that FP is
  112277. ever reliable when bitstream sync is at stake; verify via integer
  112278. means that vals really is the greatest value of dim for which
  112279. vals^b->bim <= b->entries */
  112280. /* treat the above as an initial guess */
  112281. while(1){
  112282. long acc=1;
  112283. long acc1=1;
  112284. int i;
  112285. for(i=0;i<b->dim;i++){
  112286. acc*=vals;
  112287. acc1*=vals+1;
  112288. }
  112289. if(acc<=b->entries && acc1>b->entries){
  112290. return(vals);
  112291. }else{
  112292. if(acc>b->entries){
  112293. vals--;
  112294. }else{
  112295. vals++;
  112296. }
  112297. }
  112298. }
  112299. }
  112300. /* unpack the quantized list of values for encode/decode ***********/
  112301. /* we need to deal with two map types: in map type 1, the values are
  112302. generated algorithmically (each column of the vector counts through
  112303. the values in the quant vector). in map type 2, all the values came
  112304. in in an explicit list. Both value lists must be unpacked */
  112305. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  112306. long j,k,count=0;
  112307. if(b->maptype==1 || b->maptype==2){
  112308. int quantvals;
  112309. float mindel=_float32_unpack(b->q_min);
  112310. float delta=_float32_unpack(b->q_delta);
  112311. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  112312. /* maptype 1 and 2 both use a quantized value vector, but
  112313. different sizes */
  112314. switch(b->maptype){
  112315. case 1:
  112316. /* most of the time, entries%dimensions == 0, but we need to be
  112317. well defined. We define that the possible vales at each
  112318. scalar is values == entries/dim. If entries%dim != 0, we'll
  112319. have 'too few' values (values*dim<entries), which means that
  112320. we'll have 'left over' entries; left over entries use zeroed
  112321. values (and are wasted). So don't generate codebooks like
  112322. that */
  112323. quantvals=_book_maptype1_quantvals(b);
  112324. for(j=0;j<b->entries;j++){
  112325. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  112326. float last=0.f;
  112327. int indexdiv=1;
  112328. for(k=0;k<b->dim;k++){
  112329. int index= (j/indexdiv)%quantvals;
  112330. float val=b->quantlist[index];
  112331. val=fabs(val)*delta+mindel+last;
  112332. if(b->q_sequencep)last=val;
  112333. if(sparsemap)
  112334. r[sparsemap[count]*b->dim+k]=val;
  112335. else
  112336. r[count*b->dim+k]=val;
  112337. indexdiv*=quantvals;
  112338. }
  112339. count++;
  112340. }
  112341. }
  112342. break;
  112343. case 2:
  112344. for(j=0;j<b->entries;j++){
  112345. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  112346. float last=0.f;
  112347. for(k=0;k<b->dim;k++){
  112348. float val=b->quantlist[j*b->dim+k];
  112349. val=fabs(val)*delta+mindel+last;
  112350. if(b->q_sequencep)last=val;
  112351. if(sparsemap)
  112352. r[sparsemap[count]*b->dim+k]=val;
  112353. else
  112354. r[count*b->dim+k]=val;
  112355. }
  112356. count++;
  112357. }
  112358. }
  112359. break;
  112360. }
  112361. return(r);
  112362. }
  112363. return(NULL);
  112364. }
  112365. void vorbis_staticbook_clear(static_codebook *b){
  112366. if(b->allocedp){
  112367. if(b->quantlist)_ogg_free(b->quantlist);
  112368. if(b->lengthlist)_ogg_free(b->lengthlist);
  112369. if(b->nearest_tree){
  112370. _ogg_free(b->nearest_tree->ptr0);
  112371. _ogg_free(b->nearest_tree->ptr1);
  112372. _ogg_free(b->nearest_tree->p);
  112373. _ogg_free(b->nearest_tree->q);
  112374. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  112375. _ogg_free(b->nearest_tree);
  112376. }
  112377. if(b->thresh_tree){
  112378. _ogg_free(b->thresh_tree->quantthresh);
  112379. _ogg_free(b->thresh_tree->quantmap);
  112380. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  112381. _ogg_free(b->thresh_tree);
  112382. }
  112383. memset(b,0,sizeof(*b));
  112384. }
  112385. }
  112386. void vorbis_staticbook_destroy(static_codebook *b){
  112387. if(b->allocedp){
  112388. vorbis_staticbook_clear(b);
  112389. _ogg_free(b);
  112390. }
  112391. }
  112392. void vorbis_book_clear(codebook *b){
  112393. /* static book is not cleared; we're likely called on the lookup and
  112394. the static codebook belongs to the info struct */
  112395. if(b->valuelist)_ogg_free(b->valuelist);
  112396. if(b->codelist)_ogg_free(b->codelist);
  112397. if(b->dec_index)_ogg_free(b->dec_index);
  112398. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  112399. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  112400. memset(b,0,sizeof(*b));
  112401. }
  112402. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  112403. memset(c,0,sizeof(*c));
  112404. c->c=s;
  112405. c->entries=s->entries;
  112406. c->used_entries=s->entries;
  112407. c->dim=s->dim;
  112408. c->codelist=_make_words(s->lengthlist,s->entries,0);
  112409. c->valuelist=_book_unquantize(s,s->entries,NULL);
  112410. return(0);
  112411. }
  112412. static int sort32a(const void *a,const void *b){
  112413. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  112414. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  112415. }
  112416. /* decode codebook arrangement is more heavily optimized than encode */
  112417. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  112418. int i,j,n=0,tabn;
  112419. int *sortindex;
  112420. memset(c,0,sizeof(*c));
  112421. /* count actually used entries */
  112422. for(i=0;i<s->entries;i++)
  112423. if(s->lengthlist[i]>0)
  112424. n++;
  112425. c->entries=s->entries;
  112426. c->used_entries=n;
  112427. c->dim=s->dim;
  112428. /* two different remappings go on here.
  112429. First, we collapse the likely sparse codebook down only to
  112430. actually represented values/words. This collapsing needs to be
  112431. indexed as map-valueless books are used to encode original entry
  112432. positions as integers.
  112433. Second, we reorder all vectors, including the entry index above,
  112434. by sorted bitreversed codeword to allow treeless decode. */
  112435. {
  112436. /* perform sort */
  112437. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  112438. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  112439. if(codes==NULL)goto err_out;
  112440. for(i=0;i<n;i++){
  112441. codes[i]=bitreverse(codes[i]);
  112442. codep[i]=codes+i;
  112443. }
  112444. qsort(codep,n,sizeof(*codep),sort32a);
  112445. sortindex=(int*)alloca(n*sizeof(*sortindex));
  112446. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  112447. /* the index is a reverse index */
  112448. for(i=0;i<n;i++){
  112449. int position=codep[i]-codes;
  112450. sortindex[position]=i;
  112451. }
  112452. for(i=0;i<n;i++)
  112453. c->codelist[sortindex[i]]=codes[i];
  112454. _ogg_free(codes);
  112455. }
  112456. c->valuelist=_book_unquantize(s,n,sortindex);
  112457. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  112458. for(n=0,i=0;i<s->entries;i++)
  112459. if(s->lengthlist[i]>0)
  112460. c->dec_index[sortindex[n++]]=i;
  112461. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  112462. for(n=0,i=0;i<s->entries;i++)
  112463. if(s->lengthlist[i]>0)
  112464. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  112465. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  112466. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  112467. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  112468. tabn=1<<c->dec_firsttablen;
  112469. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  112470. c->dec_maxlength=0;
  112471. for(i=0;i<n;i++){
  112472. if(c->dec_maxlength<c->dec_codelengths[i])
  112473. c->dec_maxlength=c->dec_codelengths[i];
  112474. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  112475. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  112476. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  112477. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  112478. }
  112479. }
  112480. /* now fill in 'unused' entries in the firsttable with hi/lo search
  112481. hints for the non-direct-hits */
  112482. {
  112483. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  112484. long lo=0,hi=0;
  112485. for(i=0;i<tabn;i++){
  112486. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  112487. if(c->dec_firsttable[bitreverse(word)]==0){
  112488. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  112489. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  112490. /* we only actually have 15 bits per hint to play with here.
  112491. In order to overflow gracefully (nothing breaks, efficiency
  112492. just drops), encode as the difference from the extremes. */
  112493. {
  112494. unsigned long loval=lo;
  112495. unsigned long hival=n-hi;
  112496. if(loval>0x7fff)loval=0x7fff;
  112497. if(hival>0x7fff)hival=0x7fff;
  112498. c->dec_firsttable[bitreverse(word)]=
  112499. 0x80000000UL | (loval<<15) | hival;
  112500. }
  112501. }
  112502. }
  112503. }
  112504. return(0);
  112505. err_out:
  112506. vorbis_book_clear(c);
  112507. return(-1);
  112508. }
  112509. static float _dist(int el,float *ref, float *b,int step){
  112510. int i;
  112511. float acc=0.f;
  112512. for(i=0;i<el;i++){
  112513. float val=(ref[i]-b[i*step]);
  112514. acc+=val*val;
  112515. }
  112516. return(acc);
  112517. }
  112518. int _best(codebook *book, float *a, int step){
  112519. encode_aux_threshmatch *tt=book->c->thresh_tree;
  112520. #if 0
  112521. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  112522. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  112523. #endif
  112524. int dim=book->dim;
  112525. int k,o;
  112526. /*int savebest=-1;
  112527. float saverr;*/
  112528. /* do we have a threshhold encode hint? */
  112529. if(tt){
  112530. int index=0,i;
  112531. /* find the quant val of each scalar */
  112532. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  112533. i=tt->threshvals>>1;
  112534. if(a[o]<tt->quantthresh[i]){
  112535. for(;i>0;i--)
  112536. if(a[o]>=tt->quantthresh[i-1])
  112537. break;
  112538. }else{
  112539. for(i++;i<tt->threshvals-1;i++)
  112540. if(a[o]<tt->quantthresh[i])break;
  112541. }
  112542. index=(index*tt->quantvals)+tt->quantmap[i];
  112543. }
  112544. /* regular lattices are easy :-) */
  112545. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  112546. use a decision tree after all
  112547. and fall through*/
  112548. return(index);
  112549. }
  112550. #if 0
  112551. /* do we have a pigeonhole encode hint? */
  112552. if(pt){
  112553. const static_codebook *c=book->c;
  112554. int i,besti=-1;
  112555. float best=0.f;
  112556. int entry=0;
  112557. /* dealing with sequentialness is a pain in the ass */
  112558. if(c->q_sequencep){
  112559. int pv;
  112560. long mul=1;
  112561. float qlast=0;
  112562. for(k=0,o=0;k<dim;k++,o+=step){
  112563. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  112564. if(pv<0 || pv>=pt->mapentries)break;
  112565. entry+=pt->pigeonmap[pv]*mul;
  112566. mul*=pt->quantvals;
  112567. qlast+=pv*pt->del+pt->min;
  112568. }
  112569. }else{
  112570. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  112571. int pv=(int)((a[o]-pt->min)/pt->del);
  112572. if(pv<0 || pv>=pt->mapentries)break;
  112573. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  112574. }
  112575. }
  112576. /* must be within the pigeonholable range; if we quant outside (or
  112577. in an entry that we define no list for), brute force it */
  112578. if(k==dim && pt->fitlength[entry]){
  112579. /* search the abbreviated list */
  112580. long *list=pt->fitlist+pt->fitmap[entry];
  112581. for(i=0;i<pt->fitlength[entry];i++){
  112582. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  112583. if(besti==-1 || this<best){
  112584. best=this;
  112585. besti=list[i];
  112586. }
  112587. }
  112588. return(besti);
  112589. }
  112590. }
  112591. if(nt){
  112592. /* optimized using the decision tree */
  112593. while(1){
  112594. float c=0.f;
  112595. float *p=book->valuelist+nt->p[ptr];
  112596. float *q=book->valuelist+nt->q[ptr];
  112597. for(k=0,o=0;k<dim;k++,o+=step)
  112598. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  112599. if(c>0.f) /* in A */
  112600. ptr= -nt->ptr0[ptr];
  112601. else /* in B */
  112602. ptr= -nt->ptr1[ptr];
  112603. if(ptr<=0)break;
  112604. }
  112605. return(-ptr);
  112606. }
  112607. #endif
  112608. /* brute force it! */
  112609. {
  112610. const static_codebook *c=book->c;
  112611. int i,besti=-1;
  112612. float best=0.f;
  112613. float *e=book->valuelist;
  112614. for(i=0;i<book->entries;i++){
  112615. if(c->lengthlist[i]>0){
  112616. float thisx=_dist(dim,e,a,step);
  112617. if(besti==-1 || thisx<best){
  112618. best=thisx;
  112619. besti=i;
  112620. }
  112621. }
  112622. e+=dim;
  112623. }
  112624. /*if(savebest!=-1 && savebest!=besti){
  112625. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  112626. "original:");
  112627. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  112628. fprintf(stderr,"\n"
  112629. "pigeonhole (entry %d, err %g):",savebest,saverr);
  112630. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  112631. (book->valuelist+savebest*dim)[i]);
  112632. fprintf(stderr,"\n"
  112633. "bruteforce (entry %d, err %g):",besti,best);
  112634. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  112635. (book->valuelist+besti*dim)[i]);
  112636. fprintf(stderr,"\n");
  112637. }*/
  112638. return(besti);
  112639. }
  112640. }
  112641. long vorbis_book_codeword(codebook *book,int entry){
  112642. if(book->c) /* only use with encode; decode optimizations are
  112643. allowed to break this */
  112644. return book->codelist[entry];
  112645. return -1;
  112646. }
  112647. long vorbis_book_codelen(codebook *book,int entry){
  112648. if(book->c) /* only use with encode; decode optimizations are
  112649. allowed to break this */
  112650. return book->c->lengthlist[entry];
  112651. return -1;
  112652. }
  112653. #ifdef _V_SELFTEST
  112654. /* Unit tests of the dequantizer; this stuff will be OK
  112655. cross-platform, I simply want to be sure that special mapping cases
  112656. actually work properly; a bug could go unnoticed for a while */
  112657. #include <stdio.h>
  112658. /* cases:
  112659. no mapping
  112660. full, explicit mapping
  112661. algorithmic mapping
  112662. nonsequential
  112663. sequential
  112664. */
  112665. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  112666. static long partial_quantlist1[]={0,7,2};
  112667. /* no mapping */
  112668. static_codebook test1={
  112669. 4,16,
  112670. NULL,
  112671. 0,
  112672. 0,0,0,0,
  112673. NULL,
  112674. NULL,NULL
  112675. };
  112676. static float *test1_result=NULL;
  112677. /* linear, full mapping, nonsequential */
  112678. static_codebook test2={
  112679. 4,3,
  112680. NULL,
  112681. 2,
  112682. -533200896,1611661312,4,0,
  112683. full_quantlist1,
  112684. NULL,NULL
  112685. };
  112686. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  112687. /* linear, full mapping, sequential */
  112688. static_codebook test3={
  112689. 4,3,
  112690. NULL,
  112691. 2,
  112692. -533200896,1611661312,4,1,
  112693. full_quantlist1,
  112694. NULL,NULL
  112695. };
  112696. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  112697. /* linear, algorithmic mapping, nonsequential */
  112698. static_codebook test4={
  112699. 3,27,
  112700. NULL,
  112701. 1,
  112702. -533200896,1611661312,4,0,
  112703. partial_quantlist1,
  112704. NULL,NULL
  112705. };
  112706. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  112707. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  112708. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  112709. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  112710. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  112711. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  112712. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  112713. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  112714. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  112715. /* linear, algorithmic mapping, sequential */
  112716. static_codebook test5={
  112717. 3,27,
  112718. NULL,
  112719. 1,
  112720. -533200896,1611661312,4,1,
  112721. partial_quantlist1,
  112722. NULL,NULL
  112723. };
  112724. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  112725. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  112726. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  112727. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  112728. -3, 1, 5, 4, 8,12, -1, 3, 7,
  112729. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  112730. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  112731. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  112732. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  112733. void run_test(static_codebook *b,float *comp){
  112734. float *out=_book_unquantize(b,b->entries,NULL);
  112735. int i;
  112736. if(comp){
  112737. if(!out){
  112738. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  112739. exit(1);
  112740. }
  112741. for(i=0;i<b->entries*b->dim;i++)
  112742. if(fabs(out[i]-comp[i])>.0001){
  112743. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  112744. "position %d, %g != %g\n",i,out[i],comp[i]);
  112745. exit(1);
  112746. }
  112747. }else{
  112748. if(out){
  112749. fprintf(stderr,"_book_unquantize returned a value array: \n"
  112750. " correct result should have been NULL\n");
  112751. exit(1);
  112752. }
  112753. }
  112754. }
  112755. int main(){
  112756. /* run the nine dequant tests, and compare to the hand-rolled results */
  112757. fprintf(stderr,"Dequant test 1... ");
  112758. run_test(&test1,test1_result);
  112759. fprintf(stderr,"OK\nDequant test 2... ");
  112760. run_test(&test2,test2_result);
  112761. fprintf(stderr,"OK\nDequant test 3... ");
  112762. run_test(&test3,test3_result);
  112763. fprintf(stderr,"OK\nDequant test 4... ");
  112764. run_test(&test4,test4_result);
  112765. fprintf(stderr,"OK\nDequant test 5... ");
  112766. run_test(&test5,test5_result);
  112767. fprintf(stderr,"OK\n\n");
  112768. return(0);
  112769. }
  112770. #endif
  112771. #endif
  112772. /********* End of inlined file: sharedbook.c *********/
  112773. /********* Start of inlined file: smallft.c *********/
  112774. /* FFT implementation from OggSquish, minus cosine transforms,
  112775. * minus all but radix 2/4 case. In Vorbis we only need this
  112776. * cut-down version.
  112777. *
  112778. * To do more than just power-of-two sized vectors, see the full
  112779. * version I wrote for NetLib.
  112780. *
  112781. * Note that the packing is a little strange; rather than the FFT r/i
  112782. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  112783. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  112784. * FORTRAN version
  112785. */
  112786. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112787. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112788. // tasks..
  112789. #ifdef _MSC_VER
  112790. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112791. #endif
  112792. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112793. #if JUCE_USE_OGGVORBIS
  112794. #include <stdlib.h>
  112795. #include <string.h>
  112796. #include <math.h>
  112797. static void drfti1(int n, float *wa, int *ifac){
  112798. static int ntryh[4] = { 4,2,3,5 };
  112799. static float tpi = 6.28318530717958648f;
  112800. float arg,argh,argld,fi;
  112801. int ntry=0,i,j=-1;
  112802. int k1, l1, l2, ib;
  112803. int ld, ii, ip, is, nq, nr;
  112804. int ido, ipm, nfm1;
  112805. int nl=n;
  112806. int nf=0;
  112807. L101:
  112808. j++;
  112809. if (j < 4)
  112810. ntry=ntryh[j];
  112811. else
  112812. ntry+=2;
  112813. L104:
  112814. nq=nl/ntry;
  112815. nr=nl-ntry*nq;
  112816. if (nr!=0) goto L101;
  112817. nf++;
  112818. ifac[nf+1]=ntry;
  112819. nl=nq;
  112820. if(ntry!=2)goto L107;
  112821. if(nf==1)goto L107;
  112822. for (i=1;i<nf;i++){
  112823. ib=nf-i+1;
  112824. ifac[ib+1]=ifac[ib];
  112825. }
  112826. ifac[2] = 2;
  112827. L107:
  112828. if(nl!=1)goto L104;
  112829. ifac[0]=n;
  112830. ifac[1]=nf;
  112831. argh=tpi/n;
  112832. is=0;
  112833. nfm1=nf-1;
  112834. l1=1;
  112835. if(nfm1==0)return;
  112836. for (k1=0;k1<nfm1;k1++){
  112837. ip=ifac[k1+2];
  112838. ld=0;
  112839. l2=l1*ip;
  112840. ido=n/l2;
  112841. ipm=ip-1;
  112842. for (j=0;j<ipm;j++){
  112843. ld+=l1;
  112844. i=is;
  112845. argld=(float)ld*argh;
  112846. fi=0.f;
  112847. for (ii=2;ii<ido;ii+=2){
  112848. fi+=1.f;
  112849. arg=fi*argld;
  112850. wa[i++]=cos(arg);
  112851. wa[i++]=sin(arg);
  112852. }
  112853. is+=ido;
  112854. }
  112855. l1=l2;
  112856. }
  112857. }
  112858. static void fdrffti(int n, float *wsave, int *ifac){
  112859. if (n == 1) return;
  112860. drfti1(n, wsave+n, ifac);
  112861. }
  112862. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  112863. int i,k;
  112864. float ti2,tr2;
  112865. int t0,t1,t2,t3,t4,t5,t6;
  112866. t1=0;
  112867. t0=(t2=l1*ido);
  112868. t3=ido<<1;
  112869. for(k=0;k<l1;k++){
  112870. ch[t1<<1]=cc[t1]+cc[t2];
  112871. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  112872. t1+=ido;
  112873. t2+=ido;
  112874. }
  112875. if(ido<2)return;
  112876. if(ido==2)goto L105;
  112877. t1=0;
  112878. t2=t0;
  112879. for(k=0;k<l1;k++){
  112880. t3=t2;
  112881. t4=(t1<<1)+(ido<<1);
  112882. t5=t1;
  112883. t6=t1+t1;
  112884. for(i=2;i<ido;i+=2){
  112885. t3+=2;
  112886. t4-=2;
  112887. t5+=2;
  112888. t6+=2;
  112889. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  112890. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  112891. ch[t6]=cc[t5]+ti2;
  112892. ch[t4]=ti2-cc[t5];
  112893. ch[t6-1]=cc[t5-1]+tr2;
  112894. ch[t4-1]=cc[t5-1]-tr2;
  112895. }
  112896. t1+=ido;
  112897. t2+=ido;
  112898. }
  112899. if(ido%2==1)return;
  112900. L105:
  112901. t3=(t2=(t1=ido)-1);
  112902. t2+=t0;
  112903. for(k=0;k<l1;k++){
  112904. ch[t1]=-cc[t2];
  112905. ch[t1-1]=cc[t3];
  112906. t1+=ido<<1;
  112907. t2+=ido;
  112908. t3+=ido;
  112909. }
  112910. }
  112911. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  112912. float *wa2,float *wa3){
  112913. static float hsqt2 = .70710678118654752f;
  112914. int i,k,t0,t1,t2,t3,t4,t5,t6;
  112915. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  112916. t0=l1*ido;
  112917. t1=t0;
  112918. t4=t1<<1;
  112919. t2=t1+(t1<<1);
  112920. t3=0;
  112921. for(k=0;k<l1;k++){
  112922. tr1=cc[t1]+cc[t2];
  112923. tr2=cc[t3]+cc[t4];
  112924. ch[t5=t3<<2]=tr1+tr2;
  112925. ch[(ido<<2)+t5-1]=tr2-tr1;
  112926. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  112927. ch[t5]=cc[t2]-cc[t1];
  112928. t1+=ido;
  112929. t2+=ido;
  112930. t3+=ido;
  112931. t4+=ido;
  112932. }
  112933. if(ido<2)return;
  112934. if(ido==2)goto L105;
  112935. t1=0;
  112936. for(k=0;k<l1;k++){
  112937. t2=t1;
  112938. t4=t1<<2;
  112939. t5=(t6=ido<<1)+t4;
  112940. for(i=2;i<ido;i+=2){
  112941. t3=(t2+=2);
  112942. t4+=2;
  112943. t5-=2;
  112944. t3+=t0;
  112945. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  112946. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  112947. t3+=t0;
  112948. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  112949. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  112950. t3+=t0;
  112951. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  112952. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  112953. tr1=cr2+cr4;
  112954. tr4=cr4-cr2;
  112955. ti1=ci2+ci4;
  112956. ti4=ci2-ci4;
  112957. ti2=cc[t2]+ci3;
  112958. ti3=cc[t2]-ci3;
  112959. tr2=cc[t2-1]+cr3;
  112960. tr3=cc[t2-1]-cr3;
  112961. ch[t4-1]=tr1+tr2;
  112962. ch[t4]=ti1+ti2;
  112963. ch[t5-1]=tr3-ti4;
  112964. ch[t5]=tr4-ti3;
  112965. ch[t4+t6-1]=ti4+tr3;
  112966. ch[t4+t6]=tr4+ti3;
  112967. ch[t5+t6-1]=tr2-tr1;
  112968. ch[t5+t6]=ti1-ti2;
  112969. }
  112970. t1+=ido;
  112971. }
  112972. if(ido&1)return;
  112973. L105:
  112974. t2=(t1=t0+ido-1)+(t0<<1);
  112975. t3=ido<<2;
  112976. t4=ido;
  112977. t5=ido<<1;
  112978. t6=ido;
  112979. for(k=0;k<l1;k++){
  112980. ti1=-hsqt2*(cc[t1]+cc[t2]);
  112981. tr1=hsqt2*(cc[t1]-cc[t2]);
  112982. ch[t4-1]=tr1+cc[t6-1];
  112983. ch[t4+t5-1]=cc[t6-1]-tr1;
  112984. ch[t4]=ti1-cc[t1+t0];
  112985. ch[t4+t5]=ti1+cc[t1+t0];
  112986. t1+=ido;
  112987. t2+=ido;
  112988. t4+=t3;
  112989. t6+=ido;
  112990. }
  112991. }
  112992. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  112993. float *c2,float *ch,float *ch2,float *wa){
  112994. static float tpi=6.283185307179586f;
  112995. int idij,ipph,i,j,k,l,ic,ik,is;
  112996. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  112997. float dc2,ai1,ai2,ar1,ar2,ds2;
  112998. int nbd;
  112999. float dcp,arg,dsp,ar1h,ar2h;
  113000. int idp2,ipp2;
  113001. arg=tpi/(float)ip;
  113002. dcp=cos(arg);
  113003. dsp=sin(arg);
  113004. ipph=(ip+1)>>1;
  113005. ipp2=ip;
  113006. idp2=ido;
  113007. nbd=(ido-1)>>1;
  113008. t0=l1*ido;
  113009. t10=ip*ido;
  113010. if(ido==1)goto L119;
  113011. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  113012. t1=0;
  113013. for(j=1;j<ip;j++){
  113014. t1+=t0;
  113015. t2=t1;
  113016. for(k=0;k<l1;k++){
  113017. ch[t2]=c1[t2];
  113018. t2+=ido;
  113019. }
  113020. }
  113021. is=-ido;
  113022. t1=0;
  113023. if(nbd>l1){
  113024. for(j=1;j<ip;j++){
  113025. t1+=t0;
  113026. is+=ido;
  113027. t2= -ido+t1;
  113028. for(k=0;k<l1;k++){
  113029. idij=is-1;
  113030. t2+=ido;
  113031. t3=t2;
  113032. for(i=2;i<ido;i+=2){
  113033. idij+=2;
  113034. t3+=2;
  113035. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113036. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113037. }
  113038. }
  113039. }
  113040. }else{
  113041. for(j=1;j<ip;j++){
  113042. is+=ido;
  113043. idij=is-1;
  113044. t1+=t0;
  113045. t2=t1;
  113046. for(i=2;i<ido;i+=2){
  113047. idij+=2;
  113048. t2+=2;
  113049. t3=t2;
  113050. for(k=0;k<l1;k++){
  113051. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113052. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113053. t3+=ido;
  113054. }
  113055. }
  113056. }
  113057. }
  113058. t1=0;
  113059. t2=ipp2*t0;
  113060. if(nbd<l1){
  113061. for(j=1;j<ipph;j++){
  113062. t1+=t0;
  113063. t2-=t0;
  113064. t3=t1;
  113065. t4=t2;
  113066. for(i=2;i<ido;i+=2){
  113067. t3+=2;
  113068. t4+=2;
  113069. t5=t3-ido;
  113070. t6=t4-ido;
  113071. for(k=0;k<l1;k++){
  113072. t5+=ido;
  113073. t6+=ido;
  113074. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113075. c1[t6-1]=ch[t5]-ch[t6];
  113076. c1[t5]=ch[t5]+ch[t6];
  113077. c1[t6]=ch[t6-1]-ch[t5-1];
  113078. }
  113079. }
  113080. }
  113081. }else{
  113082. for(j=1;j<ipph;j++){
  113083. t1+=t0;
  113084. t2-=t0;
  113085. t3=t1;
  113086. t4=t2;
  113087. for(k=0;k<l1;k++){
  113088. t5=t3;
  113089. t6=t4;
  113090. for(i=2;i<ido;i+=2){
  113091. t5+=2;
  113092. t6+=2;
  113093. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113094. c1[t6-1]=ch[t5]-ch[t6];
  113095. c1[t5]=ch[t5]+ch[t6];
  113096. c1[t6]=ch[t6-1]-ch[t5-1];
  113097. }
  113098. t3+=ido;
  113099. t4+=ido;
  113100. }
  113101. }
  113102. }
  113103. L119:
  113104. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113105. t1=0;
  113106. t2=ipp2*idl1;
  113107. for(j=1;j<ipph;j++){
  113108. t1+=t0;
  113109. t2-=t0;
  113110. t3=t1-ido;
  113111. t4=t2-ido;
  113112. for(k=0;k<l1;k++){
  113113. t3+=ido;
  113114. t4+=ido;
  113115. c1[t3]=ch[t3]+ch[t4];
  113116. c1[t4]=ch[t4]-ch[t3];
  113117. }
  113118. }
  113119. ar1=1.f;
  113120. ai1=0.f;
  113121. t1=0;
  113122. t2=ipp2*idl1;
  113123. t3=(ip-1)*idl1;
  113124. for(l=1;l<ipph;l++){
  113125. t1+=idl1;
  113126. t2-=idl1;
  113127. ar1h=dcp*ar1-dsp*ai1;
  113128. ai1=dcp*ai1+dsp*ar1;
  113129. ar1=ar1h;
  113130. t4=t1;
  113131. t5=t2;
  113132. t6=t3;
  113133. t7=idl1;
  113134. for(ik=0;ik<idl1;ik++){
  113135. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  113136. ch2[t5++]=ai1*c2[t6++];
  113137. }
  113138. dc2=ar1;
  113139. ds2=ai1;
  113140. ar2=ar1;
  113141. ai2=ai1;
  113142. t4=idl1;
  113143. t5=(ipp2-1)*idl1;
  113144. for(j=2;j<ipph;j++){
  113145. t4+=idl1;
  113146. t5-=idl1;
  113147. ar2h=dc2*ar2-ds2*ai2;
  113148. ai2=dc2*ai2+ds2*ar2;
  113149. ar2=ar2h;
  113150. t6=t1;
  113151. t7=t2;
  113152. t8=t4;
  113153. t9=t5;
  113154. for(ik=0;ik<idl1;ik++){
  113155. ch2[t6++]+=ar2*c2[t8++];
  113156. ch2[t7++]+=ai2*c2[t9++];
  113157. }
  113158. }
  113159. }
  113160. t1=0;
  113161. for(j=1;j<ipph;j++){
  113162. t1+=idl1;
  113163. t2=t1;
  113164. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  113165. }
  113166. if(ido<l1)goto L132;
  113167. t1=0;
  113168. t2=0;
  113169. for(k=0;k<l1;k++){
  113170. t3=t1;
  113171. t4=t2;
  113172. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  113173. t1+=ido;
  113174. t2+=t10;
  113175. }
  113176. goto L135;
  113177. L132:
  113178. for(i=0;i<ido;i++){
  113179. t1=i;
  113180. t2=i;
  113181. for(k=0;k<l1;k++){
  113182. cc[t2]=ch[t1];
  113183. t1+=ido;
  113184. t2+=t10;
  113185. }
  113186. }
  113187. L135:
  113188. t1=0;
  113189. t2=ido<<1;
  113190. t3=0;
  113191. t4=ipp2*t0;
  113192. for(j=1;j<ipph;j++){
  113193. t1+=t2;
  113194. t3+=t0;
  113195. t4-=t0;
  113196. t5=t1;
  113197. t6=t3;
  113198. t7=t4;
  113199. for(k=0;k<l1;k++){
  113200. cc[t5-1]=ch[t6];
  113201. cc[t5]=ch[t7];
  113202. t5+=t10;
  113203. t6+=ido;
  113204. t7+=ido;
  113205. }
  113206. }
  113207. if(ido==1)return;
  113208. if(nbd<l1)goto L141;
  113209. t1=-ido;
  113210. t3=0;
  113211. t4=0;
  113212. t5=ipp2*t0;
  113213. for(j=1;j<ipph;j++){
  113214. t1+=t2;
  113215. t3+=t2;
  113216. t4+=t0;
  113217. t5-=t0;
  113218. t6=t1;
  113219. t7=t3;
  113220. t8=t4;
  113221. t9=t5;
  113222. for(k=0;k<l1;k++){
  113223. for(i=2;i<ido;i+=2){
  113224. ic=idp2-i;
  113225. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  113226. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  113227. cc[i+t7]=ch[i+t8]+ch[i+t9];
  113228. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  113229. }
  113230. t6+=t10;
  113231. t7+=t10;
  113232. t8+=ido;
  113233. t9+=ido;
  113234. }
  113235. }
  113236. return;
  113237. L141:
  113238. t1=-ido;
  113239. t3=0;
  113240. t4=0;
  113241. t5=ipp2*t0;
  113242. for(j=1;j<ipph;j++){
  113243. t1+=t2;
  113244. t3+=t2;
  113245. t4+=t0;
  113246. t5-=t0;
  113247. for(i=2;i<ido;i+=2){
  113248. t6=idp2+t1-i;
  113249. t7=i+t3;
  113250. t8=i+t4;
  113251. t9=i+t5;
  113252. for(k=0;k<l1;k++){
  113253. cc[t7-1]=ch[t8-1]+ch[t9-1];
  113254. cc[t6-1]=ch[t8-1]-ch[t9-1];
  113255. cc[t7]=ch[t8]+ch[t9];
  113256. cc[t6]=ch[t9]-ch[t8];
  113257. t6+=t10;
  113258. t7+=t10;
  113259. t8+=ido;
  113260. t9+=ido;
  113261. }
  113262. }
  113263. }
  113264. }
  113265. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  113266. int i,k1,l1,l2;
  113267. int na,kh,nf;
  113268. int ip,iw,ido,idl1,ix2,ix3;
  113269. nf=ifac[1];
  113270. na=1;
  113271. l2=n;
  113272. iw=n;
  113273. for(k1=0;k1<nf;k1++){
  113274. kh=nf-k1;
  113275. ip=ifac[kh+1];
  113276. l1=l2/ip;
  113277. ido=n/l2;
  113278. idl1=ido*l1;
  113279. iw-=(ip-1)*ido;
  113280. na=1-na;
  113281. if(ip!=4)goto L102;
  113282. ix2=iw+ido;
  113283. ix3=ix2+ido;
  113284. if(na!=0)
  113285. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113286. else
  113287. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113288. goto L110;
  113289. L102:
  113290. if(ip!=2)goto L104;
  113291. if(na!=0)goto L103;
  113292. dradf2(ido,l1,c,ch,wa+iw-1);
  113293. goto L110;
  113294. L103:
  113295. dradf2(ido,l1,ch,c,wa+iw-1);
  113296. goto L110;
  113297. L104:
  113298. if(ido==1)na=1-na;
  113299. if(na!=0)goto L109;
  113300. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  113301. na=1;
  113302. goto L110;
  113303. L109:
  113304. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  113305. na=0;
  113306. L110:
  113307. l2=l1;
  113308. }
  113309. if(na==1)return;
  113310. for(i=0;i<n;i++)c[i]=ch[i];
  113311. }
  113312. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  113313. int i,k,t0,t1,t2,t3,t4,t5,t6;
  113314. float ti2,tr2;
  113315. t0=l1*ido;
  113316. t1=0;
  113317. t2=0;
  113318. t3=(ido<<1)-1;
  113319. for(k=0;k<l1;k++){
  113320. ch[t1]=cc[t2]+cc[t3+t2];
  113321. ch[t1+t0]=cc[t2]-cc[t3+t2];
  113322. t2=(t1+=ido)<<1;
  113323. }
  113324. if(ido<2)return;
  113325. if(ido==2)goto L105;
  113326. t1=0;
  113327. t2=0;
  113328. for(k=0;k<l1;k++){
  113329. t3=t1;
  113330. t5=(t4=t2)+(ido<<1);
  113331. t6=t0+t1;
  113332. for(i=2;i<ido;i+=2){
  113333. t3+=2;
  113334. t4+=2;
  113335. t5-=2;
  113336. t6+=2;
  113337. ch[t3-1]=cc[t4-1]+cc[t5-1];
  113338. tr2=cc[t4-1]-cc[t5-1];
  113339. ch[t3]=cc[t4]-cc[t5];
  113340. ti2=cc[t4]+cc[t5];
  113341. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  113342. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  113343. }
  113344. t2=(t1+=ido)<<1;
  113345. }
  113346. if(ido%2==1)return;
  113347. L105:
  113348. t1=ido-1;
  113349. t2=ido-1;
  113350. for(k=0;k<l1;k++){
  113351. ch[t1]=cc[t2]+cc[t2];
  113352. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  113353. t1+=ido;
  113354. t2+=ido<<1;
  113355. }
  113356. }
  113357. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  113358. float *wa2){
  113359. static float taur = -.5f;
  113360. static float taui = .8660254037844386f;
  113361. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113362. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  113363. t0=l1*ido;
  113364. t1=0;
  113365. t2=t0<<1;
  113366. t3=ido<<1;
  113367. t4=ido+(ido<<1);
  113368. t5=0;
  113369. for(k=0;k<l1;k++){
  113370. tr2=cc[t3-1]+cc[t3-1];
  113371. cr2=cc[t5]+(taur*tr2);
  113372. ch[t1]=cc[t5]+tr2;
  113373. ci3=taui*(cc[t3]+cc[t3]);
  113374. ch[t1+t0]=cr2-ci3;
  113375. ch[t1+t2]=cr2+ci3;
  113376. t1+=ido;
  113377. t3+=t4;
  113378. t5+=t4;
  113379. }
  113380. if(ido==1)return;
  113381. t1=0;
  113382. t3=ido<<1;
  113383. for(k=0;k<l1;k++){
  113384. t7=t1+(t1<<1);
  113385. t6=(t5=t7+t3);
  113386. t8=t1;
  113387. t10=(t9=t1+t0)+t0;
  113388. for(i=2;i<ido;i+=2){
  113389. t5+=2;
  113390. t6-=2;
  113391. t7+=2;
  113392. t8+=2;
  113393. t9+=2;
  113394. t10+=2;
  113395. tr2=cc[t5-1]+cc[t6-1];
  113396. cr2=cc[t7-1]+(taur*tr2);
  113397. ch[t8-1]=cc[t7-1]+tr2;
  113398. ti2=cc[t5]-cc[t6];
  113399. ci2=cc[t7]+(taur*ti2);
  113400. ch[t8]=cc[t7]+ti2;
  113401. cr3=taui*(cc[t5-1]-cc[t6-1]);
  113402. ci3=taui*(cc[t5]+cc[t6]);
  113403. dr2=cr2-ci3;
  113404. dr3=cr2+ci3;
  113405. di2=ci2+cr3;
  113406. di3=ci2-cr3;
  113407. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  113408. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  113409. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  113410. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  113411. }
  113412. t1+=ido;
  113413. }
  113414. }
  113415. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  113416. float *wa2,float *wa3){
  113417. static float sqrt2=1.414213562373095f;
  113418. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  113419. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  113420. t0=l1*ido;
  113421. t1=0;
  113422. t2=ido<<2;
  113423. t3=0;
  113424. t6=ido<<1;
  113425. for(k=0;k<l1;k++){
  113426. t4=t3+t6;
  113427. t5=t1;
  113428. tr3=cc[t4-1]+cc[t4-1];
  113429. tr4=cc[t4]+cc[t4];
  113430. tr1=cc[t3]-cc[(t4+=t6)-1];
  113431. tr2=cc[t3]+cc[t4-1];
  113432. ch[t5]=tr2+tr3;
  113433. ch[t5+=t0]=tr1-tr4;
  113434. ch[t5+=t0]=tr2-tr3;
  113435. ch[t5+=t0]=tr1+tr4;
  113436. t1+=ido;
  113437. t3+=t2;
  113438. }
  113439. if(ido<2)return;
  113440. if(ido==2)goto L105;
  113441. t1=0;
  113442. for(k=0;k<l1;k++){
  113443. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  113444. t7=t1;
  113445. for(i=2;i<ido;i+=2){
  113446. t2+=2;
  113447. t3+=2;
  113448. t4-=2;
  113449. t5-=2;
  113450. t7+=2;
  113451. ti1=cc[t2]+cc[t5];
  113452. ti2=cc[t2]-cc[t5];
  113453. ti3=cc[t3]-cc[t4];
  113454. tr4=cc[t3]+cc[t4];
  113455. tr1=cc[t2-1]-cc[t5-1];
  113456. tr2=cc[t2-1]+cc[t5-1];
  113457. ti4=cc[t3-1]-cc[t4-1];
  113458. tr3=cc[t3-1]+cc[t4-1];
  113459. ch[t7-1]=tr2+tr3;
  113460. cr3=tr2-tr3;
  113461. ch[t7]=ti2+ti3;
  113462. ci3=ti2-ti3;
  113463. cr2=tr1-tr4;
  113464. cr4=tr1+tr4;
  113465. ci2=ti1+ti4;
  113466. ci4=ti1-ti4;
  113467. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  113468. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  113469. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  113470. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  113471. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  113472. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  113473. }
  113474. t1+=ido;
  113475. }
  113476. if(ido%2 == 1)return;
  113477. L105:
  113478. t1=ido;
  113479. t2=ido<<2;
  113480. t3=ido-1;
  113481. t4=ido+(ido<<1);
  113482. for(k=0;k<l1;k++){
  113483. t5=t3;
  113484. ti1=cc[t1]+cc[t4];
  113485. ti2=cc[t4]-cc[t1];
  113486. tr1=cc[t1-1]-cc[t4-1];
  113487. tr2=cc[t1-1]+cc[t4-1];
  113488. ch[t5]=tr2+tr2;
  113489. ch[t5+=t0]=sqrt2*(tr1-ti1);
  113490. ch[t5+=t0]=ti2+ti2;
  113491. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  113492. t3+=ido;
  113493. t1+=t2;
  113494. t4+=t2;
  113495. }
  113496. }
  113497. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113498. float *c2,float *ch,float *ch2,float *wa){
  113499. static float tpi=6.283185307179586f;
  113500. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  113501. t11,t12;
  113502. float dc2,ai1,ai2,ar1,ar2,ds2;
  113503. int nbd;
  113504. float dcp,arg,dsp,ar1h,ar2h;
  113505. int ipp2;
  113506. t10=ip*ido;
  113507. t0=l1*ido;
  113508. arg=tpi/(float)ip;
  113509. dcp=cos(arg);
  113510. dsp=sin(arg);
  113511. nbd=(ido-1)>>1;
  113512. ipp2=ip;
  113513. ipph=(ip+1)>>1;
  113514. if(ido<l1)goto L103;
  113515. t1=0;
  113516. t2=0;
  113517. for(k=0;k<l1;k++){
  113518. t3=t1;
  113519. t4=t2;
  113520. for(i=0;i<ido;i++){
  113521. ch[t3]=cc[t4];
  113522. t3++;
  113523. t4++;
  113524. }
  113525. t1+=ido;
  113526. t2+=t10;
  113527. }
  113528. goto L106;
  113529. L103:
  113530. t1=0;
  113531. for(i=0;i<ido;i++){
  113532. t2=t1;
  113533. t3=t1;
  113534. for(k=0;k<l1;k++){
  113535. ch[t2]=cc[t3];
  113536. t2+=ido;
  113537. t3+=t10;
  113538. }
  113539. t1++;
  113540. }
  113541. L106:
  113542. t1=0;
  113543. t2=ipp2*t0;
  113544. t7=(t5=ido<<1);
  113545. for(j=1;j<ipph;j++){
  113546. t1+=t0;
  113547. t2-=t0;
  113548. t3=t1;
  113549. t4=t2;
  113550. t6=t5;
  113551. for(k=0;k<l1;k++){
  113552. ch[t3]=cc[t6-1]+cc[t6-1];
  113553. ch[t4]=cc[t6]+cc[t6];
  113554. t3+=ido;
  113555. t4+=ido;
  113556. t6+=t10;
  113557. }
  113558. t5+=t7;
  113559. }
  113560. if (ido == 1)goto L116;
  113561. if(nbd<l1)goto L112;
  113562. t1=0;
  113563. t2=ipp2*t0;
  113564. t7=0;
  113565. for(j=1;j<ipph;j++){
  113566. t1+=t0;
  113567. t2-=t0;
  113568. t3=t1;
  113569. t4=t2;
  113570. t7+=(ido<<1);
  113571. t8=t7;
  113572. for(k=0;k<l1;k++){
  113573. t5=t3;
  113574. t6=t4;
  113575. t9=t8;
  113576. t11=t8;
  113577. for(i=2;i<ido;i+=2){
  113578. t5+=2;
  113579. t6+=2;
  113580. t9+=2;
  113581. t11-=2;
  113582. ch[t5-1]=cc[t9-1]+cc[t11-1];
  113583. ch[t6-1]=cc[t9-1]-cc[t11-1];
  113584. ch[t5]=cc[t9]-cc[t11];
  113585. ch[t6]=cc[t9]+cc[t11];
  113586. }
  113587. t3+=ido;
  113588. t4+=ido;
  113589. t8+=t10;
  113590. }
  113591. }
  113592. goto L116;
  113593. L112:
  113594. t1=0;
  113595. t2=ipp2*t0;
  113596. t7=0;
  113597. for(j=1;j<ipph;j++){
  113598. t1+=t0;
  113599. t2-=t0;
  113600. t3=t1;
  113601. t4=t2;
  113602. t7+=(ido<<1);
  113603. t8=t7;
  113604. t9=t7;
  113605. for(i=2;i<ido;i+=2){
  113606. t3+=2;
  113607. t4+=2;
  113608. t8+=2;
  113609. t9-=2;
  113610. t5=t3;
  113611. t6=t4;
  113612. t11=t8;
  113613. t12=t9;
  113614. for(k=0;k<l1;k++){
  113615. ch[t5-1]=cc[t11-1]+cc[t12-1];
  113616. ch[t6-1]=cc[t11-1]-cc[t12-1];
  113617. ch[t5]=cc[t11]-cc[t12];
  113618. ch[t6]=cc[t11]+cc[t12];
  113619. t5+=ido;
  113620. t6+=ido;
  113621. t11+=t10;
  113622. t12+=t10;
  113623. }
  113624. }
  113625. }
  113626. L116:
  113627. ar1=1.f;
  113628. ai1=0.f;
  113629. t1=0;
  113630. t9=(t2=ipp2*idl1);
  113631. t3=(ip-1)*idl1;
  113632. for(l=1;l<ipph;l++){
  113633. t1+=idl1;
  113634. t2-=idl1;
  113635. ar1h=dcp*ar1-dsp*ai1;
  113636. ai1=dcp*ai1+dsp*ar1;
  113637. ar1=ar1h;
  113638. t4=t1;
  113639. t5=t2;
  113640. t6=0;
  113641. t7=idl1;
  113642. t8=t3;
  113643. for(ik=0;ik<idl1;ik++){
  113644. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  113645. c2[t5++]=ai1*ch2[t8++];
  113646. }
  113647. dc2=ar1;
  113648. ds2=ai1;
  113649. ar2=ar1;
  113650. ai2=ai1;
  113651. t6=idl1;
  113652. t7=t9-idl1;
  113653. for(j=2;j<ipph;j++){
  113654. t6+=idl1;
  113655. t7-=idl1;
  113656. ar2h=dc2*ar2-ds2*ai2;
  113657. ai2=dc2*ai2+ds2*ar2;
  113658. ar2=ar2h;
  113659. t4=t1;
  113660. t5=t2;
  113661. t11=t6;
  113662. t12=t7;
  113663. for(ik=0;ik<idl1;ik++){
  113664. c2[t4++]+=ar2*ch2[t11++];
  113665. c2[t5++]+=ai2*ch2[t12++];
  113666. }
  113667. }
  113668. }
  113669. t1=0;
  113670. for(j=1;j<ipph;j++){
  113671. t1+=idl1;
  113672. t2=t1;
  113673. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  113674. }
  113675. t1=0;
  113676. t2=ipp2*t0;
  113677. for(j=1;j<ipph;j++){
  113678. t1+=t0;
  113679. t2-=t0;
  113680. t3=t1;
  113681. t4=t2;
  113682. for(k=0;k<l1;k++){
  113683. ch[t3]=c1[t3]-c1[t4];
  113684. ch[t4]=c1[t3]+c1[t4];
  113685. t3+=ido;
  113686. t4+=ido;
  113687. }
  113688. }
  113689. if(ido==1)goto L132;
  113690. if(nbd<l1)goto L128;
  113691. t1=0;
  113692. t2=ipp2*t0;
  113693. for(j=1;j<ipph;j++){
  113694. t1+=t0;
  113695. t2-=t0;
  113696. t3=t1;
  113697. t4=t2;
  113698. for(k=0;k<l1;k++){
  113699. t5=t3;
  113700. t6=t4;
  113701. for(i=2;i<ido;i+=2){
  113702. t5+=2;
  113703. t6+=2;
  113704. ch[t5-1]=c1[t5-1]-c1[t6];
  113705. ch[t6-1]=c1[t5-1]+c1[t6];
  113706. ch[t5]=c1[t5]+c1[t6-1];
  113707. ch[t6]=c1[t5]-c1[t6-1];
  113708. }
  113709. t3+=ido;
  113710. t4+=ido;
  113711. }
  113712. }
  113713. goto L132;
  113714. L128:
  113715. t1=0;
  113716. t2=ipp2*t0;
  113717. for(j=1;j<ipph;j++){
  113718. t1+=t0;
  113719. t2-=t0;
  113720. t3=t1;
  113721. t4=t2;
  113722. for(i=2;i<ido;i+=2){
  113723. t3+=2;
  113724. t4+=2;
  113725. t5=t3;
  113726. t6=t4;
  113727. for(k=0;k<l1;k++){
  113728. ch[t5-1]=c1[t5-1]-c1[t6];
  113729. ch[t6-1]=c1[t5-1]+c1[t6];
  113730. ch[t5]=c1[t5]+c1[t6-1];
  113731. ch[t6]=c1[t5]-c1[t6-1];
  113732. t5+=ido;
  113733. t6+=ido;
  113734. }
  113735. }
  113736. }
  113737. L132:
  113738. if(ido==1)return;
  113739. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113740. t1=0;
  113741. for(j=1;j<ip;j++){
  113742. t2=(t1+=t0);
  113743. for(k=0;k<l1;k++){
  113744. c1[t2]=ch[t2];
  113745. t2+=ido;
  113746. }
  113747. }
  113748. if(nbd>l1)goto L139;
  113749. is= -ido-1;
  113750. t1=0;
  113751. for(j=1;j<ip;j++){
  113752. is+=ido;
  113753. t1+=t0;
  113754. idij=is;
  113755. t2=t1;
  113756. for(i=2;i<ido;i+=2){
  113757. t2+=2;
  113758. idij+=2;
  113759. t3=t2;
  113760. for(k=0;k<l1;k++){
  113761. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  113762. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  113763. t3+=ido;
  113764. }
  113765. }
  113766. }
  113767. return;
  113768. L139:
  113769. is= -ido-1;
  113770. t1=0;
  113771. for(j=1;j<ip;j++){
  113772. is+=ido;
  113773. t1+=t0;
  113774. t2=t1;
  113775. for(k=0;k<l1;k++){
  113776. idij=is;
  113777. t3=t2;
  113778. for(i=2;i<ido;i+=2){
  113779. idij+=2;
  113780. t3+=2;
  113781. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  113782. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  113783. }
  113784. t2+=ido;
  113785. }
  113786. }
  113787. }
  113788. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  113789. int i,k1,l1,l2;
  113790. int na;
  113791. int nf,ip,iw,ix2,ix3,ido,idl1;
  113792. nf=ifac[1];
  113793. na=0;
  113794. l1=1;
  113795. iw=1;
  113796. for(k1=0;k1<nf;k1++){
  113797. ip=ifac[k1 + 2];
  113798. l2=ip*l1;
  113799. ido=n/l2;
  113800. idl1=ido*l1;
  113801. if(ip!=4)goto L103;
  113802. ix2=iw+ido;
  113803. ix3=ix2+ido;
  113804. if(na!=0)
  113805. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113806. else
  113807. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113808. na=1-na;
  113809. goto L115;
  113810. L103:
  113811. if(ip!=2)goto L106;
  113812. if(na!=0)
  113813. dradb2(ido,l1,ch,c,wa+iw-1);
  113814. else
  113815. dradb2(ido,l1,c,ch,wa+iw-1);
  113816. na=1-na;
  113817. goto L115;
  113818. L106:
  113819. if(ip!=3)goto L109;
  113820. ix2=iw+ido;
  113821. if(na!=0)
  113822. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  113823. else
  113824. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  113825. na=1-na;
  113826. goto L115;
  113827. L109:
  113828. /* The radix five case can be translated later..... */
  113829. /* if(ip!=5)goto L112;
  113830. ix2=iw+ido;
  113831. ix3=ix2+ido;
  113832. ix4=ix3+ido;
  113833. if(na!=0)
  113834. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  113835. else
  113836. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  113837. na=1-na;
  113838. goto L115;
  113839. L112:*/
  113840. if(na!=0)
  113841. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  113842. else
  113843. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  113844. if(ido==1)na=1-na;
  113845. L115:
  113846. l1=l2;
  113847. iw+=(ip-1)*ido;
  113848. }
  113849. if(na==0)return;
  113850. for(i=0;i<n;i++)c[i]=ch[i];
  113851. }
  113852. void drft_forward(drft_lookup *l,float *data){
  113853. if(l->n==1)return;
  113854. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  113855. }
  113856. void drft_backward(drft_lookup *l,float *data){
  113857. if (l->n==1)return;
  113858. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  113859. }
  113860. void drft_init(drft_lookup *l,int n){
  113861. l->n=n;
  113862. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  113863. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  113864. fdrffti(n, l->trigcache, l->splitcache);
  113865. }
  113866. void drft_clear(drft_lookup *l){
  113867. if(l){
  113868. if(l->trigcache)_ogg_free(l->trigcache);
  113869. if(l->splitcache)_ogg_free(l->splitcache);
  113870. memset(l,0,sizeof(*l));
  113871. }
  113872. }
  113873. #endif
  113874. /********* End of inlined file: smallft.c *********/
  113875. /********* Start of inlined file: synthesis.c *********/
  113876. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113877. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113878. // tasks..
  113879. #ifdef _MSC_VER
  113880. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113881. #endif
  113882. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113883. #if JUCE_USE_OGGVORBIS
  113884. #include <stdio.h>
  113885. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  113886. vorbis_dsp_state *vd=vb->vd;
  113887. private_state *b=(private_state*)vd->backend_state;
  113888. vorbis_info *vi=vd->vi;
  113889. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113890. oggpack_buffer *opb=&vb->opb;
  113891. int type,mode,i;
  113892. /* first things first. Make sure decode is ready */
  113893. _vorbis_block_ripcord(vb);
  113894. oggpack_readinit(opb,op->packet,op->bytes);
  113895. /* Check the packet type */
  113896. if(oggpack_read(opb,1)!=0){
  113897. /* Oops. This is not an audio data packet */
  113898. return(OV_ENOTAUDIO);
  113899. }
  113900. /* read our mode and pre/post windowsize */
  113901. mode=oggpack_read(opb,b->modebits);
  113902. if(mode==-1)return(OV_EBADPACKET);
  113903. vb->mode=mode;
  113904. vb->W=ci->mode_param[mode]->blockflag;
  113905. if(vb->W){
  113906. /* this doesn;t get mapped through mode selection as it's used
  113907. only for window selection */
  113908. vb->lW=oggpack_read(opb,1);
  113909. vb->nW=oggpack_read(opb,1);
  113910. if(vb->nW==-1) return(OV_EBADPACKET);
  113911. }else{
  113912. vb->lW=0;
  113913. vb->nW=0;
  113914. }
  113915. /* more setup */
  113916. vb->granulepos=op->granulepos;
  113917. vb->sequence=op->packetno;
  113918. vb->eofflag=op->e_o_s;
  113919. /* alloc pcm passback storage */
  113920. vb->pcmend=ci->blocksizes[vb->W];
  113921. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  113922. for(i=0;i<vi->channels;i++)
  113923. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  113924. /* unpack_header enforces range checking */
  113925. type=ci->map_type[ci->mode_param[mode]->mapping];
  113926. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  113927. mapping]));
  113928. }
  113929. /* used to track pcm position without actually performing decode.
  113930. Useful for sequential 'fast forward' */
  113931. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  113932. vorbis_dsp_state *vd=vb->vd;
  113933. private_state *b=(private_state*)vd->backend_state;
  113934. vorbis_info *vi=vd->vi;
  113935. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113936. oggpack_buffer *opb=&vb->opb;
  113937. int mode;
  113938. /* first things first. Make sure decode is ready */
  113939. _vorbis_block_ripcord(vb);
  113940. oggpack_readinit(opb,op->packet,op->bytes);
  113941. /* Check the packet type */
  113942. if(oggpack_read(opb,1)!=0){
  113943. /* Oops. This is not an audio data packet */
  113944. return(OV_ENOTAUDIO);
  113945. }
  113946. /* read our mode and pre/post windowsize */
  113947. mode=oggpack_read(opb,b->modebits);
  113948. if(mode==-1)return(OV_EBADPACKET);
  113949. vb->mode=mode;
  113950. vb->W=ci->mode_param[mode]->blockflag;
  113951. if(vb->W){
  113952. vb->lW=oggpack_read(opb,1);
  113953. vb->nW=oggpack_read(opb,1);
  113954. if(vb->nW==-1) return(OV_EBADPACKET);
  113955. }else{
  113956. vb->lW=0;
  113957. vb->nW=0;
  113958. }
  113959. /* more setup */
  113960. vb->granulepos=op->granulepos;
  113961. vb->sequence=op->packetno;
  113962. vb->eofflag=op->e_o_s;
  113963. /* no pcm */
  113964. vb->pcmend=0;
  113965. vb->pcm=NULL;
  113966. return(0);
  113967. }
  113968. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  113969. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113970. oggpack_buffer opb;
  113971. int mode;
  113972. oggpack_readinit(&opb,op->packet,op->bytes);
  113973. /* Check the packet type */
  113974. if(oggpack_read(&opb,1)!=0){
  113975. /* Oops. This is not an audio data packet */
  113976. return(OV_ENOTAUDIO);
  113977. }
  113978. {
  113979. int modebits=0;
  113980. int v=ci->modes;
  113981. while(v>1){
  113982. modebits++;
  113983. v>>=1;
  113984. }
  113985. /* read our mode and pre/post windowsize */
  113986. mode=oggpack_read(&opb,modebits);
  113987. }
  113988. if(mode==-1)return(OV_EBADPACKET);
  113989. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  113990. }
  113991. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  113992. /* set / clear half-sample-rate mode */
  113993. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113994. /* right now, our MDCT can't handle < 64 sample windows. */
  113995. if(ci->blocksizes[0]<=64 && flag)return -1;
  113996. ci->halfrate_flag=(flag?1:0);
  113997. return 0;
  113998. }
  113999. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  114000. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114001. return ci->halfrate_flag;
  114002. }
  114003. #endif
  114004. /********* End of inlined file: synthesis.c *********/
  114005. /********* Start of inlined file: vorbisenc.c *********/
  114006. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114007. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114008. // tasks..
  114009. #ifdef _MSC_VER
  114010. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114011. #endif
  114012. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114013. #if JUCE_USE_OGGVORBIS
  114014. #include <stdlib.h>
  114015. #include <string.h>
  114016. #include <math.h>
  114017. /* careful with this; it's using static array sizing to make managing
  114018. all the modes a little less annoying. If we use a residue backend
  114019. with > 12 partition types, or a different division of iteration,
  114020. this needs to be updated. */
  114021. typedef struct {
  114022. static_codebook *books[12][3];
  114023. } static_bookblock;
  114024. typedef struct {
  114025. int res_type;
  114026. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  114027. vorbis_info_residue0 *res;
  114028. static_codebook *book_aux;
  114029. static_codebook *book_aux_managed;
  114030. static_bookblock *books_base;
  114031. static_bookblock *books_base_managed;
  114032. } vorbis_residue_template;
  114033. typedef struct {
  114034. vorbis_info_mapping0 *map;
  114035. vorbis_residue_template *res;
  114036. } vorbis_mapping_template;
  114037. typedef struct vp_adjblock{
  114038. int block[P_BANDS];
  114039. } vp_adjblock;
  114040. typedef struct {
  114041. int data[NOISE_COMPAND_LEVELS];
  114042. } compandblock;
  114043. /* high level configuration information for setting things up
  114044. step-by-step with the detailed vorbis_encode_ctl interface.
  114045. There's a fair amount of redundancy such that interactive setup
  114046. does not directly deal with any vorbis_info or codec_setup_info
  114047. initialization; it's all stored (until full init) in this highlevel
  114048. setup, then flushed out to the real codec setup structs later. */
  114049. typedef struct {
  114050. int att[P_NOISECURVES];
  114051. float boost;
  114052. float decay;
  114053. } att3;
  114054. typedef struct { int data[P_NOISECURVES]; } adj3;
  114055. typedef struct {
  114056. int pre[PACKETBLOBS];
  114057. int post[PACKETBLOBS];
  114058. float kHz[PACKETBLOBS];
  114059. float lowpasskHz[PACKETBLOBS];
  114060. } adj_stereo;
  114061. typedef struct {
  114062. int lo;
  114063. int hi;
  114064. int fixed;
  114065. } noiseguard;
  114066. typedef struct {
  114067. int data[P_NOISECURVES][17];
  114068. } noise3;
  114069. typedef struct {
  114070. int mappings;
  114071. double *rate_mapping;
  114072. double *quality_mapping;
  114073. int coupling_restriction;
  114074. long samplerate_min_restriction;
  114075. long samplerate_max_restriction;
  114076. int *blocksize_short;
  114077. int *blocksize_long;
  114078. att3 *psy_tone_masteratt;
  114079. int *psy_tone_0dB;
  114080. int *psy_tone_dBsuppress;
  114081. vp_adjblock *psy_tone_adj_impulse;
  114082. vp_adjblock *psy_tone_adj_long;
  114083. vp_adjblock *psy_tone_adj_other;
  114084. noiseguard *psy_noiseguards;
  114085. noise3 *psy_noise_bias_impulse;
  114086. noise3 *psy_noise_bias_padding;
  114087. noise3 *psy_noise_bias_trans;
  114088. noise3 *psy_noise_bias_long;
  114089. int *psy_noise_dBsuppress;
  114090. compandblock *psy_noise_compand;
  114091. double *psy_noise_compand_short_mapping;
  114092. double *psy_noise_compand_long_mapping;
  114093. int *psy_noise_normal_start[2];
  114094. int *psy_noise_normal_partition[2];
  114095. double *psy_noise_normal_thresh;
  114096. int *psy_ath_float;
  114097. int *psy_ath_abs;
  114098. double *psy_lowpass;
  114099. vorbis_info_psy_global *global_params;
  114100. double *global_mapping;
  114101. adj_stereo *stereo_modes;
  114102. static_codebook ***floor_books;
  114103. vorbis_info_floor1 *floor_params;
  114104. int *floor_short_mapping;
  114105. int *floor_long_mapping;
  114106. vorbis_mapping_template *maps;
  114107. } ve_setup_data_template;
  114108. /* a few static coder conventions */
  114109. static vorbis_info_mode _mode_template[2]={
  114110. {0,0,0,0},
  114111. {1,0,0,1}
  114112. };
  114113. static vorbis_info_mapping0 _map_nominal[2]={
  114114. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  114115. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  114116. };
  114117. /********* Start of inlined file: setup_44.h *********/
  114118. /********* Start of inlined file: floor_all.h *********/
  114119. /********* Start of inlined file: floor_books.h *********/
  114120. static long _huff_lengthlist_line_256x7_0sub1[] = {
  114121. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  114122. };
  114123. static static_codebook _huff_book_line_256x7_0sub1 = {
  114124. 1, 9,
  114125. _huff_lengthlist_line_256x7_0sub1,
  114126. 0, 0, 0, 0, 0,
  114127. NULL,
  114128. NULL,
  114129. NULL,
  114130. NULL,
  114131. 0
  114132. };
  114133. static long _huff_lengthlist_line_256x7_0sub2[] = {
  114134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  114135. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  114136. };
  114137. static static_codebook _huff_book_line_256x7_0sub2 = {
  114138. 1, 25,
  114139. _huff_lengthlist_line_256x7_0sub2,
  114140. 0, 0, 0, 0, 0,
  114141. NULL,
  114142. NULL,
  114143. NULL,
  114144. NULL,
  114145. 0
  114146. };
  114147. static long _huff_lengthlist_line_256x7_0sub3[] = {
  114148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  114150. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  114151. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  114152. };
  114153. static static_codebook _huff_book_line_256x7_0sub3 = {
  114154. 1, 64,
  114155. _huff_lengthlist_line_256x7_0sub3,
  114156. 0, 0, 0, 0, 0,
  114157. NULL,
  114158. NULL,
  114159. NULL,
  114160. NULL,
  114161. 0
  114162. };
  114163. static long _huff_lengthlist_line_256x7_1sub1[] = {
  114164. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  114165. };
  114166. static static_codebook _huff_book_line_256x7_1sub1 = {
  114167. 1, 9,
  114168. _huff_lengthlist_line_256x7_1sub1,
  114169. 0, 0, 0, 0, 0,
  114170. NULL,
  114171. NULL,
  114172. NULL,
  114173. NULL,
  114174. 0
  114175. };
  114176. static long _huff_lengthlist_line_256x7_1sub2[] = {
  114177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  114178. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  114179. };
  114180. static static_codebook _huff_book_line_256x7_1sub2 = {
  114181. 1, 25,
  114182. _huff_lengthlist_line_256x7_1sub2,
  114183. 0, 0, 0, 0, 0,
  114184. NULL,
  114185. NULL,
  114186. NULL,
  114187. NULL,
  114188. 0
  114189. };
  114190. static long _huff_lengthlist_line_256x7_1sub3[] = {
  114191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  114193. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  114194. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  114195. };
  114196. static static_codebook _huff_book_line_256x7_1sub3 = {
  114197. 1, 64,
  114198. _huff_lengthlist_line_256x7_1sub3,
  114199. 0, 0, 0, 0, 0,
  114200. NULL,
  114201. NULL,
  114202. NULL,
  114203. NULL,
  114204. 0
  114205. };
  114206. static long _huff_lengthlist_line_256x7_class0[] = {
  114207. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  114208. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  114209. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  114210. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  114211. };
  114212. static static_codebook _huff_book_line_256x7_class0 = {
  114213. 1, 64,
  114214. _huff_lengthlist_line_256x7_class0,
  114215. 0, 0, 0, 0, 0,
  114216. NULL,
  114217. NULL,
  114218. NULL,
  114219. NULL,
  114220. 0
  114221. };
  114222. static long _huff_lengthlist_line_256x7_class1[] = {
  114223. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  114224. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  114225. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  114226. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  114227. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  114228. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  114229. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  114230. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  114231. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  114232. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  114233. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  114234. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  114235. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114236. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114237. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  114238. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  114239. };
  114240. static static_codebook _huff_book_line_256x7_class1 = {
  114241. 1, 256,
  114242. _huff_lengthlist_line_256x7_class1,
  114243. 0, 0, 0, 0, 0,
  114244. NULL,
  114245. NULL,
  114246. NULL,
  114247. NULL,
  114248. 0
  114249. };
  114250. static long _huff_lengthlist_line_512x17_0sub0[] = {
  114251. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  114252. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  114253. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  114254. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  114255. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  114256. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  114257. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  114258. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114259. };
  114260. static static_codebook _huff_book_line_512x17_0sub0 = {
  114261. 1, 128,
  114262. _huff_lengthlist_line_512x17_0sub0,
  114263. 0, 0, 0, 0, 0,
  114264. NULL,
  114265. NULL,
  114266. NULL,
  114267. NULL,
  114268. 0
  114269. };
  114270. static long _huff_lengthlist_line_512x17_1sub0[] = {
  114271. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  114272. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  114273. };
  114274. static static_codebook _huff_book_line_512x17_1sub0 = {
  114275. 1, 32,
  114276. _huff_lengthlist_line_512x17_1sub0,
  114277. 0, 0, 0, 0, 0,
  114278. NULL,
  114279. NULL,
  114280. NULL,
  114281. NULL,
  114282. 0
  114283. };
  114284. static long _huff_lengthlist_line_512x17_1sub1[] = {
  114285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114287. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  114288. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  114289. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  114290. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  114291. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  114292. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114293. };
  114294. static static_codebook _huff_book_line_512x17_1sub1 = {
  114295. 1, 128,
  114296. _huff_lengthlist_line_512x17_1sub1,
  114297. 0, 0, 0, 0, 0,
  114298. NULL,
  114299. NULL,
  114300. NULL,
  114301. NULL,
  114302. 0
  114303. };
  114304. static long _huff_lengthlist_line_512x17_2sub1[] = {
  114305. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  114306. 5, 3,
  114307. };
  114308. static static_codebook _huff_book_line_512x17_2sub1 = {
  114309. 1, 18,
  114310. _huff_lengthlist_line_512x17_2sub1,
  114311. 0, 0, 0, 0, 0,
  114312. NULL,
  114313. NULL,
  114314. NULL,
  114315. NULL,
  114316. 0
  114317. };
  114318. static long _huff_lengthlist_line_512x17_2sub2[] = {
  114319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114320. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  114321. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  114322. 9, 8,
  114323. };
  114324. static static_codebook _huff_book_line_512x17_2sub2 = {
  114325. 1, 50,
  114326. _huff_lengthlist_line_512x17_2sub2,
  114327. 0, 0, 0, 0, 0,
  114328. NULL,
  114329. NULL,
  114330. NULL,
  114331. NULL,
  114332. 0
  114333. };
  114334. static long _huff_lengthlist_line_512x17_2sub3[] = {
  114335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114338. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  114339. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  114340. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114341. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114343. };
  114344. static static_codebook _huff_book_line_512x17_2sub3 = {
  114345. 1, 128,
  114346. _huff_lengthlist_line_512x17_2sub3,
  114347. 0, 0, 0, 0, 0,
  114348. NULL,
  114349. NULL,
  114350. NULL,
  114351. NULL,
  114352. 0
  114353. };
  114354. static long _huff_lengthlist_line_512x17_3sub1[] = {
  114355. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  114356. 5, 5,
  114357. };
  114358. static static_codebook _huff_book_line_512x17_3sub1 = {
  114359. 1, 18,
  114360. _huff_lengthlist_line_512x17_3sub1,
  114361. 0, 0, 0, 0, 0,
  114362. NULL,
  114363. NULL,
  114364. NULL,
  114365. NULL,
  114366. 0
  114367. };
  114368. static long _huff_lengthlist_line_512x17_3sub2[] = {
  114369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114370. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  114371. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  114372. 11,14,
  114373. };
  114374. static static_codebook _huff_book_line_512x17_3sub2 = {
  114375. 1, 50,
  114376. _huff_lengthlist_line_512x17_3sub2,
  114377. 0, 0, 0, 0, 0,
  114378. NULL,
  114379. NULL,
  114380. NULL,
  114381. NULL,
  114382. 0
  114383. };
  114384. static long _huff_lengthlist_line_512x17_3sub3[] = {
  114385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114388. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  114389. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114390. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114391. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114392. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114393. };
  114394. static static_codebook _huff_book_line_512x17_3sub3 = {
  114395. 1, 128,
  114396. _huff_lengthlist_line_512x17_3sub3,
  114397. 0, 0, 0, 0, 0,
  114398. NULL,
  114399. NULL,
  114400. NULL,
  114401. NULL,
  114402. 0
  114403. };
  114404. static long _huff_lengthlist_line_512x17_class1[] = {
  114405. 1, 2, 3, 6, 5, 4, 7, 7,
  114406. };
  114407. static static_codebook _huff_book_line_512x17_class1 = {
  114408. 1, 8,
  114409. _huff_lengthlist_line_512x17_class1,
  114410. 0, 0, 0, 0, 0,
  114411. NULL,
  114412. NULL,
  114413. NULL,
  114414. NULL,
  114415. 0
  114416. };
  114417. static long _huff_lengthlist_line_512x17_class2[] = {
  114418. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  114419. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  114420. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  114421. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  114422. };
  114423. static static_codebook _huff_book_line_512x17_class2 = {
  114424. 1, 64,
  114425. _huff_lengthlist_line_512x17_class2,
  114426. 0, 0, 0, 0, 0,
  114427. NULL,
  114428. NULL,
  114429. NULL,
  114430. NULL,
  114431. 0
  114432. };
  114433. static long _huff_lengthlist_line_512x17_class3[] = {
  114434. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  114435. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  114436. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  114437. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  114438. };
  114439. static static_codebook _huff_book_line_512x17_class3 = {
  114440. 1, 64,
  114441. _huff_lengthlist_line_512x17_class3,
  114442. 0, 0, 0, 0, 0,
  114443. NULL,
  114444. NULL,
  114445. NULL,
  114446. NULL,
  114447. 0
  114448. };
  114449. static long _huff_lengthlist_line_128x4_class0[] = {
  114450. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  114451. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  114452. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  114453. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  114454. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  114455. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  114456. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  114457. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  114458. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  114459. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  114460. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  114461. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  114462. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  114463. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  114464. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  114465. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  114466. };
  114467. static static_codebook _huff_book_line_128x4_class0 = {
  114468. 1, 256,
  114469. _huff_lengthlist_line_128x4_class0,
  114470. 0, 0, 0, 0, 0,
  114471. NULL,
  114472. NULL,
  114473. NULL,
  114474. NULL,
  114475. 0
  114476. };
  114477. static long _huff_lengthlist_line_128x4_0sub0[] = {
  114478. 2, 2, 2, 2,
  114479. };
  114480. static static_codebook _huff_book_line_128x4_0sub0 = {
  114481. 1, 4,
  114482. _huff_lengthlist_line_128x4_0sub0,
  114483. 0, 0, 0, 0, 0,
  114484. NULL,
  114485. NULL,
  114486. NULL,
  114487. NULL,
  114488. 0
  114489. };
  114490. static long _huff_lengthlist_line_128x4_0sub1[] = {
  114491. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  114492. };
  114493. static static_codebook _huff_book_line_128x4_0sub1 = {
  114494. 1, 10,
  114495. _huff_lengthlist_line_128x4_0sub1,
  114496. 0, 0, 0, 0, 0,
  114497. NULL,
  114498. NULL,
  114499. NULL,
  114500. NULL,
  114501. 0
  114502. };
  114503. static long _huff_lengthlist_line_128x4_0sub2[] = {
  114504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  114505. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  114506. };
  114507. static static_codebook _huff_book_line_128x4_0sub2 = {
  114508. 1, 25,
  114509. _huff_lengthlist_line_128x4_0sub2,
  114510. 0, 0, 0, 0, 0,
  114511. NULL,
  114512. NULL,
  114513. NULL,
  114514. NULL,
  114515. 0
  114516. };
  114517. static long _huff_lengthlist_line_128x4_0sub3[] = {
  114518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  114520. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  114521. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  114522. };
  114523. static static_codebook _huff_book_line_128x4_0sub3 = {
  114524. 1, 64,
  114525. _huff_lengthlist_line_128x4_0sub3,
  114526. 0, 0, 0, 0, 0,
  114527. NULL,
  114528. NULL,
  114529. NULL,
  114530. NULL,
  114531. 0
  114532. };
  114533. static long _huff_lengthlist_line_256x4_class0[] = {
  114534. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  114535. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  114536. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  114537. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  114538. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  114539. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  114540. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  114541. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  114542. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  114543. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  114544. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  114545. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  114546. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  114547. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  114548. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  114549. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  114550. };
  114551. static static_codebook _huff_book_line_256x4_class0 = {
  114552. 1, 256,
  114553. _huff_lengthlist_line_256x4_class0,
  114554. 0, 0, 0, 0, 0,
  114555. NULL,
  114556. NULL,
  114557. NULL,
  114558. NULL,
  114559. 0
  114560. };
  114561. static long _huff_lengthlist_line_256x4_0sub0[] = {
  114562. 2, 2, 2, 2,
  114563. };
  114564. static static_codebook _huff_book_line_256x4_0sub0 = {
  114565. 1, 4,
  114566. _huff_lengthlist_line_256x4_0sub0,
  114567. 0, 0, 0, 0, 0,
  114568. NULL,
  114569. NULL,
  114570. NULL,
  114571. NULL,
  114572. 0
  114573. };
  114574. static long _huff_lengthlist_line_256x4_0sub1[] = {
  114575. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  114576. };
  114577. static static_codebook _huff_book_line_256x4_0sub1 = {
  114578. 1, 10,
  114579. _huff_lengthlist_line_256x4_0sub1,
  114580. 0, 0, 0, 0, 0,
  114581. NULL,
  114582. NULL,
  114583. NULL,
  114584. NULL,
  114585. 0
  114586. };
  114587. static long _huff_lengthlist_line_256x4_0sub2[] = {
  114588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  114589. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  114590. };
  114591. static static_codebook _huff_book_line_256x4_0sub2 = {
  114592. 1, 25,
  114593. _huff_lengthlist_line_256x4_0sub2,
  114594. 0, 0, 0, 0, 0,
  114595. NULL,
  114596. NULL,
  114597. NULL,
  114598. NULL,
  114599. 0
  114600. };
  114601. static long _huff_lengthlist_line_256x4_0sub3[] = {
  114602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  114604. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  114605. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  114606. };
  114607. static static_codebook _huff_book_line_256x4_0sub3 = {
  114608. 1, 64,
  114609. _huff_lengthlist_line_256x4_0sub3,
  114610. 0, 0, 0, 0, 0,
  114611. NULL,
  114612. NULL,
  114613. NULL,
  114614. NULL,
  114615. 0
  114616. };
  114617. static long _huff_lengthlist_line_128x7_class0[] = {
  114618. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  114619. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  114620. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  114621. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  114622. };
  114623. static static_codebook _huff_book_line_128x7_class0 = {
  114624. 1, 64,
  114625. _huff_lengthlist_line_128x7_class0,
  114626. 0, 0, 0, 0, 0,
  114627. NULL,
  114628. NULL,
  114629. NULL,
  114630. NULL,
  114631. 0
  114632. };
  114633. static long _huff_lengthlist_line_128x7_class1[] = {
  114634. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  114635. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  114636. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  114637. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  114638. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  114639. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  114640. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  114641. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  114642. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  114643. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  114644. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  114645. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  114646. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  114647. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  114648. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  114649. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  114650. };
  114651. static static_codebook _huff_book_line_128x7_class1 = {
  114652. 1, 256,
  114653. _huff_lengthlist_line_128x7_class1,
  114654. 0, 0, 0, 0, 0,
  114655. NULL,
  114656. NULL,
  114657. NULL,
  114658. NULL,
  114659. 0
  114660. };
  114661. static long _huff_lengthlist_line_128x7_0sub1[] = {
  114662. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  114663. };
  114664. static static_codebook _huff_book_line_128x7_0sub1 = {
  114665. 1, 9,
  114666. _huff_lengthlist_line_128x7_0sub1,
  114667. 0, 0, 0, 0, 0,
  114668. NULL,
  114669. NULL,
  114670. NULL,
  114671. NULL,
  114672. 0
  114673. };
  114674. static long _huff_lengthlist_line_128x7_0sub2[] = {
  114675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  114676. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  114677. };
  114678. static static_codebook _huff_book_line_128x7_0sub2 = {
  114679. 1, 25,
  114680. _huff_lengthlist_line_128x7_0sub2,
  114681. 0, 0, 0, 0, 0,
  114682. NULL,
  114683. NULL,
  114684. NULL,
  114685. NULL,
  114686. 0
  114687. };
  114688. static long _huff_lengthlist_line_128x7_0sub3[] = {
  114689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  114691. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  114692. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  114693. };
  114694. static static_codebook _huff_book_line_128x7_0sub3 = {
  114695. 1, 64,
  114696. _huff_lengthlist_line_128x7_0sub3,
  114697. 0, 0, 0, 0, 0,
  114698. NULL,
  114699. NULL,
  114700. NULL,
  114701. NULL,
  114702. 0
  114703. };
  114704. static long _huff_lengthlist_line_128x7_1sub1[] = {
  114705. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  114706. };
  114707. static static_codebook _huff_book_line_128x7_1sub1 = {
  114708. 1, 9,
  114709. _huff_lengthlist_line_128x7_1sub1,
  114710. 0, 0, 0, 0, 0,
  114711. NULL,
  114712. NULL,
  114713. NULL,
  114714. NULL,
  114715. 0
  114716. };
  114717. static long _huff_lengthlist_line_128x7_1sub2[] = {
  114718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  114719. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  114720. };
  114721. static static_codebook _huff_book_line_128x7_1sub2 = {
  114722. 1, 25,
  114723. _huff_lengthlist_line_128x7_1sub2,
  114724. 0, 0, 0, 0, 0,
  114725. NULL,
  114726. NULL,
  114727. NULL,
  114728. NULL,
  114729. 0
  114730. };
  114731. static long _huff_lengthlist_line_128x7_1sub3[] = {
  114732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  114734. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  114735. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  114736. };
  114737. static static_codebook _huff_book_line_128x7_1sub3 = {
  114738. 1, 64,
  114739. _huff_lengthlist_line_128x7_1sub3,
  114740. 0, 0, 0, 0, 0,
  114741. NULL,
  114742. NULL,
  114743. NULL,
  114744. NULL,
  114745. 0
  114746. };
  114747. static long _huff_lengthlist_line_128x11_class1[] = {
  114748. 1, 6, 3, 7, 2, 4, 5, 7,
  114749. };
  114750. static static_codebook _huff_book_line_128x11_class1 = {
  114751. 1, 8,
  114752. _huff_lengthlist_line_128x11_class1,
  114753. 0, 0, 0, 0, 0,
  114754. NULL,
  114755. NULL,
  114756. NULL,
  114757. NULL,
  114758. 0
  114759. };
  114760. static long _huff_lengthlist_line_128x11_class2[] = {
  114761. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  114762. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  114763. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  114764. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  114765. };
  114766. static static_codebook _huff_book_line_128x11_class2 = {
  114767. 1, 64,
  114768. _huff_lengthlist_line_128x11_class2,
  114769. 0, 0, 0, 0, 0,
  114770. NULL,
  114771. NULL,
  114772. NULL,
  114773. NULL,
  114774. 0
  114775. };
  114776. static long _huff_lengthlist_line_128x11_class3[] = {
  114777. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  114778. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  114779. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  114780. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  114781. };
  114782. static static_codebook _huff_book_line_128x11_class3 = {
  114783. 1, 64,
  114784. _huff_lengthlist_line_128x11_class3,
  114785. 0, 0, 0, 0, 0,
  114786. NULL,
  114787. NULL,
  114788. NULL,
  114789. NULL,
  114790. 0
  114791. };
  114792. static long _huff_lengthlist_line_128x11_0sub0[] = {
  114793. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  114794. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  114795. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  114796. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  114797. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  114798. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  114799. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  114800. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  114801. };
  114802. static static_codebook _huff_book_line_128x11_0sub0 = {
  114803. 1, 128,
  114804. _huff_lengthlist_line_128x11_0sub0,
  114805. 0, 0, 0, 0, 0,
  114806. NULL,
  114807. NULL,
  114808. NULL,
  114809. NULL,
  114810. 0
  114811. };
  114812. static long _huff_lengthlist_line_128x11_1sub0[] = {
  114813. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  114814. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  114815. };
  114816. static static_codebook _huff_book_line_128x11_1sub0 = {
  114817. 1, 32,
  114818. _huff_lengthlist_line_128x11_1sub0,
  114819. 0, 0, 0, 0, 0,
  114820. NULL,
  114821. NULL,
  114822. NULL,
  114823. NULL,
  114824. 0
  114825. };
  114826. static long _huff_lengthlist_line_128x11_1sub1[] = {
  114827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114829. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  114830. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  114831. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  114832. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  114833. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  114834. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  114835. };
  114836. static static_codebook _huff_book_line_128x11_1sub1 = {
  114837. 1, 128,
  114838. _huff_lengthlist_line_128x11_1sub1,
  114839. 0, 0, 0, 0, 0,
  114840. NULL,
  114841. NULL,
  114842. NULL,
  114843. NULL,
  114844. 0
  114845. };
  114846. static long _huff_lengthlist_line_128x11_2sub1[] = {
  114847. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  114848. 5, 5,
  114849. };
  114850. static static_codebook _huff_book_line_128x11_2sub1 = {
  114851. 1, 18,
  114852. _huff_lengthlist_line_128x11_2sub1,
  114853. 0, 0, 0, 0, 0,
  114854. NULL,
  114855. NULL,
  114856. NULL,
  114857. NULL,
  114858. 0
  114859. };
  114860. static long _huff_lengthlist_line_128x11_2sub2[] = {
  114861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114862. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  114863. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  114864. 8,11,
  114865. };
  114866. static static_codebook _huff_book_line_128x11_2sub2 = {
  114867. 1, 50,
  114868. _huff_lengthlist_line_128x11_2sub2,
  114869. 0, 0, 0, 0, 0,
  114870. NULL,
  114871. NULL,
  114872. NULL,
  114873. NULL,
  114874. 0
  114875. };
  114876. static long _huff_lengthlist_line_128x11_2sub3[] = {
  114877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114880. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  114881. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114882. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114883. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114884. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114885. };
  114886. static static_codebook _huff_book_line_128x11_2sub3 = {
  114887. 1, 128,
  114888. _huff_lengthlist_line_128x11_2sub3,
  114889. 0, 0, 0, 0, 0,
  114890. NULL,
  114891. NULL,
  114892. NULL,
  114893. NULL,
  114894. 0
  114895. };
  114896. static long _huff_lengthlist_line_128x11_3sub1[] = {
  114897. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  114898. 5, 4,
  114899. };
  114900. static static_codebook _huff_book_line_128x11_3sub1 = {
  114901. 1, 18,
  114902. _huff_lengthlist_line_128x11_3sub1,
  114903. 0, 0, 0, 0, 0,
  114904. NULL,
  114905. NULL,
  114906. NULL,
  114907. NULL,
  114908. 0
  114909. };
  114910. static long _huff_lengthlist_line_128x11_3sub2[] = {
  114911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114912. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  114913. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  114914. 12, 6,
  114915. };
  114916. static static_codebook _huff_book_line_128x11_3sub2 = {
  114917. 1, 50,
  114918. _huff_lengthlist_line_128x11_3sub2,
  114919. 0, 0, 0, 0, 0,
  114920. NULL,
  114921. NULL,
  114922. NULL,
  114923. NULL,
  114924. 0
  114925. };
  114926. static long _huff_lengthlist_line_128x11_3sub3[] = {
  114927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114930. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  114931. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  114932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  114935. };
  114936. static static_codebook _huff_book_line_128x11_3sub3 = {
  114937. 1, 128,
  114938. _huff_lengthlist_line_128x11_3sub3,
  114939. 0, 0, 0, 0, 0,
  114940. NULL,
  114941. NULL,
  114942. NULL,
  114943. NULL,
  114944. 0
  114945. };
  114946. static long _huff_lengthlist_line_128x17_class1[] = {
  114947. 1, 3, 4, 7, 2, 5, 6, 7,
  114948. };
  114949. static static_codebook _huff_book_line_128x17_class1 = {
  114950. 1, 8,
  114951. _huff_lengthlist_line_128x17_class1,
  114952. 0, 0, 0, 0, 0,
  114953. NULL,
  114954. NULL,
  114955. NULL,
  114956. NULL,
  114957. 0
  114958. };
  114959. static long _huff_lengthlist_line_128x17_class2[] = {
  114960. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  114961. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  114962. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  114963. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114964. };
  114965. static static_codebook _huff_book_line_128x17_class2 = {
  114966. 1, 64,
  114967. _huff_lengthlist_line_128x17_class2,
  114968. 0, 0, 0, 0, 0,
  114969. NULL,
  114970. NULL,
  114971. NULL,
  114972. NULL,
  114973. 0
  114974. };
  114975. static long _huff_lengthlist_line_128x17_class3[] = {
  114976. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  114977. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  114978. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  114979. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  114980. };
  114981. static static_codebook _huff_book_line_128x17_class3 = {
  114982. 1, 64,
  114983. _huff_lengthlist_line_128x17_class3,
  114984. 0, 0, 0, 0, 0,
  114985. NULL,
  114986. NULL,
  114987. NULL,
  114988. NULL,
  114989. 0
  114990. };
  114991. static long _huff_lengthlist_line_128x17_0sub0[] = {
  114992. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  114993. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  114994. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  114995. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  114996. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  114997. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  114998. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  114999. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115000. };
  115001. static static_codebook _huff_book_line_128x17_0sub0 = {
  115002. 1, 128,
  115003. _huff_lengthlist_line_128x17_0sub0,
  115004. 0, 0, 0, 0, 0,
  115005. NULL,
  115006. NULL,
  115007. NULL,
  115008. NULL,
  115009. 0
  115010. };
  115011. static long _huff_lengthlist_line_128x17_1sub0[] = {
  115012. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115013. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  115014. };
  115015. static static_codebook _huff_book_line_128x17_1sub0 = {
  115016. 1, 32,
  115017. _huff_lengthlist_line_128x17_1sub0,
  115018. 0, 0, 0, 0, 0,
  115019. NULL,
  115020. NULL,
  115021. NULL,
  115022. NULL,
  115023. 0
  115024. };
  115025. static long _huff_lengthlist_line_128x17_1sub1[] = {
  115026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115028. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  115029. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  115030. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  115031. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  115032. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  115033. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  115034. };
  115035. static static_codebook _huff_book_line_128x17_1sub1 = {
  115036. 1, 128,
  115037. _huff_lengthlist_line_128x17_1sub1,
  115038. 0, 0, 0, 0, 0,
  115039. NULL,
  115040. NULL,
  115041. NULL,
  115042. NULL,
  115043. 0
  115044. };
  115045. static long _huff_lengthlist_line_128x17_2sub1[] = {
  115046. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  115047. 9, 4,
  115048. };
  115049. static static_codebook _huff_book_line_128x17_2sub1 = {
  115050. 1, 18,
  115051. _huff_lengthlist_line_128x17_2sub1,
  115052. 0, 0, 0, 0, 0,
  115053. NULL,
  115054. NULL,
  115055. NULL,
  115056. NULL,
  115057. 0
  115058. };
  115059. static long _huff_lengthlist_line_128x17_2sub2[] = {
  115060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115061. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  115062. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  115063. 13,13,
  115064. };
  115065. static static_codebook _huff_book_line_128x17_2sub2 = {
  115066. 1, 50,
  115067. _huff_lengthlist_line_128x17_2sub2,
  115068. 0, 0, 0, 0, 0,
  115069. NULL,
  115070. NULL,
  115071. NULL,
  115072. NULL,
  115073. 0
  115074. };
  115075. static long _huff_lengthlist_line_128x17_2sub3[] = {
  115076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115079. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115080. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  115081. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115082. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115083. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115084. };
  115085. static static_codebook _huff_book_line_128x17_2sub3 = {
  115086. 1, 128,
  115087. _huff_lengthlist_line_128x17_2sub3,
  115088. 0, 0, 0, 0, 0,
  115089. NULL,
  115090. NULL,
  115091. NULL,
  115092. NULL,
  115093. 0
  115094. };
  115095. static long _huff_lengthlist_line_128x17_3sub1[] = {
  115096. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  115097. 6, 4,
  115098. };
  115099. static static_codebook _huff_book_line_128x17_3sub1 = {
  115100. 1, 18,
  115101. _huff_lengthlist_line_128x17_3sub1,
  115102. 0, 0, 0, 0, 0,
  115103. NULL,
  115104. NULL,
  115105. NULL,
  115106. NULL,
  115107. 0
  115108. };
  115109. static long _huff_lengthlist_line_128x17_3sub2[] = {
  115110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115111. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115112. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  115113. 10, 8,
  115114. };
  115115. static static_codebook _huff_book_line_128x17_3sub2 = {
  115116. 1, 50,
  115117. _huff_lengthlist_line_128x17_3sub2,
  115118. 0, 0, 0, 0, 0,
  115119. NULL,
  115120. NULL,
  115121. NULL,
  115122. NULL,
  115123. 0
  115124. };
  115125. static long _huff_lengthlist_line_128x17_3sub3[] = {
  115126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115129. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  115130. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  115131. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115134. };
  115135. static static_codebook _huff_book_line_128x17_3sub3 = {
  115136. 1, 128,
  115137. _huff_lengthlist_line_128x17_3sub3,
  115138. 0, 0, 0, 0, 0,
  115139. NULL,
  115140. NULL,
  115141. NULL,
  115142. NULL,
  115143. 0
  115144. };
  115145. static long _huff_lengthlist_line_1024x27_class1[] = {
  115146. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  115147. };
  115148. static static_codebook _huff_book_line_1024x27_class1 = {
  115149. 1, 16,
  115150. _huff_lengthlist_line_1024x27_class1,
  115151. 0, 0, 0, 0, 0,
  115152. NULL,
  115153. NULL,
  115154. NULL,
  115155. NULL,
  115156. 0
  115157. };
  115158. static long _huff_lengthlist_line_1024x27_class2[] = {
  115159. 1, 4, 2, 6, 3, 7, 5, 7,
  115160. };
  115161. static static_codebook _huff_book_line_1024x27_class2 = {
  115162. 1, 8,
  115163. _huff_lengthlist_line_1024x27_class2,
  115164. 0, 0, 0, 0, 0,
  115165. NULL,
  115166. NULL,
  115167. NULL,
  115168. NULL,
  115169. 0
  115170. };
  115171. static long _huff_lengthlist_line_1024x27_class3[] = {
  115172. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  115173. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  115174. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  115175. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  115176. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  115177. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  115178. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  115179. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  115180. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  115181. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  115182. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  115183. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115184. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  115185. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  115186. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  115187. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115188. };
  115189. static static_codebook _huff_book_line_1024x27_class3 = {
  115190. 1, 256,
  115191. _huff_lengthlist_line_1024x27_class3,
  115192. 0, 0, 0, 0, 0,
  115193. NULL,
  115194. NULL,
  115195. NULL,
  115196. NULL,
  115197. 0
  115198. };
  115199. static long _huff_lengthlist_line_1024x27_class4[] = {
  115200. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  115201. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  115202. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  115203. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  115204. };
  115205. static static_codebook _huff_book_line_1024x27_class4 = {
  115206. 1, 64,
  115207. _huff_lengthlist_line_1024x27_class4,
  115208. 0, 0, 0, 0, 0,
  115209. NULL,
  115210. NULL,
  115211. NULL,
  115212. NULL,
  115213. 0
  115214. };
  115215. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  115216. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115217. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  115218. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  115219. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  115220. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  115221. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  115222. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  115223. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  115224. };
  115225. static static_codebook _huff_book_line_1024x27_0sub0 = {
  115226. 1, 128,
  115227. _huff_lengthlist_line_1024x27_0sub0,
  115228. 0, 0, 0, 0, 0,
  115229. NULL,
  115230. NULL,
  115231. NULL,
  115232. NULL,
  115233. 0
  115234. };
  115235. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  115236. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  115237. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  115238. };
  115239. static static_codebook _huff_book_line_1024x27_1sub0 = {
  115240. 1, 32,
  115241. _huff_lengthlist_line_1024x27_1sub0,
  115242. 0, 0, 0, 0, 0,
  115243. NULL,
  115244. NULL,
  115245. NULL,
  115246. NULL,
  115247. 0
  115248. };
  115249. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  115250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115252. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  115253. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  115254. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  115255. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  115256. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  115257. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  115258. };
  115259. static static_codebook _huff_book_line_1024x27_1sub1 = {
  115260. 1, 128,
  115261. _huff_lengthlist_line_1024x27_1sub1,
  115262. 0, 0, 0, 0, 0,
  115263. NULL,
  115264. NULL,
  115265. NULL,
  115266. NULL,
  115267. 0
  115268. };
  115269. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  115270. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115271. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  115272. };
  115273. static static_codebook _huff_book_line_1024x27_2sub0 = {
  115274. 1, 32,
  115275. _huff_lengthlist_line_1024x27_2sub0,
  115276. 0, 0, 0, 0, 0,
  115277. NULL,
  115278. NULL,
  115279. NULL,
  115280. NULL,
  115281. 0
  115282. };
  115283. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  115284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115286. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  115287. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  115288. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  115289. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  115290. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  115291. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  115292. };
  115293. static static_codebook _huff_book_line_1024x27_2sub1 = {
  115294. 1, 128,
  115295. _huff_lengthlist_line_1024x27_2sub1,
  115296. 0, 0, 0, 0, 0,
  115297. NULL,
  115298. NULL,
  115299. NULL,
  115300. NULL,
  115301. 0
  115302. };
  115303. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  115304. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  115305. 5, 5,
  115306. };
  115307. static static_codebook _huff_book_line_1024x27_3sub1 = {
  115308. 1, 18,
  115309. _huff_lengthlist_line_1024x27_3sub1,
  115310. 0, 0, 0, 0, 0,
  115311. NULL,
  115312. NULL,
  115313. NULL,
  115314. NULL,
  115315. 0
  115316. };
  115317. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  115318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115319. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  115320. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  115321. 9,11,
  115322. };
  115323. static static_codebook _huff_book_line_1024x27_3sub2 = {
  115324. 1, 50,
  115325. _huff_lengthlist_line_1024x27_3sub2,
  115326. 0, 0, 0, 0, 0,
  115327. NULL,
  115328. NULL,
  115329. NULL,
  115330. NULL,
  115331. 0
  115332. };
  115333. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  115334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115337. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  115338. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  115339. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115340. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115341. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115342. };
  115343. static static_codebook _huff_book_line_1024x27_3sub3 = {
  115344. 1, 128,
  115345. _huff_lengthlist_line_1024x27_3sub3,
  115346. 0, 0, 0, 0, 0,
  115347. NULL,
  115348. NULL,
  115349. NULL,
  115350. NULL,
  115351. 0
  115352. };
  115353. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  115354. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  115355. 5, 4,
  115356. };
  115357. static static_codebook _huff_book_line_1024x27_4sub1 = {
  115358. 1, 18,
  115359. _huff_lengthlist_line_1024x27_4sub1,
  115360. 0, 0, 0, 0, 0,
  115361. NULL,
  115362. NULL,
  115363. NULL,
  115364. NULL,
  115365. 0
  115366. };
  115367. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  115368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115369. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  115370. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  115371. 9,12,
  115372. };
  115373. static static_codebook _huff_book_line_1024x27_4sub2 = {
  115374. 1, 50,
  115375. _huff_lengthlist_line_1024x27_4sub2,
  115376. 0, 0, 0, 0, 0,
  115377. NULL,
  115378. NULL,
  115379. NULL,
  115380. NULL,
  115381. 0
  115382. };
  115383. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  115384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115387. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  115388. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  115389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115391. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  115392. };
  115393. static static_codebook _huff_book_line_1024x27_4sub3 = {
  115394. 1, 128,
  115395. _huff_lengthlist_line_1024x27_4sub3,
  115396. 0, 0, 0, 0, 0,
  115397. NULL,
  115398. NULL,
  115399. NULL,
  115400. NULL,
  115401. 0
  115402. };
  115403. static long _huff_lengthlist_line_2048x27_class1[] = {
  115404. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  115405. };
  115406. static static_codebook _huff_book_line_2048x27_class1 = {
  115407. 1, 16,
  115408. _huff_lengthlist_line_2048x27_class1,
  115409. 0, 0, 0, 0, 0,
  115410. NULL,
  115411. NULL,
  115412. NULL,
  115413. NULL,
  115414. 0
  115415. };
  115416. static long _huff_lengthlist_line_2048x27_class2[] = {
  115417. 1, 2, 3, 6, 4, 7, 5, 7,
  115418. };
  115419. static static_codebook _huff_book_line_2048x27_class2 = {
  115420. 1, 8,
  115421. _huff_lengthlist_line_2048x27_class2,
  115422. 0, 0, 0, 0, 0,
  115423. NULL,
  115424. NULL,
  115425. NULL,
  115426. NULL,
  115427. 0
  115428. };
  115429. static long _huff_lengthlist_line_2048x27_class3[] = {
  115430. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  115431. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  115432. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  115433. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  115434. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  115435. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  115436. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  115437. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  115438. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  115439. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  115440. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  115441. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115442. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  115443. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  115444. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115445. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115446. };
  115447. static static_codebook _huff_book_line_2048x27_class3 = {
  115448. 1, 256,
  115449. _huff_lengthlist_line_2048x27_class3,
  115450. 0, 0, 0, 0, 0,
  115451. NULL,
  115452. NULL,
  115453. NULL,
  115454. NULL,
  115455. 0
  115456. };
  115457. static long _huff_lengthlist_line_2048x27_class4[] = {
  115458. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  115459. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  115460. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  115461. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  115462. };
  115463. static static_codebook _huff_book_line_2048x27_class4 = {
  115464. 1, 64,
  115465. _huff_lengthlist_line_2048x27_class4,
  115466. 0, 0, 0, 0, 0,
  115467. NULL,
  115468. NULL,
  115469. NULL,
  115470. NULL,
  115471. 0
  115472. };
  115473. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  115474. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115475. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  115476. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  115477. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  115478. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  115479. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  115480. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  115481. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  115482. };
  115483. static static_codebook _huff_book_line_2048x27_0sub0 = {
  115484. 1, 128,
  115485. _huff_lengthlist_line_2048x27_0sub0,
  115486. 0, 0, 0, 0, 0,
  115487. NULL,
  115488. NULL,
  115489. NULL,
  115490. NULL,
  115491. 0
  115492. };
  115493. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  115494. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  115495. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  115496. };
  115497. static static_codebook _huff_book_line_2048x27_1sub0 = {
  115498. 1, 32,
  115499. _huff_lengthlist_line_2048x27_1sub0,
  115500. 0, 0, 0, 0, 0,
  115501. NULL,
  115502. NULL,
  115503. NULL,
  115504. NULL,
  115505. 0
  115506. };
  115507. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  115508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115510. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  115511. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  115512. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  115513. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  115514. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  115515. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  115516. };
  115517. static static_codebook _huff_book_line_2048x27_1sub1 = {
  115518. 1, 128,
  115519. _huff_lengthlist_line_2048x27_1sub1,
  115520. 0, 0, 0, 0, 0,
  115521. NULL,
  115522. NULL,
  115523. NULL,
  115524. NULL,
  115525. 0
  115526. };
  115527. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  115528. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115529. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  115530. };
  115531. static static_codebook _huff_book_line_2048x27_2sub0 = {
  115532. 1, 32,
  115533. _huff_lengthlist_line_2048x27_2sub0,
  115534. 0, 0, 0, 0, 0,
  115535. NULL,
  115536. NULL,
  115537. NULL,
  115538. NULL,
  115539. 0
  115540. };
  115541. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  115542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115544. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  115545. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  115546. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  115547. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  115548. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  115549. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115550. };
  115551. static static_codebook _huff_book_line_2048x27_2sub1 = {
  115552. 1, 128,
  115553. _huff_lengthlist_line_2048x27_2sub1,
  115554. 0, 0, 0, 0, 0,
  115555. NULL,
  115556. NULL,
  115557. NULL,
  115558. NULL,
  115559. 0
  115560. };
  115561. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  115562. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  115563. 5, 5,
  115564. };
  115565. static static_codebook _huff_book_line_2048x27_3sub1 = {
  115566. 1, 18,
  115567. _huff_lengthlist_line_2048x27_3sub1,
  115568. 0, 0, 0, 0, 0,
  115569. NULL,
  115570. NULL,
  115571. NULL,
  115572. NULL,
  115573. 0
  115574. };
  115575. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  115576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115577. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  115578. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  115579. 10,12,
  115580. };
  115581. static static_codebook _huff_book_line_2048x27_3sub2 = {
  115582. 1, 50,
  115583. _huff_lengthlist_line_2048x27_3sub2,
  115584. 0, 0, 0, 0, 0,
  115585. NULL,
  115586. NULL,
  115587. NULL,
  115588. NULL,
  115589. 0
  115590. };
  115591. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  115592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115595. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  115596. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115597. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115598. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115599. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115600. };
  115601. static static_codebook _huff_book_line_2048x27_3sub3 = {
  115602. 1, 128,
  115603. _huff_lengthlist_line_2048x27_3sub3,
  115604. 0, 0, 0, 0, 0,
  115605. NULL,
  115606. NULL,
  115607. NULL,
  115608. NULL,
  115609. 0
  115610. };
  115611. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  115612. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  115613. 4, 5,
  115614. };
  115615. static static_codebook _huff_book_line_2048x27_4sub1 = {
  115616. 1, 18,
  115617. _huff_lengthlist_line_2048x27_4sub1,
  115618. 0, 0, 0, 0, 0,
  115619. NULL,
  115620. NULL,
  115621. NULL,
  115622. NULL,
  115623. 0
  115624. };
  115625. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  115626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115627. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  115628. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  115629. 10,10,
  115630. };
  115631. static static_codebook _huff_book_line_2048x27_4sub2 = {
  115632. 1, 50,
  115633. _huff_lengthlist_line_2048x27_4sub2,
  115634. 0, 0, 0, 0, 0,
  115635. NULL,
  115636. NULL,
  115637. NULL,
  115638. NULL,
  115639. 0
  115640. };
  115641. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  115642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115645. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  115646. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  115647. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115648. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115649. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115650. };
  115651. static static_codebook _huff_book_line_2048x27_4sub3 = {
  115652. 1, 128,
  115653. _huff_lengthlist_line_2048x27_4sub3,
  115654. 0, 0, 0, 0, 0,
  115655. NULL,
  115656. NULL,
  115657. NULL,
  115658. NULL,
  115659. 0
  115660. };
  115661. static long _huff_lengthlist_line_256x4low_class0[] = {
  115662. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  115663. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  115664. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  115665. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  115666. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  115667. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  115668. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  115669. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  115670. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  115671. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  115672. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  115673. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  115674. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  115675. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  115676. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  115677. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  115678. };
  115679. static static_codebook _huff_book_line_256x4low_class0 = {
  115680. 1, 256,
  115681. _huff_lengthlist_line_256x4low_class0,
  115682. 0, 0, 0, 0, 0,
  115683. NULL,
  115684. NULL,
  115685. NULL,
  115686. NULL,
  115687. 0
  115688. };
  115689. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  115690. 1, 3, 2, 3,
  115691. };
  115692. static static_codebook _huff_book_line_256x4low_0sub0 = {
  115693. 1, 4,
  115694. _huff_lengthlist_line_256x4low_0sub0,
  115695. 0, 0, 0, 0, 0,
  115696. NULL,
  115697. NULL,
  115698. NULL,
  115699. NULL,
  115700. 0
  115701. };
  115702. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  115703. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  115704. };
  115705. static static_codebook _huff_book_line_256x4low_0sub1 = {
  115706. 1, 10,
  115707. _huff_lengthlist_line_256x4low_0sub1,
  115708. 0, 0, 0, 0, 0,
  115709. NULL,
  115710. NULL,
  115711. NULL,
  115712. NULL,
  115713. 0
  115714. };
  115715. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  115716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  115717. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  115718. };
  115719. static static_codebook _huff_book_line_256x4low_0sub2 = {
  115720. 1, 25,
  115721. _huff_lengthlist_line_256x4low_0sub2,
  115722. 0, 0, 0, 0, 0,
  115723. NULL,
  115724. NULL,
  115725. NULL,
  115726. NULL,
  115727. 0
  115728. };
  115729. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  115730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  115732. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  115733. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  115734. };
  115735. static static_codebook _huff_book_line_256x4low_0sub3 = {
  115736. 1, 64,
  115737. _huff_lengthlist_line_256x4low_0sub3,
  115738. 0, 0, 0, 0, 0,
  115739. NULL,
  115740. NULL,
  115741. NULL,
  115742. NULL,
  115743. 0
  115744. };
  115745. /********* End of inlined file: floor_books.h *********/
  115746. static static_codebook *_floor_128x4_books[]={
  115747. &_huff_book_line_128x4_class0,
  115748. &_huff_book_line_128x4_0sub0,
  115749. &_huff_book_line_128x4_0sub1,
  115750. &_huff_book_line_128x4_0sub2,
  115751. &_huff_book_line_128x4_0sub3,
  115752. };
  115753. static static_codebook *_floor_256x4_books[]={
  115754. &_huff_book_line_256x4_class0,
  115755. &_huff_book_line_256x4_0sub0,
  115756. &_huff_book_line_256x4_0sub1,
  115757. &_huff_book_line_256x4_0sub2,
  115758. &_huff_book_line_256x4_0sub3,
  115759. };
  115760. static static_codebook *_floor_128x7_books[]={
  115761. &_huff_book_line_128x7_class0,
  115762. &_huff_book_line_128x7_class1,
  115763. &_huff_book_line_128x7_0sub1,
  115764. &_huff_book_line_128x7_0sub2,
  115765. &_huff_book_line_128x7_0sub3,
  115766. &_huff_book_line_128x7_1sub1,
  115767. &_huff_book_line_128x7_1sub2,
  115768. &_huff_book_line_128x7_1sub3,
  115769. };
  115770. static static_codebook *_floor_256x7_books[]={
  115771. &_huff_book_line_256x7_class0,
  115772. &_huff_book_line_256x7_class1,
  115773. &_huff_book_line_256x7_0sub1,
  115774. &_huff_book_line_256x7_0sub2,
  115775. &_huff_book_line_256x7_0sub3,
  115776. &_huff_book_line_256x7_1sub1,
  115777. &_huff_book_line_256x7_1sub2,
  115778. &_huff_book_line_256x7_1sub3,
  115779. };
  115780. static static_codebook *_floor_128x11_books[]={
  115781. &_huff_book_line_128x11_class1,
  115782. &_huff_book_line_128x11_class2,
  115783. &_huff_book_line_128x11_class3,
  115784. &_huff_book_line_128x11_0sub0,
  115785. &_huff_book_line_128x11_1sub0,
  115786. &_huff_book_line_128x11_1sub1,
  115787. &_huff_book_line_128x11_2sub1,
  115788. &_huff_book_line_128x11_2sub2,
  115789. &_huff_book_line_128x11_2sub3,
  115790. &_huff_book_line_128x11_3sub1,
  115791. &_huff_book_line_128x11_3sub2,
  115792. &_huff_book_line_128x11_3sub3,
  115793. };
  115794. static static_codebook *_floor_128x17_books[]={
  115795. &_huff_book_line_128x17_class1,
  115796. &_huff_book_line_128x17_class2,
  115797. &_huff_book_line_128x17_class3,
  115798. &_huff_book_line_128x17_0sub0,
  115799. &_huff_book_line_128x17_1sub0,
  115800. &_huff_book_line_128x17_1sub1,
  115801. &_huff_book_line_128x17_2sub1,
  115802. &_huff_book_line_128x17_2sub2,
  115803. &_huff_book_line_128x17_2sub3,
  115804. &_huff_book_line_128x17_3sub1,
  115805. &_huff_book_line_128x17_3sub2,
  115806. &_huff_book_line_128x17_3sub3,
  115807. };
  115808. static static_codebook *_floor_256x4low_books[]={
  115809. &_huff_book_line_256x4low_class0,
  115810. &_huff_book_line_256x4low_0sub0,
  115811. &_huff_book_line_256x4low_0sub1,
  115812. &_huff_book_line_256x4low_0sub2,
  115813. &_huff_book_line_256x4low_0sub3,
  115814. };
  115815. static static_codebook *_floor_1024x27_books[]={
  115816. &_huff_book_line_1024x27_class1,
  115817. &_huff_book_line_1024x27_class2,
  115818. &_huff_book_line_1024x27_class3,
  115819. &_huff_book_line_1024x27_class4,
  115820. &_huff_book_line_1024x27_0sub0,
  115821. &_huff_book_line_1024x27_1sub0,
  115822. &_huff_book_line_1024x27_1sub1,
  115823. &_huff_book_line_1024x27_2sub0,
  115824. &_huff_book_line_1024x27_2sub1,
  115825. &_huff_book_line_1024x27_3sub1,
  115826. &_huff_book_line_1024x27_3sub2,
  115827. &_huff_book_line_1024x27_3sub3,
  115828. &_huff_book_line_1024x27_4sub1,
  115829. &_huff_book_line_1024x27_4sub2,
  115830. &_huff_book_line_1024x27_4sub3,
  115831. };
  115832. static static_codebook *_floor_2048x27_books[]={
  115833. &_huff_book_line_2048x27_class1,
  115834. &_huff_book_line_2048x27_class2,
  115835. &_huff_book_line_2048x27_class3,
  115836. &_huff_book_line_2048x27_class4,
  115837. &_huff_book_line_2048x27_0sub0,
  115838. &_huff_book_line_2048x27_1sub0,
  115839. &_huff_book_line_2048x27_1sub1,
  115840. &_huff_book_line_2048x27_2sub0,
  115841. &_huff_book_line_2048x27_2sub1,
  115842. &_huff_book_line_2048x27_3sub1,
  115843. &_huff_book_line_2048x27_3sub2,
  115844. &_huff_book_line_2048x27_3sub3,
  115845. &_huff_book_line_2048x27_4sub1,
  115846. &_huff_book_line_2048x27_4sub2,
  115847. &_huff_book_line_2048x27_4sub3,
  115848. };
  115849. static static_codebook *_floor_512x17_books[]={
  115850. &_huff_book_line_512x17_class1,
  115851. &_huff_book_line_512x17_class2,
  115852. &_huff_book_line_512x17_class3,
  115853. &_huff_book_line_512x17_0sub0,
  115854. &_huff_book_line_512x17_1sub0,
  115855. &_huff_book_line_512x17_1sub1,
  115856. &_huff_book_line_512x17_2sub1,
  115857. &_huff_book_line_512x17_2sub2,
  115858. &_huff_book_line_512x17_2sub3,
  115859. &_huff_book_line_512x17_3sub1,
  115860. &_huff_book_line_512x17_3sub2,
  115861. &_huff_book_line_512x17_3sub3,
  115862. };
  115863. static static_codebook **_floor_books[10]={
  115864. _floor_128x4_books,
  115865. _floor_256x4_books,
  115866. _floor_128x7_books,
  115867. _floor_256x7_books,
  115868. _floor_128x11_books,
  115869. _floor_128x17_books,
  115870. _floor_256x4low_books,
  115871. _floor_1024x27_books,
  115872. _floor_2048x27_books,
  115873. _floor_512x17_books,
  115874. };
  115875. static vorbis_info_floor1 _floor[10]={
  115876. /* 128 x 4 */
  115877. {
  115878. 1,{0},{4},{2},{0},
  115879. {{1,2,3,4}},
  115880. 4,{0,128, 33,8,16,70},
  115881. 60,30,500, 1.,18., -1
  115882. },
  115883. /* 256 x 4 */
  115884. {
  115885. 1,{0},{4},{2},{0},
  115886. {{1,2,3,4}},
  115887. 4,{0,256, 66,16,32,140},
  115888. 60,30,500, 1.,18., -1
  115889. },
  115890. /* 128 x 7 */
  115891. {
  115892. 2,{0,1},{3,4},{2,2},{0,1},
  115893. {{-1,2,3,4},{-1,5,6,7}},
  115894. 4,{0,128, 14,4,58, 2,8,28,90},
  115895. 60,30,500, 1.,18., -1
  115896. },
  115897. /* 256 x 7 */
  115898. {
  115899. 2,{0,1},{3,4},{2,2},{0,1},
  115900. {{-1,2,3,4},{-1,5,6,7}},
  115901. 4,{0,256, 28,8,116, 4,16,56,180},
  115902. 60,30,500, 1.,18., -1
  115903. },
  115904. /* 128 x 11 */
  115905. {
  115906. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115907. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115908. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  115909. 60,30,500, 1,18., -1
  115910. },
  115911. /* 128 x 17 */
  115912. {
  115913. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115914. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115915. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  115916. 60,30,500, 1,18., -1
  115917. },
  115918. /* 256 x 4 (low bitrate version) */
  115919. {
  115920. 1,{0},{4},{2},{0},
  115921. {{1,2,3,4}},
  115922. 4,{0,256, 66,16,32,140},
  115923. 60,30,500, 1.,18., -1
  115924. },
  115925. /* 1024 x 27 */
  115926. {
  115927. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  115928. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  115929. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  115930. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  115931. 60,30,500, 3,18., -1 /* lowpass */
  115932. },
  115933. /* 2048 x 27 */
  115934. {
  115935. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  115936. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  115937. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  115938. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  115939. 60,30,500, 3,18., -1 /* lowpass */
  115940. },
  115941. /* 512 x 17 */
  115942. {
  115943. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115944. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115945. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  115946. 7,23,39, 55,79,110, 156,232,360},
  115947. 60,30,500, 1,18., -1 /* lowpass! */
  115948. },
  115949. };
  115950. /********* End of inlined file: floor_all.h *********/
  115951. /********* Start of inlined file: residue_44.h *********/
  115952. /********* Start of inlined file: res_books_stereo.h *********/
  115953. static long _vq_quantlist__16c0_s_p1_0[] = {
  115954. 1,
  115955. 0,
  115956. 2,
  115957. };
  115958. static long _vq_lengthlist__16c0_s_p1_0[] = {
  115959. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  115960. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115964. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  115965. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115969. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  115970. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  116005. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  116010. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  116015. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116050. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116051. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116055. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116056. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  116057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116060. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116061. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  116062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116369. 0,
  116370. };
  116371. static float _vq_quantthresh__16c0_s_p1_0[] = {
  116372. -0.5, 0.5,
  116373. };
  116374. static long _vq_quantmap__16c0_s_p1_0[] = {
  116375. 1, 0, 2,
  116376. };
  116377. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  116378. _vq_quantthresh__16c0_s_p1_0,
  116379. _vq_quantmap__16c0_s_p1_0,
  116380. 3,
  116381. 3
  116382. };
  116383. static static_codebook _16c0_s_p1_0 = {
  116384. 8, 6561,
  116385. _vq_lengthlist__16c0_s_p1_0,
  116386. 1, -535822336, 1611661312, 2, 0,
  116387. _vq_quantlist__16c0_s_p1_0,
  116388. NULL,
  116389. &_vq_auxt__16c0_s_p1_0,
  116390. NULL,
  116391. 0
  116392. };
  116393. static long _vq_quantlist__16c0_s_p2_0[] = {
  116394. 2,
  116395. 1,
  116396. 3,
  116397. 0,
  116398. 4,
  116399. };
  116400. static long _vq_lengthlist__16c0_s_p2_0[] = {
  116401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116440. 0,
  116441. };
  116442. static float _vq_quantthresh__16c0_s_p2_0[] = {
  116443. -1.5, -0.5, 0.5, 1.5,
  116444. };
  116445. static long _vq_quantmap__16c0_s_p2_0[] = {
  116446. 3, 1, 0, 2, 4,
  116447. };
  116448. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  116449. _vq_quantthresh__16c0_s_p2_0,
  116450. _vq_quantmap__16c0_s_p2_0,
  116451. 5,
  116452. 5
  116453. };
  116454. static static_codebook _16c0_s_p2_0 = {
  116455. 4, 625,
  116456. _vq_lengthlist__16c0_s_p2_0,
  116457. 1, -533725184, 1611661312, 3, 0,
  116458. _vq_quantlist__16c0_s_p2_0,
  116459. NULL,
  116460. &_vq_auxt__16c0_s_p2_0,
  116461. NULL,
  116462. 0
  116463. };
  116464. static long _vq_quantlist__16c0_s_p3_0[] = {
  116465. 2,
  116466. 1,
  116467. 3,
  116468. 0,
  116469. 4,
  116470. };
  116471. static long _vq_lengthlist__16c0_s_p3_0[] = {
  116472. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  116474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116475. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  116477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116478. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  116479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116511. 0,
  116512. };
  116513. static float _vq_quantthresh__16c0_s_p3_0[] = {
  116514. -1.5, -0.5, 0.5, 1.5,
  116515. };
  116516. static long _vq_quantmap__16c0_s_p3_0[] = {
  116517. 3, 1, 0, 2, 4,
  116518. };
  116519. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  116520. _vq_quantthresh__16c0_s_p3_0,
  116521. _vq_quantmap__16c0_s_p3_0,
  116522. 5,
  116523. 5
  116524. };
  116525. static static_codebook _16c0_s_p3_0 = {
  116526. 4, 625,
  116527. _vq_lengthlist__16c0_s_p3_0,
  116528. 1, -533725184, 1611661312, 3, 0,
  116529. _vq_quantlist__16c0_s_p3_0,
  116530. NULL,
  116531. &_vq_auxt__16c0_s_p3_0,
  116532. NULL,
  116533. 0
  116534. };
  116535. static long _vq_quantlist__16c0_s_p4_0[] = {
  116536. 4,
  116537. 3,
  116538. 5,
  116539. 2,
  116540. 6,
  116541. 1,
  116542. 7,
  116543. 0,
  116544. 8,
  116545. };
  116546. static long _vq_lengthlist__16c0_s_p4_0[] = {
  116547. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  116548. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  116549. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  116550. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  116551. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116552. 0,
  116553. };
  116554. static float _vq_quantthresh__16c0_s_p4_0[] = {
  116555. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  116556. };
  116557. static long _vq_quantmap__16c0_s_p4_0[] = {
  116558. 7, 5, 3, 1, 0, 2, 4, 6,
  116559. 8,
  116560. };
  116561. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  116562. _vq_quantthresh__16c0_s_p4_0,
  116563. _vq_quantmap__16c0_s_p4_0,
  116564. 9,
  116565. 9
  116566. };
  116567. static static_codebook _16c0_s_p4_0 = {
  116568. 2, 81,
  116569. _vq_lengthlist__16c0_s_p4_0,
  116570. 1, -531628032, 1611661312, 4, 0,
  116571. _vq_quantlist__16c0_s_p4_0,
  116572. NULL,
  116573. &_vq_auxt__16c0_s_p4_0,
  116574. NULL,
  116575. 0
  116576. };
  116577. static long _vq_quantlist__16c0_s_p5_0[] = {
  116578. 4,
  116579. 3,
  116580. 5,
  116581. 2,
  116582. 6,
  116583. 1,
  116584. 7,
  116585. 0,
  116586. 8,
  116587. };
  116588. static long _vq_lengthlist__16c0_s_p5_0[] = {
  116589. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  116590. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  116591. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  116592. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  116593. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  116594. 10,
  116595. };
  116596. static float _vq_quantthresh__16c0_s_p5_0[] = {
  116597. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  116598. };
  116599. static long _vq_quantmap__16c0_s_p5_0[] = {
  116600. 7, 5, 3, 1, 0, 2, 4, 6,
  116601. 8,
  116602. };
  116603. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  116604. _vq_quantthresh__16c0_s_p5_0,
  116605. _vq_quantmap__16c0_s_p5_0,
  116606. 9,
  116607. 9
  116608. };
  116609. static static_codebook _16c0_s_p5_0 = {
  116610. 2, 81,
  116611. _vq_lengthlist__16c0_s_p5_0,
  116612. 1, -531628032, 1611661312, 4, 0,
  116613. _vq_quantlist__16c0_s_p5_0,
  116614. NULL,
  116615. &_vq_auxt__16c0_s_p5_0,
  116616. NULL,
  116617. 0
  116618. };
  116619. static long _vq_quantlist__16c0_s_p6_0[] = {
  116620. 8,
  116621. 7,
  116622. 9,
  116623. 6,
  116624. 10,
  116625. 5,
  116626. 11,
  116627. 4,
  116628. 12,
  116629. 3,
  116630. 13,
  116631. 2,
  116632. 14,
  116633. 1,
  116634. 15,
  116635. 0,
  116636. 16,
  116637. };
  116638. static long _vq_lengthlist__16c0_s_p6_0[] = {
  116639. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  116640. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  116641. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  116642. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  116643. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  116644. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  116645. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  116646. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  116647. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  116648. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  116649. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  116650. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  116651. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  116652. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  116653. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  116654. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  116655. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  116656. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  116657. 14,
  116658. };
  116659. static float _vq_quantthresh__16c0_s_p6_0[] = {
  116660. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  116661. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  116662. };
  116663. static long _vq_quantmap__16c0_s_p6_0[] = {
  116664. 15, 13, 11, 9, 7, 5, 3, 1,
  116665. 0, 2, 4, 6, 8, 10, 12, 14,
  116666. 16,
  116667. };
  116668. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  116669. _vq_quantthresh__16c0_s_p6_0,
  116670. _vq_quantmap__16c0_s_p6_0,
  116671. 17,
  116672. 17
  116673. };
  116674. static static_codebook _16c0_s_p6_0 = {
  116675. 2, 289,
  116676. _vq_lengthlist__16c0_s_p6_0,
  116677. 1, -529530880, 1611661312, 5, 0,
  116678. _vq_quantlist__16c0_s_p6_0,
  116679. NULL,
  116680. &_vq_auxt__16c0_s_p6_0,
  116681. NULL,
  116682. 0
  116683. };
  116684. static long _vq_quantlist__16c0_s_p7_0[] = {
  116685. 1,
  116686. 0,
  116687. 2,
  116688. };
  116689. static long _vq_lengthlist__16c0_s_p7_0[] = {
  116690. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  116691. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  116692. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  116693. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  116694. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  116695. 13,
  116696. };
  116697. static float _vq_quantthresh__16c0_s_p7_0[] = {
  116698. -5.5, 5.5,
  116699. };
  116700. static long _vq_quantmap__16c0_s_p7_0[] = {
  116701. 1, 0, 2,
  116702. };
  116703. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  116704. _vq_quantthresh__16c0_s_p7_0,
  116705. _vq_quantmap__16c0_s_p7_0,
  116706. 3,
  116707. 3
  116708. };
  116709. static static_codebook _16c0_s_p7_0 = {
  116710. 4, 81,
  116711. _vq_lengthlist__16c0_s_p7_0,
  116712. 1, -529137664, 1618345984, 2, 0,
  116713. _vq_quantlist__16c0_s_p7_0,
  116714. NULL,
  116715. &_vq_auxt__16c0_s_p7_0,
  116716. NULL,
  116717. 0
  116718. };
  116719. static long _vq_quantlist__16c0_s_p7_1[] = {
  116720. 5,
  116721. 4,
  116722. 6,
  116723. 3,
  116724. 7,
  116725. 2,
  116726. 8,
  116727. 1,
  116728. 9,
  116729. 0,
  116730. 10,
  116731. };
  116732. static long _vq_lengthlist__16c0_s_p7_1[] = {
  116733. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  116734. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  116735. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  116736. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  116737. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  116738. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  116739. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  116740. 11,11,11, 9, 9, 9, 9,10,10,
  116741. };
  116742. static float _vq_quantthresh__16c0_s_p7_1[] = {
  116743. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  116744. 3.5, 4.5,
  116745. };
  116746. static long _vq_quantmap__16c0_s_p7_1[] = {
  116747. 9, 7, 5, 3, 1, 0, 2, 4,
  116748. 6, 8, 10,
  116749. };
  116750. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  116751. _vq_quantthresh__16c0_s_p7_1,
  116752. _vq_quantmap__16c0_s_p7_1,
  116753. 11,
  116754. 11
  116755. };
  116756. static static_codebook _16c0_s_p7_1 = {
  116757. 2, 121,
  116758. _vq_lengthlist__16c0_s_p7_1,
  116759. 1, -531365888, 1611661312, 4, 0,
  116760. _vq_quantlist__16c0_s_p7_1,
  116761. NULL,
  116762. &_vq_auxt__16c0_s_p7_1,
  116763. NULL,
  116764. 0
  116765. };
  116766. static long _vq_quantlist__16c0_s_p8_0[] = {
  116767. 6,
  116768. 5,
  116769. 7,
  116770. 4,
  116771. 8,
  116772. 3,
  116773. 9,
  116774. 2,
  116775. 10,
  116776. 1,
  116777. 11,
  116778. 0,
  116779. 12,
  116780. };
  116781. static long _vq_lengthlist__16c0_s_p8_0[] = {
  116782. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  116783. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  116784. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  116785. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  116786. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  116787. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  116788. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  116789. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  116790. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  116791. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  116792. 0,12,13,13,12,13,14,14,14,
  116793. };
  116794. static float _vq_quantthresh__16c0_s_p8_0[] = {
  116795. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  116796. 12.5, 17.5, 22.5, 27.5,
  116797. };
  116798. static long _vq_quantmap__16c0_s_p8_0[] = {
  116799. 11, 9, 7, 5, 3, 1, 0, 2,
  116800. 4, 6, 8, 10, 12,
  116801. };
  116802. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  116803. _vq_quantthresh__16c0_s_p8_0,
  116804. _vq_quantmap__16c0_s_p8_0,
  116805. 13,
  116806. 13
  116807. };
  116808. static static_codebook _16c0_s_p8_0 = {
  116809. 2, 169,
  116810. _vq_lengthlist__16c0_s_p8_0,
  116811. 1, -526516224, 1616117760, 4, 0,
  116812. _vq_quantlist__16c0_s_p8_0,
  116813. NULL,
  116814. &_vq_auxt__16c0_s_p8_0,
  116815. NULL,
  116816. 0
  116817. };
  116818. static long _vq_quantlist__16c0_s_p8_1[] = {
  116819. 2,
  116820. 1,
  116821. 3,
  116822. 0,
  116823. 4,
  116824. };
  116825. static long _vq_lengthlist__16c0_s_p8_1[] = {
  116826. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  116827. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  116828. };
  116829. static float _vq_quantthresh__16c0_s_p8_1[] = {
  116830. -1.5, -0.5, 0.5, 1.5,
  116831. };
  116832. static long _vq_quantmap__16c0_s_p8_1[] = {
  116833. 3, 1, 0, 2, 4,
  116834. };
  116835. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  116836. _vq_quantthresh__16c0_s_p8_1,
  116837. _vq_quantmap__16c0_s_p8_1,
  116838. 5,
  116839. 5
  116840. };
  116841. static static_codebook _16c0_s_p8_1 = {
  116842. 2, 25,
  116843. _vq_lengthlist__16c0_s_p8_1,
  116844. 1, -533725184, 1611661312, 3, 0,
  116845. _vq_quantlist__16c0_s_p8_1,
  116846. NULL,
  116847. &_vq_auxt__16c0_s_p8_1,
  116848. NULL,
  116849. 0
  116850. };
  116851. static long _vq_quantlist__16c0_s_p9_0[] = {
  116852. 1,
  116853. 0,
  116854. 2,
  116855. };
  116856. static long _vq_lengthlist__16c0_s_p9_0[] = {
  116857. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116858. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116859. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116860. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116862. 7,
  116863. };
  116864. static float _vq_quantthresh__16c0_s_p9_0[] = {
  116865. -157.5, 157.5,
  116866. };
  116867. static long _vq_quantmap__16c0_s_p9_0[] = {
  116868. 1, 0, 2,
  116869. };
  116870. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  116871. _vq_quantthresh__16c0_s_p9_0,
  116872. _vq_quantmap__16c0_s_p9_0,
  116873. 3,
  116874. 3
  116875. };
  116876. static static_codebook _16c0_s_p9_0 = {
  116877. 4, 81,
  116878. _vq_lengthlist__16c0_s_p9_0,
  116879. 1, -518803456, 1628680192, 2, 0,
  116880. _vq_quantlist__16c0_s_p9_0,
  116881. NULL,
  116882. &_vq_auxt__16c0_s_p9_0,
  116883. NULL,
  116884. 0
  116885. };
  116886. static long _vq_quantlist__16c0_s_p9_1[] = {
  116887. 7,
  116888. 6,
  116889. 8,
  116890. 5,
  116891. 9,
  116892. 4,
  116893. 10,
  116894. 3,
  116895. 11,
  116896. 2,
  116897. 12,
  116898. 1,
  116899. 13,
  116900. 0,
  116901. 14,
  116902. };
  116903. static long _vq_lengthlist__16c0_s_p9_1[] = {
  116904. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  116905. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  116906. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  116907. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  116908. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116909. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116911. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116912. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116913. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116915. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116916. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116917. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116918. 10,
  116919. };
  116920. static float _vq_quantthresh__16c0_s_p9_1[] = {
  116921. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  116922. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  116923. };
  116924. static long _vq_quantmap__16c0_s_p9_1[] = {
  116925. 13, 11, 9, 7, 5, 3, 1, 0,
  116926. 2, 4, 6, 8, 10, 12, 14,
  116927. };
  116928. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  116929. _vq_quantthresh__16c0_s_p9_1,
  116930. _vq_quantmap__16c0_s_p9_1,
  116931. 15,
  116932. 15
  116933. };
  116934. static static_codebook _16c0_s_p9_1 = {
  116935. 2, 225,
  116936. _vq_lengthlist__16c0_s_p9_1,
  116937. 1, -520986624, 1620377600, 4, 0,
  116938. _vq_quantlist__16c0_s_p9_1,
  116939. NULL,
  116940. &_vq_auxt__16c0_s_p9_1,
  116941. NULL,
  116942. 0
  116943. };
  116944. static long _vq_quantlist__16c0_s_p9_2[] = {
  116945. 10,
  116946. 9,
  116947. 11,
  116948. 8,
  116949. 12,
  116950. 7,
  116951. 13,
  116952. 6,
  116953. 14,
  116954. 5,
  116955. 15,
  116956. 4,
  116957. 16,
  116958. 3,
  116959. 17,
  116960. 2,
  116961. 18,
  116962. 1,
  116963. 19,
  116964. 0,
  116965. 20,
  116966. };
  116967. static long _vq_lengthlist__16c0_s_p9_2[] = {
  116968. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  116969. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  116970. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  116971. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  116972. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  116973. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  116974. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  116975. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  116976. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  116977. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  116978. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  116979. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  116980. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  116981. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  116982. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  116983. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  116984. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  116985. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  116986. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  116987. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  116988. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  116989. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  116990. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  116991. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  116992. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  116993. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  116994. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  116995. 10,11,10,10,11, 9,10,10,10,
  116996. };
  116997. static float _vq_quantthresh__16c0_s_p9_2[] = {
  116998. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  116999. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  117000. 6.5, 7.5, 8.5, 9.5,
  117001. };
  117002. static long _vq_quantmap__16c0_s_p9_2[] = {
  117003. 19, 17, 15, 13, 11, 9, 7, 5,
  117004. 3, 1, 0, 2, 4, 6, 8, 10,
  117005. 12, 14, 16, 18, 20,
  117006. };
  117007. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  117008. _vq_quantthresh__16c0_s_p9_2,
  117009. _vq_quantmap__16c0_s_p9_2,
  117010. 21,
  117011. 21
  117012. };
  117013. static static_codebook _16c0_s_p9_2 = {
  117014. 2, 441,
  117015. _vq_lengthlist__16c0_s_p9_2,
  117016. 1, -529268736, 1611661312, 5, 0,
  117017. _vq_quantlist__16c0_s_p9_2,
  117018. NULL,
  117019. &_vq_auxt__16c0_s_p9_2,
  117020. NULL,
  117021. 0
  117022. };
  117023. static long _huff_lengthlist__16c0_s_single[] = {
  117024. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  117025. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  117026. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  117027. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  117028. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  117029. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  117030. 16,16,18,18,
  117031. };
  117032. static static_codebook _huff_book__16c0_s_single = {
  117033. 2, 100,
  117034. _huff_lengthlist__16c0_s_single,
  117035. 0, 0, 0, 0, 0,
  117036. NULL,
  117037. NULL,
  117038. NULL,
  117039. NULL,
  117040. 0
  117041. };
  117042. static long _huff_lengthlist__16c1_s_long[] = {
  117043. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  117044. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  117045. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  117046. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  117047. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  117048. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  117049. 12,11,11,13,
  117050. };
  117051. static static_codebook _huff_book__16c1_s_long = {
  117052. 2, 100,
  117053. _huff_lengthlist__16c1_s_long,
  117054. 0, 0, 0, 0, 0,
  117055. NULL,
  117056. NULL,
  117057. NULL,
  117058. NULL,
  117059. 0
  117060. };
  117061. static long _vq_quantlist__16c1_s_p1_0[] = {
  117062. 1,
  117063. 0,
  117064. 2,
  117065. };
  117066. static long _vq_lengthlist__16c1_s_p1_0[] = {
  117067. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117068. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117072. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117073. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117077. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  117078. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  117113. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117118. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117123. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117158. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117159. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117163. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117164. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  117165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117168. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117169. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  117170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117477. 0,
  117478. };
  117479. static float _vq_quantthresh__16c1_s_p1_0[] = {
  117480. -0.5, 0.5,
  117481. };
  117482. static long _vq_quantmap__16c1_s_p1_0[] = {
  117483. 1, 0, 2,
  117484. };
  117485. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  117486. _vq_quantthresh__16c1_s_p1_0,
  117487. _vq_quantmap__16c1_s_p1_0,
  117488. 3,
  117489. 3
  117490. };
  117491. static static_codebook _16c1_s_p1_0 = {
  117492. 8, 6561,
  117493. _vq_lengthlist__16c1_s_p1_0,
  117494. 1, -535822336, 1611661312, 2, 0,
  117495. _vq_quantlist__16c1_s_p1_0,
  117496. NULL,
  117497. &_vq_auxt__16c1_s_p1_0,
  117498. NULL,
  117499. 0
  117500. };
  117501. static long _vq_quantlist__16c1_s_p2_0[] = {
  117502. 2,
  117503. 1,
  117504. 3,
  117505. 0,
  117506. 4,
  117507. };
  117508. static long _vq_lengthlist__16c1_s_p2_0[] = {
  117509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117548. 0,
  117549. };
  117550. static float _vq_quantthresh__16c1_s_p2_0[] = {
  117551. -1.5, -0.5, 0.5, 1.5,
  117552. };
  117553. static long _vq_quantmap__16c1_s_p2_0[] = {
  117554. 3, 1, 0, 2, 4,
  117555. };
  117556. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  117557. _vq_quantthresh__16c1_s_p2_0,
  117558. _vq_quantmap__16c1_s_p2_0,
  117559. 5,
  117560. 5
  117561. };
  117562. static static_codebook _16c1_s_p2_0 = {
  117563. 4, 625,
  117564. _vq_lengthlist__16c1_s_p2_0,
  117565. 1, -533725184, 1611661312, 3, 0,
  117566. _vq_quantlist__16c1_s_p2_0,
  117567. NULL,
  117568. &_vq_auxt__16c1_s_p2_0,
  117569. NULL,
  117570. 0
  117571. };
  117572. static long _vq_quantlist__16c1_s_p3_0[] = {
  117573. 2,
  117574. 1,
  117575. 3,
  117576. 0,
  117577. 4,
  117578. };
  117579. static long _vq_lengthlist__16c1_s_p3_0[] = {
  117580. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  117582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117583. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  117585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117586. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  117587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117619. 0,
  117620. };
  117621. static float _vq_quantthresh__16c1_s_p3_0[] = {
  117622. -1.5, -0.5, 0.5, 1.5,
  117623. };
  117624. static long _vq_quantmap__16c1_s_p3_0[] = {
  117625. 3, 1, 0, 2, 4,
  117626. };
  117627. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  117628. _vq_quantthresh__16c1_s_p3_0,
  117629. _vq_quantmap__16c1_s_p3_0,
  117630. 5,
  117631. 5
  117632. };
  117633. static static_codebook _16c1_s_p3_0 = {
  117634. 4, 625,
  117635. _vq_lengthlist__16c1_s_p3_0,
  117636. 1, -533725184, 1611661312, 3, 0,
  117637. _vq_quantlist__16c1_s_p3_0,
  117638. NULL,
  117639. &_vq_auxt__16c1_s_p3_0,
  117640. NULL,
  117641. 0
  117642. };
  117643. static long _vq_quantlist__16c1_s_p4_0[] = {
  117644. 4,
  117645. 3,
  117646. 5,
  117647. 2,
  117648. 6,
  117649. 1,
  117650. 7,
  117651. 0,
  117652. 8,
  117653. };
  117654. static long _vq_lengthlist__16c1_s_p4_0[] = {
  117655. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  117656. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  117657. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  117658. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  117659. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117660. 0,
  117661. };
  117662. static float _vq_quantthresh__16c1_s_p4_0[] = {
  117663. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117664. };
  117665. static long _vq_quantmap__16c1_s_p4_0[] = {
  117666. 7, 5, 3, 1, 0, 2, 4, 6,
  117667. 8,
  117668. };
  117669. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  117670. _vq_quantthresh__16c1_s_p4_0,
  117671. _vq_quantmap__16c1_s_p4_0,
  117672. 9,
  117673. 9
  117674. };
  117675. static static_codebook _16c1_s_p4_0 = {
  117676. 2, 81,
  117677. _vq_lengthlist__16c1_s_p4_0,
  117678. 1, -531628032, 1611661312, 4, 0,
  117679. _vq_quantlist__16c1_s_p4_0,
  117680. NULL,
  117681. &_vq_auxt__16c1_s_p4_0,
  117682. NULL,
  117683. 0
  117684. };
  117685. static long _vq_quantlist__16c1_s_p5_0[] = {
  117686. 4,
  117687. 3,
  117688. 5,
  117689. 2,
  117690. 6,
  117691. 1,
  117692. 7,
  117693. 0,
  117694. 8,
  117695. };
  117696. static long _vq_lengthlist__16c1_s_p5_0[] = {
  117697. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  117698. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  117699. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  117700. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  117701. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  117702. 10,
  117703. };
  117704. static float _vq_quantthresh__16c1_s_p5_0[] = {
  117705. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117706. };
  117707. static long _vq_quantmap__16c1_s_p5_0[] = {
  117708. 7, 5, 3, 1, 0, 2, 4, 6,
  117709. 8,
  117710. };
  117711. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  117712. _vq_quantthresh__16c1_s_p5_0,
  117713. _vq_quantmap__16c1_s_p5_0,
  117714. 9,
  117715. 9
  117716. };
  117717. static static_codebook _16c1_s_p5_0 = {
  117718. 2, 81,
  117719. _vq_lengthlist__16c1_s_p5_0,
  117720. 1, -531628032, 1611661312, 4, 0,
  117721. _vq_quantlist__16c1_s_p5_0,
  117722. NULL,
  117723. &_vq_auxt__16c1_s_p5_0,
  117724. NULL,
  117725. 0
  117726. };
  117727. static long _vq_quantlist__16c1_s_p6_0[] = {
  117728. 8,
  117729. 7,
  117730. 9,
  117731. 6,
  117732. 10,
  117733. 5,
  117734. 11,
  117735. 4,
  117736. 12,
  117737. 3,
  117738. 13,
  117739. 2,
  117740. 14,
  117741. 1,
  117742. 15,
  117743. 0,
  117744. 16,
  117745. };
  117746. static long _vq_lengthlist__16c1_s_p6_0[] = {
  117747. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  117748. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  117749. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  117750. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  117751. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  117752. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  117753. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  117754. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  117755. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  117756. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  117757. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  117758. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  117759. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  117760. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  117761. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  117762. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  117763. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  117764. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  117765. 14,
  117766. };
  117767. static float _vq_quantthresh__16c1_s_p6_0[] = {
  117768. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  117769. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  117770. };
  117771. static long _vq_quantmap__16c1_s_p6_0[] = {
  117772. 15, 13, 11, 9, 7, 5, 3, 1,
  117773. 0, 2, 4, 6, 8, 10, 12, 14,
  117774. 16,
  117775. };
  117776. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  117777. _vq_quantthresh__16c1_s_p6_0,
  117778. _vq_quantmap__16c1_s_p6_0,
  117779. 17,
  117780. 17
  117781. };
  117782. static static_codebook _16c1_s_p6_0 = {
  117783. 2, 289,
  117784. _vq_lengthlist__16c1_s_p6_0,
  117785. 1, -529530880, 1611661312, 5, 0,
  117786. _vq_quantlist__16c1_s_p6_0,
  117787. NULL,
  117788. &_vq_auxt__16c1_s_p6_0,
  117789. NULL,
  117790. 0
  117791. };
  117792. static long _vq_quantlist__16c1_s_p7_0[] = {
  117793. 1,
  117794. 0,
  117795. 2,
  117796. };
  117797. static long _vq_lengthlist__16c1_s_p7_0[] = {
  117798. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  117799. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  117800. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  117801. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  117802. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  117803. 11,
  117804. };
  117805. static float _vq_quantthresh__16c1_s_p7_0[] = {
  117806. -5.5, 5.5,
  117807. };
  117808. static long _vq_quantmap__16c1_s_p7_0[] = {
  117809. 1, 0, 2,
  117810. };
  117811. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  117812. _vq_quantthresh__16c1_s_p7_0,
  117813. _vq_quantmap__16c1_s_p7_0,
  117814. 3,
  117815. 3
  117816. };
  117817. static static_codebook _16c1_s_p7_0 = {
  117818. 4, 81,
  117819. _vq_lengthlist__16c1_s_p7_0,
  117820. 1, -529137664, 1618345984, 2, 0,
  117821. _vq_quantlist__16c1_s_p7_0,
  117822. NULL,
  117823. &_vq_auxt__16c1_s_p7_0,
  117824. NULL,
  117825. 0
  117826. };
  117827. static long _vq_quantlist__16c1_s_p7_1[] = {
  117828. 5,
  117829. 4,
  117830. 6,
  117831. 3,
  117832. 7,
  117833. 2,
  117834. 8,
  117835. 1,
  117836. 9,
  117837. 0,
  117838. 10,
  117839. };
  117840. static long _vq_lengthlist__16c1_s_p7_1[] = {
  117841. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  117842. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  117843. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  117844. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  117845. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  117846. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  117847. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  117848. 10,10,10, 8, 8, 8, 8, 9, 9,
  117849. };
  117850. static float _vq_quantthresh__16c1_s_p7_1[] = {
  117851. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  117852. 3.5, 4.5,
  117853. };
  117854. static long _vq_quantmap__16c1_s_p7_1[] = {
  117855. 9, 7, 5, 3, 1, 0, 2, 4,
  117856. 6, 8, 10,
  117857. };
  117858. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  117859. _vq_quantthresh__16c1_s_p7_1,
  117860. _vq_quantmap__16c1_s_p7_1,
  117861. 11,
  117862. 11
  117863. };
  117864. static static_codebook _16c1_s_p7_1 = {
  117865. 2, 121,
  117866. _vq_lengthlist__16c1_s_p7_1,
  117867. 1, -531365888, 1611661312, 4, 0,
  117868. _vq_quantlist__16c1_s_p7_1,
  117869. NULL,
  117870. &_vq_auxt__16c1_s_p7_1,
  117871. NULL,
  117872. 0
  117873. };
  117874. static long _vq_quantlist__16c1_s_p8_0[] = {
  117875. 6,
  117876. 5,
  117877. 7,
  117878. 4,
  117879. 8,
  117880. 3,
  117881. 9,
  117882. 2,
  117883. 10,
  117884. 1,
  117885. 11,
  117886. 0,
  117887. 12,
  117888. };
  117889. static long _vq_lengthlist__16c1_s_p8_0[] = {
  117890. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  117891. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  117892. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  117893. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  117894. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  117895. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  117896. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  117897. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  117898. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  117899. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  117900. 0,12,12,12,12,13,13,14,15,
  117901. };
  117902. static float _vq_quantthresh__16c1_s_p8_0[] = {
  117903. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  117904. 12.5, 17.5, 22.5, 27.5,
  117905. };
  117906. static long _vq_quantmap__16c1_s_p8_0[] = {
  117907. 11, 9, 7, 5, 3, 1, 0, 2,
  117908. 4, 6, 8, 10, 12,
  117909. };
  117910. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  117911. _vq_quantthresh__16c1_s_p8_0,
  117912. _vq_quantmap__16c1_s_p8_0,
  117913. 13,
  117914. 13
  117915. };
  117916. static static_codebook _16c1_s_p8_0 = {
  117917. 2, 169,
  117918. _vq_lengthlist__16c1_s_p8_0,
  117919. 1, -526516224, 1616117760, 4, 0,
  117920. _vq_quantlist__16c1_s_p8_0,
  117921. NULL,
  117922. &_vq_auxt__16c1_s_p8_0,
  117923. NULL,
  117924. 0
  117925. };
  117926. static long _vq_quantlist__16c1_s_p8_1[] = {
  117927. 2,
  117928. 1,
  117929. 3,
  117930. 0,
  117931. 4,
  117932. };
  117933. static long _vq_lengthlist__16c1_s_p8_1[] = {
  117934. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  117935. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  117936. };
  117937. static float _vq_quantthresh__16c1_s_p8_1[] = {
  117938. -1.5, -0.5, 0.5, 1.5,
  117939. };
  117940. static long _vq_quantmap__16c1_s_p8_1[] = {
  117941. 3, 1, 0, 2, 4,
  117942. };
  117943. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  117944. _vq_quantthresh__16c1_s_p8_1,
  117945. _vq_quantmap__16c1_s_p8_1,
  117946. 5,
  117947. 5
  117948. };
  117949. static static_codebook _16c1_s_p8_1 = {
  117950. 2, 25,
  117951. _vq_lengthlist__16c1_s_p8_1,
  117952. 1, -533725184, 1611661312, 3, 0,
  117953. _vq_quantlist__16c1_s_p8_1,
  117954. NULL,
  117955. &_vq_auxt__16c1_s_p8_1,
  117956. NULL,
  117957. 0
  117958. };
  117959. static long _vq_quantlist__16c1_s_p9_0[] = {
  117960. 6,
  117961. 5,
  117962. 7,
  117963. 4,
  117964. 8,
  117965. 3,
  117966. 9,
  117967. 2,
  117968. 10,
  117969. 1,
  117970. 11,
  117971. 0,
  117972. 12,
  117973. };
  117974. static long _vq_lengthlist__16c1_s_p9_0[] = {
  117975. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117976. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117977. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117978. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117979. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117980. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117981. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117982. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117983. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117984. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117985. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117986. };
  117987. static float _vq_quantthresh__16c1_s_p9_0[] = {
  117988. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  117989. 787.5, 1102.5, 1417.5, 1732.5,
  117990. };
  117991. static long _vq_quantmap__16c1_s_p9_0[] = {
  117992. 11, 9, 7, 5, 3, 1, 0, 2,
  117993. 4, 6, 8, 10, 12,
  117994. };
  117995. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  117996. _vq_quantthresh__16c1_s_p9_0,
  117997. _vq_quantmap__16c1_s_p9_0,
  117998. 13,
  117999. 13
  118000. };
  118001. static static_codebook _16c1_s_p9_0 = {
  118002. 2, 169,
  118003. _vq_lengthlist__16c1_s_p9_0,
  118004. 1, -513964032, 1628680192, 4, 0,
  118005. _vq_quantlist__16c1_s_p9_0,
  118006. NULL,
  118007. &_vq_auxt__16c1_s_p9_0,
  118008. NULL,
  118009. 0
  118010. };
  118011. static long _vq_quantlist__16c1_s_p9_1[] = {
  118012. 7,
  118013. 6,
  118014. 8,
  118015. 5,
  118016. 9,
  118017. 4,
  118018. 10,
  118019. 3,
  118020. 11,
  118021. 2,
  118022. 12,
  118023. 1,
  118024. 13,
  118025. 0,
  118026. 14,
  118027. };
  118028. static long _vq_lengthlist__16c1_s_p9_1[] = {
  118029. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  118030. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  118031. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  118032. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  118033. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  118034. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  118035. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  118036. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118037. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118038. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118039. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118040. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118041. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  118042. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118043. 13,
  118044. };
  118045. static float _vq_quantthresh__16c1_s_p9_1[] = {
  118046. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118047. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118048. };
  118049. static long _vq_quantmap__16c1_s_p9_1[] = {
  118050. 13, 11, 9, 7, 5, 3, 1, 0,
  118051. 2, 4, 6, 8, 10, 12, 14,
  118052. };
  118053. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  118054. _vq_quantthresh__16c1_s_p9_1,
  118055. _vq_quantmap__16c1_s_p9_1,
  118056. 15,
  118057. 15
  118058. };
  118059. static static_codebook _16c1_s_p9_1 = {
  118060. 2, 225,
  118061. _vq_lengthlist__16c1_s_p9_1,
  118062. 1, -520986624, 1620377600, 4, 0,
  118063. _vq_quantlist__16c1_s_p9_1,
  118064. NULL,
  118065. &_vq_auxt__16c1_s_p9_1,
  118066. NULL,
  118067. 0
  118068. };
  118069. static long _vq_quantlist__16c1_s_p9_2[] = {
  118070. 10,
  118071. 9,
  118072. 11,
  118073. 8,
  118074. 12,
  118075. 7,
  118076. 13,
  118077. 6,
  118078. 14,
  118079. 5,
  118080. 15,
  118081. 4,
  118082. 16,
  118083. 3,
  118084. 17,
  118085. 2,
  118086. 18,
  118087. 1,
  118088. 19,
  118089. 0,
  118090. 20,
  118091. };
  118092. static long _vq_lengthlist__16c1_s_p9_2[] = {
  118093. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  118094. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  118095. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  118096. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  118097. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  118098. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  118099. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  118100. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  118101. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  118102. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  118103. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  118104. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  118105. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  118106. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  118107. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  118108. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  118109. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  118110. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  118111. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  118112. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  118113. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  118114. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  118115. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  118116. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  118117. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  118118. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  118119. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  118120. 11,11,11,11,12,11,11,12,11,
  118121. };
  118122. static float _vq_quantthresh__16c1_s_p9_2[] = {
  118123. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118124. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118125. 6.5, 7.5, 8.5, 9.5,
  118126. };
  118127. static long _vq_quantmap__16c1_s_p9_2[] = {
  118128. 19, 17, 15, 13, 11, 9, 7, 5,
  118129. 3, 1, 0, 2, 4, 6, 8, 10,
  118130. 12, 14, 16, 18, 20,
  118131. };
  118132. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  118133. _vq_quantthresh__16c1_s_p9_2,
  118134. _vq_quantmap__16c1_s_p9_2,
  118135. 21,
  118136. 21
  118137. };
  118138. static static_codebook _16c1_s_p9_2 = {
  118139. 2, 441,
  118140. _vq_lengthlist__16c1_s_p9_2,
  118141. 1, -529268736, 1611661312, 5, 0,
  118142. _vq_quantlist__16c1_s_p9_2,
  118143. NULL,
  118144. &_vq_auxt__16c1_s_p9_2,
  118145. NULL,
  118146. 0
  118147. };
  118148. static long _huff_lengthlist__16c1_s_short[] = {
  118149. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  118150. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  118151. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  118152. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  118153. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  118154. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  118155. 9, 9,10,13,
  118156. };
  118157. static static_codebook _huff_book__16c1_s_short = {
  118158. 2, 100,
  118159. _huff_lengthlist__16c1_s_short,
  118160. 0, 0, 0, 0, 0,
  118161. NULL,
  118162. NULL,
  118163. NULL,
  118164. NULL,
  118165. 0
  118166. };
  118167. static long _huff_lengthlist__16c2_s_long[] = {
  118168. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  118169. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  118170. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  118171. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  118172. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  118173. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  118174. 14,14,16,18,
  118175. };
  118176. static static_codebook _huff_book__16c2_s_long = {
  118177. 2, 100,
  118178. _huff_lengthlist__16c2_s_long,
  118179. 0, 0, 0, 0, 0,
  118180. NULL,
  118181. NULL,
  118182. NULL,
  118183. NULL,
  118184. 0
  118185. };
  118186. static long _vq_quantlist__16c2_s_p1_0[] = {
  118187. 1,
  118188. 0,
  118189. 2,
  118190. };
  118191. static long _vq_lengthlist__16c2_s_p1_0[] = {
  118192. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  118193. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118197. 0,
  118198. };
  118199. static float _vq_quantthresh__16c2_s_p1_0[] = {
  118200. -0.5, 0.5,
  118201. };
  118202. static long _vq_quantmap__16c2_s_p1_0[] = {
  118203. 1, 0, 2,
  118204. };
  118205. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  118206. _vq_quantthresh__16c2_s_p1_0,
  118207. _vq_quantmap__16c2_s_p1_0,
  118208. 3,
  118209. 3
  118210. };
  118211. static static_codebook _16c2_s_p1_0 = {
  118212. 4, 81,
  118213. _vq_lengthlist__16c2_s_p1_0,
  118214. 1, -535822336, 1611661312, 2, 0,
  118215. _vq_quantlist__16c2_s_p1_0,
  118216. NULL,
  118217. &_vq_auxt__16c2_s_p1_0,
  118218. NULL,
  118219. 0
  118220. };
  118221. static long _vq_quantlist__16c2_s_p2_0[] = {
  118222. 2,
  118223. 1,
  118224. 3,
  118225. 0,
  118226. 4,
  118227. };
  118228. static long _vq_lengthlist__16c2_s_p2_0[] = {
  118229. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  118230. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  118231. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  118232. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  118233. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  118234. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  118235. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  118236. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  118237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118241. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  118242. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  118243. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  118244. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118249. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  118250. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  118251. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  118252. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118257. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  118258. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  118259. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  118260. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  118265. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  118266. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  118267. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  118268. 13,
  118269. };
  118270. static float _vq_quantthresh__16c2_s_p2_0[] = {
  118271. -1.5, -0.5, 0.5, 1.5,
  118272. };
  118273. static long _vq_quantmap__16c2_s_p2_0[] = {
  118274. 3, 1, 0, 2, 4,
  118275. };
  118276. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  118277. _vq_quantthresh__16c2_s_p2_0,
  118278. _vq_quantmap__16c2_s_p2_0,
  118279. 5,
  118280. 5
  118281. };
  118282. static static_codebook _16c2_s_p2_0 = {
  118283. 4, 625,
  118284. _vq_lengthlist__16c2_s_p2_0,
  118285. 1, -533725184, 1611661312, 3, 0,
  118286. _vq_quantlist__16c2_s_p2_0,
  118287. NULL,
  118288. &_vq_auxt__16c2_s_p2_0,
  118289. NULL,
  118290. 0
  118291. };
  118292. static long _vq_quantlist__16c2_s_p3_0[] = {
  118293. 4,
  118294. 3,
  118295. 5,
  118296. 2,
  118297. 6,
  118298. 1,
  118299. 7,
  118300. 0,
  118301. 8,
  118302. };
  118303. static long _vq_lengthlist__16c2_s_p3_0[] = {
  118304. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  118305. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  118306. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  118307. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  118308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118309. 0,
  118310. };
  118311. static float _vq_quantthresh__16c2_s_p3_0[] = {
  118312. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118313. };
  118314. static long _vq_quantmap__16c2_s_p3_0[] = {
  118315. 7, 5, 3, 1, 0, 2, 4, 6,
  118316. 8,
  118317. };
  118318. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  118319. _vq_quantthresh__16c2_s_p3_0,
  118320. _vq_quantmap__16c2_s_p3_0,
  118321. 9,
  118322. 9
  118323. };
  118324. static static_codebook _16c2_s_p3_0 = {
  118325. 2, 81,
  118326. _vq_lengthlist__16c2_s_p3_0,
  118327. 1, -531628032, 1611661312, 4, 0,
  118328. _vq_quantlist__16c2_s_p3_0,
  118329. NULL,
  118330. &_vq_auxt__16c2_s_p3_0,
  118331. NULL,
  118332. 0
  118333. };
  118334. static long _vq_quantlist__16c2_s_p4_0[] = {
  118335. 8,
  118336. 7,
  118337. 9,
  118338. 6,
  118339. 10,
  118340. 5,
  118341. 11,
  118342. 4,
  118343. 12,
  118344. 3,
  118345. 13,
  118346. 2,
  118347. 14,
  118348. 1,
  118349. 15,
  118350. 0,
  118351. 16,
  118352. };
  118353. static long _vq_lengthlist__16c2_s_p4_0[] = {
  118354. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  118355. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  118356. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  118357. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  118358. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  118359. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  118360. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  118361. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  118362. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  118363. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  118364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118372. 0,
  118373. };
  118374. static float _vq_quantthresh__16c2_s_p4_0[] = {
  118375. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118376. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118377. };
  118378. static long _vq_quantmap__16c2_s_p4_0[] = {
  118379. 15, 13, 11, 9, 7, 5, 3, 1,
  118380. 0, 2, 4, 6, 8, 10, 12, 14,
  118381. 16,
  118382. };
  118383. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  118384. _vq_quantthresh__16c2_s_p4_0,
  118385. _vq_quantmap__16c2_s_p4_0,
  118386. 17,
  118387. 17
  118388. };
  118389. static static_codebook _16c2_s_p4_0 = {
  118390. 2, 289,
  118391. _vq_lengthlist__16c2_s_p4_0,
  118392. 1, -529530880, 1611661312, 5, 0,
  118393. _vq_quantlist__16c2_s_p4_0,
  118394. NULL,
  118395. &_vq_auxt__16c2_s_p4_0,
  118396. NULL,
  118397. 0
  118398. };
  118399. static long _vq_quantlist__16c2_s_p5_0[] = {
  118400. 1,
  118401. 0,
  118402. 2,
  118403. };
  118404. static long _vq_lengthlist__16c2_s_p5_0[] = {
  118405. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  118406. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  118407. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  118408. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  118409. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  118410. 12,
  118411. };
  118412. static float _vq_quantthresh__16c2_s_p5_0[] = {
  118413. -5.5, 5.5,
  118414. };
  118415. static long _vq_quantmap__16c2_s_p5_0[] = {
  118416. 1, 0, 2,
  118417. };
  118418. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  118419. _vq_quantthresh__16c2_s_p5_0,
  118420. _vq_quantmap__16c2_s_p5_0,
  118421. 3,
  118422. 3
  118423. };
  118424. static static_codebook _16c2_s_p5_0 = {
  118425. 4, 81,
  118426. _vq_lengthlist__16c2_s_p5_0,
  118427. 1, -529137664, 1618345984, 2, 0,
  118428. _vq_quantlist__16c2_s_p5_0,
  118429. NULL,
  118430. &_vq_auxt__16c2_s_p5_0,
  118431. NULL,
  118432. 0
  118433. };
  118434. static long _vq_quantlist__16c2_s_p5_1[] = {
  118435. 5,
  118436. 4,
  118437. 6,
  118438. 3,
  118439. 7,
  118440. 2,
  118441. 8,
  118442. 1,
  118443. 9,
  118444. 0,
  118445. 10,
  118446. };
  118447. static long _vq_lengthlist__16c2_s_p5_1[] = {
  118448. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  118449. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  118450. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  118451. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  118452. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  118453. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  118454. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  118455. 11,11,11, 7, 7, 8, 8, 8, 8,
  118456. };
  118457. static float _vq_quantthresh__16c2_s_p5_1[] = {
  118458. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118459. 3.5, 4.5,
  118460. };
  118461. static long _vq_quantmap__16c2_s_p5_1[] = {
  118462. 9, 7, 5, 3, 1, 0, 2, 4,
  118463. 6, 8, 10,
  118464. };
  118465. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  118466. _vq_quantthresh__16c2_s_p5_1,
  118467. _vq_quantmap__16c2_s_p5_1,
  118468. 11,
  118469. 11
  118470. };
  118471. static static_codebook _16c2_s_p5_1 = {
  118472. 2, 121,
  118473. _vq_lengthlist__16c2_s_p5_1,
  118474. 1, -531365888, 1611661312, 4, 0,
  118475. _vq_quantlist__16c2_s_p5_1,
  118476. NULL,
  118477. &_vq_auxt__16c2_s_p5_1,
  118478. NULL,
  118479. 0
  118480. };
  118481. static long _vq_quantlist__16c2_s_p6_0[] = {
  118482. 6,
  118483. 5,
  118484. 7,
  118485. 4,
  118486. 8,
  118487. 3,
  118488. 9,
  118489. 2,
  118490. 10,
  118491. 1,
  118492. 11,
  118493. 0,
  118494. 12,
  118495. };
  118496. static long _vq_lengthlist__16c2_s_p6_0[] = {
  118497. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  118498. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  118499. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  118500. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  118501. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  118502. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  118503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118507. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118508. };
  118509. static float _vq_quantthresh__16c2_s_p6_0[] = {
  118510. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118511. 12.5, 17.5, 22.5, 27.5,
  118512. };
  118513. static long _vq_quantmap__16c2_s_p6_0[] = {
  118514. 11, 9, 7, 5, 3, 1, 0, 2,
  118515. 4, 6, 8, 10, 12,
  118516. };
  118517. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  118518. _vq_quantthresh__16c2_s_p6_0,
  118519. _vq_quantmap__16c2_s_p6_0,
  118520. 13,
  118521. 13
  118522. };
  118523. static static_codebook _16c2_s_p6_0 = {
  118524. 2, 169,
  118525. _vq_lengthlist__16c2_s_p6_0,
  118526. 1, -526516224, 1616117760, 4, 0,
  118527. _vq_quantlist__16c2_s_p6_0,
  118528. NULL,
  118529. &_vq_auxt__16c2_s_p6_0,
  118530. NULL,
  118531. 0
  118532. };
  118533. static long _vq_quantlist__16c2_s_p6_1[] = {
  118534. 2,
  118535. 1,
  118536. 3,
  118537. 0,
  118538. 4,
  118539. };
  118540. static long _vq_lengthlist__16c2_s_p6_1[] = {
  118541. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  118542. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  118543. };
  118544. static float _vq_quantthresh__16c2_s_p6_1[] = {
  118545. -1.5, -0.5, 0.5, 1.5,
  118546. };
  118547. static long _vq_quantmap__16c2_s_p6_1[] = {
  118548. 3, 1, 0, 2, 4,
  118549. };
  118550. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  118551. _vq_quantthresh__16c2_s_p6_1,
  118552. _vq_quantmap__16c2_s_p6_1,
  118553. 5,
  118554. 5
  118555. };
  118556. static static_codebook _16c2_s_p6_1 = {
  118557. 2, 25,
  118558. _vq_lengthlist__16c2_s_p6_1,
  118559. 1, -533725184, 1611661312, 3, 0,
  118560. _vq_quantlist__16c2_s_p6_1,
  118561. NULL,
  118562. &_vq_auxt__16c2_s_p6_1,
  118563. NULL,
  118564. 0
  118565. };
  118566. static long _vq_quantlist__16c2_s_p7_0[] = {
  118567. 6,
  118568. 5,
  118569. 7,
  118570. 4,
  118571. 8,
  118572. 3,
  118573. 9,
  118574. 2,
  118575. 10,
  118576. 1,
  118577. 11,
  118578. 0,
  118579. 12,
  118580. };
  118581. static long _vq_lengthlist__16c2_s_p7_0[] = {
  118582. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  118583. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  118584. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  118585. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  118586. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  118587. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  118588. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  118589. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  118590. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  118591. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  118592. 18,13,14,13,13,14,13,15,14,
  118593. };
  118594. static float _vq_quantthresh__16c2_s_p7_0[] = {
  118595. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  118596. 27.5, 38.5, 49.5, 60.5,
  118597. };
  118598. static long _vq_quantmap__16c2_s_p7_0[] = {
  118599. 11, 9, 7, 5, 3, 1, 0, 2,
  118600. 4, 6, 8, 10, 12,
  118601. };
  118602. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  118603. _vq_quantthresh__16c2_s_p7_0,
  118604. _vq_quantmap__16c2_s_p7_0,
  118605. 13,
  118606. 13
  118607. };
  118608. static static_codebook _16c2_s_p7_0 = {
  118609. 2, 169,
  118610. _vq_lengthlist__16c2_s_p7_0,
  118611. 1, -523206656, 1618345984, 4, 0,
  118612. _vq_quantlist__16c2_s_p7_0,
  118613. NULL,
  118614. &_vq_auxt__16c2_s_p7_0,
  118615. NULL,
  118616. 0
  118617. };
  118618. static long _vq_quantlist__16c2_s_p7_1[] = {
  118619. 5,
  118620. 4,
  118621. 6,
  118622. 3,
  118623. 7,
  118624. 2,
  118625. 8,
  118626. 1,
  118627. 9,
  118628. 0,
  118629. 10,
  118630. };
  118631. static long _vq_lengthlist__16c2_s_p7_1[] = {
  118632. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  118633. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  118634. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  118635. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  118636. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  118637. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  118638. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  118639. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  118640. };
  118641. static float _vq_quantthresh__16c2_s_p7_1[] = {
  118642. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118643. 3.5, 4.5,
  118644. };
  118645. static long _vq_quantmap__16c2_s_p7_1[] = {
  118646. 9, 7, 5, 3, 1, 0, 2, 4,
  118647. 6, 8, 10,
  118648. };
  118649. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  118650. _vq_quantthresh__16c2_s_p7_1,
  118651. _vq_quantmap__16c2_s_p7_1,
  118652. 11,
  118653. 11
  118654. };
  118655. static static_codebook _16c2_s_p7_1 = {
  118656. 2, 121,
  118657. _vq_lengthlist__16c2_s_p7_1,
  118658. 1, -531365888, 1611661312, 4, 0,
  118659. _vq_quantlist__16c2_s_p7_1,
  118660. NULL,
  118661. &_vq_auxt__16c2_s_p7_1,
  118662. NULL,
  118663. 0
  118664. };
  118665. static long _vq_quantlist__16c2_s_p8_0[] = {
  118666. 7,
  118667. 6,
  118668. 8,
  118669. 5,
  118670. 9,
  118671. 4,
  118672. 10,
  118673. 3,
  118674. 11,
  118675. 2,
  118676. 12,
  118677. 1,
  118678. 13,
  118679. 0,
  118680. 14,
  118681. };
  118682. static long _vq_lengthlist__16c2_s_p8_0[] = {
  118683. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  118684. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  118685. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  118686. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  118687. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  118688. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  118689. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  118690. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  118691. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  118692. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  118693. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  118694. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  118695. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  118696. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  118697. 13,
  118698. };
  118699. static float _vq_quantthresh__16c2_s_p8_0[] = {
  118700. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118701. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118702. };
  118703. static long _vq_quantmap__16c2_s_p8_0[] = {
  118704. 13, 11, 9, 7, 5, 3, 1, 0,
  118705. 2, 4, 6, 8, 10, 12, 14,
  118706. };
  118707. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  118708. _vq_quantthresh__16c2_s_p8_0,
  118709. _vq_quantmap__16c2_s_p8_0,
  118710. 15,
  118711. 15
  118712. };
  118713. static static_codebook _16c2_s_p8_0 = {
  118714. 2, 225,
  118715. _vq_lengthlist__16c2_s_p8_0,
  118716. 1, -520986624, 1620377600, 4, 0,
  118717. _vq_quantlist__16c2_s_p8_0,
  118718. NULL,
  118719. &_vq_auxt__16c2_s_p8_0,
  118720. NULL,
  118721. 0
  118722. };
  118723. static long _vq_quantlist__16c2_s_p8_1[] = {
  118724. 10,
  118725. 9,
  118726. 11,
  118727. 8,
  118728. 12,
  118729. 7,
  118730. 13,
  118731. 6,
  118732. 14,
  118733. 5,
  118734. 15,
  118735. 4,
  118736. 16,
  118737. 3,
  118738. 17,
  118739. 2,
  118740. 18,
  118741. 1,
  118742. 19,
  118743. 0,
  118744. 20,
  118745. };
  118746. static long _vq_lengthlist__16c2_s_p8_1[] = {
  118747. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  118748. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  118749. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  118750. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  118751. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  118752. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  118753. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  118754. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  118755. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  118756. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  118757. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  118758. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  118759. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  118760. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  118761. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  118762. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  118763. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  118764. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  118765. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  118766. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  118767. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  118768. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  118769. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  118770. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  118771. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  118772. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  118773. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  118774. 10,11,10,10,10,10,10,10,10,
  118775. };
  118776. static float _vq_quantthresh__16c2_s_p8_1[] = {
  118777. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118778. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118779. 6.5, 7.5, 8.5, 9.5,
  118780. };
  118781. static long _vq_quantmap__16c2_s_p8_1[] = {
  118782. 19, 17, 15, 13, 11, 9, 7, 5,
  118783. 3, 1, 0, 2, 4, 6, 8, 10,
  118784. 12, 14, 16, 18, 20,
  118785. };
  118786. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  118787. _vq_quantthresh__16c2_s_p8_1,
  118788. _vq_quantmap__16c2_s_p8_1,
  118789. 21,
  118790. 21
  118791. };
  118792. static static_codebook _16c2_s_p8_1 = {
  118793. 2, 441,
  118794. _vq_lengthlist__16c2_s_p8_1,
  118795. 1, -529268736, 1611661312, 5, 0,
  118796. _vq_quantlist__16c2_s_p8_1,
  118797. NULL,
  118798. &_vq_auxt__16c2_s_p8_1,
  118799. NULL,
  118800. 0
  118801. };
  118802. static long _vq_quantlist__16c2_s_p9_0[] = {
  118803. 6,
  118804. 5,
  118805. 7,
  118806. 4,
  118807. 8,
  118808. 3,
  118809. 9,
  118810. 2,
  118811. 10,
  118812. 1,
  118813. 11,
  118814. 0,
  118815. 12,
  118816. };
  118817. static long _vq_lengthlist__16c2_s_p9_0[] = {
  118818. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118819. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118820. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118821. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118822. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118823. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118824. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118825. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118826. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118827. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118828. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118829. };
  118830. static float _vq_quantthresh__16c2_s_p9_0[] = {
  118831. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  118832. 2327.5, 3258.5, 4189.5, 5120.5,
  118833. };
  118834. static long _vq_quantmap__16c2_s_p9_0[] = {
  118835. 11, 9, 7, 5, 3, 1, 0, 2,
  118836. 4, 6, 8, 10, 12,
  118837. };
  118838. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  118839. _vq_quantthresh__16c2_s_p9_0,
  118840. _vq_quantmap__16c2_s_p9_0,
  118841. 13,
  118842. 13
  118843. };
  118844. static static_codebook _16c2_s_p9_0 = {
  118845. 2, 169,
  118846. _vq_lengthlist__16c2_s_p9_0,
  118847. 1, -510275072, 1631393792, 4, 0,
  118848. _vq_quantlist__16c2_s_p9_0,
  118849. NULL,
  118850. &_vq_auxt__16c2_s_p9_0,
  118851. NULL,
  118852. 0
  118853. };
  118854. static long _vq_quantlist__16c2_s_p9_1[] = {
  118855. 8,
  118856. 7,
  118857. 9,
  118858. 6,
  118859. 10,
  118860. 5,
  118861. 11,
  118862. 4,
  118863. 12,
  118864. 3,
  118865. 13,
  118866. 2,
  118867. 14,
  118868. 1,
  118869. 15,
  118870. 0,
  118871. 16,
  118872. };
  118873. static long _vq_lengthlist__16c2_s_p9_1[] = {
  118874. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  118875. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  118876. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  118877. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  118878. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  118879. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  118880. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  118881. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  118882. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  118883. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  118884. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118885. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118886. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118887. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118888. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118889. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  118890. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  118891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118892. 10,
  118893. };
  118894. static float _vq_quantthresh__16c2_s_p9_1[] = {
  118895. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  118896. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  118897. };
  118898. static long _vq_quantmap__16c2_s_p9_1[] = {
  118899. 15, 13, 11, 9, 7, 5, 3, 1,
  118900. 0, 2, 4, 6, 8, 10, 12, 14,
  118901. 16,
  118902. };
  118903. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  118904. _vq_quantthresh__16c2_s_p9_1,
  118905. _vq_quantmap__16c2_s_p9_1,
  118906. 17,
  118907. 17
  118908. };
  118909. static static_codebook _16c2_s_p9_1 = {
  118910. 2, 289,
  118911. _vq_lengthlist__16c2_s_p9_1,
  118912. 1, -518488064, 1622704128, 5, 0,
  118913. _vq_quantlist__16c2_s_p9_1,
  118914. NULL,
  118915. &_vq_auxt__16c2_s_p9_1,
  118916. NULL,
  118917. 0
  118918. };
  118919. static long _vq_quantlist__16c2_s_p9_2[] = {
  118920. 13,
  118921. 12,
  118922. 14,
  118923. 11,
  118924. 15,
  118925. 10,
  118926. 16,
  118927. 9,
  118928. 17,
  118929. 8,
  118930. 18,
  118931. 7,
  118932. 19,
  118933. 6,
  118934. 20,
  118935. 5,
  118936. 21,
  118937. 4,
  118938. 22,
  118939. 3,
  118940. 23,
  118941. 2,
  118942. 24,
  118943. 1,
  118944. 25,
  118945. 0,
  118946. 26,
  118947. };
  118948. static long _vq_lengthlist__16c2_s_p9_2[] = {
  118949. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  118950. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  118951. };
  118952. static float _vq_quantthresh__16c2_s_p9_2[] = {
  118953. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  118954. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118955. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  118956. 11.5, 12.5,
  118957. };
  118958. static long _vq_quantmap__16c2_s_p9_2[] = {
  118959. 25, 23, 21, 19, 17, 15, 13, 11,
  118960. 9, 7, 5, 3, 1, 0, 2, 4,
  118961. 6, 8, 10, 12, 14, 16, 18, 20,
  118962. 22, 24, 26,
  118963. };
  118964. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  118965. _vq_quantthresh__16c2_s_p9_2,
  118966. _vq_quantmap__16c2_s_p9_2,
  118967. 27,
  118968. 27
  118969. };
  118970. static static_codebook _16c2_s_p9_2 = {
  118971. 1, 27,
  118972. _vq_lengthlist__16c2_s_p9_2,
  118973. 1, -528875520, 1611661312, 5, 0,
  118974. _vq_quantlist__16c2_s_p9_2,
  118975. NULL,
  118976. &_vq_auxt__16c2_s_p9_2,
  118977. NULL,
  118978. 0
  118979. };
  118980. static long _huff_lengthlist__16c2_s_short[] = {
  118981. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  118982. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  118983. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  118984. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  118985. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  118986. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  118987. 15,12,14,14,
  118988. };
  118989. static static_codebook _huff_book__16c2_s_short = {
  118990. 2, 100,
  118991. _huff_lengthlist__16c2_s_short,
  118992. 0, 0, 0, 0, 0,
  118993. NULL,
  118994. NULL,
  118995. NULL,
  118996. NULL,
  118997. 0
  118998. };
  118999. static long _vq_quantlist__8c0_s_p1_0[] = {
  119000. 1,
  119001. 0,
  119002. 2,
  119003. };
  119004. static long _vq_lengthlist__8c0_s_p1_0[] = {
  119005. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119006. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119010. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  119011. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119015. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119016. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119051. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  119056. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  119061. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119096. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119097. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119101. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119102. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  119103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119106. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119107. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  119108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119415. 0,
  119416. };
  119417. static float _vq_quantthresh__8c0_s_p1_0[] = {
  119418. -0.5, 0.5,
  119419. };
  119420. static long _vq_quantmap__8c0_s_p1_0[] = {
  119421. 1, 0, 2,
  119422. };
  119423. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  119424. _vq_quantthresh__8c0_s_p1_0,
  119425. _vq_quantmap__8c0_s_p1_0,
  119426. 3,
  119427. 3
  119428. };
  119429. static static_codebook _8c0_s_p1_0 = {
  119430. 8, 6561,
  119431. _vq_lengthlist__8c0_s_p1_0,
  119432. 1, -535822336, 1611661312, 2, 0,
  119433. _vq_quantlist__8c0_s_p1_0,
  119434. NULL,
  119435. &_vq_auxt__8c0_s_p1_0,
  119436. NULL,
  119437. 0
  119438. };
  119439. static long _vq_quantlist__8c0_s_p2_0[] = {
  119440. 2,
  119441. 1,
  119442. 3,
  119443. 0,
  119444. 4,
  119445. };
  119446. static long _vq_lengthlist__8c0_s_p2_0[] = {
  119447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119486. 0,
  119487. };
  119488. static float _vq_quantthresh__8c0_s_p2_0[] = {
  119489. -1.5, -0.5, 0.5, 1.5,
  119490. };
  119491. static long _vq_quantmap__8c0_s_p2_0[] = {
  119492. 3, 1, 0, 2, 4,
  119493. };
  119494. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  119495. _vq_quantthresh__8c0_s_p2_0,
  119496. _vq_quantmap__8c0_s_p2_0,
  119497. 5,
  119498. 5
  119499. };
  119500. static static_codebook _8c0_s_p2_0 = {
  119501. 4, 625,
  119502. _vq_lengthlist__8c0_s_p2_0,
  119503. 1, -533725184, 1611661312, 3, 0,
  119504. _vq_quantlist__8c0_s_p2_0,
  119505. NULL,
  119506. &_vq_auxt__8c0_s_p2_0,
  119507. NULL,
  119508. 0
  119509. };
  119510. static long _vq_quantlist__8c0_s_p3_0[] = {
  119511. 2,
  119512. 1,
  119513. 3,
  119514. 0,
  119515. 4,
  119516. };
  119517. static long _vq_lengthlist__8c0_s_p3_0[] = {
  119518. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  119520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119521. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  119523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119524. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  119525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119557. 0,
  119558. };
  119559. static float _vq_quantthresh__8c0_s_p3_0[] = {
  119560. -1.5, -0.5, 0.5, 1.5,
  119561. };
  119562. static long _vq_quantmap__8c0_s_p3_0[] = {
  119563. 3, 1, 0, 2, 4,
  119564. };
  119565. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  119566. _vq_quantthresh__8c0_s_p3_0,
  119567. _vq_quantmap__8c0_s_p3_0,
  119568. 5,
  119569. 5
  119570. };
  119571. static static_codebook _8c0_s_p3_0 = {
  119572. 4, 625,
  119573. _vq_lengthlist__8c0_s_p3_0,
  119574. 1, -533725184, 1611661312, 3, 0,
  119575. _vq_quantlist__8c0_s_p3_0,
  119576. NULL,
  119577. &_vq_auxt__8c0_s_p3_0,
  119578. NULL,
  119579. 0
  119580. };
  119581. static long _vq_quantlist__8c0_s_p4_0[] = {
  119582. 4,
  119583. 3,
  119584. 5,
  119585. 2,
  119586. 6,
  119587. 1,
  119588. 7,
  119589. 0,
  119590. 8,
  119591. };
  119592. static long _vq_lengthlist__8c0_s_p4_0[] = {
  119593. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119594. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119595. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119596. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  119597. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119598. 0,
  119599. };
  119600. static float _vq_quantthresh__8c0_s_p4_0[] = {
  119601. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119602. };
  119603. static long _vq_quantmap__8c0_s_p4_0[] = {
  119604. 7, 5, 3, 1, 0, 2, 4, 6,
  119605. 8,
  119606. };
  119607. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  119608. _vq_quantthresh__8c0_s_p4_0,
  119609. _vq_quantmap__8c0_s_p4_0,
  119610. 9,
  119611. 9
  119612. };
  119613. static static_codebook _8c0_s_p4_0 = {
  119614. 2, 81,
  119615. _vq_lengthlist__8c0_s_p4_0,
  119616. 1, -531628032, 1611661312, 4, 0,
  119617. _vq_quantlist__8c0_s_p4_0,
  119618. NULL,
  119619. &_vq_auxt__8c0_s_p4_0,
  119620. NULL,
  119621. 0
  119622. };
  119623. static long _vq_quantlist__8c0_s_p5_0[] = {
  119624. 4,
  119625. 3,
  119626. 5,
  119627. 2,
  119628. 6,
  119629. 1,
  119630. 7,
  119631. 0,
  119632. 8,
  119633. };
  119634. static long _vq_lengthlist__8c0_s_p5_0[] = {
  119635. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119636. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  119637. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  119638. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119639. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119640. 10,
  119641. };
  119642. static float _vq_quantthresh__8c0_s_p5_0[] = {
  119643. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119644. };
  119645. static long _vq_quantmap__8c0_s_p5_0[] = {
  119646. 7, 5, 3, 1, 0, 2, 4, 6,
  119647. 8,
  119648. };
  119649. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  119650. _vq_quantthresh__8c0_s_p5_0,
  119651. _vq_quantmap__8c0_s_p5_0,
  119652. 9,
  119653. 9
  119654. };
  119655. static static_codebook _8c0_s_p5_0 = {
  119656. 2, 81,
  119657. _vq_lengthlist__8c0_s_p5_0,
  119658. 1, -531628032, 1611661312, 4, 0,
  119659. _vq_quantlist__8c0_s_p5_0,
  119660. NULL,
  119661. &_vq_auxt__8c0_s_p5_0,
  119662. NULL,
  119663. 0
  119664. };
  119665. static long _vq_quantlist__8c0_s_p6_0[] = {
  119666. 8,
  119667. 7,
  119668. 9,
  119669. 6,
  119670. 10,
  119671. 5,
  119672. 11,
  119673. 4,
  119674. 12,
  119675. 3,
  119676. 13,
  119677. 2,
  119678. 14,
  119679. 1,
  119680. 15,
  119681. 0,
  119682. 16,
  119683. };
  119684. static long _vq_lengthlist__8c0_s_p6_0[] = {
  119685. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  119686. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119687. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119688. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  119689. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  119690. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  119691. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  119692. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  119693. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  119694. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119695. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  119696. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  119697. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  119698. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  119699. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  119700. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  119701. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  119702. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  119703. 14,
  119704. };
  119705. static float _vq_quantthresh__8c0_s_p6_0[] = {
  119706. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119707. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119708. };
  119709. static long _vq_quantmap__8c0_s_p6_0[] = {
  119710. 15, 13, 11, 9, 7, 5, 3, 1,
  119711. 0, 2, 4, 6, 8, 10, 12, 14,
  119712. 16,
  119713. };
  119714. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  119715. _vq_quantthresh__8c0_s_p6_0,
  119716. _vq_quantmap__8c0_s_p6_0,
  119717. 17,
  119718. 17
  119719. };
  119720. static static_codebook _8c0_s_p6_0 = {
  119721. 2, 289,
  119722. _vq_lengthlist__8c0_s_p6_0,
  119723. 1, -529530880, 1611661312, 5, 0,
  119724. _vq_quantlist__8c0_s_p6_0,
  119725. NULL,
  119726. &_vq_auxt__8c0_s_p6_0,
  119727. NULL,
  119728. 0
  119729. };
  119730. static long _vq_quantlist__8c0_s_p7_0[] = {
  119731. 1,
  119732. 0,
  119733. 2,
  119734. };
  119735. static long _vq_lengthlist__8c0_s_p7_0[] = {
  119736. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  119737. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  119738. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  119739. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  119740. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  119741. 10,
  119742. };
  119743. static float _vq_quantthresh__8c0_s_p7_0[] = {
  119744. -5.5, 5.5,
  119745. };
  119746. static long _vq_quantmap__8c0_s_p7_0[] = {
  119747. 1, 0, 2,
  119748. };
  119749. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  119750. _vq_quantthresh__8c0_s_p7_0,
  119751. _vq_quantmap__8c0_s_p7_0,
  119752. 3,
  119753. 3
  119754. };
  119755. static static_codebook _8c0_s_p7_0 = {
  119756. 4, 81,
  119757. _vq_lengthlist__8c0_s_p7_0,
  119758. 1, -529137664, 1618345984, 2, 0,
  119759. _vq_quantlist__8c0_s_p7_0,
  119760. NULL,
  119761. &_vq_auxt__8c0_s_p7_0,
  119762. NULL,
  119763. 0
  119764. };
  119765. static long _vq_quantlist__8c0_s_p7_1[] = {
  119766. 5,
  119767. 4,
  119768. 6,
  119769. 3,
  119770. 7,
  119771. 2,
  119772. 8,
  119773. 1,
  119774. 9,
  119775. 0,
  119776. 10,
  119777. };
  119778. static long _vq_lengthlist__8c0_s_p7_1[] = {
  119779. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  119780. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  119781. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  119782. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  119783. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  119784. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  119785. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  119786. 10,10,10, 9, 9, 9,10,10,10,
  119787. };
  119788. static float _vq_quantthresh__8c0_s_p7_1[] = {
  119789. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119790. 3.5, 4.5,
  119791. };
  119792. static long _vq_quantmap__8c0_s_p7_1[] = {
  119793. 9, 7, 5, 3, 1, 0, 2, 4,
  119794. 6, 8, 10,
  119795. };
  119796. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  119797. _vq_quantthresh__8c0_s_p7_1,
  119798. _vq_quantmap__8c0_s_p7_1,
  119799. 11,
  119800. 11
  119801. };
  119802. static static_codebook _8c0_s_p7_1 = {
  119803. 2, 121,
  119804. _vq_lengthlist__8c0_s_p7_1,
  119805. 1, -531365888, 1611661312, 4, 0,
  119806. _vq_quantlist__8c0_s_p7_1,
  119807. NULL,
  119808. &_vq_auxt__8c0_s_p7_1,
  119809. NULL,
  119810. 0
  119811. };
  119812. static long _vq_quantlist__8c0_s_p8_0[] = {
  119813. 6,
  119814. 5,
  119815. 7,
  119816. 4,
  119817. 8,
  119818. 3,
  119819. 9,
  119820. 2,
  119821. 10,
  119822. 1,
  119823. 11,
  119824. 0,
  119825. 12,
  119826. };
  119827. static long _vq_lengthlist__8c0_s_p8_0[] = {
  119828. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  119829. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  119830. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  119831. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  119832. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  119833. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  119834. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  119835. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  119836. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  119837. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  119838. 0, 0,13,13,11,13,13,11,12,
  119839. };
  119840. static float _vq_quantthresh__8c0_s_p8_0[] = {
  119841. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119842. 12.5, 17.5, 22.5, 27.5,
  119843. };
  119844. static long _vq_quantmap__8c0_s_p8_0[] = {
  119845. 11, 9, 7, 5, 3, 1, 0, 2,
  119846. 4, 6, 8, 10, 12,
  119847. };
  119848. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  119849. _vq_quantthresh__8c0_s_p8_0,
  119850. _vq_quantmap__8c0_s_p8_0,
  119851. 13,
  119852. 13
  119853. };
  119854. static static_codebook _8c0_s_p8_0 = {
  119855. 2, 169,
  119856. _vq_lengthlist__8c0_s_p8_0,
  119857. 1, -526516224, 1616117760, 4, 0,
  119858. _vq_quantlist__8c0_s_p8_0,
  119859. NULL,
  119860. &_vq_auxt__8c0_s_p8_0,
  119861. NULL,
  119862. 0
  119863. };
  119864. static long _vq_quantlist__8c0_s_p8_1[] = {
  119865. 2,
  119866. 1,
  119867. 3,
  119868. 0,
  119869. 4,
  119870. };
  119871. static long _vq_lengthlist__8c0_s_p8_1[] = {
  119872. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  119873. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119874. };
  119875. static float _vq_quantthresh__8c0_s_p8_1[] = {
  119876. -1.5, -0.5, 0.5, 1.5,
  119877. };
  119878. static long _vq_quantmap__8c0_s_p8_1[] = {
  119879. 3, 1, 0, 2, 4,
  119880. };
  119881. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  119882. _vq_quantthresh__8c0_s_p8_1,
  119883. _vq_quantmap__8c0_s_p8_1,
  119884. 5,
  119885. 5
  119886. };
  119887. static static_codebook _8c0_s_p8_1 = {
  119888. 2, 25,
  119889. _vq_lengthlist__8c0_s_p8_1,
  119890. 1, -533725184, 1611661312, 3, 0,
  119891. _vq_quantlist__8c0_s_p8_1,
  119892. NULL,
  119893. &_vq_auxt__8c0_s_p8_1,
  119894. NULL,
  119895. 0
  119896. };
  119897. static long _vq_quantlist__8c0_s_p9_0[] = {
  119898. 1,
  119899. 0,
  119900. 2,
  119901. };
  119902. static long _vq_lengthlist__8c0_s_p9_0[] = {
  119903. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119904. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119905. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119906. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119907. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119908. 7,
  119909. };
  119910. static float _vq_quantthresh__8c0_s_p9_0[] = {
  119911. -157.5, 157.5,
  119912. };
  119913. static long _vq_quantmap__8c0_s_p9_0[] = {
  119914. 1, 0, 2,
  119915. };
  119916. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  119917. _vq_quantthresh__8c0_s_p9_0,
  119918. _vq_quantmap__8c0_s_p9_0,
  119919. 3,
  119920. 3
  119921. };
  119922. static static_codebook _8c0_s_p9_0 = {
  119923. 4, 81,
  119924. _vq_lengthlist__8c0_s_p9_0,
  119925. 1, -518803456, 1628680192, 2, 0,
  119926. _vq_quantlist__8c0_s_p9_0,
  119927. NULL,
  119928. &_vq_auxt__8c0_s_p9_0,
  119929. NULL,
  119930. 0
  119931. };
  119932. static long _vq_quantlist__8c0_s_p9_1[] = {
  119933. 7,
  119934. 6,
  119935. 8,
  119936. 5,
  119937. 9,
  119938. 4,
  119939. 10,
  119940. 3,
  119941. 11,
  119942. 2,
  119943. 12,
  119944. 1,
  119945. 13,
  119946. 0,
  119947. 14,
  119948. };
  119949. static long _vq_lengthlist__8c0_s_p9_1[] = {
  119950. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  119951. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  119952. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  119953. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  119954. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  119955. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  119956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119964. 11,
  119965. };
  119966. static float _vq_quantthresh__8c0_s_p9_1[] = {
  119967. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119968. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119969. };
  119970. static long _vq_quantmap__8c0_s_p9_1[] = {
  119971. 13, 11, 9, 7, 5, 3, 1, 0,
  119972. 2, 4, 6, 8, 10, 12, 14,
  119973. };
  119974. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  119975. _vq_quantthresh__8c0_s_p9_1,
  119976. _vq_quantmap__8c0_s_p9_1,
  119977. 15,
  119978. 15
  119979. };
  119980. static static_codebook _8c0_s_p9_1 = {
  119981. 2, 225,
  119982. _vq_lengthlist__8c0_s_p9_1,
  119983. 1, -520986624, 1620377600, 4, 0,
  119984. _vq_quantlist__8c0_s_p9_1,
  119985. NULL,
  119986. &_vq_auxt__8c0_s_p9_1,
  119987. NULL,
  119988. 0
  119989. };
  119990. static long _vq_quantlist__8c0_s_p9_2[] = {
  119991. 10,
  119992. 9,
  119993. 11,
  119994. 8,
  119995. 12,
  119996. 7,
  119997. 13,
  119998. 6,
  119999. 14,
  120000. 5,
  120001. 15,
  120002. 4,
  120003. 16,
  120004. 3,
  120005. 17,
  120006. 2,
  120007. 18,
  120008. 1,
  120009. 19,
  120010. 0,
  120011. 20,
  120012. };
  120013. static long _vq_lengthlist__8c0_s_p9_2[] = {
  120014. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  120015. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  120016. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  120017. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  120018. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  120019. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  120020. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  120021. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  120022. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  120023. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  120024. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  120025. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  120026. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  120027. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  120028. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  120029. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  120030. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  120031. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  120032. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  120033. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  120034. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  120035. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  120036. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  120037. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  120038. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  120039. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  120040. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  120041. 10,11, 9,11,10, 9,10, 9,10,
  120042. };
  120043. static float _vq_quantthresh__8c0_s_p9_2[] = {
  120044. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120045. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120046. 6.5, 7.5, 8.5, 9.5,
  120047. };
  120048. static long _vq_quantmap__8c0_s_p9_2[] = {
  120049. 19, 17, 15, 13, 11, 9, 7, 5,
  120050. 3, 1, 0, 2, 4, 6, 8, 10,
  120051. 12, 14, 16, 18, 20,
  120052. };
  120053. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  120054. _vq_quantthresh__8c0_s_p9_2,
  120055. _vq_quantmap__8c0_s_p9_2,
  120056. 21,
  120057. 21
  120058. };
  120059. static static_codebook _8c0_s_p9_2 = {
  120060. 2, 441,
  120061. _vq_lengthlist__8c0_s_p9_2,
  120062. 1, -529268736, 1611661312, 5, 0,
  120063. _vq_quantlist__8c0_s_p9_2,
  120064. NULL,
  120065. &_vq_auxt__8c0_s_p9_2,
  120066. NULL,
  120067. 0
  120068. };
  120069. static long _huff_lengthlist__8c0_s_single[] = {
  120070. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  120071. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  120072. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  120073. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  120074. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  120075. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  120076. 17,16,17,17,
  120077. };
  120078. static static_codebook _huff_book__8c0_s_single = {
  120079. 2, 100,
  120080. _huff_lengthlist__8c0_s_single,
  120081. 0, 0, 0, 0, 0,
  120082. NULL,
  120083. NULL,
  120084. NULL,
  120085. NULL,
  120086. 0
  120087. };
  120088. static long _vq_quantlist__8c1_s_p1_0[] = {
  120089. 1,
  120090. 0,
  120091. 2,
  120092. };
  120093. static long _vq_lengthlist__8c1_s_p1_0[] = {
  120094. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120095. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120099. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120100. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120104. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120105. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  120140. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120145. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120150. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120185. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120186. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120190. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120191. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  120192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120195. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120196. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  120197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120504. 0,
  120505. };
  120506. static float _vq_quantthresh__8c1_s_p1_0[] = {
  120507. -0.5, 0.5,
  120508. };
  120509. static long _vq_quantmap__8c1_s_p1_0[] = {
  120510. 1, 0, 2,
  120511. };
  120512. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  120513. _vq_quantthresh__8c1_s_p1_0,
  120514. _vq_quantmap__8c1_s_p1_0,
  120515. 3,
  120516. 3
  120517. };
  120518. static static_codebook _8c1_s_p1_0 = {
  120519. 8, 6561,
  120520. _vq_lengthlist__8c1_s_p1_0,
  120521. 1, -535822336, 1611661312, 2, 0,
  120522. _vq_quantlist__8c1_s_p1_0,
  120523. NULL,
  120524. &_vq_auxt__8c1_s_p1_0,
  120525. NULL,
  120526. 0
  120527. };
  120528. static long _vq_quantlist__8c1_s_p2_0[] = {
  120529. 2,
  120530. 1,
  120531. 3,
  120532. 0,
  120533. 4,
  120534. };
  120535. static long _vq_lengthlist__8c1_s_p2_0[] = {
  120536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120575. 0,
  120576. };
  120577. static float _vq_quantthresh__8c1_s_p2_0[] = {
  120578. -1.5, -0.5, 0.5, 1.5,
  120579. };
  120580. static long _vq_quantmap__8c1_s_p2_0[] = {
  120581. 3, 1, 0, 2, 4,
  120582. };
  120583. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  120584. _vq_quantthresh__8c1_s_p2_0,
  120585. _vq_quantmap__8c1_s_p2_0,
  120586. 5,
  120587. 5
  120588. };
  120589. static static_codebook _8c1_s_p2_0 = {
  120590. 4, 625,
  120591. _vq_lengthlist__8c1_s_p2_0,
  120592. 1, -533725184, 1611661312, 3, 0,
  120593. _vq_quantlist__8c1_s_p2_0,
  120594. NULL,
  120595. &_vq_auxt__8c1_s_p2_0,
  120596. NULL,
  120597. 0
  120598. };
  120599. static long _vq_quantlist__8c1_s_p3_0[] = {
  120600. 2,
  120601. 1,
  120602. 3,
  120603. 0,
  120604. 4,
  120605. };
  120606. static long _vq_lengthlist__8c1_s_p3_0[] = {
  120607. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  120609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120610. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  120612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120613. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120646. 0,
  120647. };
  120648. static float _vq_quantthresh__8c1_s_p3_0[] = {
  120649. -1.5, -0.5, 0.5, 1.5,
  120650. };
  120651. static long _vq_quantmap__8c1_s_p3_0[] = {
  120652. 3, 1, 0, 2, 4,
  120653. };
  120654. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  120655. _vq_quantthresh__8c1_s_p3_0,
  120656. _vq_quantmap__8c1_s_p3_0,
  120657. 5,
  120658. 5
  120659. };
  120660. static static_codebook _8c1_s_p3_0 = {
  120661. 4, 625,
  120662. _vq_lengthlist__8c1_s_p3_0,
  120663. 1, -533725184, 1611661312, 3, 0,
  120664. _vq_quantlist__8c1_s_p3_0,
  120665. NULL,
  120666. &_vq_auxt__8c1_s_p3_0,
  120667. NULL,
  120668. 0
  120669. };
  120670. static long _vq_quantlist__8c1_s_p4_0[] = {
  120671. 4,
  120672. 3,
  120673. 5,
  120674. 2,
  120675. 6,
  120676. 1,
  120677. 7,
  120678. 0,
  120679. 8,
  120680. };
  120681. static long _vq_lengthlist__8c1_s_p4_0[] = {
  120682. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120683. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120684. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120685. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  120686. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120687. 0,
  120688. };
  120689. static float _vq_quantthresh__8c1_s_p4_0[] = {
  120690. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120691. };
  120692. static long _vq_quantmap__8c1_s_p4_0[] = {
  120693. 7, 5, 3, 1, 0, 2, 4, 6,
  120694. 8,
  120695. };
  120696. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  120697. _vq_quantthresh__8c1_s_p4_0,
  120698. _vq_quantmap__8c1_s_p4_0,
  120699. 9,
  120700. 9
  120701. };
  120702. static static_codebook _8c1_s_p4_0 = {
  120703. 2, 81,
  120704. _vq_lengthlist__8c1_s_p4_0,
  120705. 1, -531628032, 1611661312, 4, 0,
  120706. _vq_quantlist__8c1_s_p4_0,
  120707. NULL,
  120708. &_vq_auxt__8c1_s_p4_0,
  120709. NULL,
  120710. 0
  120711. };
  120712. static long _vq_quantlist__8c1_s_p5_0[] = {
  120713. 4,
  120714. 3,
  120715. 5,
  120716. 2,
  120717. 6,
  120718. 1,
  120719. 7,
  120720. 0,
  120721. 8,
  120722. };
  120723. static long _vq_lengthlist__8c1_s_p5_0[] = {
  120724. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  120725. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  120726. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  120727. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  120728. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120729. 10,
  120730. };
  120731. static float _vq_quantthresh__8c1_s_p5_0[] = {
  120732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120733. };
  120734. static long _vq_quantmap__8c1_s_p5_0[] = {
  120735. 7, 5, 3, 1, 0, 2, 4, 6,
  120736. 8,
  120737. };
  120738. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  120739. _vq_quantthresh__8c1_s_p5_0,
  120740. _vq_quantmap__8c1_s_p5_0,
  120741. 9,
  120742. 9
  120743. };
  120744. static static_codebook _8c1_s_p5_0 = {
  120745. 2, 81,
  120746. _vq_lengthlist__8c1_s_p5_0,
  120747. 1, -531628032, 1611661312, 4, 0,
  120748. _vq_quantlist__8c1_s_p5_0,
  120749. NULL,
  120750. &_vq_auxt__8c1_s_p5_0,
  120751. NULL,
  120752. 0
  120753. };
  120754. static long _vq_quantlist__8c1_s_p6_0[] = {
  120755. 8,
  120756. 7,
  120757. 9,
  120758. 6,
  120759. 10,
  120760. 5,
  120761. 11,
  120762. 4,
  120763. 12,
  120764. 3,
  120765. 13,
  120766. 2,
  120767. 14,
  120768. 1,
  120769. 15,
  120770. 0,
  120771. 16,
  120772. };
  120773. static long _vq_lengthlist__8c1_s_p6_0[] = {
  120774. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  120775. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120776. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  120777. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  120778. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  120779. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  120780. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  120781. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  120782. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120783. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120784. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120785. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  120786. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  120787. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120788. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  120789. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  120790. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120791. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120792. 14,
  120793. };
  120794. static float _vq_quantthresh__8c1_s_p6_0[] = {
  120795. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120796. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120797. };
  120798. static long _vq_quantmap__8c1_s_p6_0[] = {
  120799. 15, 13, 11, 9, 7, 5, 3, 1,
  120800. 0, 2, 4, 6, 8, 10, 12, 14,
  120801. 16,
  120802. };
  120803. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  120804. _vq_quantthresh__8c1_s_p6_0,
  120805. _vq_quantmap__8c1_s_p6_0,
  120806. 17,
  120807. 17
  120808. };
  120809. static static_codebook _8c1_s_p6_0 = {
  120810. 2, 289,
  120811. _vq_lengthlist__8c1_s_p6_0,
  120812. 1, -529530880, 1611661312, 5, 0,
  120813. _vq_quantlist__8c1_s_p6_0,
  120814. NULL,
  120815. &_vq_auxt__8c1_s_p6_0,
  120816. NULL,
  120817. 0
  120818. };
  120819. static long _vq_quantlist__8c1_s_p7_0[] = {
  120820. 1,
  120821. 0,
  120822. 2,
  120823. };
  120824. static long _vq_lengthlist__8c1_s_p7_0[] = {
  120825. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  120826. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  120827. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  120828. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  120829. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  120830. 9,
  120831. };
  120832. static float _vq_quantthresh__8c1_s_p7_0[] = {
  120833. -5.5, 5.5,
  120834. };
  120835. static long _vq_quantmap__8c1_s_p7_0[] = {
  120836. 1, 0, 2,
  120837. };
  120838. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  120839. _vq_quantthresh__8c1_s_p7_0,
  120840. _vq_quantmap__8c1_s_p7_0,
  120841. 3,
  120842. 3
  120843. };
  120844. static static_codebook _8c1_s_p7_0 = {
  120845. 4, 81,
  120846. _vq_lengthlist__8c1_s_p7_0,
  120847. 1, -529137664, 1618345984, 2, 0,
  120848. _vq_quantlist__8c1_s_p7_0,
  120849. NULL,
  120850. &_vq_auxt__8c1_s_p7_0,
  120851. NULL,
  120852. 0
  120853. };
  120854. static long _vq_quantlist__8c1_s_p7_1[] = {
  120855. 5,
  120856. 4,
  120857. 6,
  120858. 3,
  120859. 7,
  120860. 2,
  120861. 8,
  120862. 1,
  120863. 9,
  120864. 0,
  120865. 10,
  120866. };
  120867. static long _vq_lengthlist__8c1_s_p7_1[] = {
  120868. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  120869. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  120870. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120871. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  120872. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  120873. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  120874. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  120875. 10,10,10, 8, 8, 8, 8, 8, 8,
  120876. };
  120877. static float _vq_quantthresh__8c1_s_p7_1[] = {
  120878. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120879. 3.5, 4.5,
  120880. };
  120881. static long _vq_quantmap__8c1_s_p7_1[] = {
  120882. 9, 7, 5, 3, 1, 0, 2, 4,
  120883. 6, 8, 10,
  120884. };
  120885. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  120886. _vq_quantthresh__8c1_s_p7_1,
  120887. _vq_quantmap__8c1_s_p7_1,
  120888. 11,
  120889. 11
  120890. };
  120891. static static_codebook _8c1_s_p7_1 = {
  120892. 2, 121,
  120893. _vq_lengthlist__8c1_s_p7_1,
  120894. 1, -531365888, 1611661312, 4, 0,
  120895. _vq_quantlist__8c1_s_p7_1,
  120896. NULL,
  120897. &_vq_auxt__8c1_s_p7_1,
  120898. NULL,
  120899. 0
  120900. };
  120901. static long _vq_quantlist__8c1_s_p8_0[] = {
  120902. 6,
  120903. 5,
  120904. 7,
  120905. 4,
  120906. 8,
  120907. 3,
  120908. 9,
  120909. 2,
  120910. 10,
  120911. 1,
  120912. 11,
  120913. 0,
  120914. 12,
  120915. };
  120916. static long _vq_lengthlist__8c1_s_p8_0[] = {
  120917. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  120918. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  120919. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  120920. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  120921. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  120922. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  120923. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  120924. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  120925. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  120926. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  120927. 0,12,12,11,10,12,11,13,12,
  120928. };
  120929. static float _vq_quantthresh__8c1_s_p8_0[] = {
  120930. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120931. 12.5, 17.5, 22.5, 27.5,
  120932. };
  120933. static long _vq_quantmap__8c1_s_p8_0[] = {
  120934. 11, 9, 7, 5, 3, 1, 0, 2,
  120935. 4, 6, 8, 10, 12,
  120936. };
  120937. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  120938. _vq_quantthresh__8c1_s_p8_0,
  120939. _vq_quantmap__8c1_s_p8_0,
  120940. 13,
  120941. 13
  120942. };
  120943. static static_codebook _8c1_s_p8_0 = {
  120944. 2, 169,
  120945. _vq_lengthlist__8c1_s_p8_0,
  120946. 1, -526516224, 1616117760, 4, 0,
  120947. _vq_quantlist__8c1_s_p8_0,
  120948. NULL,
  120949. &_vq_auxt__8c1_s_p8_0,
  120950. NULL,
  120951. 0
  120952. };
  120953. static long _vq_quantlist__8c1_s_p8_1[] = {
  120954. 2,
  120955. 1,
  120956. 3,
  120957. 0,
  120958. 4,
  120959. };
  120960. static long _vq_lengthlist__8c1_s_p8_1[] = {
  120961. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120962. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120963. };
  120964. static float _vq_quantthresh__8c1_s_p8_1[] = {
  120965. -1.5, -0.5, 0.5, 1.5,
  120966. };
  120967. static long _vq_quantmap__8c1_s_p8_1[] = {
  120968. 3, 1, 0, 2, 4,
  120969. };
  120970. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  120971. _vq_quantthresh__8c1_s_p8_1,
  120972. _vq_quantmap__8c1_s_p8_1,
  120973. 5,
  120974. 5
  120975. };
  120976. static static_codebook _8c1_s_p8_1 = {
  120977. 2, 25,
  120978. _vq_lengthlist__8c1_s_p8_1,
  120979. 1, -533725184, 1611661312, 3, 0,
  120980. _vq_quantlist__8c1_s_p8_1,
  120981. NULL,
  120982. &_vq_auxt__8c1_s_p8_1,
  120983. NULL,
  120984. 0
  120985. };
  120986. static long _vq_quantlist__8c1_s_p9_0[] = {
  120987. 6,
  120988. 5,
  120989. 7,
  120990. 4,
  120991. 8,
  120992. 3,
  120993. 9,
  120994. 2,
  120995. 10,
  120996. 1,
  120997. 11,
  120998. 0,
  120999. 12,
  121000. };
  121001. static long _vq_lengthlist__8c1_s_p9_0[] = {
  121002. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  121003. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  121004. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121007. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121011. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121012. 10,10,10,10,10, 9, 9, 9, 9,
  121013. };
  121014. static float _vq_quantthresh__8c1_s_p9_0[] = {
  121015. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121016. 787.5, 1102.5, 1417.5, 1732.5,
  121017. };
  121018. static long _vq_quantmap__8c1_s_p9_0[] = {
  121019. 11, 9, 7, 5, 3, 1, 0, 2,
  121020. 4, 6, 8, 10, 12,
  121021. };
  121022. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  121023. _vq_quantthresh__8c1_s_p9_0,
  121024. _vq_quantmap__8c1_s_p9_0,
  121025. 13,
  121026. 13
  121027. };
  121028. static static_codebook _8c1_s_p9_0 = {
  121029. 2, 169,
  121030. _vq_lengthlist__8c1_s_p9_0,
  121031. 1, -513964032, 1628680192, 4, 0,
  121032. _vq_quantlist__8c1_s_p9_0,
  121033. NULL,
  121034. &_vq_auxt__8c1_s_p9_0,
  121035. NULL,
  121036. 0
  121037. };
  121038. static long _vq_quantlist__8c1_s_p9_1[] = {
  121039. 7,
  121040. 6,
  121041. 8,
  121042. 5,
  121043. 9,
  121044. 4,
  121045. 10,
  121046. 3,
  121047. 11,
  121048. 2,
  121049. 12,
  121050. 1,
  121051. 13,
  121052. 0,
  121053. 14,
  121054. };
  121055. static long _vq_lengthlist__8c1_s_p9_1[] = {
  121056. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  121057. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  121058. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  121059. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  121060. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  121061. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  121062. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  121063. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  121064. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  121065. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  121066. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  121067. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  121068. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  121069. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  121070. 15,
  121071. };
  121072. static float _vq_quantthresh__8c1_s_p9_1[] = {
  121073. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121074. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121075. };
  121076. static long _vq_quantmap__8c1_s_p9_1[] = {
  121077. 13, 11, 9, 7, 5, 3, 1, 0,
  121078. 2, 4, 6, 8, 10, 12, 14,
  121079. };
  121080. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  121081. _vq_quantthresh__8c1_s_p9_1,
  121082. _vq_quantmap__8c1_s_p9_1,
  121083. 15,
  121084. 15
  121085. };
  121086. static static_codebook _8c1_s_p9_1 = {
  121087. 2, 225,
  121088. _vq_lengthlist__8c1_s_p9_1,
  121089. 1, -520986624, 1620377600, 4, 0,
  121090. _vq_quantlist__8c1_s_p9_1,
  121091. NULL,
  121092. &_vq_auxt__8c1_s_p9_1,
  121093. NULL,
  121094. 0
  121095. };
  121096. static long _vq_quantlist__8c1_s_p9_2[] = {
  121097. 10,
  121098. 9,
  121099. 11,
  121100. 8,
  121101. 12,
  121102. 7,
  121103. 13,
  121104. 6,
  121105. 14,
  121106. 5,
  121107. 15,
  121108. 4,
  121109. 16,
  121110. 3,
  121111. 17,
  121112. 2,
  121113. 18,
  121114. 1,
  121115. 19,
  121116. 0,
  121117. 20,
  121118. };
  121119. static long _vq_lengthlist__8c1_s_p9_2[] = {
  121120. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  121121. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  121122. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  121123. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  121124. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  121125. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  121126. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  121127. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  121128. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  121129. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  121130. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  121131. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  121132. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  121133. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  121134. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  121135. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  121136. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121137. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  121138. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  121139. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  121140. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121141. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  121142. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  121143. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  121144. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  121145. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  121146. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  121147. 10,10,10,10,10,10,10,10,10,
  121148. };
  121149. static float _vq_quantthresh__8c1_s_p9_2[] = {
  121150. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121151. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121152. 6.5, 7.5, 8.5, 9.5,
  121153. };
  121154. static long _vq_quantmap__8c1_s_p9_2[] = {
  121155. 19, 17, 15, 13, 11, 9, 7, 5,
  121156. 3, 1, 0, 2, 4, 6, 8, 10,
  121157. 12, 14, 16, 18, 20,
  121158. };
  121159. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  121160. _vq_quantthresh__8c1_s_p9_2,
  121161. _vq_quantmap__8c1_s_p9_2,
  121162. 21,
  121163. 21
  121164. };
  121165. static static_codebook _8c1_s_p9_2 = {
  121166. 2, 441,
  121167. _vq_lengthlist__8c1_s_p9_2,
  121168. 1, -529268736, 1611661312, 5, 0,
  121169. _vq_quantlist__8c1_s_p9_2,
  121170. NULL,
  121171. &_vq_auxt__8c1_s_p9_2,
  121172. NULL,
  121173. 0
  121174. };
  121175. static long _huff_lengthlist__8c1_s_single[] = {
  121176. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  121177. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  121178. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  121179. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  121180. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  121181. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  121182. 9, 7, 7, 8,
  121183. };
  121184. static static_codebook _huff_book__8c1_s_single = {
  121185. 2, 100,
  121186. _huff_lengthlist__8c1_s_single,
  121187. 0, 0, 0, 0, 0,
  121188. NULL,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. 0
  121193. };
  121194. static long _huff_lengthlist__44c2_s_long[] = {
  121195. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  121196. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  121197. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  121198. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  121199. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  121200. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  121201. 10, 8, 8, 9,
  121202. };
  121203. static static_codebook _huff_book__44c2_s_long = {
  121204. 2, 100,
  121205. _huff_lengthlist__44c2_s_long,
  121206. 0, 0, 0, 0, 0,
  121207. NULL,
  121208. NULL,
  121209. NULL,
  121210. NULL,
  121211. 0
  121212. };
  121213. static long _vq_quantlist__44c2_s_p1_0[] = {
  121214. 1,
  121215. 0,
  121216. 2,
  121217. };
  121218. static long _vq_lengthlist__44c2_s_p1_0[] = {
  121219. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  121220. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121225. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  121230. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121265. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  121266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121270. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  121271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  121275. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  121276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121310. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  121311. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121315. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  121316. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  121317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121320. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  121321. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  121322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0,
  121630. };
  121631. static float _vq_quantthresh__44c2_s_p1_0[] = {
  121632. -0.5, 0.5,
  121633. };
  121634. static long _vq_quantmap__44c2_s_p1_0[] = {
  121635. 1, 0, 2,
  121636. };
  121637. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  121638. _vq_quantthresh__44c2_s_p1_0,
  121639. _vq_quantmap__44c2_s_p1_0,
  121640. 3,
  121641. 3
  121642. };
  121643. static static_codebook _44c2_s_p1_0 = {
  121644. 8, 6561,
  121645. _vq_lengthlist__44c2_s_p1_0,
  121646. 1, -535822336, 1611661312, 2, 0,
  121647. _vq_quantlist__44c2_s_p1_0,
  121648. NULL,
  121649. &_vq_auxt__44c2_s_p1_0,
  121650. NULL,
  121651. 0
  121652. };
  121653. static long _vq_quantlist__44c2_s_p2_0[] = {
  121654. 2,
  121655. 1,
  121656. 3,
  121657. 0,
  121658. 4,
  121659. };
  121660. static long _vq_lengthlist__44c2_s_p2_0[] = {
  121661. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  121662. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  121663. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  121664. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  121665. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  121671. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  121672. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  121673. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  121679. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  121680. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  121687. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  121688. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0,
  121701. };
  121702. static float _vq_quantthresh__44c2_s_p2_0[] = {
  121703. -1.5, -0.5, 0.5, 1.5,
  121704. };
  121705. static long _vq_quantmap__44c2_s_p2_0[] = {
  121706. 3, 1, 0, 2, 4,
  121707. };
  121708. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  121709. _vq_quantthresh__44c2_s_p2_0,
  121710. _vq_quantmap__44c2_s_p2_0,
  121711. 5,
  121712. 5
  121713. };
  121714. static static_codebook _44c2_s_p2_0 = {
  121715. 4, 625,
  121716. _vq_lengthlist__44c2_s_p2_0,
  121717. 1, -533725184, 1611661312, 3, 0,
  121718. _vq_quantlist__44c2_s_p2_0,
  121719. NULL,
  121720. &_vq_auxt__44c2_s_p2_0,
  121721. NULL,
  121722. 0
  121723. };
  121724. static long _vq_quantlist__44c2_s_p3_0[] = {
  121725. 2,
  121726. 1,
  121727. 3,
  121728. 0,
  121729. 4,
  121730. };
  121731. static long _vq_lengthlist__44c2_s_p3_0[] = {
  121732. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0,
  121772. };
  121773. static float _vq_quantthresh__44c2_s_p3_0[] = {
  121774. -1.5, -0.5, 0.5, 1.5,
  121775. };
  121776. static long _vq_quantmap__44c2_s_p3_0[] = {
  121777. 3, 1, 0, 2, 4,
  121778. };
  121779. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  121780. _vq_quantthresh__44c2_s_p3_0,
  121781. _vq_quantmap__44c2_s_p3_0,
  121782. 5,
  121783. 5
  121784. };
  121785. static static_codebook _44c2_s_p3_0 = {
  121786. 4, 625,
  121787. _vq_lengthlist__44c2_s_p3_0,
  121788. 1, -533725184, 1611661312, 3, 0,
  121789. _vq_quantlist__44c2_s_p3_0,
  121790. NULL,
  121791. &_vq_auxt__44c2_s_p3_0,
  121792. NULL,
  121793. 0
  121794. };
  121795. static long _vq_quantlist__44c2_s_p4_0[] = {
  121796. 4,
  121797. 3,
  121798. 5,
  121799. 2,
  121800. 6,
  121801. 1,
  121802. 7,
  121803. 0,
  121804. 8,
  121805. };
  121806. static long _vq_lengthlist__44c2_s_p4_0[] = {
  121807. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  121808. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  121809. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  121810. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  121811. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0,
  121813. };
  121814. static float _vq_quantthresh__44c2_s_p4_0[] = {
  121815. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121816. };
  121817. static long _vq_quantmap__44c2_s_p4_0[] = {
  121818. 7, 5, 3, 1, 0, 2, 4, 6,
  121819. 8,
  121820. };
  121821. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  121822. _vq_quantthresh__44c2_s_p4_0,
  121823. _vq_quantmap__44c2_s_p4_0,
  121824. 9,
  121825. 9
  121826. };
  121827. static static_codebook _44c2_s_p4_0 = {
  121828. 2, 81,
  121829. _vq_lengthlist__44c2_s_p4_0,
  121830. 1, -531628032, 1611661312, 4, 0,
  121831. _vq_quantlist__44c2_s_p4_0,
  121832. NULL,
  121833. &_vq_auxt__44c2_s_p4_0,
  121834. NULL,
  121835. 0
  121836. };
  121837. static long _vq_quantlist__44c2_s_p5_0[] = {
  121838. 4,
  121839. 3,
  121840. 5,
  121841. 2,
  121842. 6,
  121843. 1,
  121844. 7,
  121845. 0,
  121846. 8,
  121847. };
  121848. static long _vq_lengthlist__44c2_s_p5_0[] = {
  121849. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  121850. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  121851. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  121852. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121853. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  121854. 11,
  121855. };
  121856. static float _vq_quantthresh__44c2_s_p5_0[] = {
  121857. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121858. };
  121859. static long _vq_quantmap__44c2_s_p5_0[] = {
  121860. 7, 5, 3, 1, 0, 2, 4, 6,
  121861. 8,
  121862. };
  121863. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  121864. _vq_quantthresh__44c2_s_p5_0,
  121865. _vq_quantmap__44c2_s_p5_0,
  121866. 9,
  121867. 9
  121868. };
  121869. static static_codebook _44c2_s_p5_0 = {
  121870. 2, 81,
  121871. _vq_lengthlist__44c2_s_p5_0,
  121872. 1, -531628032, 1611661312, 4, 0,
  121873. _vq_quantlist__44c2_s_p5_0,
  121874. NULL,
  121875. &_vq_auxt__44c2_s_p5_0,
  121876. NULL,
  121877. 0
  121878. };
  121879. static long _vq_quantlist__44c2_s_p6_0[] = {
  121880. 8,
  121881. 7,
  121882. 9,
  121883. 6,
  121884. 10,
  121885. 5,
  121886. 11,
  121887. 4,
  121888. 12,
  121889. 3,
  121890. 13,
  121891. 2,
  121892. 14,
  121893. 1,
  121894. 15,
  121895. 0,
  121896. 16,
  121897. };
  121898. static long _vq_lengthlist__44c2_s_p6_0[] = {
  121899. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  121900. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121901. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121902. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  121903. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  121904. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  121905. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  121906. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  121907. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  121908. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121909. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121910. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  121911. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  121912. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121913. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  121914. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  121915. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121917. 14,
  121918. };
  121919. static float _vq_quantthresh__44c2_s_p6_0[] = {
  121920. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121921. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121922. };
  121923. static long _vq_quantmap__44c2_s_p6_0[] = {
  121924. 15, 13, 11, 9, 7, 5, 3, 1,
  121925. 0, 2, 4, 6, 8, 10, 12, 14,
  121926. 16,
  121927. };
  121928. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  121929. _vq_quantthresh__44c2_s_p6_0,
  121930. _vq_quantmap__44c2_s_p6_0,
  121931. 17,
  121932. 17
  121933. };
  121934. static static_codebook _44c2_s_p6_0 = {
  121935. 2, 289,
  121936. _vq_lengthlist__44c2_s_p6_0,
  121937. 1, -529530880, 1611661312, 5, 0,
  121938. _vq_quantlist__44c2_s_p6_0,
  121939. NULL,
  121940. &_vq_auxt__44c2_s_p6_0,
  121941. NULL,
  121942. 0
  121943. };
  121944. static long _vq_quantlist__44c2_s_p7_0[] = {
  121945. 1,
  121946. 0,
  121947. 2,
  121948. };
  121949. static long _vq_lengthlist__44c2_s_p7_0[] = {
  121950. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  121951. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  121952. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  121953. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  121954. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  121955. 11,
  121956. };
  121957. static float _vq_quantthresh__44c2_s_p7_0[] = {
  121958. -5.5, 5.5,
  121959. };
  121960. static long _vq_quantmap__44c2_s_p7_0[] = {
  121961. 1, 0, 2,
  121962. };
  121963. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  121964. _vq_quantthresh__44c2_s_p7_0,
  121965. _vq_quantmap__44c2_s_p7_0,
  121966. 3,
  121967. 3
  121968. };
  121969. static static_codebook _44c2_s_p7_0 = {
  121970. 4, 81,
  121971. _vq_lengthlist__44c2_s_p7_0,
  121972. 1, -529137664, 1618345984, 2, 0,
  121973. _vq_quantlist__44c2_s_p7_0,
  121974. NULL,
  121975. &_vq_auxt__44c2_s_p7_0,
  121976. NULL,
  121977. 0
  121978. };
  121979. static long _vq_quantlist__44c2_s_p7_1[] = {
  121980. 5,
  121981. 4,
  121982. 6,
  121983. 3,
  121984. 7,
  121985. 2,
  121986. 8,
  121987. 1,
  121988. 9,
  121989. 0,
  121990. 10,
  121991. };
  121992. static long _vq_lengthlist__44c2_s_p7_1[] = {
  121993. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  121994. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  121995. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121996. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  121997. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  121998. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  121999. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  122000. 10,10,10, 8, 8, 8, 8, 8, 8,
  122001. };
  122002. static float _vq_quantthresh__44c2_s_p7_1[] = {
  122003. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122004. 3.5, 4.5,
  122005. };
  122006. static long _vq_quantmap__44c2_s_p7_1[] = {
  122007. 9, 7, 5, 3, 1, 0, 2, 4,
  122008. 6, 8, 10,
  122009. };
  122010. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  122011. _vq_quantthresh__44c2_s_p7_1,
  122012. _vq_quantmap__44c2_s_p7_1,
  122013. 11,
  122014. 11
  122015. };
  122016. static static_codebook _44c2_s_p7_1 = {
  122017. 2, 121,
  122018. _vq_lengthlist__44c2_s_p7_1,
  122019. 1, -531365888, 1611661312, 4, 0,
  122020. _vq_quantlist__44c2_s_p7_1,
  122021. NULL,
  122022. &_vq_auxt__44c2_s_p7_1,
  122023. NULL,
  122024. 0
  122025. };
  122026. static long _vq_quantlist__44c2_s_p8_0[] = {
  122027. 6,
  122028. 5,
  122029. 7,
  122030. 4,
  122031. 8,
  122032. 3,
  122033. 9,
  122034. 2,
  122035. 10,
  122036. 1,
  122037. 11,
  122038. 0,
  122039. 12,
  122040. };
  122041. static long _vq_lengthlist__44c2_s_p8_0[] = {
  122042. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  122043. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  122044. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122045. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122046. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  122047. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  122048. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  122049. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  122050. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  122051. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  122052. 0,12,12,12,12,13,12,14,14,
  122053. };
  122054. static float _vq_quantthresh__44c2_s_p8_0[] = {
  122055. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122056. 12.5, 17.5, 22.5, 27.5,
  122057. };
  122058. static long _vq_quantmap__44c2_s_p8_0[] = {
  122059. 11, 9, 7, 5, 3, 1, 0, 2,
  122060. 4, 6, 8, 10, 12,
  122061. };
  122062. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  122063. _vq_quantthresh__44c2_s_p8_0,
  122064. _vq_quantmap__44c2_s_p8_0,
  122065. 13,
  122066. 13
  122067. };
  122068. static static_codebook _44c2_s_p8_0 = {
  122069. 2, 169,
  122070. _vq_lengthlist__44c2_s_p8_0,
  122071. 1, -526516224, 1616117760, 4, 0,
  122072. _vq_quantlist__44c2_s_p8_0,
  122073. NULL,
  122074. &_vq_auxt__44c2_s_p8_0,
  122075. NULL,
  122076. 0
  122077. };
  122078. static long _vq_quantlist__44c2_s_p8_1[] = {
  122079. 2,
  122080. 1,
  122081. 3,
  122082. 0,
  122083. 4,
  122084. };
  122085. static long _vq_lengthlist__44c2_s_p8_1[] = {
  122086. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  122087. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  122088. };
  122089. static float _vq_quantthresh__44c2_s_p8_1[] = {
  122090. -1.5, -0.5, 0.5, 1.5,
  122091. };
  122092. static long _vq_quantmap__44c2_s_p8_1[] = {
  122093. 3, 1, 0, 2, 4,
  122094. };
  122095. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  122096. _vq_quantthresh__44c2_s_p8_1,
  122097. _vq_quantmap__44c2_s_p8_1,
  122098. 5,
  122099. 5
  122100. };
  122101. static static_codebook _44c2_s_p8_1 = {
  122102. 2, 25,
  122103. _vq_lengthlist__44c2_s_p8_1,
  122104. 1, -533725184, 1611661312, 3, 0,
  122105. _vq_quantlist__44c2_s_p8_1,
  122106. NULL,
  122107. &_vq_auxt__44c2_s_p8_1,
  122108. NULL,
  122109. 0
  122110. };
  122111. static long _vq_quantlist__44c2_s_p9_0[] = {
  122112. 6,
  122113. 5,
  122114. 7,
  122115. 4,
  122116. 8,
  122117. 3,
  122118. 9,
  122119. 2,
  122120. 10,
  122121. 1,
  122122. 11,
  122123. 0,
  122124. 12,
  122125. };
  122126. static long _vq_lengthlist__44c2_s_p9_0[] = {
  122127. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  122128. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  122129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122130. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  122131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122137. 11,11,11,11,11,11,11,11,11,
  122138. };
  122139. static float _vq_quantthresh__44c2_s_p9_0[] = {
  122140. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  122141. 552.5, 773.5, 994.5, 1215.5,
  122142. };
  122143. static long _vq_quantmap__44c2_s_p9_0[] = {
  122144. 11, 9, 7, 5, 3, 1, 0, 2,
  122145. 4, 6, 8, 10, 12,
  122146. };
  122147. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  122148. _vq_quantthresh__44c2_s_p9_0,
  122149. _vq_quantmap__44c2_s_p9_0,
  122150. 13,
  122151. 13
  122152. };
  122153. static static_codebook _44c2_s_p9_0 = {
  122154. 2, 169,
  122155. _vq_lengthlist__44c2_s_p9_0,
  122156. 1, -514541568, 1627103232, 4, 0,
  122157. _vq_quantlist__44c2_s_p9_0,
  122158. NULL,
  122159. &_vq_auxt__44c2_s_p9_0,
  122160. NULL,
  122161. 0
  122162. };
  122163. static long _vq_quantlist__44c2_s_p9_1[] = {
  122164. 6,
  122165. 5,
  122166. 7,
  122167. 4,
  122168. 8,
  122169. 3,
  122170. 9,
  122171. 2,
  122172. 10,
  122173. 1,
  122174. 11,
  122175. 0,
  122176. 12,
  122177. };
  122178. static long _vq_lengthlist__44c2_s_p9_1[] = {
  122179. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  122180. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  122181. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  122182. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  122183. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  122184. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  122185. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  122186. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  122187. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  122188. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  122189. 17,13,12,12,10,13,11,14,14,
  122190. };
  122191. static float _vq_quantthresh__44c2_s_p9_1[] = {
  122192. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  122193. 42.5, 59.5, 76.5, 93.5,
  122194. };
  122195. static long _vq_quantmap__44c2_s_p9_1[] = {
  122196. 11, 9, 7, 5, 3, 1, 0, 2,
  122197. 4, 6, 8, 10, 12,
  122198. };
  122199. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  122200. _vq_quantthresh__44c2_s_p9_1,
  122201. _vq_quantmap__44c2_s_p9_1,
  122202. 13,
  122203. 13
  122204. };
  122205. static static_codebook _44c2_s_p9_1 = {
  122206. 2, 169,
  122207. _vq_lengthlist__44c2_s_p9_1,
  122208. 1, -522616832, 1620115456, 4, 0,
  122209. _vq_quantlist__44c2_s_p9_1,
  122210. NULL,
  122211. &_vq_auxt__44c2_s_p9_1,
  122212. NULL,
  122213. 0
  122214. };
  122215. static long _vq_quantlist__44c2_s_p9_2[] = {
  122216. 8,
  122217. 7,
  122218. 9,
  122219. 6,
  122220. 10,
  122221. 5,
  122222. 11,
  122223. 4,
  122224. 12,
  122225. 3,
  122226. 13,
  122227. 2,
  122228. 14,
  122229. 1,
  122230. 15,
  122231. 0,
  122232. 16,
  122233. };
  122234. static long _vq_lengthlist__44c2_s_p9_2[] = {
  122235. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  122236. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  122237. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  122238. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  122239. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  122240. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  122241. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  122242. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  122243. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  122244. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  122245. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  122246. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  122247. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  122248. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  122249. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  122250. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  122251. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  122252. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  122253. 10,
  122254. };
  122255. static float _vq_quantthresh__44c2_s_p9_2[] = {
  122256. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122257. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122258. };
  122259. static long _vq_quantmap__44c2_s_p9_2[] = {
  122260. 15, 13, 11, 9, 7, 5, 3, 1,
  122261. 0, 2, 4, 6, 8, 10, 12, 14,
  122262. 16,
  122263. };
  122264. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  122265. _vq_quantthresh__44c2_s_p9_2,
  122266. _vq_quantmap__44c2_s_p9_2,
  122267. 17,
  122268. 17
  122269. };
  122270. static static_codebook _44c2_s_p9_2 = {
  122271. 2, 289,
  122272. _vq_lengthlist__44c2_s_p9_2,
  122273. 1, -529530880, 1611661312, 5, 0,
  122274. _vq_quantlist__44c2_s_p9_2,
  122275. NULL,
  122276. &_vq_auxt__44c2_s_p9_2,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist__44c2_s_short[] = {
  122281. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  122282. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  122283. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  122284. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  122285. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  122286. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  122287. 6, 8, 9,12,
  122288. };
  122289. static static_codebook _huff_book__44c2_s_short = {
  122290. 2, 100,
  122291. _huff_lengthlist__44c2_s_short,
  122292. 0, 0, 0, 0, 0,
  122293. NULL,
  122294. NULL,
  122295. NULL,
  122296. NULL,
  122297. 0
  122298. };
  122299. static long _huff_lengthlist__44c3_s_long[] = {
  122300. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  122301. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  122302. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  122303. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  122304. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  122305. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  122306. 9, 8, 8, 8,
  122307. };
  122308. static static_codebook _huff_book__44c3_s_long = {
  122309. 2, 100,
  122310. _huff_lengthlist__44c3_s_long,
  122311. 0, 0, 0, 0, 0,
  122312. NULL,
  122313. NULL,
  122314. NULL,
  122315. NULL,
  122316. 0
  122317. };
  122318. static long _vq_quantlist__44c3_s_p1_0[] = {
  122319. 1,
  122320. 0,
  122321. 2,
  122322. };
  122323. static long _vq_lengthlist__44c3_s_p1_0[] = {
  122324. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  122325. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122330. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  122335. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122370. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122375. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  122380. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122416. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122421. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122426. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0,
  122735. };
  122736. static float _vq_quantthresh__44c3_s_p1_0[] = {
  122737. -0.5, 0.5,
  122738. };
  122739. static long _vq_quantmap__44c3_s_p1_0[] = {
  122740. 1, 0, 2,
  122741. };
  122742. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  122743. _vq_quantthresh__44c3_s_p1_0,
  122744. _vq_quantmap__44c3_s_p1_0,
  122745. 3,
  122746. 3
  122747. };
  122748. static static_codebook _44c3_s_p1_0 = {
  122749. 8, 6561,
  122750. _vq_lengthlist__44c3_s_p1_0,
  122751. 1, -535822336, 1611661312, 2, 0,
  122752. _vq_quantlist__44c3_s_p1_0,
  122753. NULL,
  122754. &_vq_auxt__44c3_s_p1_0,
  122755. NULL,
  122756. 0
  122757. };
  122758. static long _vq_quantlist__44c3_s_p2_0[] = {
  122759. 2,
  122760. 1,
  122761. 3,
  122762. 0,
  122763. 4,
  122764. };
  122765. static long _vq_lengthlist__44c3_s_p2_0[] = {
  122766. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  122767. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  122768. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  122769. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  122770. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  122776. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  122777. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  122778. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  122784. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  122785. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  122792. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  122793. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0,
  122806. };
  122807. static float _vq_quantthresh__44c3_s_p2_0[] = {
  122808. -1.5, -0.5, 0.5, 1.5,
  122809. };
  122810. static long _vq_quantmap__44c3_s_p2_0[] = {
  122811. 3, 1, 0, 2, 4,
  122812. };
  122813. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  122814. _vq_quantthresh__44c3_s_p2_0,
  122815. _vq_quantmap__44c3_s_p2_0,
  122816. 5,
  122817. 5
  122818. };
  122819. static static_codebook _44c3_s_p2_0 = {
  122820. 4, 625,
  122821. _vq_lengthlist__44c3_s_p2_0,
  122822. 1, -533725184, 1611661312, 3, 0,
  122823. _vq_quantlist__44c3_s_p2_0,
  122824. NULL,
  122825. &_vq_auxt__44c3_s_p2_0,
  122826. NULL,
  122827. 0
  122828. };
  122829. static long _vq_quantlist__44c3_s_p3_0[] = {
  122830. 2,
  122831. 1,
  122832. 3,
  122833. 0,
  122834. 4,
  122835. };
  122836. static long _vq_lengthlist__44c3_s_p3_0[] = {
  122837. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0,
  122877. };
  122878. static float _vq_quantthresh__44c3_s_p3_0[] = {
  122879. -1.5, -0.5, 0.5, 1.5,
  122880. };
  122881. static long _vq_quantmap__44c3_s_p3_0[] = {
  122882. 3, 1, 0, 2, 4,
  122883. };
  122884. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  122885. _vq_quantthresh__44c3_s_p3_0,
  122886. _vq_quantmap__44c3_s_p3_0,
  122887. 5,
  122888. 5
  122889. };
  122890. static static_codebook _44c3_s_p3_0 = {
  122891. 4, 625,
  122892. _vq_lengthlist__44c3_s_p3_0,
  122893. 1, -533725184, 1611661312, 3, 0,
  122894. _vq_quantlist__44c3_s_p3_0,
  122895. NULL,
  122896. &_vq_auxt__44c3_s_p3_0,
  122897. NULL,
  122898. 0
  122899. };
  122900. static long _vq_quantlist__44c3_s_p4_0[] = {
  122901. 4,
  122902. 3,
  122903. 5,
  122904. 2,
  122905. 6,
  122906. 1,
  122907. 7,
  122908. 0,
  122909. 8,
  122910. };
  122911. static long _vq_lengthlist__44c3_s_p4_0[] = {
  122912. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  122913. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  122914. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  122915. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  122916. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0,
  122918. };
  122919. static float _vq_quantthresh__44c3_s_p4_0[] = {
  122920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122921. };
  122922. static long _vq_quantmap__44c3_s_p4_0[] = {
  122923. 7, 5, 3, 1, 0, 2, 4, 6,
  122924. 8,
  122925. };
  122926. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  122927. _vq_quantthresh__44c3_s_p4_0,
  122928. _vq_quantmap__44c3_s_p4_0,
  122929. 9,
  122930. 9
  122931. };
  122932. static static_codebook _44c3_s_p4_0 = {
  122933. 2, 81,
  122934. _vq_lengthlist__44c3_s_p4_0,
  122935. 1, -531628032, 1611661312, 4, 0,
  122936. _vq_quantlist__44c3_s_p4_0,
  122937. NULL,
  122938. &_vq_auxt__44c3_s_p4_0,
  122939. NULL,
  122940. 0
  122941. };
  122942. static long _vq_quantlist__44c3_s_p5_0[] = {
  122943. 4,
  122944. 3,
  122945. 5,
  122946. 2,
  122947. 6,
  122948. 1,
  122949. 7,
  122950. 0,
  122951. 8,
  122952. };
  122953. static long _vq_lengthlist__44c3_s_p5_0[] = {
  122954. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  122955. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  122956. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  122957. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  122958. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  122959. 11,
  122960. };
  122961. static float _vq_quantthresh__44c3_s_p5_0[] = {
  122962. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122963. };
  122964. static long _vq_quantmap__44c3_s_p5_0[] = {
  122965. 7, 5, 3, 1, 0, 2, 4, 6,
  122966. 8,
  122967. };
  122968. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  122969. _vq_quantthresh__44c3_s_p5_0,
  122970. _vq_quantmap__44c3_s_p5_0,
  122971. 9,
  122972. 9
  122973. };
  122974. static static_codebook _44c3_s_p5_0 = {
  122975. 2, 81,
  122976. _vq_lengthlist__44c3_s_p5_0,
  122977. 1, -531628032, 1611661312, 4, 0,
  122978. _vq_quantlist__44c3_s_p5_0,
  122979. NULL,
  122980. &_vq_auxt__44c3_s_p5_0,
  122981. NULL,
  122982. 0
  122983. };
  122984. static long _vq_quantlist__44c3_s_p6_0[] = {
  122985. 8,
  122986. 7,
  122987. 9,
  122988. 6,
  122989. 10,
  122990. 5,
  122991. 11,
  122992. 4,
  122993. 12,
  122994. 3,
  122995. 13,
  122996. 2,
  122997. 14,
  122998. 1,
  122999. 15,
  123000. 0,
  123001. 16,
  123002. };
  123003. static long _vq_lengthlist__44c3_s_p6_0[] = {
  123004. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123005. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123006. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  123007. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123008. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123009. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123010. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  123011. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123012. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123013. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  123014. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  123015. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  123016. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  123017. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  123018. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  123019. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  123020. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  123022. 13,
  123023. };
  123024. static float _vq_quantthresh__44c3_s_p6_0[] = {
  123025. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123026. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123027. };
  123028. static long _vq_quantmap__44c3_s_p6_0[] = {
  123029. 15, 13, 11, 9, 7, 5, 3, 1,
  123030. 0, 2, 4, 6, 8, 10, 12, 14,
  123031. 16,
  123032. };
  123033. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  123034. _vq_quantthresh__44c3_s_p6_0,
  123035. _vq_quantmap__44c3_s_p6_0,
  123036. 17,
  123037. 17
  123038. };
  123039. static static_codebook _44c3_s_p6_0 = {
  123040. 2, 289,
  123041. _vq_lengthlist__44c3_s_p6_0,
  123042. 1, -529530880, 1611661312, 5, 0,
  123043. _vq_quantlist__44c3_s_p6_0,
  123044. NULL,
  123045. &_vq_auxt__44c3_s_p6_0,
  123046. NULL,
  123047. 0
  123048. };
  123049. static long _vq_quantlist__44c3_s_p7_0[] = {
  123050. 1,
  123051. 0,
  123052. 2,
  123053. };
  123054. static long _vq_lengthlist__44c3_s_p7_0[] = {
  123055. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123056. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  123057. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123058. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  123059. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  123060. 10,
  123061. };
  123062. static float _vq_quantthresh__44c3_s_p7_0[] = {
  123063. -5.5, 5.5,
  123064. };
  123065. static long _vq_quantmap__44c3_s_p7_0[] = {
  123066. 1, 0, 2,
  123067. };
  123068. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  123069. _vq_quantthresh__44c3_s_p7_0,
  123070. _vq_quantmap__44c3_s_p7_0,
  123071. 3,
  123072. 3
  123073. };
  123074. static static_codebook _44c3_s_p7_0 = {
  123075. 4, 81,
  123076. _vq_lengthlist__44c3_s_p7_0,
  123077. 1, -529137664, 1618345984, 2, 0,
  123078. _vq_quantlist__44c3_s_p7_0,
  123079. NULL,
  123080. &_vq_auxt__44c3_s_p7_0,
  123081. NULL,
  123082. 0
  123083. };
  123084. static long _vq_quantlist__44c3_s_p7_1[] = {
  123085. 5,
  123086. 4,
  123087. 6,
  123088. 3,
  123089. 7,
  123090. 2,
  123091. 8,
  123092. 1,
  123093. 9,
  123094. 0,
  123095. 10,
  123096. };
  123097. static long _vq_lengthlist__44c3_s_p7_1[] = {
  123098. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  123099. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  123100. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  123101. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123102. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123103. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123104. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  123105. 10,10,10, 8, 8, 8, 8, 8, 8,
  123106. };
  123107. static float _vq_quantthresh__44c3_s_p7_1[] = {
  123108. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123109. 3.5, 4.5,
  123110. };
  123111. static long _vq_quantmap__44c3_s_p7_1[] = {
  123112. 9, 7, 5, 3, 1, 0, 2, 4,
  123113. 6, 8, 10,
  123114. };
  123115. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  123116. _vq_quantthresh__44c3_s_p7_1,
  123117. _vq_quantmap__44c3_s_p7_1,
  123118. 11,
  123119. 11
  123120. };
  123121. static static_codebook _44c3_s_p7_1 = {
  123122. 2, 121,
  123123. _vq_lengthlist__44c3_s_p7_1,
  123124. 1, -531365888, 1611661312, 4, 0,
  123125. _vq_quantlist__44c3_s_p7_1,
  123126. NULL,
  123127. &_vq_auxt__44c3_s_p7_1,
  123128. NULL,
  123129. 0
  123130. };
  123131. static long _vq_quantlist__44c3_s_p8_0[] = {
  123132. 6,
  123133. 5,
  123134. 7,
  123135. 4,
  123136. 8,
  123137. 3,
  123138. 9,
  123139. 2,
  123140. 10,
  123141. 1,
  123142. 11,
  123143. 0,
  123144. 12,
  123145. };
  123146. static long _vq_lengthlist__44c3_s_p8_0[] = {
  123147. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  123148. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  123149. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123150. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123151. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  123152. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123153. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  123154. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  123155. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  123156. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  123157. 0,13,13,12,12,13,12,14,13,
  123158. };
  123159. static float _vq_quantthresh__44c3_s_p8_0[] = {
  123160. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123161. 12.5, 17.5, 22.5, 27.5,
  123162. };
  123163. static long _vq_quantmap__44c3_s_p8_0[] = {
  123164. 11, 9, 7, 5, 3, 1, 0, 2,
  123165. 4, 6, 8, 10, 12,
  123166. };
  123167. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  123168. _vq_quantthresh__44c3_s_p8_0,
  123169. _vq_quantmap__44c3_s_p8_0,
  123170. 13,
  123171. 13
  123172. };
  123173. static static_codebook _44c3_s_p8_0 = {
  123174. 2, 169,
  123175. _vq_lengthlist__44c3_s_p8_0,
  123176. 1, -526516224, 1616117760, 4, 0,
  123177. _vq_quantlist__44c3_s_p8_0,
  123178. NULL,
  123179. &_vq_auxt__44c3_s_p8_0,
  123180. NULL,
  123181. 0
  123182. };
  123183. static long _vq_quantlist__44c3_s_p8_1[] = {
  123184. 2,
  123185. 1,
  123186. 3,
  123187. 0,
  123188. 4,
  123189. };
  123190. static long _vq_lengthlist__44c3_s_p8_1[] = {
  123191. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  123192. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123193. };
  123194. static float _vq_quantthresh__44c3_s_p8_1[] = {
  123195. -1.5, -0.5, 0.5, 1.5,
  123196. };
  123197. static long _vq_quantmap__44c3_s_p8_1[] = {
  123198. 3, 1, 0, 2, 4,
  123199. };
  123200. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  123201. _vq_quantthresh__44c3_s_p8_1,
  123202. _vq_quantmap__44c3_s_p8_1,
  123203. 5,
  123204. 5
  123205. };
  123206. static static_codebook _44c3_s_p8_1 = {
  123207. 2, 25,
  123208. _vq_lengthlist__44c3_s_p8_1,
  123209. 1, -533725184, 1611661312, 3, 0,
  123210. _vq_quantlist__44c3_s_p8_1,
  123211. NULL,
  123212. &_vq_auxt__44c3_s_p8_1,
  123213. NULL,
  123214. 0
  123215. };
  123216. static long _vq_quantlist__44c3_s_p9_0[] = {
  123217. 6,
  123218. 5,
  123219. 7,
  123220. 4,
  123221. 8,
  123222. 3,
  123223. 9,
  123224. 2,
  123225. 10,
  123226. 1,
  123227. 11,
  123228. 0,
  123229. 12,
  123230. };
  123231. static long _vq_lengthlist__44c3_s_p9_0[] = {
  123232. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123233. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  123234. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123235. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  123236. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123237. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123238. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123239. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123240. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  123241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123242. 11,11,11,11,11,11,11,11,11,
  123243. };
  123244. static float _vq_quantthresh__44c3_s_p9_0[] = {
  123245. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  123246. 637.5, 892.5, 1147.5, 1402.5,
  123247. };
  123248. static long _vq_quantmap__44c3_s_p9_0[] = {
  123249. 11, 9, 7, 5, 3, 1, 0, 2,
  123250. 4, 6, 8, 10, 12,
  123251. };
  123252. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  123253. _vq_quantthresh__44c3_s_p9_0,
  123254. _vq_quantmap__44c3_s_p9_0,
  123255. 13,
  123256. 13
  123257. };
  123258. static static_codebook _44c3_s_p9_0 = {
  123259. 2, 169,
  123260. _vq_lengthlist__44c3_s_p9_0,
  123261. 1, -514332672, 1627381760, 4, 0,
  123262. _vq_quantlist__44c3_s_p9_0,
  123263. NULL,
  123264. &_vq_auxt__44c3_s_p9_0,
  123265. NULL,
  123266. 0
  123267. };
  123268. static long _vq_quantlist__44c3_s_p9_1[] = {
  123269. 7,
  123270. 6,
  123271. 8,
  123272. 5,
  123273. 9,
  123274. 4,
  123275. 10,
  123276. 3,
  123277. 11,
  123278. 2,
  123279. 12,
  123280. 1,
  123281. 13,
  123282. 0,
  123283. 14,
  123284. };
  123285. static long _vq_lengthlist__44c3_s_p9_1[] = {
  123286. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  123287. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  123288. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  123289. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  123290. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  123291. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  123292. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  123293. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  123294. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  123295. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  123296. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  123297. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  123298. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  123299. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  123300. 15,
  123301. };
  123302. static float _vq_quantthresh__44c3_s_p9_1[] = {
  123303. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  123304. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  123305. };
  123306. static long _vq_quantmap__44c3_s_p9_1[] = {
  123307. 13, 11, 9, 7, 5, 3, 1, 0,
  123308. 2, 4, 6, 8, 10, 12, 14,
  123309. };
  123310. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  123311. _vq_quantthresh__44c3_s_p9_1,
  123312. _vq_quantmap__44c3_s_p9_1,
  123313. 15,
  123314. 15
  123315. };
  123316. static static_codebook _44c3_s_p9_1 = {
  123317. 2, 225,
  123318. _vq_lengthlist__44c3_s_p9_1,
  123319. 1, -522338304, 1620115456, 4, 0,
  123320. _vq_quantlist__44c3_s_p9_1,
  123321. NULL,
  123322. &_vq_auxt__44c3_s_p9_1,
  123323. NULL,
  123324. 0
  123325. };
  123326. static long _vq_quantlist__44c3_s_p9_2[] = {
  123327. 8,
  123328. 7,
  123329. 9,
  123330. 6,
  123331. 10,
  123332. 5,
  123333. 11,
  123334. 4,
  123335. 12,
  123336. 3,
  123337. 13,
  123338. 2,
  123339. 14,
  123340. 1,
  123341. 15,
  123342. 0,
  123343. 16,
  123344. };
  123345. static long _vq_lengthlist__44c3_s_p9_2[] = {
  123346. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  123347. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  123348. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123349. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  123350. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  123351. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  123352. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  123353. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  123354. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  123355. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  123356. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  123357. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  123358. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  123359. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  123360. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  123361. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  123362. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  123363. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  123364. 10,
  123365. };
  123366. static float _vq_quantthresh__44c3_s_p9_2[] = {
  123367. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123368. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123369. };
  123370. static long _vq_quantmap__44c3_s_p9_2[] = {
  123371. 15, 13, 11, 9, 7, 5, 3, 1,
  123372. 0, 2, 4, 6, 8, 10, 12, 14,
  123373. 16,
  123374. };
  123375. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  123376. _vq_quantthresh__44c3_s_p9_2,
  123377. _vq_quantmap__44c3_s_p9_2,
  123378. 17,
  123379. 17
  123380. };
  123381. static static_codebook _44c3_s_p9_2 = {
  123382. 2, 289,
  123383. _vq_lengthlist__44c3_s_p9_2,
  123384. 1, -529530880, 1611661312, 5, 0,
  123385. _vq_quantlist__44c3_s_p9_2,
  123386. NULL,
  123387. &_vq_auxt__44c3_s_p9_2,
  123388. NULL,
  123389. 0
  123390. };
  123391. static long _huff_lengthlist__44c3_s_short[] = {
  123392. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  123393. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  123394. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  123395. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  123396. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  123397. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  123398. 6, 8, 9,11,
  123399. };
  123400. static static_codebook _huff_book__44c3_s_short = {
  123401. 2, 100,
  123402. _huff_lengthlist__44c3_s_short,
  123403. 0, 0, 0, 0, 0,
  123404. NULL,
  123405. NULL,
  123406. NULL,
  123407. NULL,
  123408. 0
  123409. };
  123410. static long _huff_lengthlist__44c4_s_long[] = {
  123411. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  123412. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  123413. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  123414. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  123415. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  123416. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  123417. 9, 8, 7, 7,
  123418. };
  123419. static static_codebook _huff_book__44c4_s_long = {
  123420. 2, 100,
  123421. _huff_lengthlist__44c4_s_long,
  123422. 0, 0, 0, 0, 0,
  123423. NULL,
  123424. NULL,
  123425. NULL,
  123426. NULL,
  123427. 0
  123428. };
  123429. static long _vq_quantlist__44c4_s_p1_0[] = {
  123430. 1,
  123431. 0,
  123432. 2,
  123433. };
  123434. static long _vq_lengthlist__44c4_s_p1_0[] = {
  123435. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123436. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123441. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123446. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123481. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123486. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123491. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123527. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123532. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123537. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0,
  123846. };
  123847. static float _vq_quantthresh__44c4_s_p1_0[] = {
  123848. -0.5, 0.5,
  123849. };
  123850. static long _vq_quantmap__44c4_s_p1_0[] = {
  123851. 1, 0, 2,
  123852. };
  123853. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  123854. _vq_quantthresh__44c4_s_p1_0,
  123855. _vq_quantmap__44c4_s_p1_0,
  123856. 3,
  123857. 3
  123858. };
  123859. static static_codebook _44c4_s_p1_0 = {
  123860. 8, 6561,
  123861. _vq_lengthlist__44c4_s_p1_0,
  123862. 1, -535822336, 1611661312, 2, 0,
  123863. _vq_quantlist__44c4_s_p1_0,
  123864. NULL,
  123865. &_vq_auxt__44c4_s_p1_0,
  123866. NULL,
  123867. 0
  123868. };
  123869. static long _vq_quantlist__44c4_s_p2_0[] = {
  123870. 2,
  123871. 1,
  123872. 3,
  123873. 0,
  123874. 4,
  123875. };
  123876. static long _vq_lengthlist__44c4_s_p2_0[] = {
  123877. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  123878. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  123879. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123880. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  123881. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  123887. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  123888. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  123889. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  123895. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  123896. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  123903. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  123904. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0,
  123917. };
  123918. static float _vq_quantthresh__44c4_s_p2_0[] = {
  123919. -1.5, -0.5, 0.5, 1.5,
  123920. };
  123921. static long _vq_quantmap__44c4_s_p2_0[] = {
  123922. 3, 1, 0, 2, 4,
  123923. };
  123924. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  123925. _vq_quantthresh__44c4_s_p2_0,
  123926. _vq_quantmap__44c4_s_p2_0,
  123927. 5,
  123928. 5
  123929. };
  123930. static static_codebook _44c4_s_p2_0 = {
  123931. 4, 625,
  123932. _vq_lengthlist__44c4_s_p2_0,
  123933. 1, -533725184, 1611661312, 3, 0,
  123934. _vq_quantlist__44c4_s_p2_0,
  123935. NULL,
  123936. &_vq_auxt__44c4_s_p2_0,
  123937. NULL,
  123938. 0
  123939. };
  123940. static long _vq_quantlist__44c4_s_p3_0[] = {
  123941. 2,
  123942. 1,
  123943. 3,
  123944. 0,
  123945. 4,
  123946. };
  123947. static long _vq_lengthlist__44c4_s_p3_0[] = {
  123948. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0,
  123988. };
  123989. static float _vq_quantthresh__44c4_s_p3_0[] = {
  123990. -1.5, -0.5, 0.5, 1.5,
  123991. };
  123992. static long _vq_quantmap__44c4_s_p3_0[] = {
  123993. 3, 1, 0, 2, 4,
  123994. };
  123995. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  123996. _vq_quantthresh__44c4_s_p3_0,
  123997. _vq_quantmap__44c4_s_p3_0,
  123998. 5,
  123999. 5
  124000. };
  124001. static static_codebook _44c4_s_p3_0 = {
  124002. 4, 625,
  124003. _vq_lengthlist__44c4_s_p3_0,
  124004. 1, -533725184, 1611661312, 3, 0,
  124005. _vq_quantlist__44c4_s_p3_0,
  124006. NULL,
  124007. &_vq_auxt__44c4_s_p3_0,
  124008. NULL,
  124009. 0
  124010. };
  124011. static long _vq_quantlist__44c4_s_p4_0[] = {
  124012. 4,
  124013. 3,
  124014. 5,
  124015. 2,
  124016. 6,
  124017. 1,
  124018. 7,
  124019. 0,
  124020. 8,
  124021. };
  124022. static long _vq_lengthlist__44c4_s_p4_0[] = {
  124023. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124024. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124025. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124026. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124027. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0,
  124029. };
  124030. static float _vq_quantthresh__44c4_s_p4_0[] = {
  124031. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124032. };
  124033. static long _vq_quantmap__44c4_s_p4_0[] = {
  124034. 7, 5, 3, 1, 0, 2, 4, 6,
  124035. 8,
  124036. };
  124037. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  124038. _vq_quantthresh__44c4_s_p4_0,
  124039. _vq_quantmap__44c4_s_p4_0,
  124040. 9,
  124041. 9
  124042. };
  124043. static static_codebook _44c4_s_p4_0 = {
  124044. 2, 81,
  124045. _vq_lengthlist__44c4_s_p4_0,
  124046. 1, -531628032, 1611661312, 4, 0,
  124047. _vq_quantlist__44c4_s_p4_0,
  124048. NULL,
  124049. &_vq_auxt__44c4_s_p4_0,
  124050. NULL,
  124051. 0
  124052. };
  124053. static long _vq_quantlist__44c4_s_p5_0[] = {
  124054. 4,
  124055. 3,
  124056. 5,
  124057. 2,
  124058. 6,
  124059. 1,
  124060. 7,
  124061. 0,
  124062. 8,
  124063. };
  124064. static long _vq_lengthlist__44c4_s_p5_0[] = {
  124065. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  124066. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  124067. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  124068. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  124069. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  124070. 10,
  124071. };
  124072. static float _vq_quantthresh__44c4_s_p5_0[] = {
  124073. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124074. };
  124075. static long _vq_quantmap__44c4_s_p5_0[] = {
  124076. 7, 5, 3, 1, 0, 2, 4, 6,
  124077. 8,
  124078. };
  124079. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  124080. _vq_quantthresh__44c4_s_p5_0,
  124081. _vq_quantmap__44c4_s_p5_0,
  124082. 9,
  124083. 9
  124084. };
  124085. static static_codebook _44c4_s_p5_0 = {
  124086. 2, 81,
  124087. _vq_lengthlist__44c4_s_p5_0,
  124088. 1, -531628032, 1611661312, 4, 0,
  124089. _vq_quantlist__44c4_s_p5_0,
  124090. NULL,
  124091. &_vq_auxt__44c4_s_p5_0,
  124092. NULL,
  124093. 0
  124094. };
  124095. static long _vq_quantlist__44c4_s_p6_0[] = {
  124096. 8,
  124097. 7,
  124098. 9,
  124099. 6,
  124100. 10,
  124101. 5,
  124102. 11,
  124103. 4,
  124104. 12,
  124105. 3,
  124106. 13,
  124107. 2,
  124108. 14,
  124109. 1,
  124110. 15,
  124111. 0,
  124112. 16,
  124113. };
  124114. static long _vq_lengthlist__44c4_s_p6_0[] = {
  124115. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  124116. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124117. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  124118. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124119. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124120. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124121. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124122. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124123. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124124. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  124125. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  124126. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  124127. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  124128. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  124129. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124130. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124131. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  124133. 13,
  124134. };
  124135. static float _vq_quantthresh__44c4_s_p6_0[] = {
  124136. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124137. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124138. };
  124139. static long _vq_quantmap__44c4_s_p6_0[] = {
  124140. 15, 13, 11, 9, 7, 5, 3, 1,
  124141. 0, 2, 4, 6, 8, 10, 12, 14,
  124142. 16,
  124143. };
  124144. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  124145. _vq_quantthresh__44c4_s_p6_0,
  124146. _vq_quantmap__44c4_s_p6_0,
  124147. 17,
  124148. 17
  124149. };
  124150. static static_codebook _44c4_s_p6_0 = {
  124151. 2, 289,
  124152. _vq_lengthlist__44c4_s_p6_0,
  124153. 1, -529530880, 1611661312, 5, 0,
  124154. _vq_quantlist__44c4_s_p6_0,
  124155. NULL,
  124156. &_vq_auxt__44c4_s_p6_0,
  124157. NULL,
  124158. 0
  124159. };
  124160. static long _vq_quantlist__44c4_s_p7_0[] = {
  124161. 1,
  124162. 0,
  124163. 2,
  124164. };
  124165. static long _vq_lengthlist__44c4_s_p7_0[] = {
  124166. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124167. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124168. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124169. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  124170. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124171. 10,
  124172. };
  124173. static float _vq_quantthresh__44c4_s_p7_0[] = {
  124174. -5.5, 5.5,
  124175. };
  124176. static long _vq_quantmap__44c4_s_p7_0[] = {
  124177. 1, 0, 2,
  124178. };
  124179. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  124180. _vq_quantthresh__44c4_s_p7_0,
  124181. _vq_quantmap__44c4_s_p7_0,
  124182. 3,
  124183. 3
  124184. };
  124185. static static_codebook _44c4_s_p7_0 = {
  124186. 4, 81,
  124187. _vq_lengthlist__44c4_s_p7_0,
  124188. 1, -529137664, 1618345984, 2, 0,
  124189. _vq_quantlist__44c4_s_p7_0,
  124190. NULL,
  124191. &_vq_auxt__44c4_s_p7_0,
  124192. NULL,
  124193. 0
  124194. };
  124195. static long _vq_quantlist__44c4_s_p7_1[] = {
  124196. 5,
  124197. 4,
  124198. 6,
  124199. 3,
  124200. 7,
  124201. 2,
  124202. 8,
  124203. 1,
  124204. 9,
  124205. 0,
  124206. 10,
  124207. };
  124208. static long _vq_lengthlist__44c4_s_p7_1[] = {
  124209. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124210. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124211. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124212. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  124213. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124214. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124215. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124216. 10,10,10, 8, 8, 8, 8, 9, 9,
  124217. };
  124218. static float _vq_quantthresh__44c4_s_p7_1[] = {
  124219. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124220. 3.5, 4.5,
  124221. };
  124222. static long _vq_quantmap__44c4_s_p7_1[] = {
  124223. 9, 7, 5, 3, 1, 0, 2, 4,
  124224. 6, 8, 10,
  124225. };
  124226. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  124227. _vq_quantthresh__44c4_s_p7_1,
  124228. _vq_quantmap__44c4_s_p7_1,
  124229. 11,
  124230. 11
  124231. };
  124232. static static_codebook _44c4_s_p7_1 = {
  124233. 2, 121,
  124234. _vq_lengthlist__44c4_s_p7_1,
  124235. 1, -531365888, 1611661312, 4, 0,
  124236. _vq_quantlist__44c4_s_p7_1,
  124237. NULL,
  124238. &_vq_auxt__44c4_s_p7_1,
  124239. NULL,
  124240. 0
  124241. };
  124242. static long _vq_quantlist__44c4_s_p8_0[] = {
  124243. 6,
  124244. 5,
  124245. 7,
  124246. 4,
  124247. 8,
  124248. 3,
  124249. 9,
  124250. 2,
  124251. 10,
  124252. 1,
  124253. 11,
  124254. 0,
  124255. 12,
  124256. };
  124257. static long _vq_lengthlist__44c4_s_p8_0[] = {
  124258. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124259. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124260. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124261. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124262. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  124263. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  124264. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  124265. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124266. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  124267. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  124268. 0,13,12,12,12,12,12,13,13,
  124269. };
  124270. static float _vq_quantthresh__44c4_s_p8_0[] = {
  124271. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124272. 12.5, 17.5, 22.5, 27.5,
  124273. };
  124274. static long _vq_quantmap__44c4_s_p8_0[] = {
  124275. 11, 9, 7, 5, 3, 1, 0, 2,
  124276. 4, 6, 8, 10, 12,
  124277. };
  124278. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  124279. _vq_quantthresh__44c4_s_p8_0,
  124280. _vq_quantmap__44c4_s_p8_0,
  124281. 13,
  124282. 13
  124283. };
  124284. static static_codebook _44c4_s_p8_0 = {
  124285. 2, 169,
  124286. _vq_lengthlist__44c4_s_p8_0,
  124287. 1, -526516224, 1616117760, 4, 0,
  124288. _vq_quantlist__44c4_s_p8_0,
  124289. NULL,
  124290. &_vq_auxt__44c4_s_p8_0,
  124291. NULL,
  124292. 0
  124293. };
  124294. static long _vq_quantlist__44c4_s_p8_1[] = {
  124295. 2,
  124296. 1,
  124297. 3,
  124298. 0,
  124299. 4,
  124300. };
  124301. static long _vq_lengthlist__44c4_s_p8_1[] = {
  124302. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  124303. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124304. };
  124305. static float _vq_quantthresh__44c4_s_p8_1[] = {
  124306. -1.5, -0.5, 0.5, 1.5,
  124307. };
  124308. static long _vq_quantmap__44c4_s_p8_1[] = {
  124309. 3, 1, 0, 2, 4,
  124310. };
  124311. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  124312. _vq_quantthresh__44c4_s_p8_1,
  124313. _vq_quantmap__44c4_s_p8_1,
  124314. 5,
  124315. 5
  124316. };
  124317. static static_codebook _44c4_s_p8_1 = {
  124318. 2, 25,
  124319. _vq_lengthlist__44c4_s_p8_1,
  124320. 1, -533725184, 1611661312, 3, 0,
  124321. _vq_quantlist__44c4_s_p8_1,
  124322. NULL,
  124323. &_vq_auxt__44c4_s_p8_1,
  124324. NULL,
  124325. 0
  124326. };
  124327. static long _vq_quantlist__44c4_s_p9_0[] = {
  124328. 6,
  124329. 5,
  124330. 7,
  124331. 4,
  124332. 8,
  124333. 3,
  124334. 9,
  124335. 2,
  124336. 10,
  124337. 1,
  124338. 11,
  124339. 0,
  124340. 12,
  124341. };
  124342. static long _vq_lengthlist__44c4_s_p9_0[] = {
  124343. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  124344. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  124345. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124346. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124347. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124348. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124349. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124350. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124351. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124352. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124353. 12,12,12,12,12,12,12,12,12,
  124354. };
  124355. static float _vq_quantthresh__44c4_s_p9_0[] = {
  124356. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124357. 787.5, 1102.5, 1417.5, 1732.5,
  124358. };
  124359. static long _vq_quantmap__44c4_s_p9_0[] = {
  124360. 11, 9, 7, 5, 3, 1, 0, 2,
  124361. 4, 6, 8, 10, 12,
  124362. };
  124363. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  124364. _vq_quantthresh__44c4_s_p9_0,
  124365. _vq_quantmap__44c4_s_p9_0,
  124366. 13,
  124367. 13
  124368. };
  124369. static static_codebook _44c4_s_p9_0 = {
  124370. 2, 169,
  124371. _vq_lengthlist__44c4_s_p9_0,
  124372. 1, -513964032, 1628680192, 4, 0,
  124373. _vq_quantlist__44c4_s_p9_0,
  124374. NULL,
  124375. &_vq_auxt__44c4_s_p9_0,
  124376. NULL,
  124377. 0
  124378. };
  124379. static long _vq_quantlist__44c4_s_p9_1[] = {
  124380. 7,
  124381. 6,
  124382. 8,
  124383. 5,
  124384. 9,
  124385. 4,
  124386. 10,
  124387. 3,
  124388. 11,
  124389. 2,
  124390. 12,
  124391. 1,
  124392. 13,
  124393. 0,
  124394. 14,
  124395. };
  124396. static long _vq_lengthlist__44c4_s_p9_1[] = {
  124397. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  124398. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  124399. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  124400. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  124401. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  124402. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  124403. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  124404. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  124405. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  124406. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  124407. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  124408. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  124409. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  124410. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  124411. 15,
  124412. };
  124413. static float _vq_quantthresh__44c4_s_p9_1[] = {
  124414. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124415. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124416. };
  124417. static long _vq_quantmap__44c4_s_p9_1[] = {
  124418. 13, 11, 9, 7, 5, 3, 1, 0,
  124419. 2, 4, 6, 8, 10, 12, 14,
  124420. };
  124421. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  124422. _vq_quantthresh__44c4_s_p9_1,
  124423. _vq_quantmap__44c4_s_p9_1,
  124424. 15,
  124425. 15
  124426. };
  124427. static static_codebook _44c4_s_p9_1 = {
  124428. 2, 225,
  124429. _vq_lengthlist__44c4_s_p9_1,
  124430. 1, -520986624, 1620377600, 4, 0,
  124431. _vq_quantlist__44c4_s_p9_1,
  124432. NULL,
  124433. &_vq_auxt__44c4_s_p9_1,
  124434. NULL,
  124435. 0
  124436. };
  124437. static long _vq_quantlist__44c4_s_p9_2[] = {
  124438. 10,
  124439. 9,
  124440. 11,
  124441. 8,
  124442. 12,
  124443. 7,
  124444. 13,
  124445. 6,
  124446. 14,
  124447. 5,
  124448. 15,
  124449. 4,
  124450. 16,
  124451. 3,
  124452. 17,
  124453. 2,
  124454. 18,
  124455. 1,
  124456. 19,
  124457. 0,
  124458. 20,
  124459. };
  124460. static long _vq_lengthlist__44c4_s_p9_2[] = {
  124461. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  124462. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  124463. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  124464. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124465. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  124466. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  124467. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  124468. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124469. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  124470. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  124471. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  124472. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124473. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  124474. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124475. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  124476. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  124477. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  124478. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  124479. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  124480. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  124481. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124482. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  124483. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  124484. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  124485. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  124486. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  124487. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  124488. 10,10,10,10,10,10,10,10,10,
  124489. };
  124490. static float _vq_quantthresh__44c4_s_p9_2[] = {
  124491. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124492. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124493. 6.5, 7.5, 8.5, 9.5,
  124494. };
  124495. static long _vq_quantmap__44c4_s_p9_2[] = {
  124496. 19, 17, 15, 13, 11, 9, 7, 5,
  124497. 3, 1, 0, 2, 4, 6, 8, 10,
  124498. 12, 14, 16, 18, 20,
  124499. };
  124500. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  124501. _vq_quantthresh__44c4_s_p9_2,
  124502. _vq_quantmap__44c4_s_p9_2,
  124503. 21,
  124504. 21
  124505. };
  124506. static static_codebook _44c4_s_p9_2 = {
  124507. 2, 441,
  124508. _vq_lengthlist__44c4_s_p9_2,
  124509. 1, -529268736, 1611661312, 5, 0,
  124510. _vq_quantlist__44c4_s_p9_2,
  124511. NULL,
  124512. &_vq_auxt__44c4_s_p9_2,
  124513. NULL,
  124514. 0
  124515. };
  124516. static long _huff_lengthlist__44c4_s_short[] = {
  124517. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  124518. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  124519. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  124520. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  124521. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  124522. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  124523. 7, 9,12,17,
  124524. };
  124525. static static_codebook _huff_book__44c4_s_short = {
  124526. 2, 100,
  124527. _huff_lengthlist__44c4_s_short,
  124528. 0, 0, 0, 0, 0,
  124529. NULL,
  124530. NULL,
  124531. NULL,
  124532. NULL,
  124533. 0
  124534. };
  124535. static long _huff_lengthlist__44c5_s_long[] = {
  124536. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  124537. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  124538. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  124539. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  124540. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  124541. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  124542. 9, 8, 7, 7,
  124543. };
  124544. static static_codebook _huff_book__44c5_s_long = {
  124545. 2, 100,
  124546. _huff_lengthlist__44c5_s_long,
  124547. 0, 0, 0, 0, 0,
  124548. NULL,
  124549. NULL,
  124550. NULL,
  124551. NULL,
  124552. 0
  124553. };
  124554. static long _vq_quantlist__44c5_s_p1_0[] = {
  124555. 1,
  124556. 0,
  124557. 2,
  124558. };
  124559. static long _vq_lengthlist__44c5_s_p1_0[] = {
  124560. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  124561. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  124566. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  124571. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  124606. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  124611. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  124612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124616. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124652. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124657. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  124662. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0,
  124971. };
  124972. static float _vq_quantthresh__44c5_s_p1_0[] = {
  124973. -0.5, 0.5,
  124974. };
  124975. static long _vq_quantmap__44c5_s_p1_0[] = {
  124976. 1, 0, 2,
  124977. };
  124978. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  124979. _vq_quantthresh__44c5_s_p1_0,
  124980. _vq_quantmap__44c5_s_p1_0,
  124981. 3,
  124982. 3
  124983. };
  124984. static static_codebook _44c5_s_p1_0 = {
  124985. 8, 6561,
  124986. _vq_lengthlist__44c5_s_p1_0,
  124987. 1, -535822336, 1611661312, 2, 0,
  124988. _vq_quantlist__44c5_s_p1_0,
  124989. NULL,
  124990. &_vq_auxt__44c5_s_p1_0,
  124991. NULL,
  124992. 0
  124993. };
  124994. static long _vq_quantlist__44c5_s_p2_0[] = {
  124995. 2,
  124996. 1,
  124997. 3,
  124998. 0,
  124999. 4,
  125000. };
  125001. static long _vq_lengthlist__44c5_s_p2_0[] = {
  125002. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125003. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125004. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125005. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  125006. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  125012. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  125013. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  125014. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  125020. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  125021. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  125028. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  125029. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0,
  125042. };
  125043. static float _vq_quantthresh__44c5_s_p2_0[] = {
  125044. -1.5, -0.5, 0.5, 1.5,
  125045. };
  125046. static long _vq_quantmap__44c5_s_p2_0[] = {
  125047. 3, 1, 0, 2, 4,
  125048. };
  125049. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  125050. _vq_quantthresh__44c5_s_p2_0,
  125051. _vq_quantmap__44c5_s_p2_0,
  125052. 5,
  125053. 5
  125054. };
  125055. static static_codebook _44c5_s_p2_0 = {
  125056. 4, 625,
  125057. _vq_lengthlist__44c5_s_p2_0,
  125058. 1, -533725184, 1611661312, 3, 0,
  125059. _vq_quantlist__44c5_s_p2_0,
  125060. NULL,
  125061. &_vq_auxt__44c5_s_p2_0,
  125062. NULL,
  125063. 0
  125064. };
  125065. static long _vq_quantlist__44c5_s_p3_0[] = {
  125066. 2,
  125067. 1,
  125068. 3,
  125069. 0,
  125070. 4,
  125071. };
  125072. static long _vq_lengthlist__44c5_s_p3_0[] = {
  125073. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0,
  125113. };
  125114. static float _vq_quantthresh__44c5_s_p3_0[] = {
  125115. -1.5, -0.5, 0.5, 1.5,
  125116. };
  125117. static long _vq_quantmap__44c5_s_p3_0[] = {
  125118. 3, 1, 0, 2, 4,
  125119. };
  125120. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  125121. _vq_quantthresh__44c5_s_p3_0,
  125122. _vq_quantmap__44c5_s_p3_0,
  125123. 5,
  125124. 5
  125125. };
  125126. static static_codebook _44c5_s_p3_0 = {
  125127. 4, 625,
  125128. _vq_lengthlist__44c5_s_p3_0,
  125129. 1, -533725184, 1611661312, 3, 0,
  125130. _vq_quantlist__44c5_s_p3_0,
  125131. NULL,
  125132. &_vq_auxt__44c5_s_p3_0,
  125133. NULL,
  125134. 0
  125135. };
  125136. static long _vq_quantlist__44c5_s_p4_0[] = {
  125137. 4,
  125138. 3,
  125139. 5,
  125140. 2,
  125141. 6,
  125142. 1,
  125143. 7,
  125144. 0,
  125145. 8,
  125146. };
  125147. static long _vq_lengthlist__44c5_s_p4_0[] = {
  125148. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125149. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125150. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125151. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  125152. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0,
  125154. };
  125155. static float _vq_quantthresh__44c5_s_p4_0[] = {
  125156. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125157. };
  125158. static long _vq_quantmap__44c5_s_p4_0[] = {
  125159. 7, 5, 3, 1, 0, 2, 4, 6,
  125160. 8,
  125161. };
  125162. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  125163. _vq_quantthresh__44c5_s_p4_0,
  125164. _vq_quantmap__44c5_s_p4_0,
  125165. 9,
  125166. 9
  125167. };
  125168. static static_codebook _44c5_s_p4_0 = {
  125169. 2, 81,
  125170. _vq_lengthlist__44c5_s_p4_0,
  125171. 1, -531628032, 1611661312, 4, 0,
  125172. _vq_quantlist__44c5_s_p4_0,
  125173. NULL,
  125174. &_vq_auxt__44c5_s_p4_0,
  125175. NULL,
  125176. 0
  125177. };
  125178. static long _vq_quantlist__44c5_s_p5_0[] = {
  125179. 4,
  125180. 3,
  125181. 5,
  125182. 2,
  125183. 6,
  125184. 1,
  125185. 7,
  125186. 0,
  125187. 8,
  125188. };
  125189. static long _vq_lengthlist__44c5_s_p5_0[] = {
  125190. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125191. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125192. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  125193. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125194. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125195. 10,
  125196. };
  125197. static float _vq_quantthresh__44c5_s_p5_0[] = {
  125198. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125199. };
  125200. static long _vq_quantmap__44c5_s_p5_0[] = {
  125201. 7, 5, 3, 1, 0, 2, 4, 6,
  125202. 8,
  125203. };
  125204. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  125205. _vq_quantthresh__44c5_s_p5_0,
  125206. _vq_quantmap__44c5_s_p5_0,
  125207. 9,
  125208. 9
  125209. };
  125210. static static_codebook _44c5_s_p5_0 = {
  125211. 2, 81,
  125212. _vq_lengthlist__44c5_s_p5_0,
  125213. 1, -531628032, 1611661312, 4, 0,
  125214. _vq_quantlist__44c5_s_p5_0,
  125215. NULL,
  125216. &_vq_auxt__44c5_s_p5_0,
  125217. NULL,
  125218. 0
  125219. };
  125220. static long _vq_quantlist__44c5_s_p6_0[] = {
  125221. 8,
  125222. 7,
  125223. 9,
  125224. 6,
  125225. 10,
  125226. 5,
  125227. 11,
  125228. 4,
  125229. 12,
  125230. 3,
  125231. 13,
  125232. 2,
  125233. 14,
  125234. 1,
  125235. 15,
  125236. 0,
  125237. 16,
  125238. };
  125239. static long _vq_lengthlist__44c5_s_p6_0[] = {
  125240. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  125241. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125242. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125243. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125244. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125245. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125246. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  125247. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  125248. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125249. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  125250. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  125251. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  125252. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  125253. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  125254. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  125255. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125256. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125258. 13,
  125259. };
  125260. static float _vq_quantthresh__44c5_s_p6_0[] = {
  125261. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125262. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125263. };
  125264. static long _vq_quantmap__44c5_s_p6_0[] = {
  125265. 15, 13, 11, 9, 7, 5, 3, 1,
  125266. 0, 2, 4, 6, 8, 10, 12, 14,
  125267. 16,
  125268. };
  125269. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  125270. _vq_quantthresh__44c5_s_p6_0,
  125271. _vq_quantmap__44c5_s_p6_0,
  125272. 17,
  125273. 17
  125274. };
  125275. static static_codebook _44c5_s_p6_0 = {
  125276. 2, 289,
  125277. _vq_lengthlist__44c5_s_p6_0,
  125278. 1, -529530880, 1611661312, 5, 0,
  125279. _vq_quantlist__44c5_s_p6_0,
  125280. NULL,
  125281. &_vq_auxt__44c5_s_p6_0,
  125282. NULL,
  125283. 0
  125284. };
  125285. static long _vq_quantlist__44c5_s_p7_0[] = {
  125286. 1,
  125287. 0,
  125288. 2,
  125289. };
  125290. static long _vq_lengthlist__44c5_s_p7_0[] = {
  125291. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125292. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125293. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125294. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  125295. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125296. 10,
  125297. };
  125298. static float _vq_quantthresh__44c5_s_p7_0[] = {
  125299. -5.5, 5.5,
  125300. };
  125301. static long _vq_quantmap__44c5_s_p7_0[] = {
  125302. 1, 0, 2,
  125303. };
  125304. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  125305. _vq_quantthresh__44c5_s_p7_0,
  125306. _vq_quantmap__44c5_s_p7_0,
  125307. 3,
  125308. 3
  125309. };
  125310. static static_codebook _44c5_s_p7_0 = {
  125311. 4, 81,
  125312. _vq_lengthlist__44c5_s_p7_0,
  125313. 1, -529137664, 1618345984, 2, 0,
  125314. _vq_quantlist__44c5_s_p7_0,
  125315. NULL,
  125316. &_vq_auxt__44c5_s_p7_0,
  125317. NULL,
  125318. 0
  125319. };
  125320. static long _vq_quantlist__44c5_s_p7_1[] = {
  125321. 5,
  125322. 4,
  125323. 6,
  125324. 3,
  125325. 7,
  125326. 2,
  125327. 8,
  125328. 1,
  125329. 9,
  125330. 0,
  125331. 10,
  125332. };
  125333. static long _vq_lengthlist__44c5_s_p7_1[] = {
  125334. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  125335. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125336. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125337. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125338. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  125339. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  125340. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125341. 10,10,10, 8, 8, 8, 8, 8, 8,
  125342. };
  125343. static float _vq_quantthresh__44c5_s_p7_1[] = {
  125344. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125345. 3.5, 4.5,
  125346. };
  125347. static long _vq_quantmap__44c5_s_p7_1[] = {
  125348. 9, 7, 5, 3, 1, 0, 2, 4,
  125349. 6, 8, 10,
  125350. };
  125351. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  125352. _vq_quantthresh__44c5_s_p7_1,
  125353. _vq_quantmap__44c5_s_p7_1,
  125354. 11,
  125355. 11
  125356. };
  125357. static static_codebook _44c5_s_p7_1 = {
  125358. 2, 121,
  125359. _vq_lengthlist__44c5_s_p7_1,
  125360. 1, -531365888, 1611661312, 4, 0,
  125361. _vq_quantlist__44c5_s_p7_1,
  125362. NULL,
  125363. &_vq_auxt__44c5_s_p7_1,
  125364. NULL,
  125365. 0
  125366. };
  125367. static long _vq_quantlist__44c5_s_p8_0[] = {
  125368. 6,
  125369. 5,
  125370. 7,
  125371. 4,
  125372. 8,
  125373. 3,
  125374. 9,
  125375. 2,
  125376. 10,
  125377. 1,
  125378. 11,
  125379. 0,
  125380. 12,
  125381. };
  125382. static long _vq_lengthlist__44c5_s_p8_0[] = {
  125383. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125384. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  125385. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125386. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125387. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  125388. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  125389. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  125390. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125391. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  125392. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  125393. 0,12,12,12,12,12,12,13,13,
  125394. };
  125395. static float _vq_quantthresh__44c5_s_p8_0[] = {
  125396. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125397. 12.5, 17.5, 22.5, 27.5,
  125398. };
  125399. static long _vq_quantmap__44c5_s_p8_0[] = {
  125400. 11, 9, 7, 5, 3, 1, 0, 2,
  125401. 4, 6, 8, 10, 12,
  125402. };
  125403. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  125404. _vq_quantthresh__44c5_s_p8_0,
  125405. _vq_quantmap__44c5_s_p8_0,
  125406. 13,
  125407. 13
  125408. };
  125409. static static_codebook _44c5_s_p8_0 = {
  125410. 2, 169,
  125411. _vq_lengthlist__44c5_s_p8_0,
  125412. 1, -526516224, 1616117760, 4, 0,
  125413. _vq_quantlist__44c5_s_p8_0,
  125414. NULL,
  125415. &_vq_auxt__44c5_s_p8_0,
  125416. NULL,
  125417. 0
  125418. };
  125419. static long _vq_quantlist__44c5_s_p8_1[] = {
  125420. 2,
  125421. 1,
  125422. 3,
  125423. 0,
  125424. 4,
  125425. };
  125426. static long _vq_lengthlist__44c5_s_p8_1[] = {
  125427. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125428. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125429. };
  125430. static float _vq_quantthresh__44c5_s_p8_1[] = {
  125431. -1.5, -0.5, 0.5, 1.5,
  125432. };
  125433. static long _vq_quantmap__44c5_s_p8_1[] = {
  125434. 3, 1, 0, 2, 4,
  125435. };
  125436. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  125437. _vq_quantthresh__44c5_s_p8_1,
  125438. _vq_quantmap__44c5_s_p8_1,
  125439. 5,
  125440. 5
  125441. };
  125442. static static_codebook _44c5_s_p8_1 = {
  125443. 2, 25,
  125444. _vq_lengthlist__44c5_s_p8_1,
  125445. 1, -533725184, 1611661312, 3, 0,
  125446. _vq_quantlist__44c5_s_p8_1,
  125447. NULL,
  125448. &_vq_auxt__44c5_s_p8_1,
  125449. NULL,
  125450. 0
  125451. };
  125452. static long _vq_quantlist__44c5_s_p9_0[] = {
  125453. 7,
  125454. 6,
  125455. 8,
  125456. 5,
  125457. 9,
  125458. 4,
  125459. 10,
  125460. 3,
  125461. 11,
  125462. 2,
  125463. 12,
  125464. 1,
  125465. 13,
  125466. 0,
  125467. 14,
  125468. };
  125469. static long _vq_lengthlist__44c5_s_p9_0[] = {
  125470. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  125471. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  125472. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125473. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125474. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125475. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125476. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125477. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125478. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125479. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125480. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125481. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125482. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125483. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  125484. 12,
  125485. };
  125486. static float _vq_quantthresh__44c5_s_p9_0[] = {
  125487. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  125488. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  125489. };
  125490. static long _vq_quantmap__44c5_s_p9_0[] = {
  125491. 13, 11, 9, 7, 5, 3, 1, 0,
  125492. 2, 4, 6, 8, 10, 12, 14,
  125493. };
  125494. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  125495. _vq_quantthresh__44c5_s_p9_0,
  125496. _vq_quantmap__44c5_s_p9_0,
  125497. 15,
  125498. 15
  125499. };
  125500. static static_codebook _44c5_s_p9_0 = {
  125501. 2, 225,
  125502. _vq_lengthlist__44c5_s_p9_0,
  125503. 1, -512522752, 1628852224, 4, 0,
  125504. _vq_quantlist__44c5_s_p9_0,
  125505. NULL,
  125506. &_vq_auxt__44c5_s_p9_0,
  125507. NULL,
  125508. 0
  125509. };
  125510. static long _vq_quantlist__44c5_s_p9_1[] = {
  125511. 8,
  125512. 7,
  125513. 9,
  125514. 6,
  125515. 10,
  125516. 5,
  125517. 11,
  125518. 4,
  125519. 12,
  125520. 3,
  125521. 13,
  125522. 2,
  125523. 14,
  125524. 1,
  125525. 15,
  125526. 0,
  125527. 16,
  125528. };
  125529. static long _vq_lengthlist__44c5_s_p9_1[] = {
  125530. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  125531. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  125532. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  125533. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  125534. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  125535. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  125536. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  125537. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  125538. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  125539. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  125540. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  125541. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  125542. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  125543. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  125544. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  125545. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  125546. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  125547. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  125548. 15,
  125549. };
  125550. static float _vq_quantthresh__44c5_s_p9_1[] = {
  125551. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  125552. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  125553. };
  125554. static long _vq_quantmap__44c5_s_p9_1[] = {
  125555. 15, 13, 11, 9, 7, 5, 3, 1,
  125556. 0, 2, 4, 6, 8, 10, 12, 14,
  125557. 16,
  125558. };
  125559. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  125560. _vq_quantthresh__44c5_s_p9_1,
  125561. _vq_quantmap__44c5_s_p9_1,
  125562. 17,
  125563. 17
  125564. };
  125565. static static_codebook _44c5_s_p9_1 = {
  125566. 2, 289,
  125567. _vq_lengthlist__44c5_s_p9_1,
  125568. 1, -520814592, 1620377600, 5, 0,
  125569. _vq_quantlist__44c5_s_p9_1,
  125570. NULL,
  125571. &_vq_auxt__44c5_s_p9_1,
  125572. NULL,
  125573. 0
  125574. };
  125575. static long _vq_quantlist__44c5_s_p9_2[] = {
  125576. 10,
  125577. 9,
  125578. 11,
  125579. 8,
  125580. 12,
  125581. 7,
  125582. 13,
  125583. 6,
  125584. 14,
  125585. 5,
  125586. 15,
  125587. 4,
  125588. 16,
  125589. 3,
  125590. 17,
  125591. 2,
  125592. 18,
  125593. 1,
  125594. 19,
  125595. 0,
  125596. 20,
  125597. };
  125598. static long _vq_lengthlist__44c5_s_p9_2[] = {
  125599. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125600. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  125601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  125602. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125603. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  125604. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125605. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  125606. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  125607. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  125608. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125609. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  125610. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  125611. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  125612. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  125613. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  125614. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  125615. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  125616. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125617. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  125618. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  125619. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125620. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  125621. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  125622. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  125623. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  125624. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125625. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  125626. 10,10,10,10,10,10,10,10,10,
  125627. };
  125628. static float _vq_quantthresh__44c5_s_p9_2[] = {
  125629. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125630. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125631. 6.5, 7.5, 8.5, 9.5,
  125632. };
  125633. static long _vq_quantmap__44c5_s_p9_2[] = {
  125634. 19, 17, 15, 13, 11, 9, 7, 5,
  125635. 3, 1, 0, 2, 4, 6, 8, 10,
  125636. 12, 14, 16, 18, 20,
  125637. };
  125638. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  125639. _vq_quantthresh__44c5_s_p9_2,
  125640. _vq_quantmap__44c5_s_p9_2,
  125641. 21,
  125642. 21
  125643. };
  125644. static static_codebook _44c5_s_p9_2 = {
  125645. 2, 441,
  125646. _vq_lengthlist__44c5_s_p9_2,
  125647. 1, -529268736, 1611661312, 5, 0,
  125648. _vq_quantlist__44c5_s_p9_2,
  125649. NULL,
  125650. &_vq_auxt__44c5_s_p9_2,
  125651. NULL,
  125652. 0
  125653. };
  125654. static long _huff_lengthlist__44c5_s_short[] = {
  125655. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  125656. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  125657. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  125658. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  125659. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  125660. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  125661. 6, 8,11,16,
  125662. };
  125663. static static_codebook _huff_book__44c5_s_short = {
  125664. 2, 100,
  125665. _huff_lengthlist__44c5_s_short,
  125666. 0, 0, 0, 0, 0,
  125667. NULL,
  125668. NULL,
  125669. NULL,
  125670. NULL,
  125671. 0
  125672. };
  125673. static long _huff_lengthlist__44c6_s_long[] = {
  125674. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  125675. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  125676. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  125677. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  125678. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  125679. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  125680. 11,10,10,12,
  125681. };
  125682. static static_codebook _huff_book__44c6_s_long = {
  125683. 2, 100,
  125684. _huff_lengthlist__44c6_s_long,
  125685. 0, 0, 0, 0, 0,
  125686. NULL,
  125687. NULL,
  125688. NULL,
  125689. NULL,
  125690. 0
  125691. };
  125692. static long _vq_quantlist__44c6_s_p1_0[] = {
  125693. 1,
  125694. 0,
  125695. 2,
  125696. };
  125697. static long _vq_lengthlist__44c6_s_p1_0[] = {
  125698. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  125699. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  125701. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  125702. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  125703. 8,
  125704. };
  125705. static float _vq_quantthresh__44c6_s_p1_0[] = {
  125706. -0.5, 0.5,
  125707. };
  125708. static long _vq_quantmap__44c6_s_p1_0[] = {
  125709. 1, 0, 2,
  125710. };
  125711. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  125712. _vq_quantthresh__44c6_s_p1_0,
  125713. _vq_quantmap__44c6_s_p1_0,
  125714. 3,
  125715. 3
  125716. };
  125717. static static_codebook _44c6_s_p1_0 = {
  125718. 4, 81,
  125719. _vq_lengthlist__44c6_s_p1_0,
  125720. 1, -535822336, 1611661312, 2, 0,
  125721. _vq_quantlist__44c6_s_p1_0,
  125722. NULL,
  125723. &_vq_auxt__44c6_s_p1_0,
  125724. NULL,
  125725. 0
  125726. };
  125727. static long _vq_quantlist__44c6_s_p2_0[] = {
  125728. 2,
  125729. 1,
  125730. 3,
  125731. 0,
  125732. 4,
  125733. };
  125734. static long _vq_lengthlist__44c6_s_p2_0[] = {
  125735. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  125736. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  125737. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  125738. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  125739. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  125740. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  125741. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  125742. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  125745. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  125746. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  125747. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  125748. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  125749. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  125750. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  125753. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  125754. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  125755. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  125756. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  125757. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  125758. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  125761. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  125762. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  125763. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  125764. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  125765. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  125766. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  125771. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  125772. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  125773. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  125774. 13,
  125775. };
  125776. static float _vq_quantthresh__44c6_s_p2_0[] = {
  125777. -1.5, -0.5, 0.5, 1.5,
  125778. };
  125779. static long _vq_quantmap__44c6_s_p2_0[] = {
  125780. 3, 1, 0, 2, 4,
  125781. };
  125782. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  125783. _vq_quantthresh__44c6_s_p2_0,
  125784. _vq_quantmap__44c6_s_p2_0,
  125785. 5,
  125786. 5
  125787. };
  125788. static static_codebook _44c6_s_p2_0 = {
  125789. 4, 625,
  125790. _vq_lengthlist__44c6_s_p2_0,
  125791. 1, -533725184, 1611661312, 3, 0,
  125792. _vq_quantlist__44c6_s_p2_0,
  125793. NULL,
  125794. &_vq_auxt__44c6_s_p2_0,
  125795. NULL,
  125796. 0
  125797. };
  125798. static long _vq_quantlist__44c6_s_p3_0[] = {
  125799. 4,
  125800. 3,
  125801. 5,
  125802. 2,
  125803. 6,
  125804. 1,
  125805. 7,
  125806. 0,
  125807. 8,
  125808. };
  125809. static long _vq_lengthlist__44c6_s_p3_0[] = {
  125810. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125811. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  125812. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  125813. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0,
  125816. };
  125817. static float _vq_quantthresh__44c6_s_p3_0[] = {
  125818. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125819. };
  125820. static long _vq_quantmap__44c6_s_p3_0[] = {
  125821. 7, 5, 3, 1, 0, 2, 4, 6,
  125822. 8,
  125823. };
  125824. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  125825. _vq_quantthresh__44c6_s_p3_0,
  125826. _vq_quantmap__44c6_s_p3_0,
  125827. 9,
  125828. 9
  125829. };
  125830. static static_codebook _44c6_s_p3_0 = {
  125831. 2, 81,
  125832. _vq_lengthlist__44c6_s_p3_0,
  125833. 1, -531628032, 1611661312, 4, 0,
  125834. _vq_quantlist__44c6_s_p3_0,
  125835. NULL,
  125836. &_vq_auxt__44c6_s_p3_0,
  125837. NULL,
  125838. 0
  125839. };
  125840. static long _vq_quantlist__44c6_s_p4_0[] = {
  125841. 8,
  125842. 7,
  125843. 9,
  125844. 6,
  125845. 10,
  125846. 5,
  125847. 11,
  125848. 4,
  125849. 12,
  125850. 3,
  125851. 13,
  125852. 2,
  125853. 14,
  125854. 1,
  125855. 15,
  125856. 0,
  125857. 16,
  125858. };
  125859. static long _vq_lengthlist__44c6_s_p4_0[] = {
  125860. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  125861. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125862. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  125863. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125864. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125865. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125866. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  125867. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125868. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125869. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0,
  125879. };
  125880. static float _vq_quantthresh__44c6_s_p4_0[] = {
  125881. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125882. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125883. };
  125884. static long _vq_quantmap__44c6_s_p4_0[] = {
  125885. 15, 13, 11, 9, 7, 5, 3, 1,
  125886. 0, 2, 4, 6, 8, 10, 12, 14,
  125887. 16,
  125888. };
  125889. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  125890. _vq_quantthresh__44c6_s_p4_0,
  125891. _vq_quantmap__44c6_s_p4_0,
  125892. 17,
  125893. 17
  125894. };
  125895. static static_codebook _44c6_s_p4_0 = {
  125896. 2, 289,
  125897. _vq_lengthlist__44c6_s_p4_0,
  125898. 1, -529530880, 1611661312, 5, 0,
  125899. _vq_quantlist__44c6_s_p4_0,
  125900. NULL,
  125901. &_vq_auxt__44c6_s_p4_0,
  125902. NULL,
  125903. 0
  125904. };
  125905. static long _vq_quantlist__44c6_s_p5_0[] = {
  125906. 1,
  125907. 0,
  125908. 2,
  125909. };
  125910. static long _vq_lengthlist__44c6_s_p5_0[] = {
  125911. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  125912. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  125913. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  125914. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  125915. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  125916. 12,
  125917. };
  125918. static float _vq_quantthresh__44c6_s_p5_0[] = {
  125919. -5.5, 5.5,
  125920. };
  125921. static long _vq_quantmap__44c6_s_p5_0[] = {
  125922. 1, 0, 2,
  125923. };
  125924. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  125925. _vq_quantthresh__44c6_s_p5_0,
  125926. _vq_quantmap__44c6_s_p5_0,
  125927. 3,
  125928. 3
  125929. };
  125930. static static_codebook _44c6_s_p5_0 = {
  125931. 4, 81,
  125932. _vq_lengthlist__44c6_s_p5_0,
  125933. 1, -529137664, 1618345984, 2, 0,
  125934. _vq_quantlist__44c6_s_p5_0,
  125935. NULL,
  125936. &_vq_auxt__44c6_s_p5_0,
  125937. NULL,
  125938. 0
  125939. };
  125940. static long _vq_quantlist__44c6_s_p5_1[] = {
  125941. 5,
  125942. 4,
  125943. 6,
  125944. 3,
  125945. 7,
  125946. 2,
  125947. 8,
  125948. 1,
  125949. 9,
  125950. 0,
  125951. 10,
  125952. };
  125953. static long _vq_lengthlist__44c6_s_p5_1[] = {
  125954. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  125955. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  125956. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125957. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125958. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  125959. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  125960. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  125961. 11,10,10, 7, 7, 8, 8, 8, 8,
  125962. };
  125963. static float _vq_quantthresh__44c6_s_p5_1[] = {
  125964. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125965. 3.5, 4.5,
  125966. };
  125967. static long _vq_quantmap__44c6_s_p5_1[] = {
  125968. 9, 7, 5, 3, 1, 0, 2, 4,
  125969. 6, 8, 10,
  125970. };
  125971. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  125972. _vq_quantthresh__44c6_s_p5_1,
  125973. _vq_quantmap__44c6_s_p5_1,
  125974. 11,
  125975. 11
  125976. };
  125977. static static_codebook _44c6_s_p5_1 = {
  125978. 2, 121,
  125979. _vq_lengthlist__44c6_s_p5_1,
  125980. 1, -531365888, 1611661312, 4, 0,
  125981. _vq_quantlist__44c6_s_p5_1,
  125982. NULL,
  125983. &_vq_auxt__44c6_s_p5_1,
  125984. NULL,
  125985. 0
  125986. };
  125987. static long _vq_quantlist__44c6_s_p6_0[] = {
  125988. 6,
  125989. 5,
  125990. 7,
  125991. 4,
  125992. 8,
  125993. 3,
  125994. 9,
  125995. 2,
  125996. 10,
  125997. 1,
  125998. 11,
  125999. 0,
  126000. 12,
  126001. };
  126002. static long _vq_lengthlist__44c6_s_p6_0[] = {
  126003. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  126004. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  126005. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  126006. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126007. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  126008. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. };
  126015. static float _vq_quantthresh__44c6_s_p6_0[] = {
  126016. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126017. 12.5, 17.5, 22.5, 27.5,
  126018. };
  126019. static long _vq_quantmap__44c6_s_p6_0[] = {
  126020. 11, 9, 7, 5, 3, 1, 0, 2,
  126021. 4, 6, 8, 10, 12,
  126022. };
  126023. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  126024. _vq_quantthresh__44c6_s_p6_0,
  126025. _vq_quantmap__44c6_s_p6_0,
  126026. 13,
  126027. 13
  126028. };
  126029. static static_codebook _44c6_s_p6_0 = {
  126030. 2, 169,
  126031. _vq_lengthlist__44c6_s_p6_0,
  126032. 1, -526516224, 1616117760, 4, 0,
  126033. _vq_quantlist__44c6_s_p6_0,
  126034. NULL,
  126035. &_vq_auxt__44c6_s_p6_0,
  126036. NULL,
  126037. 0
  126038. };
  126039. static long _vq_quantlist__44c6_s_p6_1[] = {
  126040. 2,
  126041. 1,
  126042. 3,
  126043. 0,
  126044. 4,
  126045. };
  126046. static long _vq_lengthlist__44c6_s_p6_1[] = {
  126047. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126048. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126049. };
  126050. static float _vq_quantthresh__44c6_s_p6_1[] = {
  126051. -1.5, -0.5, 0.5, 1.5,
  126052. };
  126053. static long _vq_quantmap__44c6_s_p6_1[] = {
  126054. 3, 1, 0, 2, 4,
  126055. };
  126056. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  126057. _vq_quantthresh__44c6_s_p6_1,
  126058. _vq_quantmap__44c6_s_p6_1,
  126059. 5,
  126060. 5
  126061. };
  126062. static static_codebook _44c6_s_p6_1 = {
  126063. 2, 25,
  126064. _vq_lengthlist__44c6_s_p6_1,
  126065. 1, -533725184, 1611661312, 3, 0,
  126066. _vq_quantlist__44c6_s_p6_1,
  126067. NULL,
  126068. &_vq_auxt__44c6_s_p6_1,
  126069. NULL,
  126070. 0
  126071. };
  126072. static long _vq_quantlist__44c6_s_p7_0[] = {
  126073. 6,
  126074. 5,
  126075. 7,
  126076. 4,
  126077. 8,
  126078. 3,
  126079. 9,
  126080. 2,
  126081. 10,
  126082. 1,
  126083. 11,
  126084. 0,
  126085. 12,
  126086. };
  126087. static long _vq_lengthlist__44c6_s_p7_0[] = {
  126088. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  126089. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  126090. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  126091. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126092. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  126093. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  126094. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  126095. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  126096. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  126097. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  126098. 20,13,13,13,13,13,13,14,14,
  126099. };
  126100. static float _vq_quantthresh__44c6_s_p7_0[] = {
  126101. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126102. 27.5, 38.5, 49.5, 60.5,
  126103. };
  126104. static long _vq_quantmap__44c6_s_p7_0[] = {
  126105. 11, 9, 7, 5, 3, 1, 0, 2,
  126106. 4, 6, 8, 10, 12,
  126107. };
  126108. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  126109. _vq_quantthresh__44c6_s_p7_0,
  126110. _vq_quantmap__44c6_s_p7_0,
  126111. 13,
  126112. 13
  126113. };
  126114. static static_codebook _44c6_s_p7_0 = {
  126115. 2, 169,
  126116. _vq_lengthlist__44c6_s_p7_0,
  126117. 1, -523206656, 1618345984, 4, 0,
  126118. _vq_quantlist__44c6_s_p7_0,
  126119. NULL,
  126120. &_vq_auxt__44c6_s_p7_0,
  126121. NULL,
  126122. 0
  126123. };
  126124. static long _vq_quantlist__44c6_s_p7_1[] = {
  126125. 5,
  126126. 4,
  126127. 6,
  126128. 3,
  126129. 7,
  126130. 2,
  126131. 8,
  126132. 1,
  126133. 9,
  126134. 0,
  126135. 10,
  126136. };
  126137. static long _vq_lengthlist__44c6_s_p7_1[] = {
  126138. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  126139. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  126140. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  126141. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  126142. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  126143. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  126144. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  126145. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  126146. };
  126147. static float _vq_quantthresh__44c6_s_p7_1[] = {
  126148. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126149. 3.5, 4.5,
  126150. };
  126151. static long _vq_quantmap__44c6_s_p7_1[] = {
  126152. 9, 7, 5, 3, 1, 0, 2, 4,
  126153. 6, 8, 10,
  126154. };
  126155. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  126156. _vq_quantthresh__44c6_s_p7_1,
  126157. _vq_quantmap__44c6_s_p7_1,
  126158. 11,
  126159. 11
  126160. };
  126161. static static_codebook _44c6_s_p7_1 = {
  126162. 2, 121,
  126163. _vq_lengthlist__44c6_s_p7_1,
  126164. 1, -531365888, 1611661312, 4, 0,
  126165. _vq_quantlist__44c6_s_p7_1,
  126166. NULL,
  126167. &_vq_auxt__44c6_s_p7_1,
  126168. NULL,
  126169. 0
  126170. };
  126171. static long _vq_quantlist__44c6_s_p8_0[] = {
  126172. 7,
  126173. 6,
  126174. 8,
  126175. 5,
  126176. 9,
  126177. 4,
  126178. 10,
  126179. 3,
  126180. 11,
  126181. 2,
  126182. 12,
  126183. 1,
  126184. 13,
  126185. 0,
  126186. 14,
  126187. };
  126188. static long _vq_lengthlist__44c6_s_p8_0[] = {
  126189. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  126190. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  126191. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  126192. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  126193. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  126194. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  126195. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  126196. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  126197. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  126198. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  126199. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  126200. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  126201. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  126202. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  126203. 14,
  126204. };
  126205. static float _vq_quantthresh__44c6_s_p8_0[] = {
  126206. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126207. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126208. };
  126209. static long _vq_quantmap__44c6_s_p8_0[] = {
  126210. 13, 11, 9, 7, 5, 3, 1, 0,
  126211. 2, 4, 6, 8, 10, 12, 14,
  126212. };
  126213. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  126214. _vq_quantthresh__44c6_s_p8_0,
  126215. _vq_quantmap__44c6_s_p8_0,
  126216. 15,
  126217. 15
  126218. };
  126219. static static_codebook _44c6_s_p8_0 = {
  126220. 2, 225,
  126221. _vq_lengthlist__44c6_s_p8_0,
  126222. 1, -520986624, 1620377600, 4, 0,
  126223. _vq_quantlist__44c6_s_p8_0,
  126224. NULL,
  126225. &_vq_auxt__44c6_s_p8_0,
  126226. NULL,
  126227. 0
  126228. };
  126229. static long _vq_quantlist__44c6_s_p8_1[] = {
  126230. 10,
  126231. 9,
  126232. 11,
  126233. 8,
  126234. 12,
  126235. 7,
  126236. 13,
  126237. 6,
  126238. 14,
  126239. 5,
  126240. 15,
  126241. 4,
  126242. 16,
  126243. 3,
  126244. 17,
  126245. 2,
  126246. 18,
  126247. 1,
  126248. 19,
  126249. 0,
  126250. 20,
  126251. };
  126252. static long _vq_lengthlist__44c6_s_p8_1[] = {
  126253. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  126254. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  126255. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  126256. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  126257. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126258. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  126259. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  126260. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  126261. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126262. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126263. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  126264. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  126265. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  126266. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  126267. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  126268. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  126269. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  126270. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  126271. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  126272. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  126273. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  126274. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126275. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126276. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126277. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  126278. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  126279. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  126280. 10,10,10,10,10,10,10,10,10,
  126281. };
  126282. static float _vq_quantthresh__44c6_s_p8_1[] = {
  126283. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126284. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126285. 6.5, 7.5, 8.5, 9.5,
  126286. };
  126287. static long _vq_quantmap__44c6_s_p8_1[] = {
  126288. 19, 17, 15, 13, 11, 9, 7, 5,
  126289. 3, 1, 0, 2, 4, 6, 8, 10,
  126290. 12, 14, 16, 18, 20,
  126291. };
  126292. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  126293. _vq_quantthresh__44c6_s_p8_1,
  126294. _vq_quantmap__44c6_s_p8_1,
  126295. 21,
  126296. 21
  126297. };
  126298. static static_codebook _44c6_s_p8_1 = {
  126299. 2, 441,
  126300. _vq_lengthlist__44c6_s_p8_1,
  126301. 1, -529268736, 1611661312, 5, 0,
  126302. _vq_quantlist__44c6_s_p8_1,
  126303. NULL,
  126304. &_vq_auxt__44c6_s_p8_1,
  126305. NULL,
  126306. 0
  126307. };
  126308. static long _vq_quantlist__44c6_s_p9_0[] = {
  126309. 6,
  126310. 5,
  126311. 7,
  126312. 4,
  126313. 8,
  126314. 3,
  126315. 9,
  126316. 2,
  126317. 10,
  126318. 1,
  126319. 11,
  126320. 0,
  126321. 12,
  126322. };
  126323. static long _vq_lengthlist__44c6_s_p9_0[] = {
  126324. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  126325. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  126326. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126327. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  126328. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126329. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126331. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126333. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126334. 10,10,10,10,10,10,10,10,10,
  126335. };
  126336. static float _vq_quantthresh__44c6_s_p9_0[] = {
  126337. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  126338. 1592.5, 2229.5, 2866.5, 3503.5,
  126339. };
  126340. static long _vq_quantmap__44c6_s_p9_0[] = {
  126341. 11, 9, 7, 5, 3, 1, 0, 2,
  126342. 4, 6, 8, 10, 12,
  126343. };
  126344. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  126345. _vq_quantthresh__44c6_s_p9_0,
  126346. _vq_quantmap__44c6_s_p9_0,
  126347. 13,
  126348. 13
  126349. };
  126350. static static_codebook _44c6_s_p9_0 = {
  126351. 2, 169,
  126352. _vq_lengthlist__44c6_s_p9_0,
  126353. 1, -511845376, 1630791680, 4, 0,
  126354. _vq_quantlist__44c6_s_p9_0,
  126355. NULL,
  126356. &_vq_auxt__44c6_s_p9_0,
  126357. NULL,
  126358. 0
  126359. };
  126360. static long _vq_quantlist__44c6_s_p9_1[] = {
  126361. 6,
  126362. 5,
  126363. 7,
  126364. 4,
  126365. 8,
  126366. 3,
  126367. 9,
  126368. 2,
  126369. 10,
  126370. 1,
  126371. 11,
  126372. 0,
  126373. 12,
  126374. };
  126375. static long _vq_lengthlist__44c6_s_p9_1[] = {
  126376. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  126377. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  126378. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  126379. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  126380. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  126381. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  126382. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  126383. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  126384. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  126385. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  126386. 15,12,10,11,11,13,11,12,13,
  126387. };
  126388. static float _vq_quantthresh__44c6_s_p9_1[] = {
  126389. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  126390. 122.5, 171.5, 220.5, 269.5,
  126391. };
  126392. static long _vq_quantmap__44c6_s_p9_1[] = {
  126393. 11, 9, 7, 5, 3, 1, 0, 2,
  126394. 4, 6, 8, 10, 12,
  126395. };
  126396. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  126397. _vq_quantthresh__44c6_s_p9_1,
  126398. _vq_quantmap__44c6_s_p9_1,
  126399. 13,
  126400. 13
  126401. };
  126402. static static_codebook _44c6_s_p9_1 = {
  126403. 2, 169,
  126404. _vq_lengthlist__44c6_s_p9_1,
  126405. 1, -518889472, 1622704128, 4, 0,
  126406. _vq_quantlist__44c6_s_p9_1,
  126407. NULL,
  126408. &_vq_auxt__44c6_s_p9_1,
  126409. NULL,
  126410. 0
  126411. };
  126412. static long _vq_quantlist__44c6_s_p9_2[] = {
  126413. 24,
  126414. 23,
  126415. 25,
  126416. 22,
  126417. 26,
  126418. 21,
  126419. 27,
  126420. 20,
  126421. 28,
  126422. 19,
  126423. 29,
  126424. 18,
  126425. 30,
  126426. 17,
  126427. 31,
  126428. 16,
  126429. 32,
  126430. 15,
  126431. 33,
  126432. 14,
  126433. 34,
  126434. 13,
  126435. 35,
  126436. 12,
  126437. 36,
  126438. 11,
  126439. 37,
  126440. 10,
  126441. 38,
  126442. 9,
  126443. 39,
  126444. 8,
  126445. 40,
  126446. 7,
  126447. 41,
  126448. 6,
  126449. 42,
  126450. 5,
  126451. 43,
  126452. 4,
  126453. 44,
  126454. 3,
  126455. 45,
  126456. 2,
  126457. 46,
  126458. 1,
  126459. 47,
  126460. 0,
  126461. 48,
  126462. };
  126463. static long _vq_lengthlist__44c6_s_p9_2[] = {
  126464. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  126465. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126466. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126467. 7,
  126468. };
  126469. static float _vq_quantthresh__44c6_s_p9_2[] = {
  126470. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  126471. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  126472. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126473. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126474. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  126475. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  126476. };
  126477. static long _vq_quantmap__44c6_s_p9_2[] = {
  126478. 47, 45, 43, 41, 39, 37, 35, 33,
  126479. 31, 29, 27, 25, 23, 21, 19, 17,
  126480. 15, 13, 11, 9, 7, 5, 3, 1,
  126481. 0, 2, 4, 6, 8, 10, 12, 14,
  126482. 16, 18, 20, 22, 24, 26, 28, 30,
  126483. 32, 34, 36, 38, 40, 42, 44, 46,
  126484. 48,
  126485. };
  126486. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  126487. _vq_quantthresh__44c6_s_p9_2,
  126488. _vq_quantmap__44c6_s_p9_2,
  126489. 49,
  126490. 49
  126491. };
  126492. static static_codebook _44c6_s_p9_2 = {
  126493. 1, 49,
  126494. _vq_lengthlist__44c6_s_p9_2,
  126495. 1, -526909440, 1611661312, 6, 0,
  126496. _vq_quantlist__44c6_s_p9_2,
  126497. NULL,
  126498. &_vq_auxt__44c6_s_p9_2,
  126499. NULL,
  126500. 0
  126501. };
  126502. static long _huff_lengthlist__44c6_s_short[] = {
  126503. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  126504. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  126505. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  126506. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  126507. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  126508. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  126509. 9,10,17,18,
  126510. };
  126511. static static_codebook _huff_book__44c6_s_short = {
  126512. 2, 100,
  126513. _huff_lengthlist__44c6_s_short,
  126514. 0, 0, 0, 0, 0,
  126515. NULL,
  126516. NULL,
  126517. NULL,
  126518. NULL,
  126519. 0
  126520. };
  126521. static long _huff_lengthlist__44c7_s_long[] = {
  126522. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  126523. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  126524. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  126525. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  126526. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  126527. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  126528. 11,10,10,12,
  126529. };
  126530. static static_codebook _huff_book__44c7_s_long = {
  126531. 2, 100,
  126532. _huff_lengthlist__44c7_s_long,
  126533. 0, 0, 0, 0, 0,
  126534. NULL,
  126535. NULL,
  126536. NULL,
  126537. NULL,
  126538. 0
  126539. };
  126540. static long _vq_quantlist__44c7_s_p1_0[] = {
  126541. 1,
  126542. 0,
  126543. 2,
  126544. };
  126545. static long _vq_lengthlist__44c7_s_p1_0[] = {
  126546. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  126547. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  126549. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  126550. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  126551. 8,
  126552. };
  126553. static float _vq_quantthresh__44c7_s_p1_0[] = {
  126554. -0.5, 0.5,
  126555. };
  126556. static long _vq_quantmap__44c7_s_p1_0[] = {
  126557. 1, 0, 2,
  126558. };
  126559. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  126560. _vq_quantthresh__44c7_s_p1_0,
  126561. _vq_quantmap__44c7_s_p1_0,
  126562. 3,
  126563. 3
  126564. };
  126565. static static_codebook _44c7_s_p1_0 = {
  126566. 4, 81,
  126567. _vq_lengthlist__44c7_s_p1_0,
  126568. 1, -535822336, 1611661312, 2, 0,
  126569. _vq_quantlist__44c7_s_p1_0,
  126570. NULL,
  126571. &_vq_auxt__44c7_s_p1_0,
  126572. NULL,
  126573. 0
  126574. };
  126575. static long _vq_quantlist__44c7_s_p2_0[] = {
  126576. 2,
  126577. 1,
  126578. 3,
  126579. 0,
  126580. 4,
  126581. };
  126582. static long _vq_lengthlist__44c7_s_p2_0[] = {
  126583. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  126584. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  126585. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  126586. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  126587. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  126588. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  126589. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  126590. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  126593. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  126594. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  126595. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  126596. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  126597. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  126598. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  126601. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  126602. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  126603. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  126604. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  126605. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  126606. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  126609. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  126610. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  126611. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  126612. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  126613. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  126614. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  126619. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  126620. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  126621. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  126622. 13,
  126623. };
  126624. static float _vq_quantthresh__44c7_s_p2_0[] = {
  126625. -1.5, -0.5, 0.5, 1.5,
  126626. };
  126627. static long _vq_quantmap__44c7_s_p2_0[] = {
  126628. 3, 1, 0, 2, 4,
  126629. };
  126630. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  126631. _vq_quantthresh__44c7_s_p2_0,
  126632. _vq_quantmap__44c7_s_p2_0,
  126633. 5,
  126634. 5
  126635. };
  126636. static static_codebook _44c7_s_p2_0 = {
  126637. 4, 625,
  126638. _vq_lengthlist__44c7_s_p2_0,
  126639. 1, -533725184, 1611661312, 3, 0,
  126640. _vq_quantlist__44c7_s_p2_0,
  126641. NULL,
  126642. &_vq_auxt__44c7_s_p2_0,
  126643. NULL,
  126644. 0
  126645. };
  126646. static long _vq_quantlist__44c7_s_p3_0[] = {
  126647. 4,
  126648. 3,
  126649. 5,
  126650. 2,
  126651. 6,
  126652. 1,
  126653. 7,
  126654. 0,
  126655. 8,
  126656. };
  126657. static long _vq_lengthlist__44c7_s_p3_0[] = {
  126658. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126659. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  126660. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  126661. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0,
  126664. };
  126665. static float _vq_quantthresh__44c7_s_p3_0[] = {
  126666. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126667. };
  126668. static long _vq_quantmap__44c7_s_p3_0[] = {
  126669. 7, 5, 3, 1, 0, 2, 4, 6,
  126670. 8,
  126671. };
  126672. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  126673. _vq_quantthresh__44c7_s_p3_0,
  126674. _vq_quantmap__44c7_s_p3_0,
  126675. 9,
  126676. 9
  126677. };
  126678. static static_codebook _44c7_s_p3_0 = {
  126679. 2, 81,
  126680. _vq_lengthlist__44c7_s_p3_0,
  126681. 1, -531628032, 1611661312, 4, 0,
  126682. _vq_quantlist__44c7_s_p3_0,
  126683. NULL,
  126684. &_vq_auxt__44c7_s_p3_0,
  126685. NULL,
  126686. 0
  126687. };
  126688. static long _vq_quantlist__44c7_s_p4_0[] = {
  126689. 8,
  126690. 7,
  126691. 9,
  126692. 6,
  126693. 10,
  126694. 5,
  126695. 11,
  126696. 4,
  126697. 12,
  126698. 3,
  126699. 13,
  126700. 2,
  126701. 14,
  126702. 1,
  126703. 15,
  126704. 0,
  126705. 16,
  126706. };
  126707. static long _vq_lengthlist__44c7_s_p4_0[] = {
  126708. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126709. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  126710. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  126711. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  126712. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  126713. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  126714. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  126715. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  126716. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  126717. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0,
  126727. };
  126728. static float _vq_quantthresh__44c7_s_p4_0[] = {
  126729. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126730. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126731. };
  126732. static long _vq_quantmap__44c7_s_p4_0[] = {
  126733. 15, 13, 11, 9, 7, 5, 3, 1,
  126734. 0, 2, 4, 6, 8, 10, 12, 14,
  126735. 16,
  126736. };
  126737. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  126738. _vq_quantthresh__44c7_s_p4_0,
  126739. _vq_quantmap__44c7_s_p4_0,
  126740. 17,
  126741. 17
  126742. };
  126743. static static_codebook _44c7_s_p4_0 = {
  126744. 2, 289,
  126745. _vq_lengthlist__44c7_s_p4_0,
  126746. 1, -529530880, 1611661312, 5, 0,
  126747. _vq_quantlist__44c7_s_p4_0,
  126748. NULL,
  126749. &_vq_auxt__44c7_s_p4_0,
  126750. NULL,
  126751. 0
  126752. };
  126753. static long _vq_quantlist__44c7_s_p5_0[] = {
  126754. 1,
  126755. 0,
  126756. 2,
  126757. };
  126758. static long _vq_lengthlist__44c7_s_p5_0[] = {
  126759. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  126760. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  126761. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  126762. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  126763. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  126764. 12,
  126765. };
  126766. static float _vq_quantthresh__44c7_s_p5_0[] = {
  126767. -5.5, 5.5,
  126768. };
  126769. static long _vq_quantmap__44c7_s_p5_0[] = {
  126770. 1, 0, 2,
  126771. };
  126772. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  126773. _vq_quantthresh__44c7_s_p5_0,
  126774. _vq_quantmap__44c7_s_p5_0,
  126775. 3,
  126776. 3
  126777. };
  126778. static static_codebook _44c7_s_p5_0 = {
  126779. 4, 81,
  126780. _vq_lengthlist__44c7_s_p5_0,
  126781. 1, -529137664, 1618345984, 2, 0,
  126782. _vq_quantlist__44c7_s_p5_0,
  126783. NULL,
  126784. &_vq_auxt__44c7_s_p5_0,
  126785. NULL,
  126786. 0
  126787. };
  126788. static long _vq_quantlist__44c7_s_p5_1[] = {
  126789. 5,
  126790. 4,
  126791. 6,
  126792. 3,
  126793. 7,
  126794. 2,
  126795. 8,
  126796. 1,
  126797. 9,
  126798. 0,
  126799. 10,
  126800. };
  126801. static long _vq_lengthlist__44c7_s_p5_1[] = {
  126802. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  126803. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  126804. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  126805. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  126806. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  126807. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  126808. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  126809. 11,11,11, 7, 7, 8, 8, 8, 8,
  126810. };
  126811. static float _vq_quantthresh__44c7_s_p5_1[] = {
  126812. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126813. 3.5, 4.5,
  126814. };
  126815. static long _vq_quantmap__44c7_s_p5_1[] = {
  126816. 9, 7, 5, 3, 1, 0, 2, 4,
  126817. 6, 8, 10,
  126818. };
  126819. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  126820. _vq_quantthresh__44c7_s_p5_1,
  126821. _vq_quantmap__44c7_s_p5_1,
  126822. 11,
  126823. 11
  126824. };
  126825. static static_codebook _44c7_s_p5_1 = {
  126826. 2, 121,
  126827. _vq_lengthlist__44c7_s_p5_1,
  126828. 1, -531365888, 1611661312, 4, 0,
  126829. _vq_quantlist__44c7_s_p5_1,
  126830. NULL,
  126831. &_vq_auxt__44c7_s_p5_1,
  126832. NULL,
  126833. 0
  126834. };
  126835. static long _vq_quantlist__44c7_s_p6_0[] = {
  126836. 6,
  126837. 5,
  126838. 7,
  126839. 4,
  126840. 8,
  126841. 3,
  126842. 9,
  126843. 2,
  126844. 10,
  126845. 1,
  126846. 11,
  126847. 0,
  126848. 12,
  126849. };
  126850. static long _vq_lengthlist__44c7_s_p6_0[] = {
  126851. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  126852. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126853. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  126854. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  126855. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  126856. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. };
  126863. static float _vq_quantthresh__44c7_s_p6_0[] = {
  126864. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126865. 12.5, 17.5, 22.5, 27.5,
  126866. };
  126867. static long _vq_quantmap__44c7_s_p6_0[] = {
  126868. 11, 9, 7, 5, 3, 1, 0, 2,
  126869. 4, 6, 8, 10, 12,
  126870. };
  126871. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  126872. _vq_quantthresh__44c7_s_p6_0,
  126873. _vq_quantmap__44c7_s_p6_0,
  126874. 13,
  126875. 13
  126876. };
  126877. static static_codebook _44c7_s_p6_0 = {
  126878. 2, 169,
  126879. _vq_lengthlist__44c7_s_p6_0,
  126880. 1, -526516224, 1616117760, 4, 0,
  126881. _vq_quantlist__44c7_s_p6_0,
  126882. NULL,
  126883. &_vq_auxt__44c7_s_p6_0,
  126884. NULL,
  126885. 0
  126886. };
  126887. static long _vq_quantlist__44c7_s_p6_1[] = {
  126888. 2,
  126889. 1,
  126890. 3,
  126891. 0,
  126892. 4,
  126893. };
  126894. static long _vq_lengthlist__44c7_s_p6_1[] = {
  126895. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126896. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126897. };
  126898. static float _vq_quantthresh__44c7_s_p6_1[] = {
  126899. -1.5, -0.5, 0.5, 1.5,
  126900. };
  126901. static long _vq_quantmap__44c7_s_p6_1[] = {
  126902. 3, 1, 0, 2, 4,
  126903. };
  126904. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  126905. _vq_quantthresh__44c7_s_p6_1,
  126906. _vq_quantmap__44c7_s_p6_1,
  126907. 5,
  126908. 5
  126909. };
  126910. static static_codebook _44c7_s_p6_1 = {
  126911. 2, 25,
  126912. _vq_lengthlist__44c7_s_p6_1,
  126913. 1, -533725184, 1611661312, 3, 0,
  126914. _vq_quantlist__44c7_s_p6_1,
  126915. NULL,
  126916. &_vq_auxt__44c7_s_p6_1,
  126917. NULL,
  126918. 0
  126919. };
  126920. static long _vq_quantlist__44c7_s_p7_0[] = {
  126921. 6,
  126922. 5,
  126923. 7,
  126924. 4,
  126925. 8,
  126926. 3,
  126927. 9,
  126928. 2,
  126929. 10,
  126930. 1,
  126931. 11,
  126932. 0,
  126933. 12,
  126934. };
  126935. static long _vq_lengthlist__44c7_s_p7_0[] = {
  126936. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  126937. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  126938. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  126939. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  126940. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  126941. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  126942. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  126943. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  126944. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  126945. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  126946. 19,13,13,13,13,14,14,15,15,
  126947. };
  126948. static float _vq_quantthresh__44c7_s_p7_0[] = {
  126949. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126950. 27.5, 38.5, 49.5, 60.5,
  126951. };
  126952. static long _vq_quantmap__44c7_s_p7_0[] = {
  126953. 11, 9, 7, 5, 3, 1, 0, 2,
  126954. 4, 6, 8, 10, 12,
  126955. };
  126956. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  126957. _vq_quantthresh__44c7_s_p7_0,
  126958. _vq_quantmap__44c7_s_p7_0,
  126959. 13,
  126960. 13
  126961. };
  126962. static static_codebook _44c7_s_p7_0 = {
  126963. 2, 169,
  126964. _vq_lengthlist__44c7_s_p7_0,
  126965. 1, -523206656, 1618345984, 4, 0,
  126966. _vq_quantlist__44c7_s_p7_0,
  126967. NULL,
  126968. &_vq_auxt__44c7_s_p7_0,
  126969. NULL,
  126970. 0
  126971. };
  126972. static long _vq_quantlist__44c7_s_p7_1[] = {
  126973. 5,
  126974. 4,
  126975. 6,
  126976. 3,
  126977. 7,
  126978. 2,
  126979. 8,
  126980. 1,
  126981. 9,
  126982. 0,
  126983. 10,
  126984. };
  126985. static long _vq_lengthlist__44c7_s_p7_1[] = {
  126986. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  126987. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  126988. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  126989. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  126990. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  126991. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  126992. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  126993. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  126994. };
  126995. static float _vq_quantthresh__44c7_s_p7_1[] = {
  126996. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126997. 3.5, 4.5,
  126998. };
  126999. static long _vq_quantmap__44c7_s_p7_1[] = {
  127000. 9, 7, 5, 3, 1, 0, 2, 4,
  127001. 6, 8, 10,
  127002. };
  127003. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  127004. _vq_quantthresh__44c7_s_p7_1,
  127005. _vq_quantmap__44c7_s_p7_1,
  127006. 11,
  127007. 11
  127008. };
  127009. static static_codebook _44c7_s_p7_1 = {
  127010. 2, 121,
  127011. _vq_lengthlist__44c7_s_p7_1,
  127012. 1, -531365888, 1611661312, 4, 0,
  127013. _vq_quantlist__44c7_s_p7_1,
  127014. NULL,
  127015. &_vq_auxt__44c7_s_p7_1,
  127016. NULL,
  127017. 0
  127018. };
  127019. static long _vq_quantlist__44c7_s_p8_0[] = {
  127020. 7,
  127021. 6,
  127022. 8,
  127023. 5,
  127024. 9,
  127025. 4,
  127026. 10,
  127027. 3,
  127028. 11,
  127029. 2,
  127030. 12,
  127031. 1,
  127032. 13,
  127033. 0,
  127034. 14,
  127035. };
  127036. static long _vq_lengthlist__44c7_s_p8_0[] = {
  127037. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  127038. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  127039. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  127040. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  127041. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  127042. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  127043. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  127044. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  127045. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  127046. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  127047. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  127048. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127049. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  127050. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  127051. 14,
  127052. };
  127053. static float _vq_quantthresh__44c7_s_p8_0[] = {
  127054. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127055. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127056. };
  127057. static long _vq_quantmap__44c7_s_p8_0[] = {
  127058. 13, 11, 9, 7, 5, 3, 1, 0,
  127059. 2, 4, 6, 8, 10, 12, 14,
  127060. };
  127061. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  127062. _vq_quantthresh__44c7_s_p8_0,
  127063. _vq_quantmap__44c7_s_p8_0,
  127064. 15,
  127065. 15
  127066. };
  127067. static static_codebook _44c7_s_p8_0 = {
  127068. 2, 225,
  127069. _vq_lengthlist__44c7_s_p8_0,
  127070. 1, -520986624, 1620377600, 4, 0,
  127071. _vq_quantlist__44c7_s_p8_0,
  127072. NULL,
  127073. &_vq_auxt__44c7_s_p8_0,
  127074. NULL,
  127075. 0
  127076. };
  127077. static long _vq_quantlist__44c7_s_p8_1[] = {
  127078. 10,
  127079. 9,
  127080. 11,
  127081. 8,
  127082. 12,
  127083. 7,
  127084. 13,
  127085. 6,
  127086. 14,
  127087. 5,
  127088. 15,
  127089. 4,
  127090. 16,
  127091. 3,
  127092. 17,
  127093. 2,
  127094. 18,
  127095. 1,
  127096. 19,
  127097. 0,
  127098. 20,
  127099. };
  127100. static long _vq_lengthlist__44c7_s_p8_1[] = {
  127101. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127102. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127103. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127104. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127105. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127106. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127107. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127108. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127109. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127110. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127111. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  127112. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  127113. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  127114. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  127115. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  127116. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  127117. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  127118. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127119. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  127120. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  127121. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  127122. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  127123. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  127124. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  127125. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  127126. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  127127. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  127128. 10,10,10,10,10,10,10,10,10,
  127129. };
  127130. static float _vq_quantthresh__44c7_s_p8_1[] = {
  127131. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127132. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127133. 6.5, 7.5, 8.5, 9.5,
  127134. };
  127135. static long _vq_quantmap__44c7_s_p8_1[] = {
  127136. 19, 17, 15, 13, 11, 9, 7, 5,
  127137. 3, 1, 0, 2, 4, 6, 8, 10,
  127138. 12, 14, 16, 18, 20,
  127139. };
  127140. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  127141. _vq_quantthresh__44c7_s_p8_1,
  127142. _vq_quantmap__44c7_s_p8_1,
  127143. 21,
  127144. 21
  127145. };
  127146. static static_codebook _44c7_s_p8_1 = {
  127147. 2, 441,
  127148. _vq_lengthlist__44c7_s_p8_1,
  127149. 1, -529268736, 1611661312, 5, 0,
  127150. _vq_quantlist__44c7_s_p8_1,
  127151. NULL,
  127152. &_vq_auxt__44c7_s_p8_1,
  127153. NULL,
  127154. 0
  127155. };
  127156. static long _vq_quantlist__44c7_s_p9_0[] = {
  127157. 6,
  127158. 5,
  127159. 7,
  127160. 4,
  127161. 8,
  127162. 3,
  127163. 9,
  127164. 2,
  127165. 10,
  127166. 1,
  127167. 11,
  127168. 0,
  127169. 12,
  127170. };
  127171. static long _vq_lengthlist__44c7_s_p9_0[] = {
  127172. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  127173. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  127174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127177. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127178. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127179. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127180. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127182. 11,11,11,11,11,11,11,11,11,
  127183. };
  127184. static float _vq_quantthresh__44c7_s_p9_0[] = {
  127185. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127186. 1592.5, 2229.5, 2866.5, 3503.5,
  127187. };
  127188. static long _vq_quantmap__44c7_s_p9_0[] = {
  127189. 11, 9, 7, 5, 3, 1, 0, 2,
  127190. 4, 6, 8, 10, 12,
  127191. };
  127192. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  127193. _vq_quantthresh__44c7_s_p9_0,
  127194. _vq_quantmap__44c7_s_p9_0,
  127195. 13,
  127196. 13
  127197. };
  127198. static static_codebook _44c7_s_p9_0 = {
  127199. 2, 169,
  127200. _vq_lengthlist__44c7_s_p9_0,
  127201. 1, -511845376, 1630791680, 4, 0,
  127202. _vq_quantlist__44c7_s_p9_0,
  127203. NULL,
  127204. &_vq_auxt__44c7_s_p9_0,
  127205. NULL,
  127206. 0
  127207. };
  127208. static long _vq_quantlist__44c7_s_p9_1[] = {
  127209. 6,
  127210. 5,
  127211. 7,
  127212. 4,
  127213. 8,
  127214. 3,
  127215. 9,
  127216. 2,
  127217. 10,
  127218. 1,
  127219. 11,
  127220. 0,
  127221. 12,
  127222. };
  127223. static long _vq_lengthlist__44c7_s_p9_1[] = {
  127224. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127225. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  127226. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  127227. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  127228. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  127229. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  127230. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  127231. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  127232. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  127233. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  127234. 15,11,11,10,10,12,12,12,12,
  127235. };
  127236. static float _vq_quantthresh__44c7_s_p9_1[] = {
  127237. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127238. 122.5, 171.5, 220.5, 269.5,
  127239. };
  127240. static long _vq_quantmap__44c7_s_p9_1[] = {
  127241. 11, 9, 7, 5, 3, 1, 0, 2,
  127242. 4, 6, 8, 10, 12,
  127243. };
  127244. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  127245. _vq_quantthresh__44c7_s_p9_1,
  127246. _vq_quantmap__44c7_s_p9_1,
  127247. 13,
  127248. 13
  127249. };
  127250. static static_codebook _44c7_s_p9_1 = {
  127251. 2, 169,
  127252. _vq_lengthlist__44c7_s_p9_1,
  127253. 1, -518889472, 1622704128, 4, 0,
  127254. _vq_quantlist__44c7_s_p9_1,
  127255. NULL,
  127256. &_vq_auxt__44c7_s_p9_1,
  127257. NULL,
  127258. 0
  127259. };
  127260. static long _vq_quantlist__44c7_s_p9_2[] = {
  127261. 24,
  127262. 23,
  127263. 25,
  127264. 22,
  127265. 26,
  127266. 21,
  127267. 27,
  127268. 20,
  127269. 28,
  127270. 19,
  127271. 29,
  127272. 18,
  127273. 30,
  127274. 17,
  127275. 31,
  127276. 16,
  127277. 32,
  127278. 15,
  127279. 33,
  127280. 14,
  127281. 34,
  127282. 13,
  127283. 35,
  127284. 12,
  127285. 36,
  127286. 11,
  127287. 37,
  127288. 10,
  127289. 38,
  127290. 9,
  127291. 39,
  127292. 8,
  127293. 40,
  127294. 7,
  127295. 41,
  127296. 6,
  127297. 42,
  127298. 5,
  127299. 43,
  127300. 4,
  127301. 44,
  127302. 3,
  127303. 45,
  127304. 2,
  127305. 46,
  127306. 1,
  127307. 47,
  127308. 0,
  127309. 48,
  127310. };
  127311. static long _vq_lengthlist__44c7_s_p9_2[] = {
  127312. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127313. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127314. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127315. 7,
  127316. };
  127317. static float _vq_quantthresh__44c7_s_p9_2[] = {
  127318. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  127319. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  127320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127322. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  127323. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  127324. };
  127325. static long _vq_quantmap__44c7_s_p9_2[] = {
  127326. 47, 45, 43, 41, 39, 37, 35, 33,
  127327. 31, 29, 27, 25, 23, 21, 19, 17,
  127328. 15, 13, 11, 9, 7, 5, 3, 1,
  127329. 0, 2, 4, 6, 8, 10, 12, 14,
  127330. 16, 18, 20, 22, 24, 26, 28, 30,
  127331. 32, 34, 36, 38, 40, 42, 44, 46,
  127332. 48,
  127333. };
  127334. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  127335. _vq_quantthresh__44c7_s_p9_2,
  127336. _vq_quantmap__44c7_s_p9_2,
  127337. 49,
  127338. 49
  127339. };
  127340. static static_codebook _44c7_s_p9_2 = {
  127341. 1, 49,
  127342. _vq_lengthlist__44c7_s_p9_2,
  127343. 1, -526909440, 1611661312, 6, 0,
  127344. _vq_quantlist__44c7_s_p9_2,
  127345. NULL,
  127346. &_vq_auxt__44c7_s_p9_2,
  127347. NULL,
  127348. 0
  127349. };
  127350. static long _huff_lengthlist__44c7_s_short[] = {
  127351. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  127352. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  127353. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  127354. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  127355. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  127356. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  127357. 10, 9,11,14,
  127358. };
  127359. static static_codebook _huff_book__44c7_s_short = {
  127360. 2, 100,
  127361. _huff_lengthlist__44c7_s_short,
  127362. 0, 0, 0, 0, 0,
  127363. NULL,
  127364. NULL,
  127365. NULL,
  127366. NULL,
  127367. 0
  127368. };
  127369. static long _huff_lengthlist__44c8_s_long[] = {
  127370. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  127371. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  127372. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  127373. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  127374. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  127375. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  127376. 11, 9, 9,10,
  127377. };
  127378. static static_codebook _huff_book__44c8_s_long = {
  127379. 2, 100,
  127380. _huff_lengthlist__44c8_s_long,
  127381. 0, 0, 0, 0, 0,
  127382. NULL,
  127383. NULL,
  127384. NULL,
  127385. NULL,
  127386. 0
  127387. };
  127388. static long _vq_quantlist__44c8_s_p1_0[] = {
  127389. 1,
  127390. 0,
  127391. 2,
  127392. };
  127393. static long _vq_lengthlist__44c8_s_p1_0[] = {
  127394. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  127395. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127397. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127398. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  127399. 8,
  127400. };
  127401. static float _vq_quantthresh__44c8_s_p1_0[] = {
  127402. -0.5, 0.5,
  127403. };
  127404. static long _vq_quantmap__44c8_s_p1_0[] = {
  127405. 1, 0, 2,
  127406. };
  127407. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  127408. _vq_quantthresh__44c8_s_p1_0,
  127409. _vq_quantmap__44c8_s_p1_0,
  127410. 3,
  127411. 3
  127412. };
  127413. static static_codebook _44c8_s_p1_0 = {
  127414. 4, 81,
  127415. _vq_lengthlist__44c8_s_p1_0,
  127416. 1, -535822336, 1611661312, 2, 0,
  127417. _vq_quantlist__44c8_s_p1_0,
  127418. NULL,
  127419. &_vq_auxt__44c8_s_p1_0,
  127420. NULL,
  127421. 0
  127422. };
  127423. static long _vq_quantlist__44c8_s_p2_0[] = {
  127424. 2,
  127425. 1,
  127426. 3,
  127427. 0,
  127428. 4,
  127429. };
  127430. static long _vq_lengthlist__44c8_s_p2_0[] = {
  127431. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127432. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127433. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127434. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  127435. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  127436. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  127437. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  127438. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127441. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  127442. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127443. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  127444. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  127445. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  127446. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  127449. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  127450. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  127451. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  127452. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  127453. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  127454. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  127457. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  127458. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127459. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  127460. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  127461. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  127462. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127467. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  127468. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  127469. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  127470. 13,
  127471. };
  127472. static float _vq_quantthresh__44c8_s_p2_0[] = {
  127473. -1.5, -0.5, 0.5, 1.5,
  127474. };
  127475. static long _vq_quantmap__44c8_s_p2_0[] = {
  127476. 3, 1, 0, 2, 4,
  127477. };
  127478. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  127479. _vq_quantthresh__44c8_s_p2_0,
  127480. _vq_quantmap__44c8_s_p2_0,
  127481. 5,
  127482. 5
  127483. };
  127484. static static_codebook _44c8_s_p2_0 = {
  127485. 4, 625,
  127486. _vq_lengthlist__44c8_s_p2_0,
  127487. 1, -533725184, 1611661312, 3, 0,
  127488. _vq_quantlist__44c8_s_p2_0,
  127489. NULL,
  127490. &_vq_auxt__44c8_s_p2_0,
  127491. NULL,
  127492. 0
  127493. };
  127494. static long _vq_quantlist__44c8_s_p3_0[] = {
  127495. 4,
  127496. 3,
  127497. 5,
  127498. 2,
  127499. 6,
  127500. 1,
  127501. 7,
  127502. 0,
  127503. 8,
  127504. };
  127505. static long _vq_lengthlist__44c8_s_p3_0[] = {
  127506. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127507. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  127508. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  127509. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0,
  127512. };
  127513. static float _vq_quantthresh__44c8_s_p3_0[] = {
  127514. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127515. };
  127516. static long _vq_quantmap__44c8_s_p3_0[] = {
  127517. 7, 5, 3, 1, 0, 2, 4, 6,
  127518. 8,
  127519. };
  127520. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  127521. _vq_quantthresh__44c8_s_p3_0,
  127522. _vq_quantmap__44c8_s_p3_0,
  127523. 9,
  127524. 9
  127525. };
  127526. static static_codebook _44c8_s_p3_0 = {
  127527. 2, 81,
  127528. _vq_lengthlist__44c8_s_p3_0,
  127529. 1, -531628032, 1611661312, 4, 0,
  127530. _vq_quantlist__44c8_s_p3_0,
  127531. NULL,
  127532. &_vq_auxt__44c8_s_p3_0,
  127533. NULL,
  127534. 0
  127535. };
  127536. static long _vq_quantlist__44c8_s_p4_0[] = {
  127537. 8,
  127538. 7,
  127539. 9,
  127540. 6,
  127541. 10,
  127542. 5,
  127543. 11,
  127544. 4,
  127545. 12,
  127546. 3,
  127547. 13,
  127548. 2,
  127549. 14,
  127550. 1,
  127551. 15,
  127552. 0,
  127553. 16,
  127554. };
  127555. static long _vq_lengthlist__44c8_s_p4_0[] = {
  127556. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  127557. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  127558. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  127559. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  127560. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  127561. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  127562. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  127563. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127564. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  127565. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0,
  127575. };
  127576. static float _vq_quantthresh__44c8_s_p4_0[] = {
  127577. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127578. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127579. };
  127580. static long _vq_quantmap__44c8_s_p4_0[] = {
  127581. 15, 13, 11, 9, 7, 5, 3, 1,
  127582. 0, 2, 4, 6, 8, 10, 12, 14,
  127583. 16,
  127584. };
  127585. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  127586. _vq_quantthresh__44c8_s_p4_0,
  127587. _vq_quantmap__44c8_s_p4_0,
  127588. 17,
  127589. 17
  127590. };
  127591. static static_codebook _44c8_s_p4_0 = {
  127592. 2, 289,
  127593. _vq_lengthlist__44c8_s_p4_0,
  127594. 1, -529530880, 1611661312, 5, 0,
  127595. _vq_quantlist__44c8_s_p4_0,
  127596. NULL,
  127597. &_vq_auxt__44c8_s_p4_0,
  127598. NULL,
  127599. 0
  127600. };
  127601. static long _vq_quantlist__44c8_s_p5_0[] = {
  127602. 1,
  127603. 0,
  127604. 2,
  127605. };
  127606. static long _vq_lengthlist__44c8_s_p5_0[] = {
  127607. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  127608. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  127609. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  127610. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  127611. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  127612. 12,
  127613. };
  127614. static float _vq_quantthresh__44c8_s_p5_0[] = {
  127615. -5.5, 5.5,
  127616. };
  127617. static long _vq_quantmap__44c8_s_p5_0[] = {
  127618. 1, 0, 2,
  127619. };
  127620. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  127621. _vq_quantthresh__44c8_s_p5_0,
  127622. _vq_quantmap__44c8_s_p5_0,
  127623. 3,
  127624. 3
  127625. };
  127626. static static_codebook _44c8_s_p5_0 = {
  127627. 4, 81,
  127628. _vq_lengthlist__44c8_s_p5_0,
  127629. 1, -529137664, 1618345984, 2, 0,
  127630. _vq_quantlist__44c8_s_p5_0,
  127631. NULL,
  127632. &_vq_auxt__44c8_s_p5_0,
  127633. NULL,
  127634. 0
  127635. };
  127636. static long _vq_quantlist__44c8_s_p5_1[] = {
  127637. 5,
  127638. 4,
  127639. 6,
  127640. 3,
  127641. 7,
  127642. 2,
  127643. 8,
  127644. 1,
  127645. 9,
  127646. 0,
  127647. 10,
  127648. };
  127649. static long _vq_lengthlist__44c8_s_p5_1[] = {
  127650. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  127651. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127652. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  127653. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  127654. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  127655. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  127656. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  127657. 11,11,11, 7, 7, 7, 7, 8, 8,
  127658. };
  127659. static float _vq_quantthresh__44c8_s_p5_1[] = {
  127660. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127661. 3.5, 4.5,
  127662. };
  127663. static long _vq_quantmap__44c8_s_p5_1[] = {
  127664. 9, 7, 5, 3, 1, 0, 2, 4,
  127665. 6, 8, 10,
  127666. };
  127667. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  127668. _vq_quantthresh__44c8_s_p5_1,
  127669. _vq_quantmap__44c8_s_p5_1,
  127670. 11,
  127671. 11
  127672. };
  127673. static static_codebook _44c8_s_p5_1 = {
  127674. 2, 121,
  127675. _vq_lengthlist__44c8_s_p5_1,
  127676. 1, -531365888, 1611661312, 4, 0,
  127677. _vq_quantlist__44c8_s_p5_1,
  127678. NULL,
  127679. &_vq_auxt__44c8_s_p5_1,
  127680. NULL,
  127681. 0
  127682. };
  127683. static long _vq_quantlist__44c8_s_p6_0[] = {
  127684. 6,
  127685. 5,
  127686. 7,
  127687. 4,
  127688. 8,
  127689. 3,
  127690. 9,
  127691. 2,
  127692. 10,
  127693. 1,
  127694. 11,
  127695. 0,
  127696. 12,
  127697. };
  127698. static long _vq_lengthlist__44c8_s_p6_0[] = {
  127699. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127700. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  127701. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  127702. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  127703. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  127704. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. };
  127711. static float _vq_quantthresh__44c8_s_p6_0[] = {
  127712. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127713. 12.5, 17.5, 22.5, 27.5,
  127714. };
  127715. static long _vq_quantmap__44c8_s_p6_0[] = {
  127716. 11, 9, 7, 5, 3, 1, 0, 2,
  127717. 4, 6, 8, 10, 12,
  127718. };
  127719. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  127720. _vq_quantthresh__44c8_s_p6_0,
  127721. _vq_quantmap__44c8_s_p6_0,
  127722. 13,
  127723. 13
  127724. };
  127725. static static_codebook _44c8_s_p6_0 = {
  127726. 2, 169,
  127727. _vq_lengthlist__44c8_s_p6_0,
  127728. 1, -526516224, 1616117760, 4, 0,
  127729. _vq_quantlist__44c8_s_p6_0,
  127730. NULL,
  127731. &_vq_auxt__44c8_s_p6_0,
  127732. NULL,
  127733. 0
  127734. };
  127735. static long _vq_quantlist__44c8_s_p6_1[] = {
  127736. 2,
  127737. 1,
  127738. 3,
  127739. 0,
  127740. 4,
  127741. };
  127742. static long _vq_lengthlist__44c8_s_p6_1[] = {
  127743. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127744. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127745. };
  127746. static float _vq_quantthresh__44c8_s_p6_1[] = {
  127747. -1.5, -0.5, 0.5, 1.5,
  127748. };
  127749. static long _vq_quantmap__44c8_s_p6_1[] = {
  127750. 3, 1, 0, 2, 4,
  127751. };
  127752. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  127753. _vq_quantthresh__44c8_s_p6_1,
  127754. _vq_quantmap__44c8_s_p6_1,
  127755. 5,
  127756. 5
  127757. };
  127758. static static_codebook _44c8_s_p6_1 = {
  127759. 2, 25,
  127760. _vq_lengthlist__44c8_s_p6_1,
  127761. 1, -533725184, 1611661312, 3, 0,
  127762. _vq_quantlist__44c8_s_p6_1,
  127763. NULL,
  127764. &_vq_auxt__44c8_s_p6_1,
  127765. NULL,
  127766. 0
  127767. };
  127768. static long _vq_quantlist__44c8_s_p7_0[] = {
  127769. 6,
  127770. 5,
  127771. 7,
  127772. 4,
  127773. 8,
  127774. 3,
  127775. 9,
  127776. 2,
  127777. 10,
  127778. 1,
  127779. 11,
  127780. 0,
  127781. 12,
  127782. };
  127783. static long _vq_lengthlist__44c8_s_p7_0[] = {
  127784. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  127785. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  127786. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  127787. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  127788. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  127789. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  127790. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  127791. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  127792. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  127793. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  127794. 20,13,13,13,13,14,13,15,15,
  127795. };
  127796. static float _vq_quantthresh__44c8_s_p7_0[] = {
  127797. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127798. 27.5, 38.5, 49.5, 60.5,
  127799. };
  127800. static long _vq_quantmap__44c8_s_p7_0[] = {
  127801. 11, 9, 7, 5, 3, 1, 0, 2,
  127802. 4, 6, 8, 10, 12,
  127803. };
  127804. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  127805. _vq_quantthresh__44c8_s_p7_0,
  127806. _vq_quantmap__44c8_s_p7_0,
  127807. 13,
  127808. 13
  127809. };
  127810. static static_codebook _44c8_s_p7_0 = {
  127811. 2, 169,
  127812. _vq_lengthlist__44c8_s_p7_0,
  127813. 1, -523206656, 1618345984, 4, 0,
  127814. _vq_quantlist__44c8_s_p7_0,
  127815. NULL,
  127816. &_vq_auxt__44c8_s_p7_0,
  127817. NULL,
  127818. 0
  127819. };
  127820. static long _vq_quantlist__44c8_s_p7_1[] = {
  127821. 5,
  127822. 4,
  127823. 6,
  127824. 3,
  127825. 7,
  127826. 2,
  127827. 8,
  127828. 1,
  127829. 9,
  127830. 0,
  127831. 10,
  127832. };
  127833. static long _vq_lengthlist__44c8_s_p7_1[] = {
  127834. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  127835. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  127836. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127837. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127838. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127839. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127840. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127841. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127842. };
  127843. static float _vq_quantthresh__44c8_s_p7_1[] = {
  127844. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127845. 3.5, 4.5,
  127846. };
  127847. static long _vq_quantmap__44c8_s_p7_1[] = {
  127848. 9, 7, 5, 3, 1, 0, 2, 4,
  127849. 6, 8, 10,
  127850. };
  127851. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  127852. _vq_quantthresh__44c8_s_p7_1,
  127853. _vq_quantmap__44c8_s_p7_1,
  127854. 11,
  127855. 11
  127856. };
  127857. static static_codebook _44c8_s_p7_1 = {
  127858. 2, 121,
  127859. _vq_lengthlist__44c8_s_p7_1,
  127860. 1, -531365888, 1611661312, 4, 0,
  127861. _vq_quantlist__44c8_s_p7_1,
  127862. NULL,
  127863. &_vq_auxt__44c8_s_p7_1,
  127864. NULL,
  127865. 0
  127866. };
  127867. static long _vq_quantlist__44c8_s_p8_0[] = {
  127868. 7,
  127869. 6,
  127870. 8,
  127871. 5,
  127872. 9,
  127873. 4,
  127874. 10,
  127875. 3,
  127876. 11,
  127877. 2,
  127878. 12,
  127879. 1,
  127880. 13,
  127881. 0,
  127882. 14,
  127883. };
  127884. static long _vq_lengthlist__44c8_s_p8_0[] = {
  127885. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  127886. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  127887. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  127888. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  127889. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  127890. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  127891. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  127892. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  127893. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  127894. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  127895. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  127896. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127897. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  127898. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  127899. 15,
  127900. };
  127901. static float _vq_quantthresh__44c8_s_p8_0[] = {
  127902. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127903. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127904. };
  127905. static long _vq_quantmap__44c8_s_p8_0[] = {
  127906. 13, 11, 9, 7, 5, 3, 1, 0,
  127907. 2, 4, 6, 8, 10, 12, 14,
  127908. };
  127909. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  127910. _vq_quantthresh__44c8_s_p8_0,
  127911. _vq_quantmap__44c8_s_p8_0,
  127912. 15,
  127913. 15
  127914. };
  127915. static static_codebook _44c8_s_p8_0 = {
  127916. 2, 225,
  127917. _vq_lengthlist__44c8_s_p8_0,
  127918. 1, -520986624, 1620377600, 4, 0,
  127919. _vq_quantlist__44c8_s_p8_0,
  127920. NULL,
  127921. &_vq_auxt__44c8_s_p8_0,
  127922. NULL,
  127923. 0
  127924. };
  127925. static long _vq_quantlist__44c8_s_p8_1[] = {
  127926. 10,
  127927. 9,
  127928. 11,
  127929. 8,
  127930. 12,
  127931. 7,
  127932. 13,
  127933. 6,
  127934. 14,
  127935. 5,
  127936. 15,
  127937. 4,
  127938. 16,
  127939. 3,
  127940. 17,
  127941. 2,
  127942. 18,
  127943. 1,
  127944. 19,
  127945. 0,
  127946. 20,
  127947. };
  127948. static long _vq_lengthlist__44c8_s_p8_1[] = {
  127949. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127950. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127951. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127952. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127953. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127954. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127955. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127956. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127957. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127958. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127959. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  127960. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  127961. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  127962. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127963. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  127964. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  127965. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  127966. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  127967. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  127968. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  127969. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  127970. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  127971. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127972. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  127973. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  127974. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  127975. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127976. 10, 9, 9,10,10, 9,10, 9, 9,
  127977. };
  127978. static float _vq_quantthresh__44c8_s_p8_1[] = {
  127979. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127980. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127981. 6.5, 7.5, 8.5, 9.5,
  127982. };
  127983. static long _vq_quantmap__44c8_s_p8_1[] = {
  127984. 19, 17, 15, 13, 11, 9, 7, 5,
  127985. 3, 1, 0, 2, 4, 6, 8, 10,
  127986. 12, 14, 16, 18, 20,
  127987. };
  127988. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  127989. _vq_quantthresh__44c8_s_p8_1,
  127990. _vq_quantmap__44c8_s_p8_1,
  127991. 21,
  127992. 21
  127993. };
  127994. static static_codebook _44c8_s_p8_1 = {
  127995. 2, 441,
  127996. _vq_lengthlist__44c8_s_p8_1,
  127997. 1, -529268736, 1611661312, 5, 0,
  127998. _vq_quantlist__44c8_s_p8_1,
  127999. NULL,
  128000. &_vq_auxt__44c8_s_p8_1,
  128001. NULL,
  128002. 0
  128003. };
  128004. static long _vq_quantlist__44c8_s_p9_0[] = {
  128005. 8,
  128006. 7,
  128007. 9,
  128008. 6,
  128009. 10,
  128010. 5,
  128011. 11,
  128012. 4,
  128013. 12,
  128014. 3,
  128015. 13,
  128016. 2,
  128017. 14,
  128018. 1,
  128019. 15,
  128020. 0,
  128021. 16,
  128022. };
  128023. static long _vq_lengthlist__44c8_s_p9_0[] = {
  128024. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128025. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  128026. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  128027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128038. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128039. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128040. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128041. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128042. 10,
  128043. };
  128044. static float _vq_quantthresh__44c8_s_p9_0[] = {
  128045. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  128046. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  128047. };
  128048. static long _vq_quantmap__44c8_s_p9_0[] = {
  128049. 15, 13, 11, 9, 7, 5, 3, 1,
  128050. 0, 2, 4, 6, 8, 10, 12, 14,
  128051. 16,
  128052. };
  128053. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  128054. _vq_quantthresh__44c8_s_p9_0,
  128055. _vq_quantmap__44c8_s_p9_0,
  128056. 17,
  128057. 17
  128058. };
  128059. static static_codebook _44c8_s_p9_0 = {
  128060. 2, 289,
  128061. _vq_lengthlist__44c8_s_p9_0,
  128062. 1, -509798400, 1631393792, 5, 0,
  128063. _vq_quantlist__44c8_s_p9_0,
  128064. NULL,
  128065. &_vq_auxt__44c8_s_p9_0,
  128066. NULL,
  128067. 0
  128068. };
  128069. static long _vq_quantlist__44c8_s_p9_1[] = {
  128070. 9,
  128071. 8,
  128072. 10,
  128073. 7,
  128074. 11,
  128075. 6,
  128076. 12,
  128077. 5,
  128078. 13,
  128079. 4,
  128080. 14,
  128081. 3,
  128082. 15,
  128083. 2,
  128084. 16,
  128085. 1,
  128086. 17,
  128087. 0,
  128088. 18,
  128089. };
  128090. static long _vq_lengthlist__44c8_s_p9_1[] = {
  128091. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  128092. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  128093. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  128094. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  128095. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  128096. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  128097. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  128098. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  128099. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  128100. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  128101. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  128102. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  128103. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  128104. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  128105. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  128106. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  128107. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  128108. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  128109. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  128110. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  128111. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  128112. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  128113. 14,13,13,14,14,15,14,15,14,
  128114. };
  128115. static float _vq_quantthresh__44c8_s_p9_1[] = {
  128116. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  128117. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  128118. 367.5, 416.5,
  128119. };
  128120. static long _vq_quantmap__44c8_s_p9_1[] = {
  128121. 17, 15, 13, 11, 9, 7, 5, 3,
  128122. 1, 0, 2, 4, 6, 8, 10, 12,
  128123. 14, 16, 18,
  128124. };
  128125. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  128126. _vq_quantthresh__44c8_s_p9_1,
  128127. _vq_quantmap__44c8_s_p9_1,
  128128. 19,
  128129. 19
  128130. };
  128131. static static_codebook _44c8_s_p9_1 = {
  128132. 2, 361,
  128133. _vq_lengthlist__44c8_s_p9_1,
  128134. 1, -518287360, 1622704128, 5, 0,
  128135. _vq_quantlist__44c8_s_p9_1,
  128136. NULL,
  128137. &_vq_auxt__44c8_s_p9_1,
  128138. NULL,
  128139. 0
  128140. };
  128141. static long _vq_quantlist__44c8_s_p9_2[] = {
  128142. 24,
  128143. 23,
  128144. 25,
  128145. 22,
  128146. 26,
  128147. 21,
  128148. 27,
  128149. 20,
  128150. 28,
  128151. 19,
  128152. 29,
  128153. 18,
  128154. 30,
  128155. 17,
  128156. 31,
  128157. 16,
  128158. 32,
  128159. 15,
  128160. 33,
  128161. 14,
  128162. 34,
  128163. 13,
  128164. 35,
  128165. 12,
  128166. 36,
  128167. 11,
  128168. 37,
  128169. 10,
  128170. 38,
  128171. 9,
  128172. 39,
  128173. 8,
  128174. 40,
  128175. 7,
  128176. 41,
  128177. 6,
  128178. 42,
  128179. 5,
  128180. 43,
  128181. 4,
  128182. 44,
  128183. 3,
  128184. 45,
  128185. 2,
  128186. 46,
  128187. 1,
  128188. 47,
  128189. 0,
  128190. 48,
  128191. };
  128192. static long _vq_lengthlist__44c8_s_p9_2[] = {
  128193. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  128194. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128195. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128196. 7,
  128197. };
  128198. static float _vq_quantthresh__44c8_s_p9_2[] = {
  128199. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128200. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128201. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128202. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128203. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128204. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128205. };
  128206. static long _vq_quantmap__44c8_s_p9_2[] = {
  128207. 47, 45, 43, 41, 39, 37, 35, 33,
  128208. 31, 29, 27, 25, 23, 21, 19, 17,
  128209. 15, 13, 11, 9, 7, 5, 3, 1,
  128210. 0, 2, 4, 6, 8, 10, 12, 14,
  128211. 16, 18, 20, 22, 24, 26, 28, 30,
  128212. 32, 34, 36, 38, 40, 42, 44, 46,
  128213. 48,
  128214. };
  128215. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  128216. _vq_quantthresh__44c8_s_p9_2,
  128217. _vq_quantmap__44c8_s_p9_2,
  128218. 49,
  128219. 49
  128220. };
  128221. static static_codebook _44c8_s_p9_2 = {
  128222. 1, 49,
  128223. _vq_lengthlist__44c8_s_p9_2,
  128224. 1, -526909440, 1611661312, 6, 0,
  128225. _vq_quantlist__44c8_s_p9_2,
  128226. NULL,
  128227. &_vq_auxt__44c8_s_p9_2,
  128228. NULL,
  128229. 0
  128230. };
  128231. static long _huff_lengthlist__44c8_s_short[] = {
  128232. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  128233. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  128234. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  128235. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  128236. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  128237. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  128238. 10, 9,11,14,
  128239. };
  128240. static static_codebook _huff_book__44c8_s_short = {
  128241. 2, 100,
  128242. _huff_lengthlist__44c8_s_short,
  128243. 0, 0, 0, 0, 0,
  128244. NULL,
  128245. NULL,
  128246. NULL,
  128247. NULL,
  128248. 0
  128249. };
  128250. static long _huff_lengthlist__44c9_s_long[] = {
  128251. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  128252. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  128253. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  128254. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  128255. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  128256. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  128257. 10, 9, 8, 9,
  128258. };
  128259. static static_codebook _huff_book__44c9_s_long = {
  128260. 2, 100,
  128261. _huff_lengthlist__44c9_s_long,
  128262. 0, 0, 0, 0, 0,
  128263. NULL,
  128264. NULL,
  128265. NULL,
  128266. NULL,
  128267. 0
  128268. };
  128269. static long _vq_quantlist__44c9_s_p1_0[] = {
  128270. 1,
  128271. 0,
  128272. 2,
  128273. };
  128274. static long _vq_lengthlist__44c9_s_p1_0[] = {
  128275. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  128276. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  128278. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128279. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  128280. 7,
  128281. };
  128282. static float _vq_quantthresh__44c9_s_p1_0[] = {
  128283. -0.5, 0.5,
  128284. };
  128285. static long _vq_quantmap__44c9_s_p1_0[] = {
  128286. 1, 0, 2,
  128287. };
  128288. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  128289. _vq_quantthresh__44c9_s_p1_0,
  128290. _vq_quantmap__44c9_s_p1_0,
  128291. 3,
  128292. 3
  128293. };
  128294. static static_codebook _44c9_s_p1_0 = {
  128295. 4, 81,
  128296. _vq_lengthlist__44c9_s_p1_0,
  128297. 1, -535822336, 1611661312, 2, 0,
  128298. _vq_quantlist__44c9_s_p1_0,
  128299. NULL,
  128300. &_vq_auxt__44c9_s_p1_0,
  128301. NULL,
  128302. 0
  128303. };
  128304. static long _vq_quantlist__44c9_s_p2_0[] = {
  128305. 2,
  128306. 1,
  128307. 3,
  128308. 0,
  128309. 4,
  128310. };
  128311. static long _vq_lengthlist__44c9_s_p2_0[] = {
  128312. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128313. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  128314. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  128315. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  128316. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  128317. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  128318. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  128319. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  128322. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  128323. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  128324. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  128325. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  128326. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  128327. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  128330. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  128331. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  128332. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  128333. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  128334. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  128335. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  128338. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  128339. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  128340. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  128341. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  128342. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  128343. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128348. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  128349. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  128350. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  128351. 12,
  128352. };
  128353. static float _vq_quantthresh__44c9_s_p2_0[] = {
  128354. -1.5, -0.5, 0.5, 1.5,
  128355. };
  128356. static long _vq_quantmap__44c9_s_p2_0[] = {
  128357. 3, 1, 0, 2, 4,
  128358. };
  128359. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  128360. _vq_quantthresh__44c9_s_p2_0,
  128361. _vq_quantmap__44c9_s_p2_0,
  128362. 5,
  128363. 5
  128364. };
  128365. static static_codebook _44c9_s_p2_0 = {
  128366. 4, 625,
  128367. _vq_lengthlist__44c9_s_p2_0,
  128368. 1, -533725184, 1611661312, 3, 0,
  128369. _vq_quantlist__44c9_s_p2_0,
  128370. NULL,
  128371. &_vq_auxt__44c9_s_p2_0,
  128372. NULL,
  128373. 0
  128374. };
  128375. static long _vq_quantlist__44c9_s_p3_0[] = {
  128376. 4,
  128377. 3,
  128378. 5,
  128379. 2,
  128380. 6,
  128381. 1,
  128382. 7,
  128383. 0,
  128384. 8,
  128385. };
  128386. static long _vq_lengthlist__44c9_s_p3_0[] = {
  128387. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  128388. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  128389. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  128390. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0,
  128393. };
  128394. static float _vq_quantthresh__44c9_s_p3_0[] = {
  128395. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128396. };
  128397. static long _vq_quantmap__44c9_s_p3_0[] = {
  128398. 7, 5, 3, 1, 0, 2, 4, 6,
  128399. 8,
  128400. };
  128401. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  128402. _vq_quantthresh__44c9_s_p3_0,
  128403. _vq_quantmap__44c9_s_p3_0,
  128404. 9,
  128405. 9
  128406. };
  128407. static static_codebook _44c9_s_p3_0 = {
  128408. 2, 81,
  128409. _vq_lengthlist__44c9_s_p3_0,
  128410. 1, -531628032, 1611661312, 4, 0,
  128411. _vq_quantlist__44c9_s_p3_0,
  128412. NULL,
  128413. &_vq_auxt__44c9_s_p3_0,
  128414. NULL,
  128415. 0
  128416. };
  128417. static long _vq_quantlist__44c9_s_p4_0[] = {
  128418. 8,
  128419. 7,
  128420. 9,
  128421. 6,
  128422. 10,
  128423. 5,
  128424. 11,
  128425. 4,
  128426. 12,
  128427. 3,
  128428. 13,
  128429. 2,
  128430. 14,
  128431. 1,
  128432. 15,
  128433. 0,
  128434. 16,
  128435. };
  128436. static long _vq_lengthlist__44c9_s_p4_0[] = {
  128437. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  128438. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  128439. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  128440. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  128441. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  128442. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  128443. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  128444. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128445. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128446. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0,
  128456. };
  128457. static float _vq_quantthresh__44c9_s_p4_0[] = {
  128458. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128459. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128460. };
  128461. static long _vq_quantmap__44c9_s_p4_0[] = {
  128462. 15, 13, 11, 9, 7, 5, 3, 1,
  128463. 0, 2, 4, 6, 8, 10, 12, 14,
  128464. 16,
  128465. };
  128466. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  128467. _vq_quantthresh__44c9_s_p4_0,
  128468. _vq_quantmap__44c9_s_p4_0,
  128469. 17,
  128470. 17
  128471. };
  128472. static static_codebook _44c9_s_p4_0 = {
  128473. 2, 289,
  128474. _vq_lengthlist__44c9_s_p4_0,
  128475. 1, -529530880, 1611661312, 5, 0,
  128476. _vq_quantlist__44c9_s_p4_0,
  128477. NULL,
  128478. &_vq_auxt__44c9_s_p4_0,
  128479. NULL,
  128480. 0
  128481. };
  128482. static long _vq_quantlist__44c9_s_p5_0[] = {
  128483. 1,
  128484. 0,
  128485. 2,
  128486. };
  128487. static long _vq_lengthlist__44c9_s_p5_0[] = {
  128488. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  128489. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  128490. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  128491. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  128492. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  128493. 12,
  128494. };
  128495. static float _vq_quantthresh__44c9_s_p5_0[] = {
  128496. -5.5, 5.5,
  128497. };
  128498. static long _vq_quantmap__44c9_s_p5_0[] = {
  128499. 1, 0, 2,
  128500. };
  128501. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  128502. _vq_quantthresh__44c9_s_p5_0,
  128503. _vq_quantmap__44c9_s_p5_0,
  128504. 3,
  128505. 3
  128506. };
  128507. static static_codebook _44c9_s_p5_0 = {
  128508. 4, 81,
  128509. _vq_lengthlist__44c9_s_p5_0,
  128510. 1, -529137664, 1618345984, 2, 0,
  128511. _vq_quantlist__44c9_s_p5_0,
  128512. NULL,
  128513. &_vq_auxt__44c9_s_p5_0,
  128514. NULL,
  128515. 0
  128516. };
  128517. static long _vq_quantlist__44c9_s_p5_1[] = {
  128518. 5,
  128519. 4,
  128520. 6,
  128521. 3,
  128522. 7,
  128523. 2,
  128524. 8,
  128525. 1,
  128526. 9,
  128527. 0,
  128528. 10,
  128529. };
  128530. static long _vq_lengthlist__44c9_s_p5_1[] = {
  128531. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  128532. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  128533. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  128534. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  128535. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  128536. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  128537. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  128538. 11,11,11, 7, 7, 7, 7, 7, 7,
  128539. };
  128540. static float _vq_quantthresh__44c9_s_p5_1[] = {
  128541. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128542. 3.5, 4.5,
  128543. };
  128544. static long _vq_quantmap__44c9_s_p5_1[] = {
  128545. 9, 7, 5, 3, 1, 0, 2, 4,
  128546. 6, 8, 10,
  128547. };
  128548. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  128549. _vq_quantthresh__44c9_s_p5_1,
  128550. _vq_quantmap__44c9_s_p5_1,
  128551. 11,
  128552. 11
  128553. };
  128554. static static_codebook _44c9_s_p5_1 = {
  128555. 2, 121,
  128556. _vq_lengthlist__44c9_s_p5_1,
  128557. 1, -531365888, 1611661312, 4, 0,
  128558. _vq_quantlist__44c9_s_p5_1,
  128559. NULL,
  128560. &_vq_auxt__44c9_s_p5_1,
  128561. NULL,
  128562. 0
  128563. };
  128564. static long _vq_quantlist__44c9_s_p6_0[] = {
  128565. 6,
  128566. 5,
  128567. 7,
  128568. 4,
  128569. 8,
  128570. 3,
  128571. 9,
  128572. 2,
  128573. 10,
  128574. 1,
  128575. 11,
  128576. 0,
  128577. 12,
  128578. };
  128579. static long _vq_lengthlist__44c9_s_p6_0[] = {
  128580. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  128581. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  128582. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  128583. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128584. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  128585. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. };
  128592. static float _vq_quantthresh__44c9_s_p6_0[] = {
  128593. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128594. 12.5, 17.5, 22.5, 27.5,
  128595. };
  128596. static long _vq_quantmap__44c9_s_p6_0[] = {
  128597. 11, 9, 7, 5, 3, 1, 0, 2,
  128598. 4, 6, 8, 10, 12,
  128599. };
  128600. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  128601. _vq_quantthresh__44c9_s_p6_0,
  128602. _vq_quantmap__44c9_s_p6_0,
  128603. 13,
  128604. 13
  128605. };
  128606. static static_codebook _44c9_s_p6_0 = {
  128607. 2, 169,
  128608. _vq_lengthlist__44c9_s_p6_0,
  128609. 1, -526516224, 1616117760, 4, 0,
  128610. _vq_quantlist__44c9_s_p6_0,
  128611. NULL,
  128612. &_vq_auxt__44c9_s_p6_0,
  128613. NULL,
  128614. 0
  128615. };
  128616. static long _vq_quantlist__44c9_s_p6_1[] = {
  128617. 2,
  128618. 1,
  128619. 3,
  128620. 0,
  128621. 4,
  128622. };
  128623. static long _vq_lengthlist__44c9_s_p6_1[] = {
  128624. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  128625. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  128626. };
  128627. static float _vq_quantthresh__44c9_s_p6_1[] = {
  128628. -1.5, -0.5, 0.5, 1.5,
  128629. };
  128630. static long _vq_quantmap__44c9_s_p6_1[] = {
  128631. 3, 1, 0, 2, 4,
  128632. };
  128633. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  128634. _vq_quantthresh__44c9_s_p6_1,
  128635. _vq_quantmap__44c9_s_p6_1,
  128636. 5,
  128637. 5
  128638. };
  128639. static static_codebook _44c9_s_p6_1 = {
  128640. 2, 25,
  128641. _vq_lengthlist__44c9_s_p6_1,
  128642. 1, -533725184, 1611661312, 3, 0,
  128643. _vq_quantlist__44c9_s_p6_1,
  128644. NULL,
  128645. &_vq_auxt__44c9_s_p6_1,
  128646. NULL,
  128647. 0
  128648. };
  128649. static long _vq_quantlist__44c9_s_p7_0[] = {
  128650. 6,
  128651. 5,
  128652. 7,
  128653. 4,
  128654. 8,
  128655. 3,
  128656. 9,
  128657. 2,
  128658. 10,
  128659. 1,
  128660. 11,
  128661. 0,
  128662. 12,
  128663. };
  128664. static long _vq_lengthlist__44c9_s_p7_0[] = {
  128665. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  128666. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  128667. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  128668. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  128669. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  128670. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  128671. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  128672. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  128673. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  128674. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  128675. 19,12,12,12,12,13,13,14,14,
  128676. };
  128677. static float _vq_quantthresh__44c9_s_p7_0[] = {
  128678. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128679. 27.5, 38.5, 49.5, 60.5,
  128680. };
  128681. static long _vq_quantmap__44c9_s_p7_0[] = {
  128682. 11, 9, 7, 5, 3, 1, 0, 2,
  128683. 4, 6, 8, 10, 12,
  128684. };
  128685. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  128686. _vq_quantthresh__44c9_s_p7_0,
  128687. _vq_quantmap__44c9_s_p7_0,
  128688. 13,
  128689. 13
  128690. };
  128691. static static_codebook _44c9_s_p7_0 = {
  128692. 2, 169,
  128693. _vq_lengthlist__44c9_s_p7_0,
  128694. 1, -523206656, 1618345984, 4, 0,
  128695. _vq_quantlist__44c9_s_p7_0,
  128696. NULL,
  128697. &_vq_auxt__44c9_s_p7_0,
  128698. NULL,
  128699. 0
  128700. };
  128701. static long _vq_quantlist__44c9_s_p7_1[] = {
  128702. 5,
  128703. 4,
  128704. 6,
  128705. 3,
  128706. 7,
  128707. 2,
  128708. 8,
  128709. 1,
  128710. 9,
  128711. 0,
  128712. 10,
  128713. };
  128714. static long _vq_lengthlist__44c9_s_p7_1[] = {
  128715. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  128716. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  128717. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  128718. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128719. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128720. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128721. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128722. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128723. };
  128724. static float _vq_quantthresh__44c9_s_p7_1[] = {
  128725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128726. 3.5, 4.5,
  128727. };
  128728. static long _vq_quantmap__44c9_s_p7_1[] = {
  128729. 9, 7, 5, 3, 1, 0, 2, 4,
  128730. 6, 8, 10,
  128731. };
  128732. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  128733. _vq_quantthresh__44c9_s_p7_1,
  128734. _vq_quantmap__44c9_s_p7_1,
  128735. 11,
  128736. 11
  128737. };
  128738. static static_codebook _44c9_s_p7_1 = {
  128739. 2, 121,
  128740. _vq_lengthlist__44c9_s_p7_1,
  128741. 1, -531365888, 1611661312, 4, 0,
  128742. _vq_quantlist__44c9_s_p7_1,
  128743. NULL,
  128744. &_vq_auxt__44c9_s_p7_1,
  128745. NULL,
  128746. 0
  128747. };
  128748. static long _vq_quantlist__44c9_s_p8_0[] = {
  128749. 7,
  128750. 6,
  128751. 8,
  128752. 5,
  128753. 9,
  128754. 4,
  128755. 10,
  128756. 3,
  128757. 11,
  128758. 2,
  128759. 12,
  128760. 1,
  128761. 13,
  128762. 0,
  128763. 14,
  128764. };
  128765. static long _vq_lengthlist__44c9_s_p8_0[] = {
  128766. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  128767. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  128768. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  128769. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  128770. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  128771. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  128772. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  128773. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  128774. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  128775. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  128776. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  128777. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  128778. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  128779. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  128780. 14,
  128781. };
  128782. static float _vq_quantthresh__44c9_s_p8_0[] = {
  128783. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128784. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128785. };
  128786. static long _vq_quantmap__44c9_s_p8_0[] = {
  128787. 13, 11, 9, 7, 5, 3, 1, 0,
  128788. 2, 4, 6, 8, 10, 12, 14,
  128789. };
  128790. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  128791. _vq_quantthresh__44c9_s_p8_0,
  128792. _vq_quantmap__44c9_s_p8_0,
  128793. 15,
  128794. 15
  128795. };
  128796. static static_codebook _44c9_s_p8_0 = {
  128797. 2, 225,
  128798. _vq_lengthlist__44c9_s_p8_0,
  128799. 1, -520986624, 1620377600, 4, 0,
  128800. _vq_quantlist__44c9_s_p8_0,
  128801. NULL,
  128802. &_vq_auxt__44c9_s_p8_0,
  128803. NULL,
  128804. 0
  128805. };
  128806. static long _vq_quantlist__44c9_s_p8_1[] = {
  128807. 10,
  128808. 9,
  128809. 11,
  128810. 8,
  128811. 12,
  128812. 7,
  128813. 13,
  128814. 6,
  128815. 14,
  128816. 5,
  128817. 15,
  128818. 4,
  128819. 16,
  128820. 3,
  128821. 17,
  128822. 2,
  128823. 18,
  128824. 1,
  128825. 19,
  128826. 0,
  128827. 20,
  128828. };
  128829. static long _vq_lengthlist__44c9_s_p8_1[] = {
  128830. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128831. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128833. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128834. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128835. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128836. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  128837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128838. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128839. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128840. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  128841. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128842. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128843. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128844. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  128845. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  128846. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  128847. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  128848. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  128849. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  128850. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  128851. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  128852. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128853. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  128854. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  128855. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  128856. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  128857. 9, 9, 9,10, 9, 9, 9, 9, 9,
  128858. };
  128859. static float _vq_quantthresh__44c9_s_p8_1[] = {
  128860. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128861. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128862. 6.5, 7.5, 8.5, 9.5,
  128863. };
  128864. static long _vq_quantmap__44c9_s_p8_1[] = {
  128865. 19, 17, 15, 13, 11, 9, 7, 5,
  128866. 3, 1, 0, 2, 4, 6, 8, 10,
  128867. 12, 14, 16, 18, 20,
  128868. };
  128869. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  128870. _vq_quantthresh__44c9_s_p8_1,
  128871. _vq_quantmap__44c9_s_p8_1,
  128872. 21,
  128873. 21
  128874. };
  128875. static static_codebook _44c9_s_p8_1 = {
  128876. 2, 441,
  128877. _vq_lengthlist__44c9_s_p8_1,
  128878. 1, -529268736, 1611661312, 5, 0,
  128879. _vq_quantlist__44c9_s_p8_1,
  128880. NULL,
  128881. &_vq_auxt__44c9_s_p8_1,
  128882. NULL,
  128883. 0
  128884. };
  128885. static long _vq_quantlist__44c9_s_p9_0[] = {
  128886. 9,
  128887. 8,
  128888. 10,
  128889. 7,
  128890. 11,
  128891. 6,
  128892. 12,
  128893. 5,
  128894. 13,
  128895. 4,
  128896. 14,
  128897. 3,
  128898. 15,
  128899. 2,
  128900. 16,
  128901. 1,
  128902. 17,
  128903. 0,
  128904. 18,
  128905. };
  128906. static long _vq_lengthlist__44c9_s_p9_0[] = {
  128907. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128908. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  128909. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  128910. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  128911. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128912. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128913. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128914. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128915. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128916. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128917. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128918. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128919. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128920. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128921. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128922. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128923. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  128924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128929. 11,11,11,11,11,11,11,11,11,
  128930. };
  128931. static float _vq_quantthresh__44c9_s_p9_0[] = {
  128932. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  128933. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  128934. 6982.5, 7913.5,
  128935. };
  128936. static long _vq_quantmap__44c9_s_p9_0[] = {
  128937. 17, 15, 13, 11, 9, 7, 5, 3,
  128938. 1, 0, 2, 4, 6, 8, 10, 12,
  128939. 14, 16, 18,
  128940. };
  128941. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  128942. _vq_quantthresh__44c9_s_p9_0,
  128943. _vq_quantmap__44c9_s_p9_0,
  128944. 19,
  128945. 19
  128946. };
  128947. static static_codebook _44c9_s_p9_0 = {
  128948. 2, 361,
  128949. _vq_lengthlist__44c9_s_p9_0,
  128950. 1, -508535424, 1631393792, 5, 0,
  128951. _vq_quantlist__44c9_s_p9_0,
  128952. NULL,
  128953. &_vq_auxt__44c9_s_p9_0,
  128954. NULL,
  128955. 0
  128956. };
  128957. static long _vq_quantlist__44c9_s_p9_1[] = {
  128958. 9,
  128959. 8,
  128960. 10,
  128961. 7,
  128962. 11,
  128963. 6,
  128964. 12,
  128965. 5,
  128966. 13,
  128967. 4,
  128968. 14,
  128969. 3,
  128970. 15,
  128971. 2,
  128972. 16,
  128973. 1,
  128974. 17,
  128975. 0,
  128976. 18,
  128977. };
  128978. static long _vq_lengthlist__44c9_s_p9_1[] = {
  128979. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  128980. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  128981. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  128982. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  128983. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  128984. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  128985. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  128986. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  128987. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  128988. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  128989. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  128990. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  128991. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  128992. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  128993. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  128994. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  128995. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  128996. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  128997. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  128998. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  128999. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  129000. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  129001. 13,13,13,14,13,14,15,15,15,
  129002. };
  129003. static float _vq_quantthresh__44c9_s_p9_1[] = {
  129004. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129005. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129006. 367.5, 416.5,
  129007. };
  129008. static long _vq_quantmap__44c9_s_p9_1[] = {
  129009. 17, 15, 13, 11, 9, 7, 5, 3,
  129010. 1, 0, 2, 4, 6, 8, 10, 12,
  129011. 14, 16, 18,
  129012. };
  129013. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  129014. _vq_quantthresh__44c9_s_p9_1,
  129015. _vq_quantmap__44c9_s_p9_1,
  129016. 19,
  129017. 19
  129018. };
  129019. static static_codebook _44c9_s_p9_1 = {
  129020. 2, 361,
  129021. _vq_lengthlist__44c9_s_p9_1,
  129022. 1, -518287360, 1622704128, 5, 0,
  129023. _vq_quantlist__44c9_s_p9_1,
  129024. NULL,
  129025. &_vq_auxt__44c9_s_p9_1,
  129026. NULL,
  129027. 0
  129028. };
  129029. static long _vq_quantlist__44c9_s_p9_2[] = {
  129030. 24,
  129031. 23,
  129032. 25,
  129033. 22,
  129034. 26,
  129035. 21,
  129036. 27,
  129037. 20,
  129038. 28,
  129039. 19,
  129040. 29,
  129041. 18,
  129042. 30,
  129043. 17,
  129044. 31,
  129045. 16,
  129046. 32,
  129047. 15,
  129048. 33,
  129049. 14,
  129050. 34,
  129051. 13,
  129052. 35,
  129053. 12,
  129054. 36,
  129055. 11,
  129056. 37,
  129057. 10,
  129058. 38,
  129059. 9,
  129060. 39,
  129061. 8,
  129062. 40,
  129063. 7,
  129064. 41,
  129065. 6,
  129066. 42,
  129067. 5,
  129068. 43,
  129069. 4,
  129070. 44,
  129071. 3,
  129072. 45,
  129073. 2,
  129074. 46,
  129075. 1,
  129076. 47,
  129077. 0,
  129078. 48,
  129079. };
  129080. static long _vq_lengthlist__44c9_s_p9_2[] = {
  129081. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129082. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129083. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129084. 7,
  129085. };
  129086. static float _vq_quantthresh__44c9_s_p9_2[] = {
  129087. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129088. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129089. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129090. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129091. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129092. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129093. };
  129094. static long _vq_quantmap__44c9_s_p9_2[] = {
  129095. 47, 45, 43, 41, 39, 37, 35, 33,
  129096. 31, 29, 27, 25, 23, 21, 19, 17,
  129097. 15, 13, 11, 9, 7, 5, 3, 1,
  129098. 0, 2, 4, 6, 8, 10, 12, 14,
  129099. 16, 18, 20, 22, 24, 26, 28, 30,
  129100. 32, 34, 36, 38, 40, 42, 44, 46,
  129101. 48,
  129102. };
  129103. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  129104. _vq_quantthresh__44c9_s_p9_2,
  129105. _vq_quantmap__44c9_s_p9_2,
  129106. 49,
  129107. 49
  129108. };
  129109. static static_codebook _44c9_s_p9_2 = {
  129110. 1, 49,
  129111. _vq_lengthlist__44c9_s_p9_2,
  129112. 1, -526909440, 1611661312, 6, 0,
  129113. _vq_quantlist__44c9_s_p9_2,
  129114. NULL,
  129115. &_vq_auxt__44c9_s_p9_2,
  129116. NULL,
  129117. 0
  129118. };
  129119. static long _huff_lengthlist__44c9_s_short[] = {
  129120. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  129121. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  129122. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  129123. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  129124. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  129125. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  129126. 9, 8,10,13,
  129127. };
  129128. static static_codebook _huff_book__44c9_s_short = {
  129129. 2, 100,
  129130. _huff_lengthlist__44c9_s_short,
  129131. 0, 0, 0, 0, 0,
  129132. NULL,
  129133. NULL,
  129134. NULL,
  129135. NULL,
  129136. 0
  129137. };
  129138. static long _huff_lengthlist__44c0_s_long[] = {
  129139. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  129140. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  129141. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  129142. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  129143. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  129144. 12,
  129145. };
  129146. static static_codebook _huff_book__44c0_s_long = {
  129147. 2, 81,
  129148. _huff_lengthlist__44c0_s_long,
  129149. 0, 0, 0, 0, 0,
  129150. NULL,
  129151. NULL,
  129152. NULL,
  129153. NULL,
  129154. 0
  129155. };
  129156. static long _vq_quantlist__44c0_s_p1_0[] = {
  129157. 1,
  129158. 0,
  129159. 2,
  129160. };
  129161. static long _vq_lengthlist__44c0_s_p1_0[] = {
  129162. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129163. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129168. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129173. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129208. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129213. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129218. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129254. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129259. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  129264. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0,
  129573. };
  129574. static float _vq_quantthresh__44c0_s_p1_0[] = {
  129575. -0.5, 0.5,
  129576. };
  129577. static long _vq_quantmap__44c0_s_p1_0[] = {
  129578. 1, 0, 2,
  129579. };
  129580. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  129581. _vq_quantthresh__44c0_s_p1_0,
  129582. _vq_quantmap__44c0_s_p1_0,
  129583. 3,
  129584. 3
  129585. };
  129586. static static_codebook _44c0_s_p1_0 = {
  129587. 8, 6561,
  129588. _vq_lengthlist__44c0_s_p1_0,
  129589. 1, -535822336, 1611661312, 2, 0,
  129590. _vq_quantlist__44c0_s_p1_0,
  129591. NULL,
  129592. &_vq_auxt__44c0_s_p1_0,
  129593. NULL,
  129594. 0
  129595. };
  129596. static long _vq_quantlist__44c0_s_p2_0[] = {
  129597. 2,
  129598. 1,
  129599. 3,
  129600. 0,
  129601. 4,
  129602. };
  129603. static long _vq_lengthlist__44c0_s_p2_0[] = {
  129604. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0,
  129644. };
  129645. static float _vq_quantthresh__44c0_s_p2_0[] = {
  129646. -1.5, -0.5, 0.5, 1.5,
  129647. };
  129648. static long _vq_quantmap__44c0_s_p2_0[] = {
  129649. 3, 1, 0, 2, 4,
  129650. };
  129651. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  129652. _vq_quantthresh__44c0_s_p2_0,
  129653. _vq_quantmap__44c0_s_p2_0,
  129654. 5,
  129655. 5
  129656. };
  129657. static static_codebook _44c0_s_p2_0 = {
  129658. 4, 625,
  129659. _vq_lengthlist__44c0_s_p2_0,
  129660. 1, -533725184, 1611661312, 3, 0,
  129661. _vq_quantlist__44c0_s_p2_0,
  129662. NULL,
  129663. &_vq_auxt__44c0_s_p2_0,
  129664. NULL,
  129665. 0
  129666. };
  129667. static long _vq_quantlist__44c0_s_p3_0[] = {
  129668. 4,
  129669. 3,
  129670. 5,
  129671. 2,
  129672. 6,
  129673. 1,
  129674. 7,
  129675. 0,
  129676. 8,
  129677. };
  129678. static long _vq_lengthlist__44c0_s_p3_0[] = {
  129679. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  129680. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  129681. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  129682. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  129683. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0,
  129685. };
  129686. static float _vq_quantthresh__44c0_s_p3_0[] = {
  129687. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129688. };
  129689. static long _vq_quantmap__44c0_s_p3_0[] = {
  129690. 7, 5, 3, 1, 0, 2, 4, 6,
  129691. 8,
  129692. };
  129693. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  129694. _vq_quantthresh__44c0_s_p3_0,
  129695. _vq_quantmap__44c0_s_p3_0,
  129696. 9,
  129697. 9
  129698. };
  129699. static static_codebook _44c0_s_p3_0 = {
  129700. 2, 81,
  129701. _vq_lengthlist__44c0_s_p3_0,
  129702. 1, -531628032, 1611661312, 4, 0,
  129703. _vq_quantlist__44c0_s_p3_0,
  129704. NULL,
  129705. &_vq_auxt__44c0_s_p3_0,
  129706. NULL,
  129707. 0
  129708. };
  129709. static long _vq_quantlist__44c0_s_p4_0[] = {
  129710. 4,
  129711. 3,
  129712. 5,
  129713. 2,
  129714. 6,
  129715. 1,
  129716. 7,
  129717. 0,
  129718. 8,
  129719. };
  129720. static long _vq_lengthlist__44c0_s_p4_0[] = {
  129721. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  129722. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  129723. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  129724. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  129725. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  129726. 10,
  129727. };
  129728. static float _vq_quantthresh__44c0_s_p4_0[] = {
  129729. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129730. };
  129731. static long _vq_quantmap__44c0_s_p4_0[] = {
  129732. 7, 5, 3, 1, 0, 2, 4, 6,
  129733. 8,
  129734. };
  129735. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  129736. _vq_quantthresh__44c0_s_p4_0,
  129737. _vq_quantmap__44c0_s_p4_0,
  129738. 9,
  129739. 9
  129740. };
  129741. static static_codebook _44c0_s_p4_0 = {
  129742. 2, 81,
  129743. _vq_lengthlist__44c0_s_p4_0,
  129744. 1, -531628032, 1611661312, 4, 0,
  129745. _vq_quantlist__44c0_s_p4_0,
  129746. NULL,
  129747. &_vq_auxt__44c0_s_p4_0,
  129748. NULL,
  129749. 0
  129750. };
  129751. static long _vq_quantlist__44c0_s_p5_0[] = {
  129752. 8,
  129753. 7,
  129754. 9,
  129755. 6,
  129756. 10,
  129757. 5,
  129758. 11,
  129759. 4,
  129760. 12,
  129761. 3,
  129762. 13,
  129763. 2,
  129764. 14,
  129765. 1,
  129766. 15,
  129767. 0,
  129768. 16,
  129769. };
  129770. static long _vq_lengthlist__44c0_s_p5_0[] = {
  129771. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129772. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  129773. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129774. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129775. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129776. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  129777. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  129778. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129779. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129780. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129781. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  129782. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129783. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  129784. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  129785. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  129786. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  129787. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  129789. 14,
  129790. };
  129791. static float _vq_quantthresh__44c0_s_p5_0[] = {
  129792. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129793. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129794. };
  129795. static long _vq_quantmap__44c0_s_p5_0[] = {
  129796. 15, 13, 11, 9, 7, 5, 3, 1,
  129797. 0, 2, 4, 6, 8, 10, 12, 14,
  129798. 16,
  129799. };
  129800. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  129801. _vq_quantthresh__44c0_s_p5_0,
  129802. _vq_quantmap__44c0_s_p5_0,
  129803. 17,
  129804. 17
  129805. };
  129806. static static_codebook _44c0_s_p5_0 = {
  129807. 2, 289,
  129808. _vq_lengthlist__44c0_s_p5_0,
  129809. 1, -529530880, 1611661312, 5, 0,
  129810. _vq_quantlist__44c0_s_p5_0,
  129811. NULL,
  129812. &_vq_auxt__44c0_s_p5_0,
  129813. NULL,
  129814. 0
  129815. };
  129816. static long _vq_quantlist__44c0_s_p6_0[] = {
  129817. 1,
  129818. 0,
  129819. 2,
  129820. };
  129821. static long _vq_lengthlist__44c0_s_p6_0[] = {
  129822. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  129823. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129824. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  129825. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  129826. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  129827. 10,
  129828. };
  129829. static float _vq_quantthresh__44c0_s_p6_0[] = {
  129830. -5.5, 5.5,
  129831. };
  129832. static long _vq_quantmap__44c0_s_p6_0[] = {
  129833. 1, 0, 2,
  129834. };
  129835. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  129836. _vq_quantthresh__44c0_s_p6_0,
  129837. _vq_quantmap__44c0_s_p6_0,
  129838. 3,
  129839. 3
  129840. };
  129841. static static_codebook _44c0_s_p6_0 = {
  129842. 4, 81,
  129843. _vq_lengthlist__44c0_s_p6_0,
  129844. 1, -529137664, 1618345984, 2, 0,
  129845. _vq_quantlist__44c0_s_p6_0,
  129846. NULL,
  129847. &_vq_auxt__44c0_s_p6_0,
  129848. NULL,
  129849. 0
  129850. };
  129851. static long _vq_quantlist__44c0_s_p6_1[] = {
  129852. 5,
  129853. 4,
  129854. 6,
  129855. 3,
  129856. 7,
  129857. 2,
  129858. 8,
  129859. 1,
  129860. 9,
  129861. 0,
  129862. 10,
  129863. };
  129864. static long _vq_lengthlist__44c0_s_p6_1[] = {
  129865. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  129866. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  129867. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  129868. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129869. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129870. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129871. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  129872. 10,10,10, 8, 8, 8, 8, 8, 8,
  129873. };
  129874. static float _vq_quantthresh__44c0_s_p6_1[] = {
  129875. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129876. 3.5, 4.5,
  129877. };
  129878. static long _vq_quantmap__44c0_s_p6_1[] = {
  129879. 9, 7, 5, 3, 1, 0, 2, 4,
  129880. 6, 8, 10,
  129881. };
  129882. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  129883. _vq_quantthresh__44c0_s_p6_1,
  129884. _vq_quantmap__44c0_s_p6_1,
  129885. 11,
  129886. 11
  129887. };
  129888. static static_codebook _44c0_s_p6_1 = {
  129889. 2, 121,
  129890. _vq_lengthlist__44c0_s_p6_1,
  129891. 1, -531365888, 1611661312, 4, 0,
  129892. _vq_quantlist__44c0_s_p6_1,
  129893. NULL,
  129894. &_vq_auxt__44c0_s_p6_1,
  129895. NULL,
  129896. 0
  129897. };
  129898. static long _vq_quantlist__44c0_s_p7_0[] = {
  129899. 6,
  129900. 5,
  129901. 7,
  129902. 4,
  129903. 8,
  129904. 3,
  129905. 9,
  129906. 2,
  129907. 10,
  129908. 1,
  129909. 11,
  129910. 0,
  129911. 12,
  129912. };
  129913. static long _vq_lengthlist__44c0_s_p7_0[] = {
  129914. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  129915. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  129916. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129917. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129918. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  129919. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  129920. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  129921. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  129922. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  129923. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  129924. 0,12,12,11,11,12,12,13,13,
  129925. };
  129926. static float _vq_quantthresh__44c0_s_p7_0[] = {
  129927. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129928. 12.5, 17.5, 22.5, 27.5,
  129929. };
  129930. static long _vq_quantmap__44c0_s_p7_0[] = {
  129931. 11, 9, 7, 5, 3, 1, 0, 2,
  129932. 4, 6, 8, 10, 12,
  129933. };
  129934. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  129935. _vq_quantthresh__44c0_s_p7_0,
  129936. _vq_quantmap__44c0_s_p7_0,
  129937. 13,
  129938. 13
  129939. };
  129940. static static_codebook _44c0_s_p7_0 = {
  129941. 2, 169,
  129942. _vq_lengthlist__44c0_s_p7_0,
  129943. 1, -526516224, 1616117760, 4, 0,
  129944. _vq_quantlist__44c0_s_p7_0,
  129945. NULL,
  129946. &_vq_auxt__44c0_s_p7_0,
  129947. NULL,
  129948. 0
  129949. };
  129950. static long _vq_quantlist__44c0_s_p7_1[] = {
  129951. 2,
  129952. 1,
  129953. 3,
  129954. 0,
  129955. 4,
  129956. };
  129957. static long _vq_lengthlist__44c0_s_p7_1[] = {
  129958. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  129959. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  129960. };
  129961. static float _vq_quantthresh__44c0_s_p7_1[] = {
  129962. -1.5, -0.5, 0.5, 1.5,
  129963. };
  129964. static long _vq_quantmap__44c0_s_p7_1[] = {
  129965. 3, 1, 0, 2, 4,
  129966. };
  129967. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  129968. _vq_quantthresh__44c0_s_p7_1,
  129969. _vq_quantmap__44c0_s_p7_1,
  129970. 5,
  129971. 5
  129972. };
  129973. static static_codebook _44c0_s_p7_1 = {
  129974. 2, 25,
  129975. _vq_lengthlist__44c0_s_p7_1,
  129976. 1, -533725184, 1611661312, 3, 0,
  129977. _vq_quantlist__44c0_s_p7_1,
  129978. NULL,
  129979. &_vq_auxt__44c0_s_p7_1,
  129980. NULL,
  129981. 0
  129982. };
  129983. static long _vq_quantlist__44c0_s_p8_0[] = {
  129984. 2,
  129985. 1,
  129986. 3,
  129987. 0,
  129988. 4,
  129989. };
  129990. static long _vq_lengthlist__44c0_s_p8_0[] = {
  129991. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  129992. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129993. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129994. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129995. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129996. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129998. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  129999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130003. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  130004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130006. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  130007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130030. 11,
  130031. };
  130032. static float _vq_quantthresh__44c0_s_p8_0[] = {
  130033. -331.5, -110.5, 110.5, 331.5,
  130034. };
  130035. static long _vq_quantmap__44c0_s_p8_0[] = {
  130036. 3, 1, 0, 2, 4,
  130037. };
  130038. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  130039. _vq_quantthresh__44c0_s_p8_0,
  130040. _vq_quantmap__44c0_s_p8_0,
  130041. 5,
  130042. 5
  130043. };
  130044. static static_codebook _44c0_s_p8_0 = {
  130045. 4, 625,
  130046. _vq_lengthlist__44c0_s_p8_0,
  130047. 1, -518283264, 1627103232, 3, 0,
  130048. _vq_quantlist__44c0_s_p8_0,
  130049. NULL,
  130050. &_vq_auxt__44c0_s_p8_0,
  130051. NULL,
  130052. 0
  130053. };
  130054. static long _vq_quantlist__44c0_s_p8_1[] = {
  130055. 6,
  130056. 5,
  130057. 7,
  130058. 4,
  130059. 8,
  130060. 3,
  130061. 9,
  130062. 2,
  130063. 10,
  130064. 1,
  130065. 11,
  130066. 0,
  130067. 12,
  130068. };
  130069. static long _vq_lengthlist__44c0_s_p8_1[] = {
  130070. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  130071. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  130072. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  130073. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  130074. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  130075. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  130076. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  130077. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  130078. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  130079. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  130080. 16,13,13,12,12,14,14,15,13,
  130081. };
  130082. static float _vq_quantthresh__44c0_s_p8_1[] = {
  130083. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  130084. 42.5, 59.5, 76.5, 93.5,
  130085. };
  130086. static long _vq_quantmap__44c0_s_p8_1[] = {
  130087. 11, 9, 7, 5, 3, 1, 0, 2,
  130088. 4, 6, 8, 10, 12,
  130089. };
  130090. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  130091. _vq_quantthresh__44c0_s_p8_1,
  130092. _vq_quantmap__44c0_s_p8_1,
  130093. 13,
  130094. 13
  130095. };
  130096. static static_codebook _44c0_s_p8_1 = {
  130097. 2, 169,
  130098. _vq_lengthlist__44c0_s_p8_1,
  130099. 1, -522616832, 1620115456, 4, 0,
  130100. _vq_quantlist__44c0_s_p8_1,
  130101. NULL,
  130102. &_vq_auxt__44c0_s_p8_1,
  130103. NULL,
  130104. 0
  130105. };
  130106. static long _vq_quantlist__44c0_s_p8_2[] = {
  130107. 8,
  130108. 7,
  130109. 9,
  130110. 6,
  130111. 10,
  130112. 5,
  130113. 11,
  130114. 4,
  130115. 12,
  130116. 3,
  130117. 13,
  130118. 2,
  130119. 14,
  130120. 1,
  130121. 15,
  130122. 0,
  130123. 16,
  130124. };
  130125. static long _vq_lengthlist__44c0_s_p8_2[] = {
  130126. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130127. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  130128. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130129. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130130. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  130131. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  130132. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  130133. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  130134. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  130135. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  130136. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  130137. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  130138. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  130139. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130140. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  130141. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  130142. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  130143. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  130144. 10,
  130145. };
  130146. static float _vq_quantthresh__44c0_s_p8_2[] = {
  130147. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130148. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130149. };
  130150. static long _vq_quantmap__44c0_s_p8_2[] = {
  130151. 15, 13, 11, 9, 7, 5, 3, 1,
  130152. 0, 2, 4, 6, 8, 10, 12, 14,
  130153. 16,
  130154. };
  130155. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  130156. _vq_quantthresh__44c0_s_p8_2,
  130157. _vq_quantmap__44c0_s_p8_2,
  130158. 17,
  130159. 17
  130160. };
  130161. static static_codebook _44c0_s_p8_2 = {
  130162. 2, 289,
  130163. _vq_lengthlist__44c0_s_p8_2,
  130164. 1, -529530880, 1611661312, 5, 0,
  130165. _vq_quantlist__44c0_s_p8_2,
  130166. NULL,
  130167. &_vq_auxt__44c0_s_p8_2,
  130168. NULL,
  130169. 0
  130170. };
  130171. static long _huff_lengthlist__44c0_s_short[] = {
  130172. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  130173. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  130174. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  130175. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  130176. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  130177. 12,
  130178. };
  130179. static static_codebook _huff_book__44c0_s_short = {
  130180. 2, 81,
  130181. _huff_lengthlist__44c0_s_short,
  130182. 0, 0, 0, 0, 0,
  130183. NULL,
  130184. NULL,
  130185. NULL,
  130186. NULL,
  130187. 0
  130188. };
  130189. static long _huff_lengthlist__44c0_sm_long[] = {
  130190. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  130191. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  130192. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  130193. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  130194. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  130195. 13,
  130196. };
  130197. static static_codebook _huff_book__44c0_sm_long = {
  130198. 2, 81,
  130199. _huff_lengthlist__44c0_sm_long,
  130200. 0, 0, 0, 0, 0,
  130201. NULL,
  130202. NULL,
  130203. NULL,
  130204. NULL,
  130205. 0
  130206. };
  130207. static long _vq_quantlist__44c0_sm_p1_0[] = {
  130208. 1,
  130209. 0,
  130210. 2,
  130211. };
  130212. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  130213. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130214. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130219. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130224. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  130259. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130264. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130269. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130305. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130310. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130315. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0,
  130624. };
  130625. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  130626. -0.5, 0.5,
  130627. };
  130628. static long _vq_quantmap__44c0_sm_p1_0[] = {
  130629. 1, 0, 2,
  130630. };
  130631. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  130632. _vq_quantthresh__44c0_sm_p1_0,
  130633. _vq_quantmap__44c0_sm_p1_0,
  130634. 3,
  130635. 3
  130636. };
  130637. static static_codebook _44c0_sm_p1_0 = {
  130638. 8, 6561,
  130639. _vq_lengthlist__44c0_sm_p1_0,
  130640. 1, -535822336, 1611661312, 2, 0,
  130641. _vq_quantlist__44c0_sm_p1_0,
  130642. NULL,
  130643. &_vq_auxt__44c0_sm_p1_0,
  130644. NULL,
  130645. 0
  130646. };
  130647. static long _vq_quantlist__44c0_sm_p2_0[] = {
  130648. 2,
  130649. 1,
  130650. 3,
  130651. 0,
  130652. 4,
  130653. };
  130654. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  130655. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0,
  130695. };
  130696. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  130697. -1.5, -0.5, 0.5, 1.5,
  130698. };
  130699. static long _vq_quantmap__44c0_sm_p2_0[] = {
  130700. 3, 1, 0, 2, 4,
  130701. };
  130702. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  130703. _vq_quantthresh__44c0_sm_p2_0,
  130704. _vq_quantmap__44c0_sm_p2_0,
  130705. 5,
  130706. 5
  130707. };
  130708. static static_codebook _44c0_sm_p2_0 = {
  130709. 4, 625,
  130710. _vq_lengthlist__44c0_sm_p2_0,
  130711. 1, -533725184, 1611661312, 3, 0,
  130712. _vq_quantlist__44c0_sm_p2_0,
  130713. NULL,
  130714. &_vq_auxt__44c0_sm_p2_0,
  130715. NULL,
  130716. 0
  130717. };
  130718. static long _vq_quantlist__44c0_sm_p3_0[] = {
  130719. 4,
  130720. 3,
  130721. 5,
  130722. 2,
  130723. 6,
  130724. 1,
  130725. 7,
  130726. 0,
  130727. 8,
  130728. };
  130729. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  130730. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  130731. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  130732. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  130733. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  130734. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0,
  130736. };
  130737. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  130738. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130739. };
  130740. static long _vq_quantmap__44c0_sm_p3_0[] = {
  130741. 7, 5, 3, 1, 0, 2, 4, 6,
  130742. 8,
  130743. };
  130744. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  130745. _vq_quantthresh__44c0_sm_p3_0,
  130746. _vq_quantmap__44c0_sm_p3_0,
  130747. 9,
  130748. 9
  130749. };
  130750. static static_codebook _44c0_sm_p3_0 = {
  130751. 2, 81,
  130752. _vq_lengthlist__44c0_sm_p3_0,
  130753. 1, -531628032, 1611661312, 4, 0,
  130754. _vq_quantlist__44c0_sm_p3_0,
  130755. NULL,
  130756. &_vq_auxt__44c0_sm_p3_0,
  130757. NULL,
  130758. 0
  130759. };
  130760. static long _vq_quantlist__44c0_sm_p4_0[] = {
  130761. 4,
  130762. 3,
  130763. 5,
  130764. 2,
  130765. 6,
  130766. 1,
  130767. 7,
  130768. 0,
  130769. 8,
  130770. };
  130771. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  130772. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  130773. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  130774. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  130775. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  130776. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  130777. 11,
  130778. };
  130779. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  130780. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130781. };
  130782. static long _vq_quantmap__44c0_sm_p4_0[] = {
  130783. 7, 5, 3, 1, 0, 2, 4, 6,
  130784. 8,
  130785. };
  130786. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  130787. _vq_quantthresh__44c0_sm_p4_0,
  130788. _vq_quantmap__44c0_sm_p4_0,
  130789. 9,
  130790. 9
  130791. };
  130792. static static_codebook _44c0_sm_p4_0 = {
  130793. 2, 81,
  130794. _vq_lengthlist__44c0_sm_p4_0,
  130795. 1, -531628032, 1611661312, 4, 0,
  130796. _vq_quantlist__44c0_sm_p4_0,
  130797. NULL,
  130798. &_vq_auxt__44c0_sm_p4_0,
  130799. NULL,
  130800. 0
  130801. };
  130802. static long _vq_quantlist__44c0_sm_p5_0[] = {
  130803. 8,
  130804. 7,
  130805. 9,
  130806. 6,
  130807. 10,
  130808. 5,
  130809. 11,
  130810. 4,
  130811. 12,
  130812. 3,
  130813. 13,
  130814. 2,
  130815. 14,
  130816. 1,
  130817. 15,
  130818. 0,
  130819. 16,
  130820. };
  130821. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  130822. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  130823. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  130824. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130825. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  130826. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  130827. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  130828. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  130829. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130830. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  130831. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  130832. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  130833. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  130834. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  130835. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  130836. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  130837. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  130838. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  130840. 14,
  130841. };
  130842. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  130843. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130844. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130845. };
  130846. static long _vq_quantmap__44c0_sm_p5_0[] = {
  130847. 15, 13, 11, 9, 7, 5, 3, 1,
  130848. 0, 2, 4, 6, 8, 10, 12, 14,
  130849. 16,
  130850. };
  130851. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  130852. _vq_quantthresh__44c0_sm_p5_0,
  130853. _vq_quantmap__44c0_sm_p5_0,
  130854. 17,
  130855. 17
  130856. };
  130857. static static_codebook _44c0_sm_p5_0 = {
  130858. 2, 289,
  130859. _vq_lengthlist__44c0_sm_p5_0,
  130860. 1, -529530880, 1611661312, 5, 0,
  130861. _vq_quantlist__44c0_sm_p5_0,
  130862. NULL,
  130863. &_vq_auxt__44c0_sm_p5_0,
  130864. NULL,
  130865. 0
  130866. };
  130867. static long _vq_quantlist__44c0_sm_p6_0[] = {
  130868. 1,
  130869. 0,
  130870. 2,
  130871. };
  130872. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  130873. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130874. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  130875. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  130876. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  130877. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  130878. 11,
  130879. };
  130880. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  130881. -5.5, 5.5,
  130882. };
  130883. static long _vq_quantmap__44c0_sm_p6_0[] = {
  130884. 1, 0, 2,
  130885. };
  130886. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  130887. _vq_quantthresh__44c0_sm_p6_0,
  130888. _vq_quantmap__44c0_sm_p6_0,
  130889. 3,
  130890. 3
  130891. };
  130892. static static_codebook _44c0_sm_p6_0 = {
  130893. 4, 81,
  130894. _vq_lengthlist__44c0_sm_p6_0,
  130895. 1, -529137664, 1618345984, 2, 0,
  130896. _vq_quantlist__44c0_sm_p6_0,
  130897. NULL,
  130898. &_vq_auxt__44c0_sm_p6_0,
  130899. NULL,
  130900. 0
  130901. };
  130902. static long _vq_quantlist__44c0_sm_p6_1[] = {
  130903. 5,
  130904. 4,
  130905. 6,
  130906. 3,
  130907. 7,
  130908. 2,
  130909. 8,
  130910. 1,
  130911. 9,
  130912. 0,
  130913. 10,
  130914. };
  130915. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  130916. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  130917. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130918. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  130919. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  130920. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  130921. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130922. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130923. 10,10,10, 8, 8, 8, 8, 8, 8,
  130924. };
  130925. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  130926. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130927. 3.5, 4.5,
  130928. };
  130929. static long _vq_quantmap__44c0_sm_p6_1[] = {
  130930. 9, 7, 5, 3, 1, 0, 2, 4,
  130931. 6, 8, 10,
  130932. };
  130933. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  130934. _vq_quantthresh__44c0_sm_p6_1,
  130935. _vq_quantmap__44c0_sm_p6_1,
  130936. 11,
  130937. 11
  130938. };
  130939. static static_codebook _44c0_sm_p6_1 = {
  130940. 2, 121,
  130941. _vq_lengthlist__44c0_sm_p6_1,
  130942. 1, -531365888, 1611661312, 4, 0,
  130943. _vq_quantlist__44c0_sm_p6_1,
  130944. NULL,
  130945. &_vq_auxt__44c0_sm_p6_1,
  130946. NULL,
  130947. 0
  130948. };
  130949. static long _vq_quantlist__44c0_sm_p7_0[] = {
  130950. 6,
  130951. 5,
  130952. 7,
  130953. 4,
  130954. 8,
  130955. 3,
  130956. 9,
  130957. 2,
  130958. 10,
  130959. 1,
  130960. 11,
  130961. 0,
  130962. 12,
  130963. };
  130964. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  130965. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  130966. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  130967. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130968. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130969. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  130970. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  130971. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  130972. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  130973. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  130974. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  130975. 0,12,12,11,11,13,12,14,14,
  130976. };
  130977. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  130978. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130979. 12.5, 17.5, 22.5, 27.5,
  130980. };
  130981. static long _vq_quantmap__44c0_sm_p7_0[] = {
  130982. 11, 9, 7, 5, 3, 1, 0, 2,
  130983. 4, 6, 8, 10, 12,
  130984. };
  130985. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  130986. _vq_quantthresh__44c0_sm_p7_0,
  130987. _vq_quantmap__44c0_sm_p7_0,
  130988. 13,
  130989. 13
  130990. };
  130991. static static_codebook _44c0_sm_p7_0 = {
  130992. 2, 169,
  130993. _vq_lengthlist__44c0_sm_p7_0,
  130994. 1, -526516224, 1616117760, 4, 0,
  130995. _vq_quantlist__44c0_sm_p7_0,
  130996. NULL,
  130997. &_vq_auxt__44c0_sm_p7_0,
  130998. NULL,
  130999. 0
  131000. };
  131001. static long _vq_quantlist__44c0_sm_p7_1[] = {
  131002. 2,
  131003. 1,
  131004. 3,
  131005. 0,
  131006. 4,
  131007. };
  131008. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  131009. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  131010. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131011. };
  131012. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  131013. -1.5, -0.5, 0.5, 1.5,
  131014. };
  131015. static long _vq_quantmap__44c0_sm_p7_1[] = {
  131016. 3, 1, 0, 2, 4,
  131017. };
  131018. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  131019. _vq_quantthresh__44c0_sm_p7_1,
  131020. _vq_quantmap__44c0_sm_p7_1,
  131021. 5,
  131022. 5
  131023. };
  131024. static static_codebook _44c0_sm_p7_1 = {
  131025. 2, 25,
  131026. _vq_lengthlist__44c0_sm_p7_1,
  131027. 1, -533725184, 1611661312, 3, 0,
  131028. _vq_quantlist__44c0_sm_p7_1,
  131029. NULL,
  131030. &_vq_auxt__44c0_sm_p7_1,
  131031. NULL,
  131032. 0
  131033. };
  131034. static long _vq_quantlist__44c0_sm_p8_0[] = {
  131035. 4,
  131036. 3,
  131037. 5,
  131038. 2,
  131039. 6,
  131040. 1,
  131041. 7,
  131042. 0,
  131043. 8,
  131044. };
  131045. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  131046. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  131047. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  131048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131049. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131051. 12,
  131052. };
  131053. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  131054. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  131055. };
  131056. static long _vq_quantmap__44c0_sm_p8_0[] = {
  131057. 7, 5, 3, 1, 0, 2, 4, 6,
  131058. 8,
  131059. };
  131060. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  131061. _vq_quantthresh__44c0_sm_p8_0,
  131062. _vq_quantmap__44c0_sm_p8_0,
  131063. 9,
  131064. 9
  131065. };
  131066. static static_codebook _44c0_sm_p8_0 = {
  131067. 2, 81,
  131068. _vq_lengthlist__44c0_sm_p8_0,
  131069. 1, -516186112, 1627103232, 4, 0,
  131070. _vq_quantlist__44c0_sm_p8_0,
  131071. NULL,
  131072. &_vq_auxt__44c0_sm_p8_0,
  131073. NULL,
  131074. 0
  131075. };
  131076. static long _vq_quantlist__44c0_sm_p8_1[] = {
  131077. 6,
  131078. 5,
  131079. 7,
  131080. 4,
  131081. 8,
  131082. 3,
  131083. 9,
  131084. 2,
  131085. 10,
  131086. 1,
  131087. 11,
  131088. 0,
  131089. 12,
  131090. };
  131091. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  131092. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  131093. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  131094. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  131095. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  131096. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  131097. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  131098. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  131099. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  131100. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  131101. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  131102. 20,13,13,12,12,16,13,15,13,
  131103. };
  131104. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  131105. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131106. 42.5, 59.5, 76.5, 93.5,
  131107. };
  131108. static long _vq_quantmap__44c0_sm_p8_1[] = {
  131109. 11, 9, 7, 5, 3, 1, 0, 2,
  131110. 4, 6, 8, 10, 12,
  131111. };
  131112. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  131113. _vq_quantthresh__44c0_sm_p8_1,
  131114. _vq_quantmap__44c0_sm_p8_1,
  131115. 13,
  131116. 13
  131117. };
  131118. static static_codebook _44c0_sm_p8_1 = {
  131119. 2, 169,
  131120. _vq_lengthlist__44c0_sm_p8_1,
  131121. 1, -522616832, 1620115456, 4, 0,
  131122. _vq_quantlist__44c0_sm_p8_1,
  131123. NULL,
  131124. &_vq_auxt__44c0_sm_p8_1,
  131125. NULL,
  131126. 0
  131127. };
  131128. static long _vq_quantlist__44c0_sm_p8_2[] = {
  131129. 8,
  131130. 7,
  131131. 9,
  131132. 6,
  131133. 10,
  131134. 5,
  131135. 11,
  131136. 4,
  131137. 12,
  131138. 3,
  131139. 13,
  131140. 2,
  131141. 14,
  131142. 1,
  131143. 15,
  131144. 0,
  131145. 16,
  131146. };
  131147. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  131148. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131149. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  131150. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  131151. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  131152. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131153. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  131154. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  131155. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  131156. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  131157. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  131158. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  131159. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  131161. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  131162. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  131163. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131164. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131165. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  131166. 9,
  131167. };
  131168. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  131169. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131170. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131171. };
  131172. static long _vq_quantmap__44c0_sm_p8_2[] = {
  131173. 15, 13, 11, 9, 7, 5, 3, 1,
  131174. 0, 2, 4, 6, 8, 10, 12, 14,
  131175. 16,
  131176. };
  131177. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  131178. _vq_quantthresh__44c0_sm_p8_2,
  131179. _vq_quantmap__44c0_sm_p8_2,
  131180. 17,
  131181. 17
  131182. };
  131183. static static_codebook _44c0_sm_p8_2 = {
  131184. 2, 289,
  131185. _vq_lengthlist__44c0_sm_p8_2,
  131186. 1, -529530880, 1611661312, 5, 0,
  131187. _vq_quantlist__44c0_sm_p8_2,
  131188. NULL,
  131189. &_vq_auxt__44c0_sm_p8_2,
  131190. NULL,
  131191. 0
  131192. };
  131193. static long _huff_lengthlist__44c0_sm_short[] = {
  131194. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  131195. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  131196. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  131197. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  131198. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  131199. 12,
  131200. };
  131201. static static_codebook _huff_book__44c0_sm_short = {
  131202. 2, 81,
  131203. _huff_lengthlist__44c0_sm_short,
  131204. 0, 0, 0, 0, 0,
  131205. NULL,
  131206. NULL,
  131207. NULL,
  131208. NULL,
  131209. 0
  131210. };
  131211. static long _huff_lengthlist__44c1_s_long[] = {
  131212. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  131213. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  131214. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  131215. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  131216. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  131217. 11,
  131218. };
  131219. static static_codebook _huff_book__44c1_s_long = {
  131220. 2, 81,
  131221. _huff_lengthlist__44c1_s_long,
  131222. 0, 0, 0, 0, 0,
  131223. NULL,
  131224. NULL,
  131225. NULL,
  131226. NULL,
  131227. 0
  131228. };
  131229. static long _vq_quantlist__44c1_s_p1_0[] = {
  131230. 1,
  131231. 0,
  131232. 2,
  131233. };
  131234. static long _vq_lengthlist__44c1_s_p1_0[] = {
  131235. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  131236. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131241. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131246. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131281. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131286. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  131291. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131327. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  131332. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  131337. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0,
  131646. };
  131647. static float _vq_quantthresh__44c1_s_p1_0[] = {
  131648. -0.5, 0.5,
  131649. };
  131650. static long _vq_quantmap__44c1_s_p1_0[] = {
  131651. 1, 0, 2,
  131652. };
  131653. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  131654. _vq_quantthresh__44c1_s_p1_0,
  131655. _vq_quantmap__44c1_s_p1_0,
  131656. 3,
  131657. 3
  131658. };
  131659. static static_codebook _44c1_s_p1_0 = {
  131660. 8, 6561,
  131661. _vq_lengthlist__44c1_s_p1_0,
  131662. 1, -535822336, 1611661312, 2, 0,
  131663. _vq_quantlist__44c1_s_p1_0,
  131664. NULL,
  131665. &_vq_auxt__44c1_s_p1_0,
  131666. NULL,
  131667. 0
  131668. };
  131669. static long _vq_quantlist__44c1_s_p2_0[] = {
  131670. 2,
  131671. 1,
  131672. 3,
  131673. 0,
  131674. 4,
  131675. };
  131676. static long _vq_lengthlist__44c1_s_p2_0[] = {
  131677. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0,
  131717. };
  131718. static float _vq_quantthresh__44c1_s_p2_0[] = {
  131719. -1.5, -0.5, 0.5, 1.5,
  131720. };
  131721. static long _vq_quantmap__44c1_s_p2_0[] = {
  131722. 3, 1, 0, 2, 4,
  131723. };
  131724. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  131725. _vq_quantthresh__44c1_s_p2_0,
  131726. _vq_quantmap__44c1_s_p2_0,
  131727. 5,
  131728. 5
  131729. };
  131730. static static_codebook _44c1_s_p2_0 = {
  131731. 4, 625,
  131732. _vq_lengthlist__44c1_s_p2_0,
  131733. 1, -533725184, 1611661312, 3, 0,
  131734. _vq_quantlist__44c1_s_p2_0,
  131735. NULL,
  131736. &_vq_auxt__44c1_s_p2_0,
  131737. NULL,
  131738. 0
  131739. };
  131740. static long _vq_quantlist__44c1_s_p3_0[] = {
  131741. 4,
  131742. 3,
  131743. 5,
  131744. 2,
  131745. 6,
  131746. 1,
  131747. 7,
  131748. 0,
  131749. 8,
  131750. };
  131751. static long _vq_lengthlist__44c1_s_p3_0[] = {
  131752. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  131753. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131754. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131755. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131756. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0,
  131758. };
  131759. static float _vq_quantthresh__44c1_s_p3_0[] = {
  131760. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131761. };
  131762. static long _vq_quantmap__44c1_s_p3_0[] = {
  131763. 7, 5, 3, 1, 0, 2, 4, 6,
  131764. 8,
  131765. };
  131766. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  131767. _vq_quantthresh__44c1_s_p3_0,
  131768. _vq_quantmap__44c1_s_p3_0,
  131769. 9,
  131770. 9
  131771. };
  131772. static static_codebook _44c1_s_p3_0 = {
  131773. 2, 81,
  131774. _vq_lengthlist__44c1_s_p3_0,
  131775. 1, -531628032, 1611661312, 4, 0,
  131776. _vq_quantlist__44c1_s_p3_0,
  131777. NULL,
  131778. &_vq_auxt__44c1_s_p3_0,
  131779. NULL,
  131780. 0
  131781. };
  131782. static long _vq_quantlist__44c1_s_p4_0[] = {
  131783. 4,
  131784. 3,
  131785. 5,
  131786. 2,
  131787. 6,
  131788. 1,
  131789. 7,
  131790. 0,
  131791. 8,
  131792. };
  131793. static long _vq_lengthlist__44c1_s_p4_0[] = {
  131794. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131795. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131796. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  131797. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131798. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  131799. 11,
  131800. };
  131801. static float _vq_quantthresh__44c1_s_p4_0[] = {
  131802. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131803. };
  131804. static long _vq_quantmap__44c1_s_p4_0[] = {
  131805. 7, 5, 3, 1, 0, 2, 4, 6,
  131806. 8,
  131807. };
  131808. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  131809. _vq_quantthresh__44c1_s_p4_0,
  131810. _vq_quantmap__44c1_s_p4_0,
  131811. 9,
  131812. 9
  131813. };
  131814. static static_codebook _44c1_s_p4_0 = {
  131815. 2, 81,
  131816. _vq_lengthlist__44c1_s_p4_0,
  131817. 1, -531628032, 1611661312, 4, 0,
  131818. _vq_quantlist__44c1_s_p4_0,
  131819. NULL,
  131820. &_vq_auxt__44c1_s_p4_0,
  131821. NULL,
  131822. 0
  131823. };
  131824. static long _vq_quantlist__44c1_s_p5_0[] = {
  131825. 8,
  131826. 7,
  131827. 9,
  131828. 6,
  131829. 10,
  131830. 5,
  131831. 11,
  131832. 4,
  131833. 12,
  131834. 3,
  131835. 13,
  131836. 2,
  131837. 14,
  131838. 1,
  131839. 15,
  131840. 0,
  131841. 16,
  131842. };
  131843. static long _vq_lengthlist__44c1_s_p5_0[] = {
  131844. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131845. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131846. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131847. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131848. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131849. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  131850. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  131851. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131852. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131853. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131854. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131855. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131856. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  131857. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  131858. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  131859. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  131860. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131862. 14,
  131863. };
  131864. static float _vq_quantthresh__44c1_s_p5_0[] = {
  131865. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131866. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131867. };
  131868. static long _vq_quantmap__44c1_s_p5_0[] = {
  131869. 15, 13, 11, 9, 7, 5, 3, 1,
  131870. 0, 2, 4, 6, 8, 10, 12, 14,
  131871. 16,
  131872. };
  131873. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  131874. _vq_quantthresh__44c1_s_p5_0,
  131875. _vq_quantmap__44c1_s_p5_0,
  131876. 17,
  131877. 17
  131878. };
  131879. static static_codebook _44c1_s_p5_0 = {
  131880. 2, 289,
  131881. _vq_lengthlist__44c1_s_p5_0,
  131882. 1, -529530880, 1611661312, 5, 0,
  131883. _vq_quantlist__44c1_s_p5_0,
  131884. NULL,
  131885. &_vq_auxt__44c1_s_p5_0,
  131886. NULL,
  131887. 0
  131888. };
  131889. static long _vq_quantlist__44c1_s_p6_0[] = {
  131890. 1,
  131891. 0,
  131892. 2,
  131893. };
  131894. static long _vq_lengthlist__44c1_s_p6_0[] = {
  131895. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131896. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  131897. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131898. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  131899. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  131900. 11,
  131901. };
  131902. static float _vq_quantthresh__44c1_s_p6_0[] = {
  131903. -5.5, 5.5,
  131904. };
  131905. static long _vq_quantmap__44c1_s_p6_0[] = {
  131906. 1, 0, 2,
  131907. };
  131908. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  131909. _vq_quantthresh__44c1_s_p6_0,
  131910. _vq_quantmap__44c1_s_p6_0,
  131911. 3,
  131912. 3
  131913. };
  131914. static static_codebook _44c1_s_p6_0 = {
  131915. 4, 81,
  131916. _vq_lengthlist__44c1_s_p6_0,
  131917. 1, -529137664, 1618345984, 2, 0,
  131918. _vq_quantlist__44c1_s_p6_0,
  131919. NULL,
  131920. &_vq_auxt__44c1_s_p6_0,
  131921. NULL,
  131922. 0
  131923. };
  131924. static long _vq_quantlist__44c1_s_p6_1[] = {
  131925. 5,
  131926. 4,
  131927. 6,
  131928. 3,
  131929. 7,
  131930. 2,
  131931. 8,
  131932. 1,
  131933. 9,
  131934. 0,
  131935. 10,
  131936. };
  131937. static long _vq_lengthlist__44c1_s_p6_1[] = {
  131938. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  131939. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  131940. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131941. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131942. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131943. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131944. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131945. 10,10,10, 8, 8, 8, 8, 8, 8,
  131946. };
  131947. static float _vq_quantthresh__44c1_s_p6_1[] = {
  131948. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131949. 3.5, 4.5,
  131950. };
  131951. static long _vq_quantmap__44c1_s_p6_1[] = {
  131952. 9, 7, 5, 3, 1, 0, 2, 4,
  131953. 6, 8, 10,
  131954. };
  131955. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  131956. _vq_quantthresh__44c1_s_p6_1,
  131957. _vq_quantmap__44c1_s_p6_1,
  131958. 11,
  131959. 11
  131960. };
  131961. static static_codebook _44c1_s_p6_1 = {
  131962. 2, 121,
  131963. _vq_lengthlist__44c1_s_p6_1,
  131964. 1, -531365888, 1611661312, 4, 0,
  131965. _vq_quantlist__44c1_s_p6_1,
  131966. NULL,
  131967. &_vq_auxt__44c1_s_p6_1,
  131968. NULL,
  131969. 0
  131970. };
  131971. static long _vq_quantlist__44c1_s_p7_0[] = {
  131972. 6,
  131973. 5,
  131974. 7,
  131975. 4,
  131976. 8,
  131977. 3,
  131978. 9,
  131979. 2,
  131980. 10,
  131981. 1,
  131982. 11,
  131983. 0,
  131984. 12,
  131985. };
  131986. static long _vq_lengthlist__44c1_s_p7_0[] = {
  131987. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  131988. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  131989. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131990. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131991. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  131992. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131993. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  131994. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131995. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131996. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  131997. 0,12,11,11,11,13,10,14,13,
  131998. };
  131999. static float _vq_quantthresh__44c1_s_p7_0[] = {
  132000. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132001. 12.5, 17.5, 22.5, 27.5,
  132002. };
  132003. static long _vq_quantmap__44c1_s_p7_0[] = {
  132004. 11, 9, 7, 5, 3, 1, 0, 2,
  132005. 4, 6, 8, 10, 12,
  132006. };
  132007. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  132008. _vq_quantthresh__44c1_s_p7_0,
  132009. _vq_quantmap__44c1_s_p7_0,
  132010. 13,
  132011. 13
  132012. };
  132013. static static_codebook _44c1_s_p7_0 = {
  132014. 2, 169,
  132015. _vq_lengthlist__44c1_s_p7_0,
  132016. 1, -526516224, 1616117760, 4, 0,
  132017. _vq_quantlist__44c1_s_p7_0,
  132018. NULL,
  132019. &_vq_auxt__44c1_s_p7_0,
  132020. NULL,
  132021. 0
  132022. };
  132023. static long _vq_quantlist__44c1_s_p7_1[] = {
  132024. 2,
  132025. 1,
  132026. 3,
  132027. 0,
  132028. 4,
  132029. };
  132030. static long _vq_lengthlist__44c1_s_p7_1[] = {
  132031. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132032. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132033. };
  132034. static float _vq_quantthresh__44c1_s_p7_1[] = {
  132035. -1.5, -0.5, 0.5, 1.5,
  132036. };
  132037. static long _vq_quantmap__44c1_s_p7_1[] = {
  132038. 3, 1, 0, 2, 4,
  132039. };
  132040. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  132041. _vq_quantthresh__44c1_s_p7_1,
  132042. _vq_quantmap__44c1_s_p7_1,
  132043. 5,
  132044. 5
  132045. };
  132046. static static_codebook _44c1_s_p7_1 = {
  132047. 2, 25,
  132048. _vq_lengthlist__44c1_s_p7_1,
  132049. 1, -533725184, 1611661312, 3, 0,
  132050. _vq_quantlist__44c1_s_p7_1,
  132051. NULL,
  132052. &_vq_auxt__44c1_s_p7_1,
  132053. NULL,
  132054. 0
  132055. };
  132056. static long _vq_quantlist__44c1_s_p8_0[] = {
  132057. 6,
  132058. 5,
  132059. 7,
  132060. 4,
  132061. 8,
  132062. 3,
  132063. 9,
  132064. 2,
  132065. 10,
  132066. 1,
  132067. 11,
  132068. 0,
  132069. 12,
  132070. };
  132071. static long _vq_lengthlist__44c1_s_p8_0[] = {
  132072. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  132073. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  132074. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132075. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132076. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132077. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132078. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132079. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132080. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132082. 10,10,10,10,10,10,10,10,10,
  132083. };
  132084. static float _vq_quantthresh__44c1_s_p8_0[] = {
  132085. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  132086. 552.5, 773.5, 994.5, 1215.5,
  132087. };
  132088. static long _vq_quantmap__44c1_s_p8_0[] = {
  132089. 11, 9, 7, 5, 3, 1, 0, 2,
  132090. 4, 6, 8, 10, 12,
  132091. };
  132092. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  132093. _vq_quantthresh__44c1_s_p8_0,
  132094. _vq_quantmap__44c1_s_p8_0,
  132095. 13,
  132096. 13
  132097. };
  132098. static static_codebook _44c1_s_p8_0 = {
  132099. 2, 169,
  132100. _vq_lengthlist__44c1_s_p8_0,
  132101. 1, -514541568, 1627103232, 4, 0,
  132102. _vq_quantlist__44c1_s_p8_0,
  132103. NULL,
  132104. &_vq_auxt__44c1_s_p8_0,
  132105. NULL,
  132106. 0
  132107. };
  132108. static long _vq_quantlist__44c1_s_p8_1[] = {
  132109. 6,
  132110. 5,
  132111. 7,
  132112. 4,
  132113. 8,
  132114. 3,
  132115. 9,
  132116. 2,
  132117. 10,
  132118. 1,
  132119. 11,
  132120. 0,
  132121. 12,
  132122. };
  132123. static long _vq_lengthlist__44c1_s_p8_1[] = {
  132124. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  132125. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132126. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  132127. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  132128. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  132129. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  132130. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  132131. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  132132. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  132133. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  132134. 16,13,12,12,11,14,12,15,13,
  132135. };
  132136. static float _vq_quantthresh__44c1_s_p8_1[] = {
  132137. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132138. 42.5, 59.5, 76.5, 93.5,
  132139. };
  132140. static long _vq_quantmap__44c1_s_p8_1[] = {
  132141. 11, 9, 7, 5, 3, 1, 0, 2,
  132142. 4, 6, 8, 10, 12,
  132143. };
  132144. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  132145. _vq_quantthresh__44c1_s_p8_1,
  132146. _vq_quantmap__44c1_s_p8_1,
  132147. 13,
  132148. 13
  132149. };
  132150. static static_codebook _44c1_s_p8_1 = {
  132151. 2, 169,
  132152. _vq_lengthlist__44c1_s_p8_1,
  132153. 1, -522616832, 1620115456, 4, 0,
  132154. _vq_quantlist__44c1_s_p8_1,
  132155. NULL,
  132156. &_vq_auxt__44c1_s_p8_1,
  132157. NULL,
  132158. 0
  132159. };
  132160. static long _vq_quantlist__44c1_s_p8_2[] = {
  132161. 8,
  132162. 7,
  132163. 9,
  132164. 6,
  132165. 10,
  132166. 5,
  132167. 11,
  132168. 4,
  132169. 12,
  132170. 3,
  132171. 13,
  132172. 2,
  132173. 14,
  132174. 1,
  132175. 15,
  132176. 0,
  132177. 16,
  132178. };
  132179. static long _vq_lengthlist__44c1_s_p8_2[] = {
  132180. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132181. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132182. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132183. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132184. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132185. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132186. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132187. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  132188. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  132189. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  132190. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  132191. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  132192. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  132193. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  132194. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132195. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  132196. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  132197. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  132198. 9,
  132199. };
  132200. static float _vq_quantthresh__44c1_s_p8_2[] = {
  132201. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132202. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132203. };
  132204. static long _vq_quantmap__44c1_s_p8_2[] = {
  132205. 15, 13, 11, 9, 7, 5, 3, 1,
  132206. 0, 2, 4, 6, 8, 10, 12, 14,
  132207. 16,
  132208. };
  132209. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  132210. _vq_quantthresh__44c1_s_p8_2,
  132211. _vq_quantmap__44c1_s_p8_2,
  132212. 17,
  132213. 17
  132214. };
  132215. static static_codebook _44c1_s_p8_2 = {
  132216. 2, 289,
  132217. _vq_lengthlist__44c1_s_p8_2,
  132218. 1, -529530880, 1611661312, 5, 0,
  132219. _vq_quantlist__44c1_s_p8_2,
  132220. NULL,
  132221. &_vq_auxt__44c1_s_p8_2,
  132222. NULL,
  132223. 0
  132224. };
  132225. static long _huff_lengthlist__44c1_s_short[] = {
  132226. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  132227. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  132228. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  132229. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  132230. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  132231. 11,
  132232. };
  132233. static static_codebook _huff_book__44c1_s_short = {
  132234. 2, 81,
  132235. _huff_lengthlist__44c1_s_short,
  132236. 0, 0, 0, 0, 0,
  132237. NULL,
  132238. NULL,
  132239. NULL,
  132240. NULL,
  132241. 0
  132242. };
  132243. static long _huff_lengthlist__44c1_sm_long[] = {
  132244. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  132245. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  132246. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  132247. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  132248. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  132249. 11,
  132250. };
  132251. static static_codebook _huff_book__44c1_sm_long = {
  132252. 2, 81,
  132253. _huff_lengthlist__44c1_sm_long,
  132254. 0, 0, 0, 0, 0,
  132255. NULL,
  132256. NULL,
  132257. NULL,
  132258. NULL,
  132259. 0
  132260. };
  132261. static long _vq_quantlist__44c1_sm_p1_0[] = {
  132262. 1,
  132263. 0,
  132264. 2,
  132265. };
  132266. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  132267. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132268. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132273. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132277. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132278. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  132313. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  132314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132318. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132323. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132358. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  132359. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132363. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132364. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132368. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132369. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  132370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132677. 0,
  132678. };
  132679. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  132680. -0.5, 0.5,
  132681. };
  132682. static long _vq_quantmap__44c1_sm_p1_0[] = {
  132683. 1, 0, 2,
  132684. };
  132685. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  132686. _vq_quantthresh__44c1_sm_p1_0,
  132687. _vq_quantmap__44c1_sm_p1_0,
  132688. 3,
  132689. 3
  132690. };
  132691. static static_codebook _44c1_sm_p1_0 = {
  132692. 8, 6561,
  132693. _vq_lengthlist__44c1_sm_p1_0,
  132694. 1, -535822336, 1611661312, 2, 0,
  132695. _vq_quantlist__44c1_sm_p1_0,
  132696. NULL,
  132697. &_vq_auxt__44c1_sm_p1_0,
  132698. NULL,
  132699. 0
  132700. };
  132701. static long _vq_quantlist__44c1_sm_p2_0[] = {
  132702. 2,
  132703. 1,
  132704. 3,
  132705. 0,
  132706. 4,
  132707. };
  132708. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  132709. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  132711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132712. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  132714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132715. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132748. 0,
  132749. };
  132750. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  132751. -1.5, -0.5, 0.5, 1.5,
  132752. };
  132753. static long _vq_quantmap__44c1_sm_p2_0[] = {
  132754. 3, 1, 0, 2, 4,
  132755. };
  132756. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  132757. _vq_quantthresh__44c1_sm_p2_0,
  132758. _vq_quantmap__44c1_sm_p2_0,
  132759. 5,
  132760. 5
  132761. };
  132762. static static_codebook _44c1_sm_p2_0 = {
  132763. 4, 625,
  132764. _vq_lengthlist__44c1_sm_p2_0,
  132765. 1, -533725184, 1611661312, 3, 0,
  132766. _vq_quantlist__44c1_sm_p2_0,
  132767. NULL,
  132768. &_vq_auxt__44c1_sm_p2_0,
  132769. NULL,
  132770. 0
  132771. };
  132772. static long _vq_quantlist__44c1_sm_p3_0[] = {
  132773. 4,
  132774. 3,
  132775. 5,
  132776. 2,
  132777. 6,
  132778. 1,
  132779. 7,
  132780. 0,
  132781. 8,
  132782. };
  132783. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  132784. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  132785. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  132786. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132787. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132788. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132789. 0,
  132790. };
  132791. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  132792. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132793. };
  132794. static long _vq_quantmap__44c1_sm_p3_0[] = {
  132795. 7, 5, 3, 1, 0, 2, 4, 6,
  132796. 8,
  132797. };
  132798. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  132799. _vq_quantthresh__44c1_sm_p3_0,
  132800. _vq_quantmap__44c1_sm_p3_0,
  132801. 9,
  132802. 9
  132803. };
  132804. static static_codebook _44c1_sm_p3_0 = {
  132805. 2, 81,
  132806. _vq_lengthlist__44c1_sm_p3_0,
  132807. 1, -531628032, 1611661312, 4, 0,
  132808. _vq_quantlist__44c1_sm_p3_0,
  132809. NULL,
  132810. &_vq_auxt__44c1_sm_p3_0,
  132811. NULL,
  132812. 0
  132813. };
  132814. static long _vq_quantlist__44c1_sm_p4_0[] = {
  132815. 4,
  132816. 3,
  132817. 5,
  132818. 2,
  132819. 6,
  132820. 1,
  132821. 7,
  132822. 0,
  132823. 8,
  132824. };
  132825. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  132826. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  132827. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  132828. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  132829. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  132830. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132831. 11,
  132832. };
  132833. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  132834. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132835. };
  132836. static long _vq_quantmap__44c1_sm_p4_0[] = {
  132837. 7, 5, 3, 1, 0, 2, 4, 6,
  132838. 8,
  132839. };
  132840. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  132841. _vq_quantthresh__44c1_sm_p4_0,
  132842. _vq_quantmap__44c1_sm_p4_0,
  132843. 9,
  132844. 9
  132845. };
  132846. static static_codebook _44c1_sm_p4_0 = {
  132847. 2, 81,
  132848. _vq_lengthlist__44c1_sm_p4_0,
  132849. 1, -531628032, 1611661312, 4, 0,
  132850. _vq_quantlist__44c1_sm_p4_0,
  132851. NULL,
  132852. &_vq_auxt__44c1_sm_p4_0,
  132853. NULL,
  132854. 0
  132855. };
  132856. static long _vq_quantlist__44c1_sm_p5_0[] = {
  132857. 8,
  132858. 7,
  132859. 9,
  132860. 6,
  132861. 10,
  132862. 5,
  132863. 11,
  132864. 4,
  132865. 12,
  132866. 3,
  132867. 13,
  132868. 2,
  132869. 14,
  132870. 1,
  132871. 15,
  132872. 0,
  132873. 16,
  132874. };
  132875. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  132876. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132877. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132878. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132879. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132880. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132881. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  132882. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  132883. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132884. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132885. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  132886. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132887. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132888. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  132889. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  132890. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  132891. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  132892. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132894. 14,
  132895. };
  132896. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  132897. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132898. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132899. };
  132900. static long _vq_quantmap__44c1_sm_p5_0[] = {
  132901. 15, 13, 11, 9, 7, 5, 3, 1,
  132902. 0, 2, 4, 6, 8, 10, 12, 14,
  132903. 16,
  132904. };
  132905. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  132906. _vq_quantthresh__44c1_sm_p5_0,
  132907. _vq_quantmap__44c1_sm_p5_0,
  132908. 17,
  132909. 17
  132910. };
  132911. static static_codebook _44c1_sm_p5_0 = {
  132912. 2, 289,
  132913. _vq_lengthlist__44c1_sm_p5_0,
  132914. 1, -529530880, 1611661312, 5, 0,
  132915. _vq_quantlist__44c1_sm_p5_0,
  132916. NULL,
  132917. &_vq_auxt__44c1_sm_p5_0,
  132918. NULL,
  132919. 0
  132920. };
  132921. static long _vq_quantlist__44c1_sm_p6_0[] = {
  132922. 1,
  132923. 0,
  132924. 2,
  132925. };
  132926. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  132927. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132928. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  132929. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  132930. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  132931. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  132932. 11,
  132933. };
  132934. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  132935. -5.5, 5.5,
  132936. };
  132937. static long _vq_quantmap__44c1_sm_p6_0[] = {
  132938. 1, 0, 2,
  132939. };
  132940. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  132941. _vq_quantthresh__44c1_sm_p6_0,
  132942. _vq_quantmap__44c1_sm_p6_0,
  132943. 3,
  132944. 3
  132945. };
  132946. static static_codebook _44c1_sm_p6_0 = {
  132947. 4, 81,
  132948. _vq_lengthlist__44c1_sm_p6_0,
  132949. 1, -529137664, 1618345984, 2, 0,
  132950. _vq_quantlist__44c1_sm_p6_0,
  132951. NULL,
  132952. &_vq_auxt__44c1_sm_p6_0,
  132953. NULL,
  132954. 0
  132955. };
  132956. static long _vq_quantlist__44c1_sm_p6_1[] = {
  132957. 5,
  132958. 4,
  132959. 6,
  132960. 3,
  132961. 7,
  132962. 2,
  132963. 8,
  132964. 1,
  132965. 9,
  132966. 0,
  132967. 10,
  132968. };
  132969. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  132970. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  132971. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132972. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132973. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132974. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132975. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  132976. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132977. 10,10,10, 8, 8, 8, 8, 8, 8,
  132978. };
  132979. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  132980. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132981. 3.5, 4.5,
  132982. };
  132983. static long _vq_quantmap__44c1_sm_p6_1[] = {
  132984. 9, 7, 5, 3, 1, 0, 2, 4,
  132985. 6, 8, 10,
  132986. };
  132987. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  132988. _vq_quantthresh__44c1_sm_p6_1,
  132989. _vq_quantmap__44c1_sm_p6_1,
  132990. 11,
  132991. 11
  132992. };
  132993. static static_codebook _44c1_sm_p6_1 = {
  132994. 2, 121,
  132995. _vq_lengthlist__44c1_sm_p6_1,
  132996. 1, -531365888, 1611661312, 4, 0,
  132997. _vq_quantlist__44c1_sm_p6_1,
  132998. NULL,
  132999. &_vq_auxt__44c1_sm_p6_1,
  133000. NULL,
  133001. 0
  133002. };
  133003. static long _vq_quantlist__44c1_sm_p7_0[] = {
  133004. 6,
  133005. 5,
  133006. 7,
  133007. 4,
  133008. 8,
  133009. 3,
  133010. 9,
  133011. 2,
  133012. 10,
  133013. 1,
  133014. 11,
  133015. 0,
  133016. 12,
  133017. };
  133018. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  133019. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133020. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133021. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133022. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133023. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133024. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  133025. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  133026. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133027. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133028. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  133029. 0,12,12,11,11,13,12,14,13,
  133030. };
  133031. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  133032. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133033. 12.5, 17.5, 22.5, 27.5,
  133034. };
  133035. static long _vq_quantmap__44c1_sm_p7_0[] = {
  133036. 11, 9, 7, 5, 3, 1, 0, 2,
  133037. 4, 6, 8, 10, 12,
  133038. };
  133039. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  133040. _vq_quantthresh__44c1_sm_p7_0,
  133041. _vq_quantmap__44c1_sm_p7_0,
  133042. 13,
  133043. 13
  133044. };
  133045. static static_codebook _44c1_sm_p7_0 = {
  133046. 2, 169,
  133047. _vq_lengthlist__44c1_sm_p7_0,
  133048. 1, -526516224, 1616117760, 4, 0,
  133049. _vq_quantlist__44c1_sm_p7_0,
  133050. NULL,
  133051. &_vq_auxt__44c1_sm_p7_0,
  133052. NULL,
  133053. 0
  133054. };
  133055. static long _vq_quantlist__44c1_sm_p7_1[] = {
  133056. 2,
  133057. 1,
  133058. 3,
  133059. 0,
  133060. 4,
  133061. };
  133062. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  133063. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133064. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133065. };
  133066. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  133067. -1.5, -0.5, 0.5, 1.5,
  133068. };
  133069. static long _vq_quantmap__44c1_sm_p7_1[] = {
  133070. 3, 1, 0, 2, 4,
  133071. };
  133072. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  133073. _vq_quantthresh__44c1_sm_p7_1,
  133074. _vq_quantmap__44c1_sm_p7_1,
  133075. 5,
  133076. 5
  133077. };
  133078. static static_codebook _44c1_sm_p7_1 = {
  133079. 2, 25,
  133080. _vq_lengthlist__44c1_sm_p7_1,
  133081. 1, -533725184, 1611661312, 3, 0,
  133082. _vq_quantlist__44c1_sm_p7_1,
  133083. NULL,
  133084. &_vq_auxt__44c1_sm_p7_1,
  133085. NULL,
  133086. 0
  133087. };
  133088. static long _vq_quantlist__44c1_sm_p8_0[] = {
  133089. 6,
  133090. 5,
  133091. 7,
  133092. 4,
  133093. 8,
  133094. 3,
  133095. 9,
  133096. 2,
  133097. 10,
  133098. 1,
  133099. 11,
  133100. 0,
  133101. 12,
  133102. };
  133103. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  133104. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  133105. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  133106. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133107. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133108. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133109. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133110. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133111. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133112. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133113. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133114. 13,13,13,13,13,13,13,13,13,
  133115. };
  133116. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  133117. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133118. 552.5, 773.5, 994.5, 1215.5,
  133119. };
  133120. static long _vq_quantmap__44c1_sm_p8_0[] = {
  133121. 11, 9, 7, 5, 3, 1, 0, 2,
  133122. 4, 6, 8, 10, 12,
  133123. };
  133124. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  133125. _vq_quantthresh__44c1_sm_p8_0,
  133126. _vq_quantmap__44c1_sm_p8_0,
  133127. 13,
  133128. 13
  133129. };
  133130. static static_codebook _44c1_sm_p8_0 = {
  133131. 2, 169,
  133132. _vq_lengthlist__44c1_sm_p8_0,
  133133. 1, -514541568, 1627103232, 4, 0,
  133134. _vq_quantlist__44c1_sm_p8_0,
  133135. NULL,
  133136. &_vq_auxt__44c1_sm_p8_0,
  133137. NULL,
  133138. 0
  133139. };
  133140. static long _vq_quantlist__44c1_sm_p8_1[] = {
  133141. 6,
  133142. 5,
  133143. 7,
  133144. 4,
  133145. 8,
  133146. 3,
  133147. 9,
  133148. 2,
  133149. 10,
  133150. 1,
  133151. 11,
  133152. 0,
  133153. 12,
  133154. };
  133155. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  133156. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133157. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  133158. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  133159. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  133160. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  133161. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  133162. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  133163. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  133164. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  133165. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  133166. 20,13,12,12,12,14,12,14,13,
  133167. };
  133168. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  133169. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133170. 42.5, 59.5, 76.5, 93.5,
  133171. };
  133172. static long _vq_quantmap__44c1_sm_p8_1[] = {
  133173. 11, 9, 7, 5, 3, 1, 0, 2,
  133174. 4, 6, 8, 10, 12,
  133175. };
  133176. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  133177. _vq_quantthresh__44c1_sm_p8_1,
  133178. _vq_quantmap__44c1_sm_p8_1,
  133179. 13,
  133180. 13
  133181. };
  133182. static static_codebook _44c1_sm_p8_1 = {
  133183. 2, 169,
  133184. _vq_lengthlist__44c1_sm_p8_1,
  133185. 1, -522616832, 1620115456, 4, 0,
  133186. _vq_quantlist__44c1_sm_p8_1,
  133187. NULL,
  133188. &_vq_auxt__44c1_sm_p8_1,
  133189. NULL,
  133190. 0
  133191. };
  133192. static long _vq_quantlist__44c1_sm_p8_2[] = {
  133193. 8,
  133194. 7,
  133195. 9,
  133196. 6,
  133197. 10,
  133198. 5,
  133199. 11,
  133200. 4,
  133201. 12,
  133202. 3,
  133203. 13,
  133204. 2,
  133205. 14,
  133206. 1,
  133207. 15,
  133208. 0,
  133209. 16,
  133210. };
  133211. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  133212. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133213. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133214. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133215. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133216. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133217. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133218. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133219. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133220. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  133221. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133222. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  133223. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  133224. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  133225. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  133226. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133227. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  133228. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133229. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  133230. 9,
  133231. };
  133232. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  133233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133235. };
  133236. static long _vq_quantmap__44c1_sm_p8_2[] = {
  133237. 15, 13, 11, 9, 7, 5, 3, 1,
  133238. 0, 2, 4, 6, 8, 10, 12, 14,
  133239. 16,
  133240. };
  133241. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  133242. _vq_quantthresh__44c1_sm_p8_2,
  133243. _vq_quantmap__44c1_sm_p8_2,
  133244. 17,
  133245. 17
  133246. };
  133247. static static_codebook _44c1_sm_p8_2 = {
  133248. 2, 289,
  133249. _vq_lengthlist__44c1_sm_p8_2,
  133250. 1, -529530880, 1611661312, 5, 0,
  133251. _vq_quantlist__44c1_sm_p8_2,
  133252. NULL,
  133253. &_vq_auxt__44c1_sm_p8_2,
  133254. NULL,
  133255. 0
  133256. };
  133257. static long _huff_lengthlist__44c1_sm_short[] = {
  133258. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  133259. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  133260. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  133261. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  133262. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  133263. 11,
  133264. };
  133265. static static_codebook _huff_book__44c1_sm_short = {
  133266. 2, 81,
  133267. _huff_lengthlist__44c1_sm_short,
  133268. 0, 0, 0, 0, 0,
  133269. NULL,
  133270. NULL,
  133271. NULL,
  133272. NULL,
  133273. 0
  133274. };
  133275. static long _huff_lengthlist__44cn1_s_long[] = {
  133276. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  133277. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  133278. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  133279. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  133280. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  133281. 20,
  133282. };
  133283. static static_codebook _huff_book__44cn1_s_long = {
  133284. 2, 81,
  133285. _huff_lengthlist__44cn1_s_long,
  133286. 0, 0, 0, 0, 0,
  133287. NULL,
  133288. NULL,
  133289. NULL,
  133290. NULL,
  133291. 0
  133292. };
  133293. static long _vq_quantlist__44cn1_s_p1_0[] = {
  133294. 1,
  133295. 0,
  133296. 2,
  133297. };
  133298. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  133299. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133300. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  133305. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133309. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  133310. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  133345. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  133350. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  133355. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  133356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  133391. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  133396. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133400. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  133401. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  133402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133709. 0,
  133710. };
  133711. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  133712. -0.5, 0.5,
  133713. };
  133714. static long _vq_quantmap__44cn1_s_p1_0[] = {
  133715. 1, 0, 2,
  133716. };
  133717. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  133718. _vq_quantthresh__44cn1_s_p1_0,
  133719. _vq_quantmap__44cn1_s_p1_0,
  133720. 3,
  133721. 3
  133722. };
  133723. static static_codebook _44cn1_s_p1_0 = {
  133724. 8, 6561,
  133725. _vq_lengthlist__44cn1_s_p1_0,
  133726. 1, -535822336, 1611661312, 2, 0,
  133727. _vq_quantlist__44cn1_s_p1_0,
  133728. NULL,
  133729. &_vq_auxt__44cn1_s_p1_0,
  133730. NULL,
  133731. 0
  133732. };
  133733. static long _vq_quantlist__44cn1_s_p2_0[] = {
  133734. 2,
  133735. 1,
  133736. 3,
  133737. 0,
  133738. 4,
  133739. };
  133740. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  133741. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133744. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133747. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133780. 0,
  133781. };
  133782. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  133783. -1.5, -0.5, 0.5, 1.5,
  133784. };
  133785. static long _vq_quantmap__44cn1_s_p2_0[] = {
  133786. 3, 1, 0, 2, 4,
  133787. };
  133788. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  133789. _vq_quantthresh__44cn1_s_p2_0,
  133790. _vq_quantmap__44cn1_s_p2_0,
  133791. 5,
  133792. 5
  133793. };
  133794. static static_codebook _44cn1_s_p2_0 = {
  133795. 4, 625,
  133796. _vq_lengthlist__44cn1_s_p2_0,
  133797. 1, -533725184, 1611661312, 3, 0,
  133798. _vq_quantlist__44cn1_s_p2_0,
  133799. NULL,
  133800. &_vq_auxt__44cn1_s_p2_0,
  133801. NULL,
  133802. 0
  133803. };
  133804. static long _vq_quantlist__44cn1_s_p3_0[] = {
  133805. 4,
  133806. 3,
  133807. 5,
  133808. 2,
  133809. 6,
  133810. 1,
  133811. 7,
  133812. 0,
  133813. 8,
  133814. };
  133815. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  133816. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  133817. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133818. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133819. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133820. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133821. 0,
  133822. };
  133823. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  133824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133825. };
  133826. static long _vq_quantmap__44cn1_s_p3_0[] = {
  133827. 7, 5, 3, 1, 0, 2, 4, 6,
  133828. 8,
  133829. };
  133830. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  133831. _vq_quantthresh__44cn1_s_p3_0,
  133832. _vq_quantmap__44cn1_s_p3_0,
  133833. 9,
  133834. 9
  133835. };
  133836. static static_codebook _44cn1_s_p3_0 = {
  133837. 2, 81,
  133838. _vq_lengthlist__44cn1_s_p3_0,
  133839. 1, -531628032, 1611661312, 4, 0,
  133840. _vq_quantlist__44cn1_s_p3_0,
  133841. NULL,
  133842. &_vq_auxt__44cn1_s_p3_0,
  133843. NULL,
  133844. 0
  133845. };
  133846. static long _vq_quantlist__44cn1_s_p4_0[] = {
  133847. 4,
  133848. 3,
  133849. 5,
  133850. 2,
  133851. 6,
  133852. 1,
  133853. 7,
  133854. 0,
  133855. 8,
  133856. };
  133857. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  133858. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  133859. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133860. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  133861. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  133862. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  133863. 11,
  133864. };
  133865. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  133866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133867. };
  133868. static long _vq_quantmap__44cn1_s_p4_0[] = {
  133869. 7, 5, 3, 1, 0, 2, 4, 6,
  133870. 8,
  133871. };
  133872. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  133873. _vq_quantthresh__44cn1_s_p4_0,
  133874. _vq_quantmap__44cn1_s_p4_0,
  133875. 9,
  133876. 9
  133877. };
  133878. static static_codebook _44cn1_s_p4_0 = {
  133879. 2, 81,
  133880. _vq_lengthlist__44cn1_s_p4_0,
  133881. 1, -531628032, 1611661312, 4, 0,
  133882. _vq_quantlist__44cn1_s_p4_0,
  133883. NULL,
  133884. &_vq_auxt__44cn1_s_p4_0,
  133885. NULL,
  133886. 0
  133887. };
  133888. static long _vq_quantlist__44cn1_s_p5_0[] = {
  133889. 8,
  133890. 7,
  133891. 9,
  133892. 6,
  133893. 10,
  133894. 5,
  133895. 11,
  133896. 4,
  133897. 12,
  133898. 3,
  133899. 13,
  133900. 2,
  133901. 14,
  133902. 1,
  133903. 15,
  133904. 0,
  133905. 16,
  133906. };
  133907. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  133908. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  133909. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133910. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133911. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133912. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133913. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  133914. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  133915. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  133916. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133917. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  133918. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133919. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133920. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  133921. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133922. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  133923. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  133924. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  133926. 14,
  133927. };
  133928. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  133929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133931. };
  133932. static long _vq_quantmap__44cn1_s_p5_0[] = {
  133933. 15, 13, 11, 9, 7, 5, 3, 1,
  133934. 0, 2, 4, 6, 8, 10, 12, 14,
  133935. 16,
  133936. };
  133937. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  133938. _vq_quantthresh__44cn1_s_p5_0,
  133939. _vq_quantmap__44cn1_s_p5_0,
  133940. 17,
  133941. 17
  133942. };
  133943. static static_codebook _44cn1_s_p5_0 = {
  133944. 2, 289,
  133945. _vq_lengthlist__44cn1_s_p5_0,
  133946. 1, -529530880, 1611661312, 5, 0,
  133947. _vq_quantlist__44cn1_s_p5_0,
  133948. NULL,
  133949. &_vq_auxt__44cn1_s_p5_0,
  133950. NULL,
  133951. 0
  133952. };
  133953. static long _vq_quantlist__44cn1_s_p6_0[] = {
  133954. 1,
  133955. 0,
  133956. 2,
  133957. };
  133958. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  133959. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  133960. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  133961. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  133962. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  133963. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  133964. 10,
  133965. };
  133966. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  133967. -5.5, 5.5,
  133968. };
  133969. static long _vq_quantmap__44cn1_s_p6_0[] = {
  133970. 1, 0, 2,
  133971. };
  133972. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  133973. _vq_quantthresh__44cn1_s_p6_0,
  133974. _vq_quantmap__44cn1_s_p6_0,
  133975. 3,
  133976. 3
  133977. };
  133978. static static_codebook _44cn1_s_p6_0 = {
  133979. 4, 81,
  133980. _vq_lengthlist__44cn1_s_p6_0,
  133981. 1, -529137664, 1618345984, 2, 0,
  133982. _vq_quantlist__44cn1_s_p6_0,
  133983. NULL,
  133984. &_vq_auxt__44cn1_s_p6_0,
  133985. NULL,
  133986. 0
  133987. };
  133988. static long _vq_quantlist__44cn1_s_p6_1[] = {
  133989. 5,
  133990. 4,
  133991. 6,
  133992. 3,
  133993. 7,
  133994. 2,
  133995. 8,
  133996. 1,
  133997. 9,
  133998. 0,
  133999. 10,
  134000. };
  134001. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  134002. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  134003. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  134004. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134005. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  134006. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  134007. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134008. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  134009. 10,10,10, 9, 9, 9, 9, 9, 9,
  134010. };
  134011. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  134012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134013. 3.5, 4.5,
  134014. };
  134015. static long _vq_quantmap__44cn1_s_p6_1[] = {
  134016. 9, 7, 5, 3, 1, 0, 2, 4,
  134017. 6, 8, 10,
  134018. };
  134019. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  134020. _vq_quantthresh__44cn1_s_p6_1,
  134021. _vq_quantmap__44cn1_s_p6_1,
  134022. 11,
  134023. 11
  134024. };
  134025. static static_codebook _44cn1_s_p6_1 = {
  134026. 2, 121,
  134027. _vq_lengthlist__44cn1_s_p6_1,
  134028. 1, -531365888, 1611661312, 4, 0,
  134029. _vq_quantlist__44cn1_s_p6_1,
  134030. NULL,
  134031. &_vq_auxt__44cn1_s_p6_1,
  134032. NULL,
  134033. 0
  134034. };
  134035. static long _vq_quantlist__44cn1_s_p7_0[] = {
  134036. 6,
  134037. 5,
  134038. 7,
  134039. 4,
  134040. 8,
  134041. 3,
  134042. 9,
  134043. 2,
  134044. 10,
  134045. 1,
  134046. 11,
  134047. 0,
  134048. 12,
  134049. };
  134050. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  134051. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134052. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  134053. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134054. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134055. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  134056. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  134057. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  134058. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  134059. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  134060. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  134061. 0,13,13,12,12,13,13,13,14,
  134062. };
  134063. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  134064. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134065. 12.5, 17.5, 22.5, 27.5,
  134066. };
  134067. static long _vq_quantmap__44cn1_s_p7_0[] = {
  134068. 11, 9, 7, 5, 3, 1, 0, 2,
  134069. 4, 6, 8, 10, 12,
  134070. };
  134071. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  134072. _vq_quantthresh__44cn1_s_p7_0,
  134073. _vq_quantmap__44cn1_s_p7_0,
  134074. 13,
  134075. 13
  134076. };
  134077. static static_codebook _44cn1_s_p7_0 = {
  134078. 2, 169,
  134079. _vq_lengthlist__44cn1_s_p7_0,
  134080. 1, -526516224, 1616117760, 4, 0,
  134081. _vq_quantlist__44cn1_s_p7_0,
  134082. NULL,
  134083. &_vq_auxt__44cn1_s_p7_0,
  134084. NULL,
  134085. 0
  134086. };
  134087. static long _vq_quantlist__44cn1_s_p7_1[] = {
  134088. 2,
  134089. 1,
  134090. 3,
  134091. 0,
  134092. 4,
  134093. };
  134094. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  134095. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134096. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134097. };
  134098. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  134099. -1.5, -0.5, 0.5, 1.5,
  134100. };
  134101. static long _vq_quantmap__44cn1_s_p7_1[] = {
  134102. 3, 1, 0, 2, 4,
  134103. };
  134104. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  134105. _vq_quantthresh__44cn1_s_p7_1,
  134106. _vq_quantmap__44cn1_s_p7_1,
  134107. 5,
  134108. 5
  134109. };
  134110. static static_codebook _44cn1_s_p7_1 = {
  134111. 2, 25,
  134112. _vq_lengthlist__44cn1_s_p7_1,
  134113. 1, -533725184, 1611661312, 3, 0,
  134114. _vq_quantlist__44cn1_s_p7_1,
  134115. NULL,
  134116. &_vq_auxt__44cn1_s_p7_1,
  134117. NULL,
  134118. 0
  134119. };
  134120. static long _vq_quantlist__44cn1_s_p8_0[] = {
  134121. 2,
  134122. 1,
  134123. 3,
  134124. 0,
  134125. 4,
  134126. };
  134127. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  134128. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  134129. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  134130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134131. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  134132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134135. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  134136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134137. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  134138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  134139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134140. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134143. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  134144. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134161. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  134162. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134163. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134164. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134165. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134166. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134167. 12,
  134168. };
  134169. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  134170. -331.5, -110.5, 110.5, 331.5,
  134171. };
  134172. static long _vq_quantmap__44cn1_s_p8_0[] = {
  134173. 3, 1, 0, 2, 4,
  134174. };
  134175. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  134176. _vq_quantthresh__44cn1_s_p8_0,
  134177. _vq_quantmap__44cn1_s_p8_0,
  134178. 5,
  134179. 5
  134180. };
  134181. static static_codebook _44cn1_s_p8_0 = {
  134182. 4, 625,
  134183. _vq_lengthlist__44cn1_s_p8_0,
  134184. 1, -518283264, 1627103232, 3, 0,
  134185. _vq_quantlist__44cn1_s_p8_0,
  134186. NULL,
  134187. &_vq_auxt__44cn1_s_p8_0,
  134188. NULL,
  134189. 0
  134190. };
  134191. static long _vq_quantlist__44cn1_s_p8_1[] = {
  134192. 6,
  134193. 5,
  134194. 7,
  134195. 4,
  134196. 8,
  134197. 3,
  134198. 9,
  134199. 2,
  134200. 10,
  134201. 1,
  134202. 11,
  134203. 0,
  134204. 12,
  134205. };
  134206. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  134207. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  134208. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  134209. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  134210. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  134211. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  134212. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  134213. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  134214. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  134215. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  134216. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  134217. 15,12,12,11,11,14,12,13,14,
  134218. };
  134219. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  134220. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134221. 42.5, 59.5, 76.5, 93.5,
  134222. };
  134223. static long _vq_quantmap__44cn1_s_p8_1[] = {
  134224. 11, 9, 7, 5, 3, 1, 0, 2,
  134225. 4, 6, 8, 10, 12,
  134226. };
  134227. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  134228. _vq_quantthresh__44cn1_s_p8_1,
  134229. _vq_quantmap__44cn1_s_p8_1,
  134230. 13,
  134231. 13
  134232. };
  134233. static static_codebook _44cn1_s_p8_1 = {
  134234. 2, 169,
  134235. _vq_lengthlist__44cn1_s_p8_1,
  134236. 1, -522616832, 1620115456, 4, 0,
  134237. _vq_quantlist__44cn1_s_p8_1,
  134238. NULL,
  134239. &_vq_auxt__44cn1_s_p8_1,
  134240. NULL,
  134241. 0
  134242. };
  134243. static long _vq_quantlist__44cn1_s_p8_2[] = {
  134244. 8,
  134245. 7,
  134246. 9,
  134247. 6,
  134248. 10,
  134249. 5,
  134250. 11,
  134251. 4,
  134252. 12,
  134253. 3,
  134254. 13,
  134255. 2,
  134256. 14,
  134257. 1,
  134258. 15,
  134259. 0,
  134260. 16,
  134261. };
  134262. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  134263. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  134264. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134265. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134266. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  134267. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  134268. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  134269. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  134270. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  134271. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  134272. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  134273. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  134274. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  134276. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  134277. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  134278. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134279. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134280. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  134281. 9,
  134282. };
  134283. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  134284. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134285. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134286. };
  134287. static long _vq_quantmap__44cn1_s_p8_2[] = {
  134288. 15, 13, 11, 9, 7, 5, 3, 1,
  134289. 0, 2, 4, 6, 8, 10, 12, 14,
  134290. 16,
  134291. };
  134292. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  134293. _vq_quantthresh__44cn1_s_p8_2,
  134294. _vq_quantmap__44cn1_s_p8_2,
  134295. 17,
  134296. 17
  134297. };
  134298. static static_codebook _44cn1_s_p8_2 = {
  134299. 2, 289,
  134300. _vq_lengthlist__44cn1_s_p8_2,
  134301. 1, -529530880, 1611661312, 5, 0,
  134302. _vq_quantlist__44cn1_s_p8_2,
  134303. NULL,
  134304. &_vq_auxt__44cn1_s_p8_2,
  134305. NULL,
  134306. 0
  134307. };
  134308. static long _huff_lengthlist__44cn1_s_short[] = {
  134309. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  134310. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  134311. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  134312. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  134313. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  134314. 10,
  134315. };
  134316. static static_codebook _huff_book__44cn1_s_short = {
  134317. 2, 81,
  134318. _huff_lengthlist__44cn1_s_short,
  134319. 0, 0, 0, 0, 0,
  134320. NULL,
  134321. NULL,
  134322. NULL,
  134323. NULL,
  134324. 0
  134325. };
  134326. static long _huff_lengthlist__44cn1_sm_long[] = {
  134327. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  134328. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  134329. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  134330. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  134331. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  134332. 17,
  134333. };
  134334. static static_codebook _huff_book__44cn1_sm_long = {
  134335. 2, 81,
  134336. _huff_lengthlist__44cn1_sm_long,
  134337. 0, 0, 0, 0, 0,
  134338. NULL,
  134339. NULL,
  134340. NULL,
  134341. NULL,
  134342. 0
  134343. };
  134344. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  134345. 1,
  134346. 0,
  134347. 2,
  134348. };
  134349. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  134350. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134351. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134356. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134361. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  134396. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  134401. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134406. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134441. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134442. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134447. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  134452. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134760. 0,
  134761. };
  134762. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  134763. -0.5, 0.5,
  134764. };
  134765. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  134766. 1, 0, 2,
  134767. };
  134768. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  134769. _vq_quantthresh__44cn1_sm_p1_0,
  134770. _vq_quantmap__44cn1_sm_p1_0,
  134771. 3,
  134772. 3
  134773. };
  134774. static static_codebook _44cn1_sm_p1_0 = {
  134775. 8, 6561,
  134776. _vq_lengthlist__44cn1_sm_p1_0,
  134777. 1, -535822336, 1611661312, 2, 0,
  134778. _vq_quantlist__44cn1_sm_p1_0,
  134779. NULL,
  134780. &_vq_auxt__44cn1_sm_p1_0,
  134781. NULL,
  134782. 0
  134783. };
  134784. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  134785. 2,
  134786. 1,
  134787. 3,
  134788. 0,
  134789. 4,
  134790. };
  134791. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  134792. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0,
  134832. };
  134833. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  134834. -1.5, -0.5, 0.5, 1.5,
  134835. };
  134836. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  134837. 3, 1, 0, 2, 4,
  134838. };
  134839. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  134840. _vq_quantthresh__44cn1_sm_p2_0,
  134841. _vq_quantmap__44cn1_sm_p2_0,
  134842. 5,
  134843. 5
  134844. };
  134845. static static_codebook _44cn1_sm_p2_0 = {
  134846. 4, 625,
  134847. _vq_lengthlist__44cn1_sm_p2_0,
  134848. 1, -533725184, 1611661312, 3, 0,
  134849. _vq_quantlist__44cn1_sm_p2_0,
  134850. NULL,
  134851. &_vq_auxt__44cn1_sm_p2_0,
  134852. NULL,
  134853. 0
  134854. };
  134855. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  134856. 4,
  134857. 3,
  134858. 5,
  134859. 2,
  134860. 6,
  134861. 1,
  134862. 7,
  134863. 0,
  134864. 8,
  134865. };
  134866. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  134867. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  134868. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  134869. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134870. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  134871. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0,
  134873. };
  134874. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  134875. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134876. };
  134877. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  134878. 7, 5, 3, 1, 0, 2, 4, 6,
  134879. 8,
  134880. };
  134881. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  134882. _vq_quantthresh__44cn1_sm_p3_0,
  134883. _vq_quantmap__44cn1_sm_p3_0,
  134884. 9,
  134885. 9
  134886. };
  134887. static static_codebook _44cn1_sm_p3_0 = {
  134888. 2, 81,
  134889. _vq_lengthlist__44cn1_sm_p3_0,
  134890. 1, -531628032, 1611661312, 4, 0,
  134891. _vq_quantlist__44cn1_sm_p3_0,
  134892. NULL,
  134893. &_vq_auxt__44cn1_sm_p3_0,
  134894. NULL,
  134895. 0
  134896. };
  134897. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  134898. 4,
  134899. 3,
  134900. 5,
  134901. 2,
  134902. 6,
  134903. 1,
  134904. 7,
  134905. 0,
  134906. 8,
  134907. };
  134908. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  134909. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  134910. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134911. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134912. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  134913. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  134914. 11,
  134915. };
  134916. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  134917. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134918. };
  134919. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  134920. 7, 5, 3, 1, 0, 2, 4, 6,
  134921. 8,
  134922. };
  134923. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  134924. _vq_quantthresh__44cn1_sm_p4_0,
  134925. _vq_quantmap__44cn1_sm_p4_0,
  134926. 9,
  134927. 9
  134928. };
  134929. static static_codebook _44cn1_sm_p4_0 = {
  134930. 2, 81,
  134931. _vq_lengthlist__44cn1_sm_p4_0,
  134932. 1, -531628032, 1611661312, 4, 0,
  134933. _vq_quantlist__44cn1_sm_p4_0,
  134934. NULL,
  134935. &_vq_auxt__44cn1_sm_p4_0,
  134936. NULL,
  134937. 0
  134938. };
  134939. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  134940. 8,
  134941. 7,
  134942. 9,
  134943. 6,
  134944. 10,
  134945. 5,
  134946. 11,
  134947. 4,
  134948. 12,
  134949. 3,
  134950. 13,
  134951. 2,
  134952. 14,
  134953. 1,
  134954. 15,
  134955. 0,
  134956. 16,
  134957. };
  134958. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  134959. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  134960. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  134961. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  134962. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134963. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  134964. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  134965. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  134966. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134967. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  134968. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134969. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  134970. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  134971. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  134972. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  134973. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  134974. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  134975. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  134977. 14,
  134978. };
  134979. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  134980. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134981. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134982. };
  134983. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  134984. 15, 13, 11, 9, 7, 5, 3, 1,
  134985. 0, 2, 4, 6, 8, 10, 12, 14,
  134986. 16,
  134987. };
  134988. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  134989. _vq_quantthresh__44cn1_sm_p5_0,
  134990. _vq_quantmap__44cn1_sm_p5_0,
  134991. 17,
  134992. 17
  134993. };
  134994. static static_codebook _44cn1_sm_p5_0 = {
  134995. 2, 289,
  134996. _vq_lengthlist__44cn1_sm_p5_0,
  134997. 1, -529530880, 1611661312, 5, 0,
  134998. _vq_quantlist__44cn1_sm_p5_0,
  134999. NULL,
  135000. &_vq_auxt__44cn1_sm_p5_0,
  135001. NULL,
  135002. 0
  135003. };
  135004. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  135005. 1,
  135006. 0,
  135007. 2,
  135008. };
  135009. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  135010. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  135011. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135012. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135013. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  135014. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  135015. 10,
  135016. };
  135017. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  135018. -5.5, 5.5,
  135019. };
  135020. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  135021. 1, 0, 2,
  135022. };
  135023. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  135024. _vq_quantthresh__44cn1_sm_p6_0,
  135025. _vq_quantmap__44cn1_sm_p6_0,
  135026. 3,
  135027. 3
  135028. };
  135029. static static_codebook _44cn1_sm_p6_0 = {
  135030. 4, 81,
  135031. _vq_lengthlist__44cn1_sm_p6_0,
  135032. 1, -529137664, 1618345984, 2, 0,
  135033. _vq_quantlist__44cn1_sm_p6_0,
  135034. NULL,
  135035. &_vq_auxt__44cn1_sm_p6_0,
  135036. NULL,
  135037. 0
  135038. };
  135039. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  135040. 5,
  135041. 4,
  135042. 6,
  135043. 3,
  135044. 7,
  135045. 2,
  135046. 8,
  135047. 1,
  135048. 9,
  135049. 0,
  135050. 10,
  135051. };
  135052. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  135053. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135054. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135055. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135056. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  135057. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  135058. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  135059. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  135060. 10,10,10, 8, 9, 8, 8, 9, 8,
  135061. };
  135062. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  135063. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135064. 3.5, 4.5,
  135065. };
  135066. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  135067. 9, 7, 5, 3, 1, 0, 2, 4,
  135068. 6, 8, 10,
  135069. };
  135070. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  135071. _vq_quantthresh__44cn1_sm_p6_1,
  135072. _vq_quantmap__44cn1_sm_p6_1,
  135073. 11,
  135074. 11
  135075. };
  135076. static static_codebook _44cn1_sm_p6_1 = {
  135077. 2, 121,
  135078. _vq_lengthlist__44cn1_sm_p6_1,
  135079. 1, -531365888, 1611661312, 4, 0,
  135080. _vq_quantlist__44cn1_sm_p6_1,
  135081. NULL,
  135082. &_vq_auxt__44cn1_sm_p6_1,
  135083. NULL,
  135084. 0
  135085. };
  135086. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  135087. 6,
  135088. 5,
  135089. 7,
  135090. 4,
  135091. 8,
  135092. 3,
  135093. 9,
  135094. 2,
  135095. 10,
  135096. 1,
  135097. 11,
  135098. 0,
  135099. 12,
  135100. };
  135101. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  135102. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  135103. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  135104. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135105. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135106. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  135107. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  135108. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135109. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  135110. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  135111. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  135112. 0,13,12,12,12,13,13,13,14,
  135113. };
  135114. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  135115. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135116. 12.5, 17.5, 22.5, 27.5,
  135117. };
  135118. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  135119. 11, 9, 7, 5, 3, 1, 0, 2,
  135120. 4, 6, 8, 10, 12,
  135121. };
  135122. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  135123. _vq_quantthresh__44cn1_sm_p7_0,
  135124. _vq_quantmap__44cn1_sm_p7_0,
  135125. 13,
  135126. 13
  135127. };
  135128. static static_codebook _44cn1_sm_p7_0 = {
  135129. 2, 169,
  135130. _vq_lengthlist__44cn1_sm_p7_0,
  135131. 1, -526516224, 1616117760, 4, 0,
  135132. _vq_quantlist__44cn1_sm_p7_0,
  135133. NULL,
  135134. &_vq_auxt__44cn1_sm_p7_0,
  135135. NULL,
  135136. 0
  135137. };
  135138. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  135139. 2,
  135140. 1,
  135141. 3,
  135142. 0,
  135143. 4,
  135144. };
  135145. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  135146. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135147. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135148. };
  135149. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  135150. -1.5, -0.5, 0.5, 1.5,
  135151. };
  135152. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  135153. 3, 1, 0, 2, 4,
  135154. };
  135155. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  135156. _vq_quantthresh__44cn1_sm_p7_1,
  135157. _vq_quantmap__44cn1_sm_p7_1,
  135158. 5,
  135159. 5
  135160. };
  135161. static static_codebook _44cn1_sm_p7_1 = {
  135162. 2, 25,
  135163. _vq_lengthlist__44cn1_sm_p7_1,
  135164. 1, -533725184, 1611661312, 3, 0,
  135165. _vq_quantlist__44cn1_sm_p7_1,
  135166. NULL,
  135167. &_vq_auxt__44cn1_sm_p7_1,
  135168. NULL,
  135169. 0
  135170. };
  135171. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  135172. 4,
  135173. 3,
  135174. 5,
  135175. 2,
  135176. 6,
  135177. 1,
  135178. 7,
  135179. 0,
  135180. 8,
  135181. };
  135182. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  135183. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  135184. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  135185. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  135186. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  135187. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  135188. 14,
  135189. };
  135190. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  135191. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  135192. };
  135193. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  135194. 7, 5, 3, 1, 0, 2, 4, 6,
  135195. 8,
  135196. };
  135197. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  135198. _vq_quantthresh__44cn1_sm_p8_0,
  135199. _vq_quantmap__44cn1_sm_p8_0,
  135200. 9,
  135201. 9
  135202. };
  135203. static static_codebook _44cn1_sm_p8_0 = {
  135204. 2, 81,
  135205. _vq_lengthlist__44cn1_sm_p8_0,
  135206. 1, -516186112, 1627103232, 4, 0,
  135207. _vq_quantlist__44cn1_sm_p8_0,
  135208. NULL,
  135209. &_vq_auxt__44cn1_sm_p8_0,
  135210. NULL,
  135211. 0
  135212. };
  135213. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  135214. 6,
  135215. 5,
  135216. 7,
  135217. 4,
  135218. 8,
  135219. 3,
  135220. 9,
  135221. 2,
  135222. 10,
  135223. 1,
  135224. 11,
  135225. 0,
  135226. 12,
  135227. };
  135228. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  135229. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  135230. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  135231. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  135232. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  135233. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  135234. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  135235. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  135236. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  135237. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  135238. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  135239. 17,12,12,11,10,13,11,13,13,
  135240. };
  135241. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  135242. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135243. 42.5, 59.5, 76.5, 93.5,
  135244. };
  135245. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  135246. 11, 9, 7, 5, 3, 1, 0, 2,
  135247. 4, 6, 8, 10, 12,
  135248. };
  135249. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  135250. _vq_quantthresh__44cn1_sm_p8_1,
  135251. _vq_quantmap__44cn1_sm_p8_1,
  135252. 13,
  135253. 13
  135254. };
  135255. static static_codebook _44cn1_sm_p8_1 = {
  135256. 2, 169,
  135257. _vq_lengthlist__44cn1_sm_p8_1,
  135258. 1, -522616832, 1620115456, 4, 0,
  135259. _vq_quantlist__44cn1_sm_p8_1,
  135260. NULL,
  135261. &_vq_auxt__44cn1_sm_p8_1,
  135262. NULL,
  135263. 0
  135264. };
  135265. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  135266. 8,
  135267. 7,
  135268. 9,
  135269. 6,
  135270. 10,
  135271. 5,
  135272. 11,
  135273. 4,
  135274. 12,
  135275. 3,
  135276. 13,
  135277. 2,
  135278. 14,
  135279. 1,
  135280. 15,
  135281. 0,
  135282. 16,
  135283. };
  135284. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  135285. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135286. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135287. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  135288. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135289. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  135290. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  135291. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  135292. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  135293. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  135294. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  135295. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  135296. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  135297. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  135298. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  135299. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  135300. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135301. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135302. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  135303. 9,
  135304. };
  135305. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  135306. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135307. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135308. };
  135309. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  135310. 15, 13, 11, 9, 7, 5, 3, 1,
  135311. 0, 2, 4, 6, 8, 10, 12, 14,
  135312. 16,
  135313. };
  135314. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  135315. _vq_quantthresh__44cn1_sm_p8_2,
  135316. _vq_quantmap__44cn1_sm_p8_2,
  135317. 17,
  135318. 17
  135319. };
  135320. static static_codebook _44cn1_sm_p8_2 = {
  135321. 2, 289,
  135322. _vq_lengthlist__44cn1_sm_p8_2,
  135323. 1, -529530880, 1611661312, 5, 0,
  135324. _vq_quantlist__44cn1_sm_p8_2,
  135325. NULL,
  135326. &_vq_auxt__44cn1_sm_p8_2,
  135327. NULL,
  135328. 0
  135329. };
  135330. static long _huff_lengthlist__44cn1_sm_short[] = {
  135331. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  135332. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  135333. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  135334. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  135335. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  135336. 9,
  135337. };
  135338. static static_codebook _huff_book__44cn1_sm_short = {
  135339. 2, 81,
  135340. _huff_lengthlist__44cn1_sm_short,
  135341. 0, 0, 0, 0, 0,
  135342. NULL,
  135343. NULL,
  135344. NULL,
  135345. NULL,
  135346. 0
  135347. };
  135348. /********* End of inlined file: res_books_stereo.h *********/
  135349. /***** residue backends *********************************************/
  135350. static vorbis_info_residue0 _residue_44_low={
  135351. 0,-1, -1, 9,-1,
  135352. /* 0 1 2 3 4 5 6 7 */
  135353. {0},
  135354. {-1},
  135355. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  135356. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  135357. };
  135358. static vorbis_info_residue0 _residue_44_mid={
  135359. 0,-1, -1, 10,-1,
  135360. /* 0 1 2 3 4 5 6 7 8 */
  135361. {0},
  135362. {-1},
  135363. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  135364. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  135365. };
  135366. static vorbis_info_residue0 _residue_44_high={
  135367. 0,-1, -1, 10,-1,
  135368. /* 0 1 2 3 4 5 6 7 8 */
  135369. {0},
  135370. {-1},
  135371. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  135372. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  135373. };
  135374. static static_bookblock _resbook_44s_n1={
  135375. {
  135376. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  135377. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  135378. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  135379. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  135380. }
  135381. };
  135382. static static_bookblock _resbook_44sm_n1={
  135383. {
  135384. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  135385. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  135386. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  135387. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  135388. }
  135389. };
  135390. static static_bookblock _resbook_44s_0={
  135391. {
  135392. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  135393. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  135394. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  135395. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  135396. }
  135397. };
  135398. static static_bookblock _resbook_44sm_0={
  135399. {
  135400. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  135401. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  135402. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  135403. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  135404. }
  135405. };
  135406. static static_bookblock _resbook_44s_1={
  135407. {
  135408. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  135409. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  135410. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  135411. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  135412. }
  135413. };
  135414. static static_bookblock _resbook_44sm_1={
  135415. {
  135416. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  135417. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  135418. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  135419. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  135420. }
  135421. };
  135422. static static_bookblock _resbook_44s_2={
  135423. {
  135424. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  135425. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  135426. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  135427. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  135428. }
  135429. };
  135430. static static_bookblock _resbook_44s_3={
  135431. {
  135432. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  135433. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  135434. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  135435. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  135436. }
  135437. };
  135438. static static_bookblock _resbook_44s_4={
  135439. {
  135440. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  135441. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  135442. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  135443. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  135444. }
  135445. };
  135446. static static_bookblock _resbook_44s_5={
  135447. {
  135448. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  135449. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  135450. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  135451. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  135452. }
  135453. };
  135454. static static_bookblock _resbook_44s_6={
  135455. {
  135456. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  135457. {0,0,&_44c6_s_p4_0},
  135458. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  135459. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  135460. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  135461. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  135462. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  135463. }
  135464. };
  135465. static static_bookblock _resbook_44s_7={
  135466. {
  135467. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  135468. {0,0,&_44c7_s_p4_0},
  135469. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  135470. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  135471. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  135472. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  135473. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  135474. }
  135475. };
  135476. static static_bookblock _resbook_44s_8={
  135477. {
  135478. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  135479. {0,0,&_44c8_s_p4_0},
  135480. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  135481. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  135482. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  135483. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  135484. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  135485. }
  135486. };
  135487. static static_bookblock _resbook_44s_9={
  135488. {
  135489. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  135490. {0,0,&_44c9_s_p4_0},
  135491. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  135492. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  135493. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  135494. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  135495. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  135496. }
  135497. };
  135498. static vorbis_residue_template _res_44s_n1[]={
  135499. {2,0, &_residue_44_low,
  135500. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  135501. &_resbook_44s_n1,&_resbook_44sm_n1},
  135502. {2,0, &_residue_44_low,
  135503. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  135504. &_resbook_44s_n1,&_resbook_44sm_n1}
  135505. };
  135506. static vorbis_residue_template _res_44s_0[]={
  135507. {2,0, &_residue_44_low,
  135508. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  135509. &_resbook_44s_0,&_resbook_44sm_0},
  135510. {2,0, &_residue_44_low,
  135511. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  135512. &_resbook_44s_0,&_resbook_44sm_0}
  135513. };
  135514. static vorbis_residue_template _res_44s_1[]={
  135515. {2,0, &_residue_44_low,
  135516. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  135517. &_resbook_44s_1,&_resbook_44sm_1},
  135518. {2,0, &_residue_44_low,
  135519. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  135520. &_resbook_44s_1,&_resbook_44sm_1}
  135521. };
  135522. static vorbis_residue_template _res_44s_2[]={
  135523. {2,0, &_residue_44_mid,
  135524. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  135525. &_resbook_44s_2,&_resbook_44s_2},
  135526. {2,0, &_residue_44_mid,
  135527. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  135528. &_resbook_44s_2,&_resbook_44s_2}
  135529. };
  135530. static vorbis_residue_template _res_44s_3[]={
  135531. {2,0, &_residue_44_mid,
  135532. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  135533. &_resbook_44s_3,&_resbook_44s_3},
  135534. {2,0, &_residue_44_mid,
  135535. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  135536. &_resbook_44s_3,&_resbook_44s_3}
  135537. };
  135538. static vorbis_residue_template _res_44s_4[]={
  135539. {2,0, &_residue_44_mid,
  135540. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  135541. &_resbook_44s_4,&_resbook_44s_4},
  135542. {2,0, &_residue_44_mid,
  135543. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  135544. &_resbook_44s_4,&_resbook_44s_4}
  135545. };
  135546. static vorbis_residue_template _res_44s_5[]={
  135547. {2,0, &_residue_44_mid,
  135548. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  135549. &_resbook_44s_5,&_resbook_44s_5},
  135550. {2,0, &_residue_44_mid,
  135551. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  135552. &_resbook_44s_5,&_resbook_44s_5}
  135553. };
  135554. static vorbis_residue_template _res_44s_6[]={
  135555. {2,0, &_residue_44_high,
  135556. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  135557. &_resbook_44s_6,&_resbook_44s_6},
  135558. {2,0, &_residue_44_high,
  135559. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  135560. &_resbook_44s_6,&_resbook_44s_6}
  135561. };
  135562. static vorbis_residue_template _res_44s_7[]={
  135563. {2,0, &_residue_44_high,
  135564. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  135565. &_resbook_44s_7,&_resbook_44s_7},
  135566. {2,0, &_residue_44_high,
  135567. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  135568. &_resbook_44s_7,&_resbook_44s_7}
  135569. };
  135570. static vorbis_residue_template _res_44s_8[]={
  135571. {2,0, &_residue_44_high,
  135572. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  135573. &_resbook_44s_8,&_resbook_44s_8},
  135574. {2,0, &_residue_44_high,
  135575. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  135576. &_resbook_44s_8,&_resbook_44s_8}
  135577. };
  135578. static vorbis_residue_template _res_44s_9[]={
  135579. {2,0, &_residue_44_high,
  135580. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  135581. &_resbook_44s_9,&_resbook_44s_9},
  135582. {2,0, &_residue_44_high,
  135583. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  135584. &_resbook_44s_9,&_resbook_44s_9}
  135585. };
  135586. static vorbis_mapping_template _mapres_template_44_stereo[]={
  135587. { _map_nominal, _res_44s_n1 }, /* -1 */
  135588. { _map_nominal, _res_44s_0 }, /* 0 */
  135589. { _map_nominal, _res_44s_1 }, /* 1 */
  135590. { _map_nominal, _res_44s_2 }, /* 2 */
  135591. { _map_nominal, _res_44s_3 }, /* 3 */
  135592. { _map_nominal, _res_44s_4 }, /* 4 */
  135593. { _map_nominal, _res_44s_5 }, /* 5 */
  135594. { _map_nominal, _res_44s_6 }, /* 6 */
  135595. { _map_nominal, _res_44s_7 }, /* 7 */
  135596. { _map_nominal, _res_44s_8 }, /* 8 */
  135597. { _map_nominal, _res_44s_9 }, /* 9 */
  135598. };
  135599. /********* End of inlined file: residue_44.h *********/
  135600. /********* Start of inlined file: psych_44.h *********/
  135601. /* preecho trigger settings *****************************************/
  135602. static vorbis_info_psy_global _psy_global_44[5]={
  135603. {8, /* lines per eighth octave */
  135604. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  135605. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  135606. -6.f,
  135607. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135608. },
  135609. {8, /* lines per eighth octave */
  135610. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  135611. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  135612. -6.f,
  135613. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135614. },
  135615. {8, /* lines per eighth octave */
  135616. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  135617. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  135618. -6.f,
  135619. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135620. },
  135621. {8, /* lines per eighth octave */
  135622. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  135623. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  135624. -6.f,
  135625. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135626. },
  135627. {8, /* lines per eighth octave */
  135628. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  135629. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  135630. -6.f,
  135631. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135632. },
  135633. };
  135634. /* noise compander lookups * low, mid, high quality ****************/
  135635. static compandblock _psy_compand_44[6]={
  135636. /* sub-mode Z short */
  135637. {{
  135638. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135639. 8, 9,10,11,12,13,14, 15, /* 15dB */
  135640. 16,17,18,19,20,21,22, 23, /* 23dB */
  135641. 24,25,26,27,28,29,30, 31, /* 31dB */
  135642. 32,33,34,35,36,37,38, 39, /* 39dB */
  135643. }},
  135644. /* mode_Z nominal short */
  135645. {{
  135646. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  135647. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  135648. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  135649. 15,16,17,17,17,18,18, 19, /* 31dB */
  135650. 19,19,20,21,22,23,24, 25, /* 39dB */
  135651. }},
  135652. /* mode A short */
  135653. {{
  135654. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  135655. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  135656. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  135657. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  135658. 11,12,13,14,15,16,17, 18, /* 39dB */
  135659. }},
  135660. /* sub-mode Z long */
  135661. {{
  135662. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135663. 8, 9,10,11,12,13,14, 15, /* 15dB */
  135664. 16,17,18,19,20,21,22, 23, /* 23dB */
  135665. 24,25,26,27,28,29,30, 31, /* 31dB */
  135666. 32,33,34,35,36,37,38, 39, /* 39dB */
  135667. }},
  135668. /* mode_Z nominal long */
  135669. {{
  135670. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135671. 8, 9,10,11,12,12,13, 13, /* 15dB */
  135672. 13,14,14,14,15,15,15, 15, /* 23dB */
  135673. 16,16,17,17,17,18,18, 19, /* 31dB */
  135674. 19,19,20,21,22,23,24, 25, /* 39dB */
  135675. }},
  135676. /* mode A long */
  135677. {{
  135678. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135679. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  135680. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  135681. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  135682. 11,12,13,14,15,16,17, 18, /* 39dB */
  135683. }}
  135684. };
  135685. /* tonal masking curve level adjustments *************************/
  135686. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  135687. /* 63 125 250 500 1 2 4 8 16 */
  135688. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  135689. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  135690. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  135691. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  135692. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  135693. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  135694. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  135695. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  135696. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  135697. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  135698. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  135699. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  135700. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  135701. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  135702. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  135703. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  135704. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  135705. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  135706. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  135707. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  135708. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  135709. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  135710. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  135711. };
  135712. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  135713. /* 63 125 250 500 1 2 4 8 16 */
  135714. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  135715. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  135716. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  135717. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  135718. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  135719. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  135720. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  135721. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  135722. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  135723. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  135724. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  135725. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  135726. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  135727. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  135728. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  135729. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  135730. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  135731. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  135732. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  135733. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  135734. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  135735. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  135736. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  135737. };
  135738. /* noise bias (transition block) */
  135739. static noise3 _psy_noisebias_trans[12]={
  135740. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135741. /* -1 */
  135742. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135743. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135744. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135745. /* 0
  135746. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135747. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  135748. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  135749. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135750. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  135751. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135752. /* 1
  135753. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135754. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  135755. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  135756. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135757. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  135758. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  135759. /* 2
  135760. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135761. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  135762. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  135763. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135764. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  135765. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  135766. /* 3
  135767. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135768. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  135769. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135770. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135771. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  135772. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135773. /* 4
  135774. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135775. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  135776. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135777. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135778. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  135779. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135780. /* 5
  135781. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135782. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  135783. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  135784. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135785. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  135786. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  135787. /* 6
  135788. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135789. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  135790. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  135791. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135792. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  135793. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  135794. /* 7
  135795. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135796. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  135797. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  135798. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135799. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  135800. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  135801. /* 8
  135802. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  135803. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  135804. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  135805. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  135806. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  135807. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135808. /* 9
  135809. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135810. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  135811. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  135812. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135813. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  135814. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  135815. /* 10 */
  135816. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  135817. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  135818. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135819. };
  135820. /* noise bias (long block) */
  135821. static noise3 _psy_noisebias_long[12]={
  135822. /*63 125 250 500 1k 2k 4k 8k 16k*/
  135823. /* -1 */
  135824. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  135825. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  135826. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135827. /* 0 */
  135828. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  135829. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  135830. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  135831. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  135832. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  135833. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135834. /* 1 */
  135835. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135836. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  135837. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  135838. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135839. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  135840. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  135841. /* 2 */
  135842. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135843. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  135844. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135845. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135846. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  135847. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135848. /* 3 */
  135849. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135850. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  135851. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135852. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135853. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  135854. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  135855. /* 4 */
  135856. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135857. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  135858. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135859. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135860. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  135861. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  135862. /* 5 */
  135863. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135864. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  135865. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  135866. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135867. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  135868. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  135869. /* 6 */
  135870. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135871. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  135872. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  135873. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135874. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  135875. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  135876. /* 7 */
  135877. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135878. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  135879. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  135880. /* 8 */
  135881. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  135882. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  135883. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  135884. /* 9 */
  135885. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135886. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  135887. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135888. /* 10 */
  135889. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  135890. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  135891. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135892. };
  135893. /* noise bias (impulse block) */
  135894. static noise3 _psy_noisebias_impulse[12]={
  135895. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135896. /* -1 */
  135897. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135898. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135899. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135900. /* 0 */
  135901. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  135902. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  135903. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  135904. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  135905. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  135906. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135907. /* 1 */
  135908. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  135909. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  135910. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  135911. /* 2 */
  135912. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135913. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135914. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135915. /* 3 */
  135916. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  135917. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135918. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135919. /* 4 */
  135920. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  135921. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135922. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135923. /* 5 */
  135924. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135925. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  135926. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  135927. /* 6
  135928. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135929. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  135930. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  135931. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135932. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  135933. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  135934. /* 7 */
  135935. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  135936. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  135937. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  135938. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  135939. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  135940. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  135941. /* 8 */
  135942. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  135943. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  135944. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  135945. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  135946. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  135947. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  135948. /* 9 */
  135949. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135950. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  135951. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  135952. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135953. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  135954. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135955. /* 10 */
  135956. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  135957. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  135958. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135959. };
  135960. /* noise bias (padding block) */
  135961. static noise3 _psy_noisebias_padding[12]={
  135962. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135963. /* -1 */
  135964. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135965. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135966. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135967. /* 0 */
  135968. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135969. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  135970. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  135971. /* 1 */
  135972. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  135973. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  135974. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  135975. /* 2 */
  135976. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135977. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  135978. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  135979. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135980. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  135981. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  135982. /* 3 */
  135983. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  135984. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  135985. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  135986. /* 4 */
  135987. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  135988. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  135989. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  135990. /* 5 */
  135991. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  135992. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  135993. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  135994. /* 6 */
  135995. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  135996. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  135997. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  135998. /* 7 */
  135999. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136000. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  136001. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  136002. /* 8 */
  136003. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  136004. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  136005. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  136006. /* 9 */
  136007. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  136008. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  136009. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  136010. /* 10 */
  136011. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  136012. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  136013. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136014. };
  136015. static noiseguard _psy_noiseguards_44[4]={
  136016. {3,3,15},
  136017. {3,3,15},
  136018. {10,10,100},
  136019. {10,10,100},
  136020. };
  136021. static int _psy_tone_suppress[12]={
  136022. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  136023. };
  136024. static int _psy_tone_0dB[12]={
  136025. 90,90,95,95,95,95,105,105,105,105,105,105,
  136026. };
  136027. static int _psy_noise_suppress[12]={
  136028. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  136029. };
  136030. static vorbis_info_psy _psy_info_template={
  136031. /* blockflag */
  136032. -1,
  136033. /* ath_adjatt, ath_maxatt */
  136034. -140.,-140.,
  136035. /* tonemask att boost/decay,suppr,curves */
  136036. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  136037. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  136038. 1, -0.f, .5f, .5f, 0,0,0,
  136039. /* noiseoffset*3, noisecompand, max_curve_dB */
  136040. {{-1},{-1},{-1}},{-1},105.f,
  136041. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  136042. 0,0,-1,-1,0.,
  136043. };
  136044. /* ath ****************/
  136045. static int _psy_ath_floater[12]={
  136046. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  136047. };
  136048. static int _psy_ath_abs[12]={
  136049. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  136050. };
  136051. /* stereo setup. These don't map directly to quality level, there's
  136052. an additional indirection as several of the below may be used in a
  136053. single bitmanaged stream
  136054. ****************/
  136055. /* various stereo possibilities */
  136056. /* stereo mode by base quality level */
  136057. static adj_stereo _psy_stereo_modes_44[12]={
  136058. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  136059. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136060. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136061. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  136062. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136063. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  136064. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136065. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136066. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  136067. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136068. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  136069. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136070. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136071. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136072. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  136073. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  136074. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136075. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136076. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136077. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  136078. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  136079. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  136080. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136081. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136082. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  136083. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136084. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136085. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136086. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  136087. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  136088. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136089. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  136090. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136091. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  136092. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136093. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  136094. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  136095. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136096. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  136097. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136098. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136099. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136100. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136101. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136102. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136103. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  136104. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136105. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  136106. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136107. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136108. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136109. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136110. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136111. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136112. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136113. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136114. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  136115. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136116. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136117. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136118. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136119. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136120. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136121. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136122. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136123. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  136124. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136125. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136126. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136127. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136128. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136129. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136130. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136131. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136132. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  136133. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136134. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136135. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136136. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136137. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  136138. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136139. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136140. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136141. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136142. };
  136143. /* tone master attenuation by base quality mode and bitrate tweak */
  136144. static att3 _psy_tone_masteratt_44[12]={
  136145. {{ 35, 21, 9}, 0, 0}, /* -1 */
  136146. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  136147. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  136148. {{ 25, 12, 2}, 0, 0}, /* 1 */
  136149. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  136150. {{ 20, 9, -3}, 0, 0}, /* 2 */
  136151. {{ 20, 9, -4}, 0, 0}, /* 3 */
  136152. {{ 20, 9, -4}, 0, 0}, /* 4 */
  136153. {{ 20, 6, -6}, 0, 0}, /* 5 */
  136154. {{ 20, 3, -10}, 0, 0}, /* 6 */
  136155. {{ 18, 1, -14}, 0, 0}, /* 7 */
  136156. {{ 18, 0, -16}, 0, 0}, /* 8 */
  136157. {{ 18, -2, -16}, 0, 0}, /* 9 */
  136158. {{ 12, -2, -20}, 0, 0}, /* 10 */
  136159. };
  136160. /* lowpass by mode **************/
  136161. static double _psy_lowpass_44[12]={
  136162. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  136163. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  136164. };
  136165. /* noise normalization **********/
  136166. static int _noise_start_short_44[11]={
  136167. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  136168. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  136169. };
  136170. static int _noise_start_long_44[11]={
  136171. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  136172. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  136173. };
  136174. static int _noise_part_short_44[11]={
  136175. 8,8,8,8,8,8,8,8,8,8,8
  136176. };
  136177. static int _noise_part_long_44[11]={
  136178. 32,32,32,32,32,32,32,32,32,32,32
  136179. };
  136180. static double _noise_thresh_44[11]={
  136181. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  136182. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  136183. };
  136184. static double _noise_thresh_5only[2]={
  136185. .5,.5,
  136186. };
  136187. /********* End of inlined file: psych_44.h *********/
  136188. static double rate_mapping_44_stereo[12]={
  136189. 22500.,32000.,40000.,48000.,56000.,64000.,
  136190. 80000.,96000.,112000.,128000.,160000.,250001.
  136191. };
  136192. static double quality_mapping_44[12]={
  136193. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  136194. };
  136195. static int blocksize_short_44[11]={
  136196. 512,256,256,256,256,256,256,256,256,256,256
  136197. };
  136198. static int blocksize_long_44[11]={
  136199. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  136200. };
  136201. static double _psy_compand_short_mapping[12]={
  136202. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  136203. };
  136204. static double _psy_compand_long_mapping[12]={
  136205. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  136206. };
  136207. static double _global_mapping_44[12]={
  136208. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  136209. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  136210. };
  136211. static int _floor_short_mapping_44[11]={
  136212. 1,0,0,2,2,4,5,5,5,5,5
  136213. };
  136214. static int _floor_long_mapping_44[11]={
  136215. 8,7,7,7,7,7,7,7,7,7,7
  136216. };
  136217. ve_setup_data_template ve_setup_44_stereo={
  136218. 11,
  136219. rate_mapping_44_stereo,
  136220. quality_mapping_44,
  136221. 2,
  136222. 40000,
  136223. 50000,
  136224. blocksize_short_44,
  136225. blocksize_long_44,
  136226. _psy_tone_masteratt_44,
  136227. _psy_tone_0dB,
  136228. _psy_tone_suppress,
  136229. _vp_tonemask_adj_otherblock,
  136230. _vp_tonemask_adj_longblock,
  136231. _vp_tonemask_adj_otherblock,
  136232. _psy_noiseguards_44,
  136233. _psy_noisebias_impulse,
  136234. _psy_noisebias_padding,
  136235. _psy_noisebias_trans,
  136236. _psy_noisebias_long,
  136237. _psy_noise_suppress,
  136238. _psy_compand_44,
  136239. _psy_compand_short_mapping,
  136240. _psy_compand_long_mapping,
  136241. {_noise_start_short_44,_noise_start_long_44},
  136242. {_noise_part_short_44,_noise_part_long_44},
  136243. _noise_thresh_44,
  136244. _psy_ath_floater,
  136245. _psy_ath_abs,
  136246. _psy_lowpass_44,
  136247. _psy_global_44,
  136248. _global_mapping_44,
  136249. _psy_stereo_modes_44,
  136250. _floor_books,
  136251. _floor,
  136252. _floor_short_mapping_44,
  136253. _floor_long_mapping_44,
  136254. _mapres_template_44_stereo
  136255. };
  136256. /********* End of inlined file: setup_44.h *********/
  136257. /********* Start of inlined file: setup_44u.h *********/
  136258. /********* Start of inlined file: residue_44u.h *********/
  136259. /********* Start of inlined file: res_books_uncoupled.h *********/
  136260. static long _vq_quantlist__16u0__p1_0[] = {
  136261. 1,
  136262. 0,
  136263. 2,
  136264. };
  136265. static long _vq_lengthlist__16u0__p1_0[] = {
  136266. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  136267. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  136268. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  136269. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  136270. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  136271. 12,
  136272. };
  136273. static float _vq_quantthresh__16u0__p1_0[] = {
  136274. -0.5, 0.5,
  136275. };
  136276. static long _vq_quantmap__16u0__p1_0[] = {
  136277. 1, 0, 2,
  136278. };
  136279. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  136280. _vq_quantthresh__16u0__p1_0,
  136281. _vq_quantmap__16u0__p1_0,
  136282. 3,
  136283. 3
  136284. };
  136285. static static_codebook _16u0__p1_0 = {
  136286. 4, 81,
  136287. _vq_lengthlist__16u0__p1_0,
  136288. 1, -535822336, 1611661312, 2, 0,
  136289. _vq_quantlist__16u0__p1_0,
  136290. NULL,
  136291. &_vq_auxt__16u0__p1_0,
  136292. NULL,
  136293. 0
  136294. };
  136295. static long _vq_quantlist__16u0__p2_0[] = {
  136296. 1,
  136297. 0,
  136298. 2,
  136299. };
  136300. static long _vq_lengthlist__16u0__p2_0[] = {
  136301. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  136302. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  136303. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  136304. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  136305. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  136306. 8,
  136307. };
  136308. static float _vq_quantthresh__16u0__p2_0[] = {
  136309. -0.5, 0.5,
  136310. };
  136311. static long _vq_quantmap__16u0__p2_0[] = {
  136312. 1, 0, 2,
  136313. };
  136314. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  136315. _vq_quantthresh__16u0__p2_0,
  136316. _vq_quantmap__16u0__p2_0,
  136317. 3,
  136318. 3
  136319. };
  136320. static static_codebook _16u0__p2_0 = {
  136321. 4, 81,
  136322. _vq_lengthlist__16u0__p2_0,
  136323. 1, -535822336, 1611661312, 2, 0,
  136324. _vq_quantlist__16u0__p2_0,
  136325. NULL,
  136326. &_vq_auxt__16u0__p2_0,
  136327. NULL,
  136328. 0
  136329. };
  136330. static long _vq_quantlist__16u0__p3_0[] = {
  136331. 2,
  136332. 1,
  136333. 3,
  136334. 0,
  136335. 4,
  136336. };
  136337. static long _vq_lengthlist__16u0__p3_0[] = {
  136338. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  136339. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  136340. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  136341. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  136342. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  136343. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  136344. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  136345. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  136346. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  136347. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  136348. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  136349. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  136350. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  136351. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  136352. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  136353. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  136354. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  136355. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  136356. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  136357. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  136358. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  136359. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  136360. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  136361. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  136362. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  136363. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  136364. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  136365. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  136366. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  136367. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  136368. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  136369. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  136370. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  136371. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  136372. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  136373. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  136374. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  136375. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  136376. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  136377. 18,
  136378. };
  136379. static float _vq_quantthresh__16u0__p3_0[] = {
  136380. -1.5, -0.5, 0.5, 1.5,
  136381. };
  136382. static long _vq_quantmap__16u0__p3_0[] = {
  136383. 3, 1, 0, 2, 4,
  136384. };
  136385. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  136386. _vq_quantthresh__16u0__p3_0,
  136387. _vq_quantmap__16u0__p3_0,
  136388. 5,
  136389. 5
  136390. };
  136391. static static_codebook _16u0__p3_0 = {
  136392. 4, 625,
  136393. _vq_lengthlist__16u0__p3_0,
  136394. 1, -533725184, 1611661312, 3, 0,
  136395. _vq_quantlist__16u0__p3_0,
  136396. NULL,
  136397. &_vq_auxt__16u0__p3_0,
  136398. NULL,
  136399. 0
  136400. };
  136401. static long _vq_quantlist__16u0__p4_0[] = {
  136402. 2,
  136403. 1,
  136404. 3,
  136405. 0,
  136406. 4,
  136407. };
  136408. static long _vq_lengthlist__16u0__p4_0[] = {
  136409. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  136410. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  136411. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  136412. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  136413. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  136414. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  136415. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  136416. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  136417. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  136418. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  136419. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  136420. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  136421. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  136422. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  136423. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  136424. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  136425. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  136426. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  136427. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  136428. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  136429. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  136430. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  136431. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  136432. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  136433. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  136434. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  136435. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  136436. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  136437. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  136438. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  136439. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  136440. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  136441. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  136442. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  136443. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  136444. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  136445. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  136446. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  136447. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  136448. 11,
  136449. };
  136450. static float _vq_quantthresh__16u0__p4_0[] = {
  136451. -1.5, -0.5, 0.5, 1.5,
  136452. };
  136453. static long _vq_quantmap__16u0__p4_0[] = {
  136454. 3, 1, 0, 2, 4,
  136455. };
  136456. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  136457. _vq_quantthresh__16u0__p4_0,
  136458. _vq_quantmap__16u0__p4_0,
  136459. 5,
  136460. 5
  136461. };
  136462. static static_codebook _16u0__p4_0 = {
  136463. 4, 625,
  136464. _vq_lengthlist__16u0__p4_0,
  136465. 1, -533725184, 1611661312, 3, 0,
  136466. _vq_quantlist__16u0__p4_0,
  136467. NULL,
  136468. &_vq_auxt__16u0__p4_0,
  136469. NULL,
  136470. 0
  136471. };
  136472. static long _vq_quantlist__16u0__p5_0[] = {
  136473. 4,
  136474. 3,
  136475. 5,
  136476. 2,
  136477. 6,
  136478. 1,
  136479. 7,
  136480. 0,
  136481. 8,
  136482. };
  136483. static long _vq_lengthlist__16u0__p5_0[] = {
  136484. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  136485. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  136486. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  136487. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  136488. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  136489. 12,
  136490. };
  136491. static float _vq_quantthresh__16u0__p5_0[] = {
  136492. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136493. };
  136494. static long _vq_quantmap__16u0__p5_0[] = {
  136495. 7, 5, 3, 1, 0, 2, 4, 6,
  136496. 8,
  136497. };
  136498. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  136499. _vq_quantthresh__16u0__p5_0,
  136500. _vq_quantmap__16u0__p5_0,
  136501. 9,
  136502. 9
  136503. };
  136504. static static_codebook _16u0__p5_0 = {
  136505. 2, 81,
  136506. _vq_lengthlist__16u0__p5_0,
  136507. 1, -531628032, 1611661312, 4, 0,
  136508. _vq_quantlist__16u0__p5_0,
  136509. NULL,
  136510. &_vq_auxt__16u0__p5_0,
  136511. NULL,
  136512. 0
  136513. };
  136514. static long _vq_quantlist__16u0__p6_0[] = {
  136515. 6,
  136516. 5,
  136517. 7,
  136518. 4,
  136519. 8,
  136520. 3,
  136521. 9,
  136522. 2,
  136523. 10,
  136524. 1,
  136525. 11,
  136526. 0,
  136527. 12,
  136528. };
  136529. static long _vq_lengthlist__16u0__p6_0[] = {
  136530. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  136531. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  136532. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  136533. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  136534. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  136535. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  136536. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  136537. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  136538. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  136539. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  136540. 18, 0,19, 0, 0, 0, 0, 0, 0,
  136541. };
  136542. static float _vq_quantthresh__16u0__p6_0[] = {
  136543. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136544. 12.5, 17.5, 22.5, 27.5,
  136545. };
  136546. static long _vq_quantmap__16u0__p6_0[] = {
  136547. 11, 9, 7, 5, 3, 1, 0, 2,
  136548. 4, 6, 8, 10, 12,
  136549. };
  136550. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  136551. _vq_quantthresh__16u0__p6_0,
  136552. _vq_quantmap__16u0__p6_0,
  136553. 13,
  136554. 13
  136555. };
  136556. static static_codebook _16u0__p6_0 = {
  136557. 2, 169,
  136558. _vq_lengthlist__16u0__p6_0,
  136559. 1, -526516224, 1616117760, 4, 0,
  136560. _vq_quantlist__16u0__p6_0,
  136561. NULL,
  136562. &_vq_auxt__16u0__p6_0,
  136563. NULL,
  136564. 0
  136565. };
  136566. static long _vq_quantlist__16u0__p6_1[] = {
  136567. 2,
  136568. 1,
  136569. 3,
  136570. 0,
  136571. 4,
  136572. };
  136573. static long _vq_lengthlist__16u0__p6_1[] = {
  136574. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  136575. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  136576. };
  136577. static float _vq_quantthresh__16u0__p6_1[] = {
  136578. -1.5, -0.5, 0.5, 1.5,
  136579. };
  136580. static long _vq_quantmap__16u0__p6_1[] = {
  136581. 3, 1, 0, 2, 4,
  136582. };
  136583. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  136584. _vq_quantthresh__16u0__p6_1,
  136585. _vq_quantmap__16u0__p6_1,
  136586. 5,
  136587. 5
  136588. };
  136589. static static_codebook _16u0__p6_1 = {
  136590. 2, 25,
  136591. _vq_lengthlist__16u0__p6_1,
  136592. 1, -533725184, 1611661312, 3, 0,
  136593. _vq_quantlist__16u0__p6_1,
  136594. NULL,
  136595. &_vq_auxt__16u0__p6_1,
  136596. NULL,
  136597. 0
  136598. };
  136599. static long _vq_quantlist__16u0__p7_0[] = {
  136600. 1,
  136601. 0,
  136602. 2,
  136603. };
  136604. static long _vq_lengthlist__16u0__p7_0[] = {
  136605. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  136606. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  136607. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136608. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136609. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136610. 7,
  136611. };
  136612. static float _vq_quantthresh__16u0__p7_0[] = {
  136613. -157.5, 157.5,
  136614. };
  136615. static long _vq_quantmap__16u0__p7_0[] = {
  136616. 1, 0, 2,
  136617. };
  136618. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  136619. _vq_quantthresh__16u0__p7_0,
  136620. _vq_quantmap__16u0__p7_0,
  136621. 3,
  136622. 3
  136623. };
  136624. static static_codebook _16u0__p7_0 = {
  136625. 4, 81,
  136626. _vq_lengthlist__16u0__p7_0,
  136627. 1, -518803456, 1628680192, 2, 0,
  136628. _vq_quantlist__16u0__p7_0,
  136629. NULL,
  136630. &_vq_auxt__16u0__p7_0,
  136631. NULL,
  136632. 0
  136633. };
  136634. static long _vq_quantlist__16u0__p7_1[] = {
  136635. 7,
  136636. 6,
  136637. 8,
  136638. 5,
  136639. 9,
  136640. 4,
  136641. 10,
  136642. 3,
  136643. 11,
  136644. 2,
  136645. 12,
  136646. 1,
  136647. 13,
  136648. 0,
  136649. 14,
  136650. };
  136651. static long _vq_lengthlist__16u0__p7_1[] = {
  136652. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  136653. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  136654. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  136655. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  136656. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  136657. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  136658. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136666. 10,
  136667. };
  136668. static float _vq_quantthresh__16u0__p7_1[] = {
  136669. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  136670. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  136671. };
  136672. static long _vq_quantmap__16u0__p7_1[] = {
  136673. 13, 11, 9, 7, 5, 3, 1, 0,
  136674. 2, 4, 6, 8, 10, 12, 14,
  136675. };
  136676. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  136677. _vq_quantthresh__16u0__p7_1,
  136678. _vq_quantmap__16u0__p7_1,
  136679. 15,
  136680. 15
  136681. };
  136682. static static_codebook _16u0__p7_1 = {
  136683. 2, 225,
  136684. _vq_lengthlist__16u0__p7_1,
  136685. 1, -520986624, 1620377600, 4, 0,
  136686. _vq_quantlist__16u0__p7_1,
  136687. NULL,
  136688. &_vq_auxt__16u0__p7_1,
  136689. NULL,
  136690. 0
  136691. };
  136692. static long _vq_quantlist__16u0__p7_2[] = {
  136693. 10,
  136694. 9,
  136695. 11,
  136696. 8,
  136697. 12,
  136698. 7,
  136699. 13,
  136700. 6,
  136701. 14,
  136702. 5,
  136703. 15,
  136704. 4,
  136705. 16,
  136706. 3,
  136707. 17,
  136708. 2,
  136709. 18,
  136710. 1,
  136711. 19,
  136712. 0,
  136713. 20,
  136714. };
  136715. static long _vq_lengthlist__16u0__p7_2[] = {
  136716. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  136717. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  136718. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  136719. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  136720. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  136721. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  136722. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  136723. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  136724. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  136725. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  136726. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  136727. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  136728. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  136729. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  136730. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  136731. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  136732. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  136733. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  136734. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  136735. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  136736. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  136737. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  136738. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  136739. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  136740. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  136741. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  136742. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  136743. 10,10,12,11,10,11,11,11,10,
  136744. };
  136745. static float _vq_quantthresh__16u0__p7_2[] = {
  136746. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  136747. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  136748. 6.5, 7.5, 8.5, 9.5,
  136749. };
  136750. static long _vq_quantmap__16u0__p7_2[] = {
  136751. 19, 17, 15, 13, 11, 9, 7, 5,
  136752. 3, 1, 0, 2, 4, 6, 8, 10,
  136753. 12, 14, 16, 18, 20,
  136754. };
  136755. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  136756. _vq_quantthresh__16u0__p7_2,
  136757. _vq_quantmap__16u0__p7_2,
  136758. 21,
  136759. 21
  136760. };
  136761. static static_codebook _16u0__p7_2 = {
  136762. 2, 441,
  136763. _vq_lengthlist__16u0__p7_2,
  136764. 1, -529268736, 1611661312, 5, 0,
  136765. _vq_quantlist__16u0__p7_2,
  136766. NULL,
  136767. &_vq_auxt__16u0__p7_2,
  136768. NULL,
  136769. 0
  136770. };
  136771. static long _huff_lengthlist__16u0__single[] = {
  136772. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  136773. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  136774. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  136775. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  136776. };
  136777. static static_codebook _huff_book__16u0__single = {
  136778. 2, 64,
  136779. _huff_lengthlist__16u0__single,
  136780. 0, 0, 0, 0, 0,
  136781. NULL,
  136782. NULL,
  136783. NULL,
  136784. NULL,
  136785. 0
  136786. };
  136787. static long _huff_lengthlist__16u1__long[] = {
  136788. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  136789. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  136790. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  136791. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  136792. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  136793. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  136794. 16,13,16,18,
  136795. };
  136796. static static_codebook _huff_book__16u1__long = {
  136797. 2, 100,
  136798. _huff_lengthlist__16u1__long,
  136799. 0, 0, 0, 0, 0,
  136800. NULL,
  136801. NULL,
  136802. NULL,
  136803. NULL,
  136804. 0
  136805. };
  136806. static long _vq_quantlist__16u1__p1_0[] = {
  136807. 1,
  136808. 0,
  136809. 2,
  136810. };
  136811. static long _vq_lengthlist__16u1__p1_0[] = {
  136812. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  136813. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  136814. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  136815. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  136816. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  136817. 11,
  136818. };
  136819. static float _vq_quantthresh__16u1__p1_0[] = {
  136820. -0.5, 0.5,
  136821. };
  136822. static long _vq_quantmap__16u1__p1_0[] = {
  136823. 1, 0, 2,
  136824. };
  136825. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  136826. _vq_quantthresh__16u1__p1_0,
  136827. _vq_quantmap__16u1__p1_0,
  136828. 3,
  136829. 3
  136830. };
  136831. static static_codebook _16u1__p1_0 = {
  136832. 4, 81,
  136833. _vq_lengthlist__16u1__p1_0,
  136834. 1, -535822336, 1611661312, 2, 0,
  136835. _vq_quantlist__16u1__p1_0,
  136836. NULL,
  136837. &_vq_auxt__16u1__p1_0,
  136838. NULL,
  136839. 0
  136840. };
  136841. static long _vq_quantlist__16u1__p2_0[] = {
  136842. 1,
  136843. 0,
  136844. 2,
  136845. };
  136846. static long _vq_lengthlist__16u1__p2_0[] = {
  136847. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  136848. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  136849. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  136850. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  136851. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  136852. 8,
  136853. };
  136854. static float _vq_quantthresh__16u1__p2_0[] = {
  136855. -0.5, 0.5,
  136856. };
  136857. static long _vq_quantmap__16u1__p2_0[] = {
  136858. 1, 0, 2,
  136859. };
  136860. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  136861. _vq_quantthresh__16u1__p2_0,
  136862. _vq_quantmap__16u1__p2_0,
  136863. 3,
  136864. 3
  136865. };
  136866. static static_codebook _16u1__p2_0 = {
  136867. 4, 81,
  136868. _vq_lengthlist__16u1__p2_0,
  136869. 1, -535822336, 1611661312, 2, 0,
  136870. _vq_quantlist__16u1__p2_0,
  136871. NULL,
  136872. &_vq_auxt__16u1__p2_0,
  136873. NULL,
  136874. 0
  136875. };
  136876. static long _vq_quantlist__16u1__p3_0[] = {
  136877. 2,
  136878. 1,
  136879. 3,
  136880. 0,
  136881. 4,
  136882. };
  136883. static long _vq_lengthlist__16u1__p3_0[] = {
  136884. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  136885. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  136886. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  136887. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  136888. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  136889. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  136890. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  136891. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  136892. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  136893. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  136894. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  136895. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  136896. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  136897. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  136898. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  136899. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  136900. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  136901. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  136902. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  136903. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  136904. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  136905. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  136906. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  136907. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  136908. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  136909. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  136910. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  136911. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  136912. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  136913. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  136914. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  136915. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  136916. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  136917. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  136918. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  136919. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  136920. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  136921. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  136922. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  136923. 16,
  136924. };
  136925. static float _vq_quantthresh__16u1__p3_0[] = {
  136926. -1.5, -0.5, 0.5, 1.5,
  136927. };
  136928. static long _vq_quantmap__16u1__p3_0[] = {
  136929. 3, 1, 0, 2, 4,
  136930. };
  136931. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  136932. _vq_quantthresh__16u1__p3_0,
  136933. _vq_quantmap__16u1__p3_0,
  136934. 5,
  136935. 5
  136936. };
  136937. static static_codebook _16u1__p3_0 = {
  136938. 4, 625,
  136939. _vq_lengthlist__16u1__p3_0,
  136940. 1, -533725184, 1611661312, 3, 0,
  136941. _vq_quantlist__16u1__p3_0,
  136942. NULL,
  136943. &_vq_auxt__16u1__p3_0,
  136944. NULL,
  136945. 0
  136946. };
  136947. static long _vq_quantlist__16u1__p4_0[] = {
  136948. 2,
  136949. 1,
  136950. 3,
  136951. 0,
  136952. 4,
  136953. };
  136954. static long _vq_lengthlist__16u1__p4_0[] = {
  136955. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  136956. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  136957. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  136958. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  136959. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  136960. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  136961. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  136962. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  136963. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  136964. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  136965. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  136966. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  136967. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  136968. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  136969. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  136970. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  136971. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  136972. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  136973. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  136974. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  136975. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  136976. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  136977. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  136978. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  136979. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  136980. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  136981. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  136982. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  136983. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  136984. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  136985. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  136986. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  136987. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  136988. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  136989. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  136990. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  136991. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  136992. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  136993. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  136994. 11,
  136995. };
  136996. static float _vq_quantthresh__16u1__p4_0[] = {
  136997. -1.5, -0.5, 0.5, 1.5,
  136998. };
  136999. static long _vq_quantmap__16u1__p4_0[] = {
  137000. 3, 1, 0, 2, 4,
  137001. };
  137002. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  137003. _vq_quantthresh__16u1__p4_0,
  137004. _vq_quantmap__16u1__p4_0,
  137005. 5,
  137006. 5
  137007. };
  137008. static static_codebook _16u1__p4_0 = {
  137009. 4, 625,
  137010. _vq_lengthlist__16u1__p4_0,
  137011. 1, -533725184, 1611661312, 3, 0,
  137012. _vq_quantlist__16u1__p4_0,
  137013. NULL,
  137014. &_vq_auxt__16u1__p4_0,
  137015. NULL,
  137016. 0
  137017. };
  137018. static long _vq_quantlist__16u1__p5_0[] = {
  137019. 4,
  137020. 3,
  137021. 5,
  137022. 2,
  137023. 6,
  137024. 1,
  137025. 7,
  137026. 0,
  137027. 8,
  137028. };
  137029. static long _vq_lengthlist__16u1__p5_0[] = {
  137030. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137031. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  137032. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  137033. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  137034. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  137035. 13,
  137036. };
  137037. static float _vq_quantthresh__16u1__p5_0[] = {
  137038. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137039. };
  137040. static long _vq_quantmap__16u1__p5_0[] = {
  137041. 7, 5, 3, 1, 0, 2, 4, 6,
  137042. 8,
  137043. };
  137044. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  137045. _vq_quantthresh__16u1__p5_0,
  137046. _vq_quantmap__16u1__p5_0,
  137047. 9,
  137048. 9
  137049. };
  137050. static static_codebook _16u1__p5_0 = {
  137051. 2, 81,
  137052. _vq_lengthlist__16u1__p5_0,
  137053. 1, -531628032, 1611661312, 4, 0,
  137054. _vq_quantlist__16u1__p5_0,
  137055. NULL,
  137056. &_vq_auxt__16u1__p5_0,
  137057. NULL,
  137058. 0
  137059. };
  137060. static long _vq_quantlist__16u1__p6_0[] = {
  137061. 4,
  137062. 3,
  137063. 5,
  137064. 2,
  137065. 6,
  137066. 1,
  137067. 7,
  137068. 0,
  137069. 8,
  137070. };
  137071. static long _vq_lengthlist__16u1__p6_0[] = {
  137072. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  137073. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  137074. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137075. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137076. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137077. 11,
  137078. };
  137079. static float _vq_quantthresh__16u1__p6_0[] = {
  137080. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137081. };
  137082. static long _vq_quantmap__16u1__p6_0[] = {
  137083. 7, 5, 3, 1, 0, 2, 4, 6,
  137084. 8,
  137085. };
  137086. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  137087. _vq_quantthresh__16u1__p6_0,
  137088. _vq_quantmap__16u1__p6_0,
  137089. 9,
  137090. 9
  137091. };
  137092. static static_codebook _16u1__p6_0 = {
  137093. 2, 81,
  137094. _vq_lengthlist__16u1__p6_0,
  137095. 1, -531628032, 1611661312, 4, 0,
  137096. _vq_quantlist__16u1__p6_0,
  137097. NULL,
  137098. &_vq_auxt__16u1__p6_0,
  137099. NULL,
  137100. 0
  137101. };
  137102. static long _vq_quantlist__16u1__p7_0[] = {
  137103. 1,
  137104. 0,
  137105. 2,
  137106. };
  137107. static long _vq_lengthlist__16u1__p7_0[] = {
  137108. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  137109. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  137110. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  137111. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  137112. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  137113. 13,
  137114. };
  137115. static float _vq_quantthresh__16u1__p7_0[] = {
  137116. -5.5, 5.5,
  137117. };
  137118. static long _vq_quantmap__16u1__p7_0[] = {
  137119. 1, 0, 2,
  137120. };
  137121. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  137122. _vq_quantthresh__16u1__p7_0,
  137123. _vq_quantmap__16u1__p7_0,
  137124. 3,
  137125. 3
  137126. };
  137127. static static_codebook _16u1__p7_0 = {
  137128. 4, 81,
  137129. _vq_lengthlist__16u1__p7_0,
  137130. 1, -529137664, 1618345984, 2, 0,
  137131. _vq_quantlist__16u1__p7_0,
  137132. NULL,
  137133. &_vq_auxt__16u1__p7_0,
  137134. NULL,
  137135. 0
  137136. };
  137137. static long _vq_quantlist__16u1__p7_1[] = {
  137138. 5,
  137139. 4,
  137140. 6,
  137141. 3,
  137142. 7,
  137143. 2,
  137144. 8,
  137145. 1,
  137146. 9,
  137147. 0,
  137148. 10,
  137149. };
  137150. static long _vq_lengthlist__16u1__p7_1[] = {
  137151. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  137152. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  137153. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  137154. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  137155. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  137156. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  137157. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  137158. 8, 9, 9,10,10,10,10,10,10,
  137159. };
  137160. static float _vq_quantthresh__16u1__p7_1[] = {
  137161. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137162. 3.5, 4.5,
  137163. };
  137164. static long _vq_quantmap__16u1__p7_1[] = {
  137165. 9, 7, 5, 3, 1, 0, 2, 4,
  137166. 6, 8, 10,
  137167. };
  137168. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  137169. _vq_quantthresh__16u1__p7_1,
  137170. _vq_quantmap__16u1__p7_1,
  137171. 11,
  137172. 11
  137173. };
  137174. static static_codebook _16u1__p7_1 = {
  137175. 2, 121,
  137176. _vq_lengthlist__16u1__p7_1,
  137177. 1, -531365888, 1611661312, 4, 0,
  137178. _vq_quantlist__16u1__p7_1,
  137179. NULL,
  137180. &_vq_auxt__16u1__p7_1,
  137181. NULL,
  137182. 0
  137183. };
  137184. static long _vq_quantlist__16u1__p8_0[] = {
  137185. 5,
  137186. 4,
  137187. 6,
  137188. 3,
  137189. 7,
  137190. 2,
  137191. 8,
  137192. 1,
  137193. 9,
  137194. 0,
  137195. 10,
  137196. };
  137197. static long _vq_lengthlist__16u1__p8_0[] = {
  137198. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  137199. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  137200. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  137201. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  137202. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  137203. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  137204. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  137205. 13,14,14,15,15,16,16,15,16,
  137206. };
  137207. static float _vq_quantthresh__16u1__p8_0[] = {
  137208. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  137209. 38.5, 49.5,
  137210. };
  137211. static long _vq_quantmap__16u1__p8_0[] = {
  137212. 9, 7, 5, 3, 1, 0, 2, 4,
  137213. 6, 8, 10,
  137214. };
  137215. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  137216. _vq_quantthresh__16u1__p8_0,
  137217. _vq_quantmap__16u1__p8_0,
  137218. 11,
  137219. 11
  137220. };
  137221. static static_codebook _16u1__p8_0 = {
  137222. 2, 121,
  137223. _vq_lengthlist__16u1__p8_0,
  137224. 1, -524582912, 1618345984, 4, 0,
  137225. _vq_quantlist__16u1__p8_0,
  137226. NULL,
  137227. &_vq_auxt__16u1__p8_0,
  137228. NULL,
  137229. 0
  137230. };
  137231. static long _vq_quantlist__16u1__p8_1[] = {
  137232. 5,
  137233. 4,
  137234. 6,
  137235. 3,
  137236. 7,
  137237. 2,
  137238. 8,
  137239. 1,
  137240. 9,
  137241. 0,
  137242. 10,
  137243. };
  137244. static long _vq_lengthlist__16u1__p8_1[] = {
  137245. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  137246. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  137247. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  137248. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137249. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137250. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137251. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137252. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  137253. };
  137254. static float _vq_quantthresh__16u1__p8_1[] = {
  137255. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137256. 3.5, 4.5,
  137257. };
  137258. static long _vq_quantmap__16u1__p8_1[] = {
  137259. 9, 7, 5, 3, 1, 0, 2, 4,
  137260. 6, 8, 10,
  137261. };
  137262. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  137263. _vq_quantthresh__16u1__p8_1,
  137264. _vq_quantmap__16u1__p8_1,
  137265. 11,
  137266. 11
  137267. };
  137268. static static_codebook _16u1__p8_1 = {
  137269. 2, 121,
  137270. _vq_lengthlist__16u1__p8_1,
  137271. 1, -531365888, 1611661312, 4, 0,
  137272. _vq_quantlist__16u1__p8_1,
  137273. NULL,
  137274. &_vq_auxt__16u1__p8_1,
  137275. NULL,
  137276. 0
  137277. };
  137278. static long _vq_quantlist__16u1__p9_0[] = {
  137279. 7,
  137280. 6,
  137281. 8,
  137282. 5,
  137283. 9,
  137284. 4,
  137285. 10,
  137286. 3,
  137287. 11,
  137288. 2,
  137289. 12,
  137290. 1,
  137291. 13,
  137292. 0,
  137293. 14,
  137294. };
  137295. static long _vq_lengthlist__16u1__p9_0[] = {
  137296. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137297. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137298. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137299. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137300. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137301. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137302. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137303. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137304. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137305. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137306. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137307. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137308. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137309. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137310. 8,
  137311. };
  137312. static float _vq_quantthresh__16u1__p9_0[] = {
  137313. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  137314. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  137315. };
  137316. static long _vq_quantmap__16u1__p9_0[] = {
  137317. 13, 11, 9, 7, 5, 3, 1, 0,
  137318. 2, 4, 6, 8, 10, 12, 14,
  137319. };
  137320. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  137321. _vq_quantthresh__16u1__p9_0,
  137322. _vq_quantmap__16u1__p9_0,
  137323. 15,
  137324. 15
  137325. };
  137326. static static_codebook _16u1__p9_0 = {
  137327. 2, 225,
  137328. _vq_lengthlist__16u1__p9_0,
  137329. 1, -514071552, 1627381760, 4, 0,
  137330. _vq_quantlist__16u1__p9_0,
  137331. NULL,
  137332. &_vq_auxt__16u1__p9_0,
  137333. NULL,
  137334. 0
  137335. };
  137336. static long _vq_quantlist__16u1__p9_1[] = {
  137337. 7,
  137338. 6,
  137339. 8,
  137340. 5,
  137341. 9,
  137342. 4,
  137343. 10,
  137344. 3,
  137345. 11,
  137346. 2,
  137347. 12,
  137348. 1,
  137349. 13,
  137350. 0,
  137351. 14,
  137352. };
  137353. static long _vq_lengthlist__16u1__p9_1[] = {
  137354. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  137355. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  137356. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  137357. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  137358. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  137359. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  137360. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  137361. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  137362. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  137363. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137364. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137365. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137366. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137367. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137368. 9,
  137369. };
  137370. static float _vq_quantthresh__16u1__p9_1[] = {
  137371. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  137372. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  137373. };
  137374. static long _vq_quantmap__16u1__p9_1[] = {
  137375. 13, 11, 9, 7, 5, 3, 1, 0,
  137376. 2, 4, 6, 8, 10, 12, 14,
  137377. };
  137378. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  137379. _vq_quantthresh__16u1__p9_1,
  137380. _vq_quantmap__16u1__p9_1,
  137381. 15,
  137382. 15
  137383. };
  137384. static static_codebook _16u1__p9_1 = {
  137385. 2, 225,
  137386. _vq_lengthlist__16u1__p9_1,
  137387. 1, -522338304, 1620115456, 4, 0,
  137388. _vq_quantlist__16u1__p9_1,
  137389. NULL,
  137390. &_vq_auxt__16u1__p9_1,
  137391. NULL,
  137392. 0
  137393. };
  137394. static long _vq_quantlist__16u1__p9_2[] = {
  137395. 8,
  137396. 7,
  137397. 9,
  137398. 6,
  137399. 10,
  137400. 5,
  137401. 11,
  137402. 4,
  137403. 12,
  137404. 3,
  137405. 13,
  137406. 2,
  137407. 14,
  137408. 1,
  137409. 15,
  137410. 0,
  137411. 16,
  137412. };
  137413. static long _vq_lengthlist__16u1__p9_2[] = {
  137414. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  137415. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  137416. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  137417. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  137418. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  137419. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  137420. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  137421. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  137422. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  137423. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  137424. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  137425. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  137426. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  137427. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  137428. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  137429. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  137430. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  137431. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  137432. 10,
  137433. };
  137434. static float _vq_quantthresh__16u1__p9_2[] = {
  137435. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137436. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137437. };
  137438. static long _vq_quantmap__16u1__p9_2[] = {
  137439. 15, 13, 11, 9, 7, 5, 3, 1,
  137440. 0, 2, 4, 6, 8, 10, 12, 14,
  137441. 16,
  137442. };
  137443. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  137444. _vq_quantthresh__16u1__p9_2,
  137445. _vq_quantmap__16u1__p9_2,
  137446. 17,
  137447. 17
  137448. };
  137449. static static_codebook _16u1__p9_2 = {
  137450. 2, 289,
  137451. _vq_lengthlist__16u1__p9_2,
  137452. 1, -529530880, 1611661312, 5, 0,
  137453. _vq_quantlist__16u1__p9_2,
  137454. NULL,
  137455. &_vq_auxt__16u1__p9_2,
  137456. NULL,
  137457. 0
  137458. };
  137459. static long _huff_lengthlist__16u1__short[] = {
  137460. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  137461. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  137462. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  137463. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  137464. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  137465. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  137466. 16,16,16,16,
  137467. };
  137468. static static_codebook _huff_book__16u1__short = {
  137469. 2, 100,
  137470. _huff_lengthlist__16u1__short,
  137471. 0, 0, 0, 0, 0,
  137472. NULL,
  137473. NULL,
  137474. NULL,
  137475. NULL,
  137476. 0
  137477. };
  137478. static long _huff_lengthlist__16u2__long[] = {
  137479. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  137480. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  137481. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  137482. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  137483. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  137484. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  137485. 13,14,18,18,
  137486. };
  137487. static static_codebook _huff_book__16u2__long = {
  137488. 2, 100,
  137489. _huff_lengthlist__16u2__long,
  137490. 0, 0, 0, 0, 0,
  137491. NULL,
  137492. NULL,
  137493. NULL,
  137494. NULL,
  137495. 0
  137496. };
  137497. static long _huff_lengthlist__16u2__short[] = {
  137498. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  137499. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  137500. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  137501. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  137502. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  137503. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  137504. 16,16,16,16,
  137505. };
  137506. static static_codebook _huff_book__16u2__short = {
  137507. 2, 100,
  137508. _huff_lengthlist__16u2__short,
  137509. 0, 0, 0, 0, 0,
  137510. NULL,
  137511. NULL,
  137512. NULL,
  137513. NULL,
  137514. 0
  137515. };
  137516. static long _vq_quantlist__16u2_p1_0[] = {
  137517. 1,
  137518. 0,
  137519. 2,
  137520. };
  137521. static long _vq_lengthlist__16u2_p1_0[] = {
  137522. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  137523. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  137524. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  137525. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  137526. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  137527. 10,
  137528. };
  137529. static float _vq_quantthresh__16u2_p1_0[] = {
  137530. -0.5, 0.5,
  137531. };
  137532. static long _vq_quantmap__16u2_p1_0[] = {
  137533. 1, 0, 2,
  137534. };
  137535. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  137536. _vq_quantthresh__16u2_p1_0,
  137537. _vq_quantmap__16u2_p1_0,
  137538. 3,
  137539. 3
  137540. };
  137541. static static_codebook _16u2_p1_0 = {
  137542. 4, 81,
  137543. _vq_lengthlist__16u2_p1_0,
  137544. 1, -535822336, 1611661312, 2, 0,
  137545. _vq_quantlist__16u2_p1_0,
  137546. NULL,
  137547. &_vq_auxt__16u2_p1_0,
  137548. NULL,
  137549. 0
  137550. };
  137551. static long _vq_quantlist__16u2_p2_0[] = {
  137552. 2,
  137553. 1,
  137554. 3,
  137555. 0,
  137556. 4,
  137557. };
  137558. static long _vq_lengthlist__16u2_p2_0[] = {
  137559. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  137560. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  137561. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  137562. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  137563. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  137564. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  137565. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  137566. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  137567. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137568. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  137569. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  137570. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  137571. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  137572. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  137573. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  137574. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  137575. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  137576. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  137577. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  137578. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  137579. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  137580. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  137581. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  137582. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  137583. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  137584. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  137585. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  137586. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  137587. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  137588. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  137589. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  137590. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  137591. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  137592. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  137593. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  137594. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  137595. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  137596. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  137597. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  137598. 13,
  137599. };
  137600. static float _vq_quantthresh__16u2_p2_0[] = {
  137601. -1.5, -0.5, 0.5, 1.5,
  137602. };
  137603. static long _vq_quantmap__16u2_p2_0[] = {
  137604. 3, 1, 0, 2, 4,
  137605. };
  137606. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  137607. _vq_quantthresh__16u2_p2_0,
  137608. _vq_quantmap__16u2_p2_0,
  137609. 5,
  137610. 5
  137611. };
  137612. static static_codebook _16u2_p2_0 = {
  137613. 4, 625,
  137614. _vq_lengthlist__16u2_p2_0,
  137615. 1, -533725184, 1611661312, 3, 0,
  137616. _vq_quantlist__16u2_p2_0,
  137617. NULL,
  137618. &_vq_auxt__16u2_p2_0,
  137619. NULL,
  137620. 0
  137621. };
  137622. static long _vq_quantlist__16u2_p3_0[] = {
  137623. 4,
  137624. 3,
  137625. 5,
  137626. 2,
  137627. 6,
  137628. 1,
  137629. 7,
  137630. 0,
  137631. 8,
  137632. };
  137633. static long _vq_lengthlist__16u2_p3_0[] = {
  137634. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  137635. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  137636. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137637. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137638. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137639. 11,
  137640. };
  137641. static float _vq_quantthresh__16u2_p3_0[] = {
  137642. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137643. };
  137644. static long _vq_quantmap__16u2_p3_0[] = {
  137645. 7, 5, 3, 1, 0, 2, 4, 6,
  137646. 8,
  137647. };
  137648. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  137649. _vq_quantthresh__16u2_p3_0,
  137650. _vq_quantmap__16u2_p3_0,
  137651. 9,
  137652. 9
  137653. };
  137654. static static_codebook _16u2_p3_0 = {
  137655. 2, 81,
  137656. _vq_lengthlist__16u2_p3_0,
  137657. 1, -531628032, 1611661312, 4, 0,
  137658. _vq_quantlist__16u2_p3_0,
  137659. NULL,
  137660. &_vq_auxt__16u2_p3_0,
  137661. NULL,
  137662. 0
  137663. };
  137664. static long _vq_quantlist__16u2_p4_0[] = {
  137665. 8,
  137666. 7,
  137667. 9,
  137668. 6,
  137669. 10,
  137670. 5,
  137671. 11,
  137672. 4,
  137673. 12,
  137674. 3,
  137675. 13,
  137676. 2,
  137677. 14,
  137678. 1,
  137679. 15,
  137680. 0,
  137681. 16,
  137682. };
  137683. static long _vq_lengthlist__16u2_p4_0[] = {
  137684. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  137685. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137686. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137687. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137688. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137689. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137690. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137691. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  137692. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  137693. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  137694. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  137695. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  137696. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  137697. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  137698. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  137699. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  137700. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  137701. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  137702. 14,
  137703. };
  137704. static float _vq_quantthresh__16u2_p4_0[] = {
  137705. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137706. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137707. };
  137708. static long _vq_quantmap__16u2_p4_0[] = {
  137709. 15, 13, 11, 9, 7, 5, 3, 1,
  137710. 0, 2, 4, 6, 8, 10, 12, 14,
  137711. 16,
  137712. };
  137713. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  137714. _vq_quantthresh__16u2_p4_0,
  137715. _vq_quantmap__16u2_p4_0,
  137716. 17,
  137717. 17
  137718. };
  137719. static static_codebook _16u2_p4_0 = {
  137720. 2, 289,
  137721. _vq_lengthlist__16u2_p4_0,
  137722. 1, -529530880, 1611661312, 5, 0,
  137723. _vq_quantlist__16u2_p4_0,
  137724. NULL,
  137725. &_vq_auxt__16u2_p4_0,
  137726. NULL,
  137727. 0
  137728. };
  137729. static long _vq_quantlist__16u2_p5_0[] = {
  137730. 1,
  137731. 0,
  137732. 2,
  137733. };
  137734. static long _vq_lengthlist__16u2_p5_0[] = {
  137735. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  137736. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  137737. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  137738. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  137739. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  137740. 10,
  137741. };
  137742. static float _vq_quantthresh__16u2_p5_0[] = {
  137743. -5.5, 5.5,
  137744. };
  137745. static long _vq_quantmap__16u2_p5_0[] = {
  137746. 1, 0, 2,
  137747. };
  137748. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  137749. _vq_quantthresh__16u2_p5_0,
  137750. _vq_quantmap__16u2_p5_0,
  137751. 3,
  137752. 3
  137753. };
  137754. static static_codebook _16u2_p5_0 = {
  137755. 4, 81,
  137756. _vq_lengthlist__16u2_p5_0,
  137757. 1, -529137664, 1618345984, 2, 0,
  137758. _vq_quantlist__16u2_p5_0,
  137759. NULL,
  137760. &_vq_auxt__16u2_p5_0,
  137761. NULL,
  137762. 0
  137763. };
  137764. static long _vq_quantlist__16u2_p5_1[] = {
  137765. 5,
  137766. 4,
  137767. 6,
  137768. 3,
  137769. 7,
  137770. 2,
  137771. 8,
  137772. 1,
  137773. 9,
  137774. 0,
  137775. 10,
  137776. };
  137777. static long _vq_lengthlist__16u2_p5_1[] = {
  137778. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  137779. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  137780. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  137781. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137782. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137783. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137784. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137785. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137786. };
  137787. static float _vq_quantthresh__16u2_p5_1[] = {
  137788. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137789. 3.5, 4.5,
  137790. };
  137791. static long _vq_quantmap__16u2_p5_1[] = {
  137792. 9, 7, 5, 3, 1, 0, 2, 4,
  137793. 6, 8, 10,
  137794. };
  137795. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  137796. _vq_quantthresh__16u2_p5_1,
  137797. _vq_quantmap__16u2_p5_1,
  137798. 11,
  137799. 11
  137800. };
  137801. static static_codebook _16u2_p5_1 = {
  137802. 2, 121,
  137803. _vq_lengthlist__16u2_p5_1,
  137804. 1, -531365888, 1611661312, 4, 0,
  137805. _vq_quantlist__16u2_p5_1,
  137806. NULL,
  137807. &_vq_auxt__16u2_p5_1,
  137808. NULL,
  137809. 0
  137810. };
  137811. static long _vq_quantlist__16u2_p6_0[] = {
  137812. 6,
  137813. 5,
  137814. 7,
  137815. 4,
  137816. 8,
  137817. 3,
  137818. 9,
  137819. 2,
  137820. 10,
  137821. 1,
  137822. 11,
  137823. 0,
  137824. 12,
  137825. };
  137826. static long _vq_lengthlist__16u2_p6_0[] = {
  137827. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  137828. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  137829. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  137830. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  137831. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  137832. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  137833. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  137834. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  137835. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  137836. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  137837. 12,13,13,14,14,14,14,15,15,
  137838. };
  137839. static float _vq_quantthresh__16u2_p6_0[] = {
  137840. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137841. 12.5, 17.5, 22.5, 27.5,
  137842. };
  137843. static long _vq_quantmap__16u2_p6_0[] = {
  137844. 11, 9, 7, 5, 3, 1, 0, 2,
  137845. 4, 6, 8, 10, 12,
  137846. };
  137847. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  137848. _vq_quantthresh__16u2_p6_0,
  137849. _vq_quantmap__16u2_p6_0,
  137850. 13,
  137851. 13
  137852. };
  137853. static static_codebook _16u2_p6_0 = {
  137854. 2, 169,
  137855. _vq_lengthlist__16u2_p6_0,
  137856. 1, -526516224, 1616117760, 4, 0,
  137857. _vq_quantlist__16u2_p6_0,
  137858. NULL,
  137859. &_vq_auxt__16u2_p6_0,
  137860. NULL,
  137861. 0
  137862. };
  137863. static long _vq_quantlist__16u2_p6_1[] = {
  137864. 2,
  137865. 1,
  137866. 3,
  137867. 0,
  137868. 4,
  137869. };
  137870. static long _vq_lengthlist__16u2_p6_1[] = {
  137871. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  137872. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  137873. };
  137874. static float _vq_quantthresh__16u2_p6_1[] = {
  137875. -1.5, -0.5, 0.5, 1.5,
  137876. };
  137877. static long _vq_quantmap__16u2_p6_1[] = {
  137878. 3, 1, 0, 2, 4,
  137879. };
  137880. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  137881. _vq_quantthresh__16u2_p6_1,
  137882. _vq_quantmap__16u2_p6_1,
  137883. 5,
  137884. 5
  137885. };
  137886. static static_codebook _16u2_p6_1 = {
  137887. 2, 25,
  137888. _vq_lengthlist__16u2_p6_1,
  137889. 1, -533725184, 1611661312, 3, 0,
  137890. _vq_quantlist__16u2_p6_1,
  137891. NULL,
  137892. &_vq_auxt__16u2_p6_1,
  137893. NULL,
  137894. 0
  137895. };
  137896. static long _vq_quantlist__16u2_p7_0[] = {
  137897. 6,
  137898. 5,
  137899. 7,
  137900. 4,
  137901. 8,
  137902. 3,
  137903. 9,
  137904. 2,
  137905. 10,
  137906. 1,
  137907. 11,
  137908. 0,
  137909. 12,
  137910. };
  137911. static long _vq_lengthlist__16u2_p7_0[] = {
  137912. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  137913. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  137914. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  137915. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  137916. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  137917. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  137918. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  137919. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  137920. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  137921. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  137922. 12,13,13,13,14,14,14,15,14,
  137923. };
  137924. static float _vq_quantthresh__16u2_p7_0[] = {
  137925. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  137926. 27.5, 38.5, 49.5, 60.5,
  137927. };
  137928. static long _vq_quantmap__16u2_p7_0[] = {
  137929. 11, 9, 7, 5, 3, 1, 0, 2,
  137930. 4, 6, 8, 10, 12,
  137931. };
  137932. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  137933. _vq_quantthresh__16u2_p7_0,
  137934. _vq_quantmap__16u2_p7_0,
  137935. 13,
  137936. 13
  137937. };
  137938. static static_codebook _16u2_p7_0 = {
  137939. 2, 169,
  137940. _vq_lengthlist__16u2_p7_0,
  137941. 1, -523206656, 1618345984, 4, 0,
  137942. _vq_quantlist__16u2_p7_0,
  137943. NULL,
  137944. &_vq_auxt__16u2_p7_0,
  137945. NULL,
  137946. 0
  137947. };
  137948. static long _vq_quantlist__16u2_p7_1[] = {
  137949. 5,
  137950. 4,
  137951. 6,
  137952. 3,
  137953. 7,
  137954. 2,
  137955. 8,
  137956. 1,
  137957. 9,
  137958. 0,
  137959. 10,
  137960. };
  137961. static long _vq_lengthlist__16u2_p7_1[] = {
  137962. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  137963. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  137964. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  137965. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  137966. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  137967. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  137968. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  137969. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137970. };
  137971. static float _vq_quantthresh__16u2_p7_1[] = {
  137972. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137973. 3.5, 4.5,
  137974. };
  137975. static long _vq_quantmap__16u2_p7_1[] = {
  137976. 9, 7, 5, 3, 1, 0, 2, 4,
  137977. 6, 8, 10,
  137978. };
  137979. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  137980. _vq_quantthresh__16u2_p7_1,
  137981. _vq_quantmap__16u2_p7_1,
  137982. 11,
  137983. 11
  137984. };
  137985. static static_codebook _16u2_p7_1 = {
  137986. 2, 121,
  137987. _vq_lengthlist__16u2_p7_1,
  137988. 1, -531365888, 1611661312, 4, 0,
  137989. _vq_quantlist__16u2_p7_1,
  137990. NULL,
  137991. &_vq_auxt__16u2_p7_1,
  137992. NULL,
  137993. 0
  137994. };
  137995. static long _vq_quantlist__16u2_p8_0[] = {
  137996. 7,
  137997. 6,
  137998. 8,
  137999. 5,
  138000. 9,
  138001. 4,
  138002. 10,
  138003. 3,
  138004. 11,
  138005. 2,
  138006. 12,
  138007. 1,
  138008. 13,
  138009. 0,
  138010. 14,
  138011. };
  138012. static long _vq_lengthlist__16u2_p8_0[] = {
  138013. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  138014. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  138015. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  138016. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  138017. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  138018. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  138019. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  138020. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  138021. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  138022. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  138023. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  138024. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  138025. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  138026. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  138027. 14,
  138028. };
  138029. static float _vq_quantthresh__16u2_p8_0[] = {
  138030. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138031. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138032. };
  138033. static long _vq_quantmap__16u2_p8_0[] = {
  138034. 13, 11, 9, 7, 5, 3, 1, 0,
  138035. 2, 4, 6, 8, 10, 12, 14,
  138036. };
  138037. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  138038. _vq_quantthresh__16u2_p8_0,
  138039. _vq_quantmap__16u2_p8_0,
  138040. 15,
  138041. 15
  138042. };
  138043. static static_codebook _16u2_p8_0 = {
  138044. 2, 225,
  138045. _vq_lengthlist__16u2_p8_0,
  138046. 1, -520986624, 1620377600, 4, 0,
  138047. _vq_quantlist__16u2_p8_0,
  138048. NULL,
  138049. &_vq_auxt__16u2_p8_0,
  138050. NULL,
  138051. 0
  138052. };
  138053. static long _vq_quantlist__16u2_p8_1[] = {
  138054. 10,
  138055. 9,
  138056. 11,
  138057. 8,
  138058. 12,
  138059. 7,
  138060. 13,
  138061. 6,
  138062. 14,
  138063. 5,
  138064. 15,
  138065. 4,
  138066. 16,
  138067. 3,
  138068. 17,
  138069. 2,
  138070. 18,
  138071. 1,
  138072. 19,
  138073. 0,
  138074. 20,
  138075. };
  138076. static long _vq_lengthlist__16u2_p8_1[] = {
  138077. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  138078. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  138079. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  138080. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  138081. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  138082. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  138083. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  138084. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  138085. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  138086. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  138087. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  138088. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  138089. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  138090. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  138091. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  138092. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  138093. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  138094. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  138095. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  138096. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  138097. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  138098. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  138099. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  138100. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  138101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  138102. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  138103. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  138104. 11,11,10,11,11,11,10,11,11,
  138105. };
  138106. static float _vq_quantthresh__16u2_p8_1[] = {
  138107. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138108. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138109. 6.5, 7.5, 8.5, 9.5,
  138110. };
  138111. static long _vq_quantmap__16u2_p8_1[] = {
  138112. 19, 17, 15, 13, 11, 9, 7, 5,
  138113. 3, 1, 0, 2, 4, 6, 8, 10,
  138114. 12, 14, 16, 18, 20,
  138115. };
  138116. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  138117. _vq_quantthresh__16u2_p8_1,
  138118. _vq_quantmap__16u2_p8_1,
  138119. 21,
  138120. 21
  138121. };
  138122. static static_codebook _16u2_p8_1 = {
  138123. 2, 441,
  138124. _vq_lengthlist__16u2_p8_1,
  138125. 1, -529268736, 1611661312, 5, 0,
  138126. _vq_quantlist__16u2_p8_1,
  138127. NULL,
  138128. &_vq_auxt__16u2_p8_1,
  138129. NULL,
  138130. 0
  138131. };
  138132. static long _vq_quantlist__16u2_p9_0[] = {
  138133. 5586,
  138134. 4655,
  138135. 6517,
  138136. 3724,
  138137. 7448,
  138138. 2793,
  138139. 8379,
  138140. 1862,
  138141. 9310,
  138142. 931,
  138143. 10241,
  138144. 0,
  138145. 11172,
  138146. 5521,
  138147. 5651,
  138148. };
  138149. static long _vq_lengthlist__16u2_p9_0[] = {
  138150. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  138151. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138152. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138153. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138154. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138155. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138156. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138157. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138159. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138162. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  138163. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  138164. 5,
  138165. };
  138166. static float _vq_quantthresh__16u2_p9_0[] = {
  138167. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  138168. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  138169. };
  138170. static long _vq_quantmap__16u2_p9_0[] = {
  138171. 11, 9, 7, 5, 3, 1, 13, 0,
  138172. 14, 2, 4, 6, 8, 10, 12,
  138173. };
  138174. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  138175. _vq_quantthresh__16u2_p9_0,
  138176. _vq_quantmap__16u2_p9_0,
  138177. 15,
  138178. 15
  138179. };
  138180. static static_codebook _16u2_p9_0 = {
  138181. 2, 225,
  138182. _vq_lengthlist__16u2_p9_0,
  138183. 1, -510275072, 1611661312, 14, 0,
  138184. _vq_quantlist__16u2_p9_0,
  138185. NULL,
  138186. &_vq_auxt__16u2_p9_0,
  138187. NULL,
  138188. 0
  138189. };
  138190. static long _vq_quantlist__16u2_p9_1[] = {
  138191. 392,
  138192. 343,
  138193. 441,
  138194. 294,
  138195. 490,
  138196. 245,
  138197. 539,
  138198. 196,
  138199. 588,
  138200. 147,
  138201. 637,
  138202. 98,
  138203. 686,
  138204. 49,
  138205. 735,
  138206. 0,
  138207. 784,
  138208. 388,
  138209. 396,
  138210. };
  138211. static long _vq_lengthlist__16u2_p9_1[] = {
  138212. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  138213. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  138214. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  138215. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  138216. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  138217. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  138218. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138219. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  138220. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  138221. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138222. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138223. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138224. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138225. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138226. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  138227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138232. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  138233. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  138234. 11,11,11,11,11,11,11, 5, 4,
  138235. };
  138236. static float _vq_quantthresh__16u2_p9_1[] = {
  138237. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  138238. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  138239. 318.5, 367.5,
  138240. };
  138241. static long _vq_quantmap__16u2_p9_1[] = {
  138242. 15, 13, 11, 9, 7, 5, 3, 1,
  138243. 17, 0, 18, 2, 4, 6, 8, 10,
  138244. 12, 14, 16,
  138245. };
  138246. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  138247. _vq_quantthresh__16u2_p9_1,
  138248. _vq_quantmap__16u2_p9_1,
  138249. 19,
  138250. 19
  138251. };
  138252. static static_codebook _16u2_p9_1 = {
  138253. 2, 361,
  138254. _vq_lengthlist__16u2_p9_1,
  138255. 1, -518488064, 1611661312, 10, 0,
  138256. _vq_quantlist__16u2_p9_1,
  138257. NULL,
  138258. &_vq_auxt__16u2_p9_1,
  138259. NULL,
  138260. 0
  138261. };
  138262. static long _vq_quantlist__16u2_p9_2[] = {
  138263. 24,
  138264. 23,
  138265. 25,
  138266. 22,
  138267. 26,
  138268. 21,
  138269. 27,
  138270. 20,
  138271. 28,
  138272. 19,
  138273. 29,
  138274. 18,
  138275. 30,
  138276. 17,
  138277. 31,
  138278. 16,
  138279. 32,
  138280. 15,
  138281. 33,
  138282. 14,
  138283. 34,
  138284. 13,
  138285. 35,
  138286. 12,
  138287. 36,
  138288. 11,
  138289. 37,
  138290. 10,
  138291. 38,
  138292. 9,
  138293. 39,
  138294. 8,
  138295. 40,
  138296. 7,
  138297. 41,
  138298. 6,
  138299. 42,
  138300. 5,
  138301. 43,
  138302. 4,
  138303. 44,
  138304. 3,
  138305. 45,
  138306. 2,
  138307. 46,
  138308. 1,
  138309. 47,
  138310. 0,
  138311. 48,
  138312. };
  138313. static long _vq_lengthlist__16u2_p9_2[] = {
  138314. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  138315. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  138316. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  138317. 11,
  138318. };
  138319. static float _vq_quantthresh__16u2_p9_2[] = {
  138320. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  138321. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  138322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138324. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  138325. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  138326. };
  138327. static long _vq_quantmap__16u2_p9_2[] = {
  138328. 47, 45, 43, 41, 39, 37, 35, 33,
  138329. 31, 29, 27, 25, 23, 21, 19, 17,
  138330. 15, 13, 11, 9, 7, 5, 3, 1,
  138331. 0, 2, 4, 6, 8, 10, 12, 14,
  138332. 16, 18, 20, 22, 24, 26, 28, 30,
  138333. 32, 34, 36, 38, 40, 42, 44, 46,
  138334. 48,
  138335. };
  138336. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  138337. _vq_quantthresh__16u2_p9_2,
  138338. _vq_quantmap__16u2_p9_2,
  138339. 49,
  138340. 49
  138341. };
  138342. static static_codebook _16u2_p9_2 = {
  138343. 1, 49,
  138344. _vq_lengthlist__16u2_p9_2,
  138345. 1, -526909440, 1611661312, 6, 0,
  138346. _vq_quantlist__16u2_p9_2,
  138347. NULL,
  138348. &_vq_auxt__16u2_p9_2,
  138349. NULL,
  138350. 0
  138351. };
  138352. static long _vq_quantlist__8u0__p1_0[] = {
  138353. 1,
  138354. 0,
  138355. 2,
  138356. };
  138357. static long _vq_lengthlist__8u0__p1_0[] = {
  138358. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  138359. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  138360. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  138361. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  138362. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  138363. 11,
  138364. };
  138365. static float _vq_quantthresh__8u0__p1_0[] = {
  138366. -0.5, 0.5,
  138367. };
  138368. static long _vq_quantmap__8u0__p1_0[] = {
  138369. 1, 0, 2,
  138370. };
  138371. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  138372. _vq_quantthresh__8u0__p1_0,
  138373. _vq_quantmap__8u0__p1_0,
  138374. 3,
  138375. 3
  138376. };
  138377. static static_codebook _8u0__p1_0 = {
  138378. 4, 81,
  138379. _vq_lengthlist__8u0__p1_0,
  138380. 1, -535822336, 1611661312, 2, 0,
  138381. _vq_quantlist__8u0__p1_0,
  138382. NULL,
  138383. &_vq_auxt__8u0__p1_0,
  138384. NULL,
  138385. 0
  138386. };
  138387. static long _vq_quantlist__8u0__p2_0[] = {
  138388. 1,
  138389. 0,
  138390. 2,
  138391. };
  138392. static long _vq_lengthlist__8u0__p2_0[] = {
  138393. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  138394. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  138395. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  138396. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  138397. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  138398. 8,
  138399. };
  138400. static float _vq_quantthresh__8u0__p2_0[] = {
  138401. -0.5, 0.5,
  138402. };
  138403. static long _vq_quantmap__8u0__p2_0[] = {
  138404. 1, 0, 2,
  138405. };
  138406. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  138407. _vq_quantthresh__8u0__p2_0,
  138408. _vq_quantmap__8u0__p2_0,
  138409. 3,
  138410. 3
  138411. };
  138412. static static_codebook _8u0__p2_0 = {
  138413. 4, 81,
  138414. _vq_lengthlist__8u0__p2_0,
  138415. 1, -535822336, 1611661312, 2, 0,
  138416. _vq_quantlist__8u0__p2_0,
  138417. NULL,
  138418. &_vq_auxt__8u0__p2_0,
  138419. NULL,
  138420. 0
  138421. };
  138422. static long _vq_quantlist__8u0__p3_0[] = {
  138423. 2,
  138424. 1,
  138425. 3,
  138426. 0,
  138427. 4,
  138428. };
  138429. static long _vq_lengthlist__8u0__p3_0[] = {
  138430. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  138431. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  138432. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  138433. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  138434. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  138435. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  138436. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  138437. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  138438. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  138439. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  138440. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  138441. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  138442. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  138443. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  138444. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  138445. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  138446. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  138447. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  138448. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  138449. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  138450. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  138451. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  138452. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  138453. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  138454. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  138455. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  138456. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  138457. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  138458. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  138459. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  138460. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  138461. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  138462. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  138463. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  138464. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  138465. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  138466. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  138467. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  138468. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  138469. 16,
  138470. };
  138471. static float _vq_quantthresh__8u0__p3_0[] = {
  138472. -1.5, -0.5, 0.5, 1.5,
  138473. };
  138474. static long _vq_quantmap__8u0__p3_0[] = {
  138475. 3, 1, 0, 2, 4,
  138476. };
  138477. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  138478. _vq_quantthresh__8u0__p3_0,
  138479. _vq_quantmap__8u0__p3_0,
  138480. 5,
  138481. 5
  138482. };
  138483. static static_codebook _8u0__p3_0 = {
  138484. 4, 625,
  138485. _vq_lengthlist__8u0__p3_0,
  138486. 1, -533725184, 1611661312, 3, 0,
  138487. _vq_quantlist__8u0__p3_0,
  138488. NULL,
  138489. &_vq_auxt__8u0__p3_0,
  138490. NULL,
  138491. 0
  138492. };
  138493. static long _vq_quantlist__8u0__p4_0[] = {
  138494. 2,
  138495. 1,
  138496. 3,
  138497. 0,
  138498. 4,
  138499. };
  138500. static long _vq_lengthlist__8u0__p4_0[] = {
  138501. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  138502. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  138503. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  138504. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  138505. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  138506. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  138507. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  138508. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  138509. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  138510. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  138511. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  138512. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  138513. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  138514. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  138515. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  138516. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  138517. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  138518. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  138519. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  138520. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  138521. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  138522. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  138523. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  138524. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  138525. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  138526. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  138527. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  138528. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  138529. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  138530. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  138531. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  138532. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  138533. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  138534. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  138535. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  138536. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  138537. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  138538. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  138539. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  138540. 12,
  138541. };
  138542. static float _vq_quantthresh__8u0__p4_0[] = {
  138543. -1.5, -0.5, 0.5, 1.5,
  138544. };
  138545. static long _vq_quantmap__8u0__p4_0[] = {
  138546. 3, 1, 0, 2, 4,
  138547. };
  138548. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  138549. _vq_quantthresh__8u0__p4_0,
  138550. _vq_quantmap__8u0__p4_0,
  138551. 5,
  138552. 5
  138553. };
  138554. static static_codebook _8u0__p4_0 = {
  138555. 4, 625,
  138556. _vq_lengthlist__8u0__p4_0,
  138557. 1, -533725184, 1611661312, 3, 0,
  138558. _vq_quantlist__8u0__p4_0,
  138559. NULL,
  138560. &_vq_auxt__8u0__p4_0,
  138561. NULL,
  138562. 0
  138563. };
  138564. static long _vq_quantlist__8u0__p5_0[] = {
  138565. 4,
  138566. 3,
  138567. 5,
  138568. 2,
  138569. 6,
  138570. 1,
  138571. 7,
  138572. 0,
  138573. 8,
  138574. };
  138575. static long _vq_lengthlist__8u0__p5_0[] = {
  138576. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  138577. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  138578. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  138579. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138580. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  138581. 12,
  138582. };
  138583. static float _vq_quantthresh__8u0__p5_0[] = {
  138584. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138585. };
  138586. static long _vq_quantmap__8u0__p5_0[] = {
  138587. 7, 5, 3, 1, 0, 2, 4, 6,
  138588. 8,
  138589. };
  138590. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  138591. _vq_quantthresh__8u0__p5_0,
  138592. _vq_quantmap__8u0__p5_0,
  138593. 9,
  138594. 9
  138595. };
  138596. static static_codebook _8u0__p5_0 = {
  138597. 2, 81,
  138598. _vq_lengthlist__8u0__p5_0,
  138599. 1, -531628032, 1611661312, 4, 0,
  138600. _vq_quantlist__8u0__p5_0,
  138601. NULL,
  138602. &_vq_auxt__8u0__p5_0,
  138603. NULL,
  138604. 0
  138605. };
  138606. static long _vq_quantlist__8u0__p6_0[] = {
  138607. 6,
  138608. 5,
  138609. 7,
  138610. 4,
  138611. 8,
  138612. 3,
  138613. 9,
  138614. 2,
  138615. 10,
  138616. 1,
  138617. 11,
  138618. 0,
  138619. 12,
  138620. };
  138621. static long _vq_lengthlist__8u0__p6_0[] = {
  138622. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  138623. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  138624. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  138625. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  138626. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  138627. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  138628. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  138629. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  138630. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  138631. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  138632. 16, 0,15, 0,17, 0, 0, 0, 0,
  138633. };
  138634. static float _vq_quantthresh__8u0__p6_0[] = {
  138635. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138636. 12.5, 17.5, 22.5, 27.5,
  138637. };
  138638. static long _vq_quantmap__8u0__p6_0[] = {
  138639. 11, 9, 7, 5, 3, 1, 0, 2,
  138640. 4, 6, 8, 10, 12,
  138641. };
  138642. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  138643. _vq_quantthresh__8u0__p6_0,
  138644. _vq_quantmap__8u0__p6_0,
  138645. 13,
  138646. 13
  138647. };
  138648. static static_codebook _8u0__p6_0 = {
  138649. 2, 169,
  138650. _vq_lengthlist__8u0__p6_0,
  138651. 1, -526516224, 1616117760, 4, 0,
  138652. _vq_quantlist__8u0__p6_0,
  138653. NULL,
  138654. &_vq_auxt__8u0__p6_0,
  138655. NULL,
  138656. 0
  138657. };
  138658. static long _vq_quantlist__8u0__p6_1[] = {
  138659. 2,
  138660. 1,
  138661. 3,
  138662. 0,
  138663. 4,
  138664. };
  138665. static long _vq_lengthlist__8u0__p6_1[] = {
  138666. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  138667. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  138668. };
  138669. static float _vq_quantthresh__8u0__p6_1[] = {
  138670. -1.5, -0.5, 0.5, 1.5,
  138671. };
  138672. static long _vq_quantmap__8u0__p6_1[] = {
  138673. 3, 1, 0, 2, 4,
  138674. };
  138675. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  138676. _vq_quantthresh__8u0__p6_1,
  138677. _vq_quantmap__8u0__p6_1,
  138678. 5,
  138679. 5
  138680. };
  138681. static static_codebook _8u0__p6_1 = {
  138682. 2, 25,
  138683. _vq_lengthlist__8u0__p6_1,
  138684. 1, -533725184, 1611661312, 3, 0,
  138685. _vq_quantlist__8u0__p6_1,
  138686. NULL,
  138687. &_vq_auxt__8u0__p6_1,
  138688. NULL,
  138689. 0
  138690. };
  138691. static long _vq_quantlist__8u0__p7_0[] = {
  138692. 1,
  138693. 0,
  138694. 2,
  138695. };
  138696. static long _vq_lengthlist__8u0__p7_0[] = {
  138697. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138698. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138699. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138700. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138701. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138702. 7,
  138703. };
  138704. static float _vq_quantthresh__8u0__p7_0[] = {
  138705. -157.5, 157.5,
  138706. };
  138707. static long _vq_quantmap__8u0__p7_0[] = {
  138708. 1, 0, 2,
  138709. };
  138710. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  138711. _vq_quantthresh__8u0__p7_0,
  138712. _vq_quantmap__8u0__p7_0,
  138713. 3,
  138714. 3
  138715. };
  138716. static static_codebook _8u0__p7_0 = {
  138717. 4, 81,
  138718. _vq_lengthlist__8u0__p7_0,
  138719. 1, -518803456, 1628680192, 2, 0,
  138720. _vq_quantlist__8u0__p7_0,
  138721. NULL,
  138722. &_vq_auxt__8u0__p7_0,
  138723. NULL,
  138724. 0
  138725. };
  138726. static long _vq_quantlist__8u0__p7_1[] = {
  138727. 7,
  138728. 6,
  138729. 8,
  138730. 5,
  138731. 9,
  138732. 4,
  138733. 10,
  138734. 3,
  138735. 11,
  138736. 2,
  138737. 12,
  138738. 1,
  138739. 13,
  138740. 0,
  138741. 14,
  138742. };
  138743. static long _vq_lengthlist__8u0__p7_1[] = {
  138744. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  138745. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  138746. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  138747. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  138748. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  138749. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  138750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138756. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  138757. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138758. 10,
  138759. };
  138760. static float _vq_quantthresh__8u0__p7_1[] = {
  138761. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138762. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138763. };
  138764. static long _vq_quantmap__8u0__p7_1[] = {
  138765. 13, 11, 9, 7, 5, 3, 1, 0,
  138766. 2, 4, 6, 8, 10, 12, 14,
  138767. };
  138768. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  138769. _vq_quantthresh__8u0__p7_1,
  138770. _vq_quantmap__8u0__p7_1,
  138771. 15,
  138772. 15
  138773. };
  138774. static static_codebook _8u0__p7_1 = {
  138775. 2, 225,
  138776. _vq_lengthlist__8u0__p7_1,
  138777. 1, -520986624, 1620377600, 4, 0,
  138778. _vq_quantlist__8u0__p7_1,
  138779. NULL,
  138780. &_vq_auxt__8u0__p7_1,
  138781. NULL,
  138782. 0
  138783. };
  138784. static long _vq_quantlist__8u0__p7_2[] = {
  138785. 10,
  138786. 9,
  138787. 11,
  138788. 8,
  138789. 12,
  138790. 7,
  138791. 13,
  138792. 6,
  138793. 14,
  138794. 5,
  138795. 15,
  138796. 4,
  138797. 16,
  138798. 3,
  138799. 17,
  138800. 2,
  138801. 18,
  138802. 1,
  138803. 19,
  138804. 0,
  138805. 20,
  138806. };
  138807. static long _vq_lengthlist__8u0__p7_2[] = {
  138808. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  138809. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  138810. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  138811. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  138812. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  138813. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  138814. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  138815. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  138816. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  138817. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  138818. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  138819. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  138820. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  138821. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  138822. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  138823. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  138824. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  138825. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  138826. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  138827. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  138828. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  138829. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  138830. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  138831. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  138832. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  138833. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  138834. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  138835. 11,12,11,11,11,10,10,11,11,
  138836. };
  138837. static float _vq_quantthresh__8u0__p7_2[] = {
  138838. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138839. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138840. 6.5, 7.5, 8.5, 9.5,
  138841. };
  138842. static long _vq_quantmap__8u0__p7_2[] = {
  138843. 19, 17, 15, 13, 11, 9, 7, 5,
  138844. 3, 1, 0, 2, 4, 6, 8, 10,
  138845. 12, 14, 16, 18, 20,
  138846. };
  138847. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  138848. _vq_quantthresh__8u0__p7_2,
  138849. _vq_quantmap__8u0__p7_2,
  138850. 21,
  138851. 21
  138852. };
  138853. static static_codebook _8u0__p7_2 = {
  138854. 2, 441,
  138855. _vq_lengthlist__8u0__p7_2,
  138856. 1, -529268736, 1611661312, 5, 0,
  138857. _vq_quantlist__8u0__p7_2,
  138858. NULL,
  138859. &_vq_auxt__8u0__p7_2,
  138860. NULL,
  138861. 0
  138862. };
  138863. static long _huff_lengthlist__8u0__single[] = {
  138864. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  138865. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  138866. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  138867. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  138868. };
  138869. static static_codebook _huff_book__8u0__single = {
  138870. 2, 64,
  138871. _huff_lengthlist__8u0__single,
  138872. 0, 0, 0, 0, 0,
  138873. NULL,
  138874. NULL,
  138875. NULL,
  138876. NULL,
  138877. 0
  138878. };
  138879. static long _vq_quantlist__8u1__p1_0[] = {
  138880. 1,
  138881. 0,
  138882. 2,
  138883. };
  138884. static long _vq_lengthlist__8u1__p1_0[] = {
  138885. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  138886. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  138887. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  138888. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  138889. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  138890. 10,
  138891. };
  138892. static float _vq_quantthresh__8u1__p1_0[] = {
  138893. -0.5, 0.5,
  138894. };
  138895. static long _vq_quantmap__8u1__p1_0[] = {
  138896. 1, 0, 2,
  138897. };
  138898. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  138899. _vq_quantthresh__8u1__p1_0,
  138900. _vq_quantmap__8u1__p1_0,
  138901. 3,
  138902. 3
  138903. };
  138904. static static_codebook _8u1__p1_0 = {
  138905. 4, 81,
  138906. _vq_lengthlist__8u1__p1_0,
  138907. 1, -535822336, 1611661312, 2, 0,
  138908. _vq_quantlist__8u1__p1_0,
  138909. NULL,
  138910. &_vq_auxt__8u1__p1_0,
  138911. NULL,
  138912. 0
  138913. };
  138914. static long _vq_quantlist__8u1__p2_0[] = {
  138915. 1,
  138916. 0,
  138917. 2,
  138918. };
  138919. static long _vq_lengthlist__8u1__p2_0[] = {
  138920. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  138921. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  138922. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  138923. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  138924. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  138925. 7,
  138926. };
  138927. static float _vq_quantthresh__8u1__p2_0[] = {
  138928. -0.5, 0.5,
  138929. };
  138930. static long _vq_quantmap__8u1__p2_0[] = {
  138931. 1, 0, 2,
  138932. };
  138933. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  138934. _vq_quantthresh__8u1__p2_0,
  138935. _vq_quantmap__8u1__p2_0,
  138936. 3,
  138937. 3
  138938. };
  138939. static static_codebook _8u1__p2_0 = {
  138940. 4, 81,
  138941. _vq_lengthlist__8u1__p2_0,
  138942. 1, -535822336, 1611661312, 2, 0,
  138943. _vq_quantlist__8u1__p2_0,
  138944. NULL,
  138945. &_vq_auxt__8u1__p2_0,
  138946. NULL,
  138947. 0
  138948. };
  138949. static long _vq_quantlist__8u1__p3_0[] = {
  138950. 2,
  138951. 1,
  138952. 3,
  138953. 0,
  138954. 4,
  138955. };
  138956. static long _vq_lengthlist__8u1__p3_0[] = {
  138957. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  138958. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  138959. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  138960. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  138961. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  138962. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  138963. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  138964. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  138965. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  138966. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  138967. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  138968. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  138969. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  138970. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  138971. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  138972. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  138973. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  138974. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  138975. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  138976. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  138977. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  138978. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  138979. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  138980. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  138981. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  138982. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  138983. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  138984. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  138985. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  138986. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  138987. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  138988. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  138989. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  138990. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  138991. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  138992. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  138993. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  138994. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  138995. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  138996. 16,
  138997. };
  138998. static float _vq_quantthresh__8u1__p3_0[] = {
  138999. -1.5, -0.5, 0.5, 1.5,
  139000. };
  139001. static long _vq_quantmap__8u1__p3_0[] = {
  139002. 3, 1, 0, 2, 4,
  139003. };
  139004. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  139005. _vq_quantthresh__8u1__p3_0,
  139006. _vq_quantmap__8u1__p3_0,
  139007. 5,
  139008. 5
  139009. };
  139010. static static_codebook _8u1__p3_0 = {
  139011. 4, 625,
  139012. _vq_lengthlist__8u1__p3_0,
  139013. 1, -533725184, 1611661312, 3, 0,
  139014. _vq_quantlist__8u1__p3_0,
  139015. NULL,
  139016. &_vq_auxt__8u1__p3_0,
  139017. NULL,
  139018. 0
  139019. };
  139020. static long _vq_quantlist__8u1__p4_0[] = {
  139021. 2,
  139022. 1,
  139023. 3,
  139024. 0,
  139025. 4,
  139026. };
  139027. static long _vq_lengthlist__8u1__p4_0[] = {
  139028. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  139029. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  139030. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  139031. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  139032. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139033. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  139034. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  139035. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  139036. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  139037. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  139038. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  139039. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  139040. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  139041. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  139042. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  139043. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  139044. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  139045. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139046. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  139047. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  139048. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  139049. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  139050. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  139051. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  139052. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  139053. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  139054. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  139055. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  139056. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  139057. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  139058. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  139059. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  139060. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  139061. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  139062. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  139063. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  139064. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  139065. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  139066. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  139067. 10,
  139068. };
  139069. static float _vq_quantthresh__8u1__p4_0[] = {
  139070. -1.5, -0.5, 0.5, 1.5,
  139071. };
  139072. static long _vq_quantmap__8u1__p4_0[] = {
  139073. 3, 1, 0, 2, 4,
  139074. };
  139075. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  139076. _vq_quantthresh__8u1__p4_0,
  139077. _vq_quantmap__8u1__p4_0,
  139078. 5,
  139079. 5
  139080. };
  139081. static static_codebook _8u1__p4_0 = {
  139082. 4, 625,
  139083. _vq_lengthlist__8u1__p4_0,
  139084. 1, -533725184, 1611661312, 3, 0,
  139085. _vq_quantlist__8u1__p4_0,
  139086. NULL,
  139087. &_vq_auxt__8u1__p4_0,
  139088. NULL,
  139089. 0
  139090. };
  139091. static long _vq_quantlist__8u1__p5_0[] = {
  139092. 4,
  139093. 3,
  139094. 5,
  139095. 2,
  139096. 6,
  139097. 1,
  139098. 7,
  139099. 0,
  139100. 8,
  139101. };
  139102. static long _vq_lengthlist__8u1__p5_0[] = {
  139103. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  139104. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139105. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  139106. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  139107. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  139108. 13,
  139109. };
  139110. static float _vq_quantthresh__8u1__p5_0[] = {
  139111. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139112. };
  139113. static long _vq_quantmap__8u1__p5_0[] = {
  139114. 7, 5, 3, 1, 0, 2, 4, 6,
  139115. 8,
  139116. };
  139117. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  139118. _vq_quantthresh__8u1__p5_0,
  139119. _vq_quantmap__8u1__p5_0,
  139120. 9,
  139121. 9
  139122. };
  139123. static static_codebook _8u1__p5_0 = {
  139124. 2, 81,
  139125. _vq_lengthlist__8u1__p5_0,
  139126. 1, -531628032, 1611661312, 4, 0,
  139127. _vq_quantlist__8u1__p5_0,
  139128. NULL,
  139129. &_vq_auxt__8u1__p5_0,
  139130. NULL,
  139131. 0
  139132. };
  139133. static long _vq_quantlist__8u1__p6_0[] = {
  139134. 4,
  139135. 3,
  139136. 5,
  139137. 2,
  139138. 6,
  139139. 1,
  139140. 7,
  139141. 0,
  139142. 8,
  139143. };
  139144. static long _vq_lengthlist__8u1__p6_0[] = {
  139145. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  139146. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139147. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  139148. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  139149. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139150. 10,
  139151. };
  139152. static float _vq_quantthresh__8u1__p6_0[] = {
  139153. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139154. };
  139155. static long _vq_quantmap__8u1__p6_0[] = {
  139156. 7, 5, 3, 1, 0, 2, 4, 6,
  139157. 8,
  139158. };
  139159. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  139160. _vq_quantthresh__8u1__p6_0,
  139161. _vq_quantmap__8u1__p6_0,
  139162. 9,
  139163. 9
  139164. };
  139165. static static_codebook _8u1__p6_0 = {
  139166. 2, 81,
  139167. _vq_lengthlist__8u1__p6_0,
  139168. 1, -531628032, 1611661312, 4, 0,
  139169. _vq_quantlist__8u1__p6_0,
  139170. NULL,
  139171. &_vq_auxt__8u1__p6_0,
  139172. NULL,
  139173. 0
  139174. };
  139175. static long _vq_quantlist__8u1__p7_0[] = {
  139176. 1,
  139177. 0,
  139178. 2,
  139179. };
  139180. static long _vq_lengthlist__8u1__p7_0[] = {
  139181. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  139182. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  139183. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  139184. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  139185. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  139186. 11,
  139187. };
  139188. static float _vq_quantthresh__8u1__p7_0[] = {
  139189. -5.5, 5.5,
  139190. };
  139191. static long _vq_quantmap__8u1__p7_0[] = {
  139192. 1, 0, 2,
  139193. };
  139194. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  139195. _vq_quantthresh__8u1__p7_0,
  139196. _vq_quantmap__8u1__p7_0,
  139197. 3,
  139198. 3
  139199. };
  139200. static static_codebook _8u1__p7_0 = {
  139201. 4, 81,
  139202. _vq_lengthlist__8u1__p7_0,
  139203. 1, -529137664, 1618345984, 2, 0,
  139204. _vq_quantlist__8u1__p7_0,
  139205. NULL,
  139206. &_vq_auxt__8u1__p7_0,
  139207. NULL,
  139208. 0
  139209. };
  139210. static long _vq_quantlist__8u1__p7_1[] = {
  139211. 5,
  139212. 4,
  139213. 6,
  139214. 3,
  139215. 7,
  139216. 2,
  139217. 8,
  139218. 1,
  139219. 9,
  139220. 0,
  139221. 10,
  139222. };
  139223. static long _vq_lengthlist__8u1__p7_1[] = {
  139224. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  139225. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  139226. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139227. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139228. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  139229. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  139230. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  139231. 9, 9, 9, 9, 9,10,10,10,10,
  139232. };
  139233. static float _vq_quantthresh__8u1__p7_1[] = {
  139234. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139235. 3.5, 4.5,
  139236. };
  139237. static long _vq_quantmap__8u1__p7_1[] = {
  139238. 9, 7, 5, 3, 1, 0, 2, 4,
  139239. 6, 8, 10,
  139240. };
  139241. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  139242. _vq_quantthresh__8u1__p7_1,
  139243. _vq_quantmap__8u1__p7_1,
  139244. 11,
  139245. 11
  139246. };
  139247. static static_codebook _8u1__p7_1 = {
  139248. 2, 121,
  139249. _vq_lengthlist__8u1__p7_1,
  139250. 1, -531365888, 1611661312, 4, 0,
  139251. _vq_quantlist__8u1__p7_1,
  139252. NULL,
  139253. &_vq_auxt__8u1__p7_1,
  139254. NULL,
  139255. 0
  139256. };
  139257. static long _vq_quantlist__8u1__p8_0[] = {
  139258. 5,
  139259. 4,
  139260. 6,
  139261. 3,
  139262. 7,
  139263. 2,
  139264. 8,
  139265. 1,
  139266. 9,
  139267. 0,
  139268. 10,
  139269. };
  139270. static long _vq_lengthlist__8u1__p8_0[] = {
  139271. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  139272. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  139273. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  139274. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  139275. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  139276. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  139277. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  139278. 12,13,13,14,14,15,15,15,15,
  139279. };
  139280. static float _vq_quantthresh__8u1__p8_0[] = {
  139281. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139282. 38.5, 49.5,
  139283. };
  139284. static long _vq_quantmap__8u1__p8_0[] = {
  139285. 9, 7, 5, 3, 1, 0, 2, 4,
  139286. 6, 8, 10,
  139287. };
  139288. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  139289. _vq_quantthresh__8u1__p8_0,
  139290. _vq_quantmap__8u1__p8_0,
  139291. 11,
  139292. 11
  139293. };
  139294. static static_codebook _8u1__p8_0 = {
  139295. 2, 121,
  139296. _vq_lengthlist__8u1__p8_0,
  139297. 1, -524582912, 1618345984, 4, 0,
  139298. _vq_quantlist__8u1__p8_0,
  139299. NULL,
  139300. &_vq_auxt__8u1__p8_0,
  139301. NULL,
  139302. 0
  139303. };
  139304. static long _vq_quantlist__8u1__p8_1[] = {
  139305. 5,
  139306. 4,
  139307. 6,
  139308. 3,
  139309. 7,
  139310. 2,
  139311. 8,
  139312. 1,
  139313. 9,
  139314. 0,
  139315. 10,
  139316. };
  139317. static long _vq_lengthlist__8u1__p8_1[] = {
  139318. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  139319. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139320. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  139321. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  139322. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139323. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  139324. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  139325. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139326. };
  139327. static float _vq_quantthresh__8u1__p8_1[] = {
  139328. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139329. 3.5, 4.5,
  139330. };
  139331. static long _vq_quantmap__8u1__p8_1[] = {
  139332. 9, 7, 5, 3, 1, 0, 2, 4,
  139333. 6, 8, 10,
  139334. };
  139335. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  139336. _vq_quantthresh__8u1__p8_1,
  139337. _vq_quantmap__8u1__p8_1,
  139338. 11,
  139339. 11
  139340. };
  139341. static static_codebook _8u1__p8_1 = {
  139342. 2, 121,
  139343. _vq_lengthlist__8u1__p8_1,
  139344. 1, -531365888, 1611661312, 4, 0,
  139345. _vq_quantlist__8u1__p8_1,
  139346. NULL,
  139347. &_vq_auxt__8u1__p8_1,
  139348. NULL,
  139349. 0
  139350. };
  139351. static long _vq_quantlist__8u1__p9_0[] = {
  139352. 7,
  139353. 6,
  139354. 8,
  139355. 5,
  139356. 9,
  139357. 4,
  139358. 10,
  139359. 3,
  139360. 11,
  139361. 2,
  139362. 12,
  139363. 1,
  139364. 13,
  139365. 0,
  139366. 14,
  139367. };
  139368. static long _vq_lengthlist__8u1__p9_0[] = {
  139369. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  139370. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  139371. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139381. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  139382. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139383. 10,
  139384. };
  139385. static float _vq_quantthresh__8u1__p9_0[] = {
  139386. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139387. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139388. };
  139389. static long _vq_quantmap__8u1__p9_0[] = {
  139390. 13, 11, 9, 7, 5, 3, 1, 0,
  139391. 2, 4, 6, 8, 10, 12, 14,
  139392. };
  139393. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  139394. _vq_quantthresh__8u1__p9_0,
  139395. _vq_quantmap__8u1__p9_0,
  139396. 15,
  139397. 15
  139398. };
  139399. static static_codebook _8u1__p9_0 = {
  139400. 2, 225,
  139401. _vq_lengthlist__8u1__p9_0,
  139402. 1, -514071552, 1627381760, 4, 0,
  139403. _vq_quantlist__8u1__p9_0,
  139404. NULL,
  139405. &_vq_auxt__8u1__p9_0,
  139406. NULL,
  139407. 0
  139408. };
  139409. static long _vq_quantlist__8u1__p9_1[] = {
  139410. 7,
  139411. 6,
  139412. 8,
  139413. 5,
  139414. 9,
  139415. 4,
  139416. 10,
  139417. 3,
  139418. 11,
  139419. 2,
  139420. 12,
  139421. 1,
  139422. 13,
  139423. 0,
  139424. 14,
  139425. };
  139426. static long _vq_lengthlist__8u1__p9_1[] = {
  139427. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  139428. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  139429. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  139430. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  139431. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  139432. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  139433. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  139434. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  139435. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  139436. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  139437. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  139438. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  139439. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  139440. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  139441. 13,
  139442. };
  139443. static float _vq_quantthresh__8u1__p9_1[] = {
  139444. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139445. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139446. };
  139447. static long _vq_quantmap__8u1__p9_1[] = {
  139448. 13, 11, 9, 7, 5, 3, 1, 0,
  139449. 2, 4, 6, 8, 10, 12, 14,
  139450. };
  139451. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  139452. _vq_quantthresh__8u1__p9_1,
  139453. _vq_quantmap__8u1__p9_1,
  139454. 15,
  139455. 15
  139456. };
  139457. static static_codebook _8u1__p9_1 = {
  139458. 2, 225,
  139459. _vq_lengthlist__8u1__p9_1,
  139460. 1, -522338304, 1620115456, 4, 0,
  139461. _vq_quantlist__8u1__p9_1,
  139462. NULL,
  139463. &_vq_auxt__8u1__p9_1,
  139464. NULL,
  139465. 0
  139466. };
  139467. static long _vq_quantlist__8u1__p9_2[] = {
  139468. 8,
  139469. 7,
  139470. 9,
  139471. 6,
  139472. 10,
  139473. 5,
  139474. 11,
  139475. 4,
  139476. 12,
  139477. 3,
  139478. 13,
  139479. 2,
  139480. 14,
  139481. 1,
  139482. 15,
  139483. 0,
  139484. 16,
  139485. };
  139486. static long _vq_lengthlist__8u1__p9_2[] = {
  139487. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139488. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  139489. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139490. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139491. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139492. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  139493. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139494. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  139495. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139496. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  139497. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  139498. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  139499. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  139500. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  139501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  139502. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  139503. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139504. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139505. 10,
  139506. };
  139507. static float _vq_quantthresh__8u1__p9_2[] = {
  139508. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139509. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139510. };
  139511. static long _vq_quantmap__8u1__p9_2[] = {
  139512. 15, 13, 11, 9, 7, 5, 3, 1,
  139513. 0, 2, 4, 6, 8, 10, 12, 14,
  139514. 16,
  139515. };
  139516. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  139517. _vq_quantthresh__8u1__p9_2,
  139518. _vq_quantmap__8u1__p9_2,
  139519. 17,
  139520. 17
  139521. };
  139522. static static_codebook _8u1__p9_2 = {
  139523. 2, 289,
  139524. _vq_lengthlist__8u1__p9_2,
  139525. 1, -529530880, 1611661312, 5, 0,
  139526. _vq_quantlist__8u1__p9_2,
  139527. NULL,
  139528. &_vq_auxt__8u1__p9_2,
  139529. NULL,
  139530. 0
  139531. };
  139532. static long _huff_lengthlist__8u1__single[] = {
  139533. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  139534. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  139535. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  139536. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  139537. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  139538. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  139539. 13, 8, 8,15,
  139540. };
  139541. static static_codebook _huff_book__8u1__single = {
  139542. 2, 100,
  139543. _huff_lengthlist__8u1__single,
  139544. 0, 0, 0, 0, 0,
  139545. NULL,
  139546. NULL,
  139547. NULL,
  139548. NULL,
  139549. 0
  139550. };
  139551. static long _huff_lengthlist__44u0__long[] = {
  139552. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  139553. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  139554. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  139555. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  139556. };
  139557. static static_codebook _huff_book__44u0__long = {
  139558. 2, 64,
  139559. _huff_lengthlist__44u0__long,
  139560. 0, 0, 0, 0, 0,
  139561. NULL,
  139562. NULL,
  139563. NULL,
  139564. NULL,
  139565. 0
  139566. };
  139567. static long _vq_quantlist__44u0__p1_0[] = {
  139568. 1,
  139569. 0,
  139570. 2,
  139571. };
  139572. static long _vq_lengthlist__44u0__p1_0[] = {
  139573. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  139574. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  139575. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  139576. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  139577. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  139578. 13,
  139579. };
  139580. static float _vq_quantthresh__44u0__p1_0[] = {
  139581. -0.5, 0.5,
  139582. };
  139583. static long _vq_quantmap__44u0__p1_0[] = {
  139584. 1, 0, 2,
  139585. };
  139586. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  139587. _vq_quantthresh__44u0__p1_0,
  139588. _vq_quantmap__44u0__p1_0,
  139589. 3,
  139590. 3
  139591. };
  139592. static static_codebook _44u0__p1_0 = {
  139593. 4, 81,
  139594. _vq_lengthlist__44u0__p1_0,
  139595. 1, -535822336, 1611661312, 2, 0,
  139596. _vq_quantlist__44u0__p1_0,
  139597. NULL,
  139598. &_vq_auxt__44u0__p1_0,
  139599. NULL,
  139600. 0
  139601. };
  139602. static long _vq_quantlist__44u0__p2_0[] = {
  139603. 1,
  139604. 0,
  139605. 2,
  139606. };
  139607. static long _vq_lengthlist__44u0__p2_0[] = {
  139608. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  139609. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  139610. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  139611. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  139612. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  139613. 9,
  139614. };
  139615. static float _vq_quantthresh__44u0__p2_0[] = {
  139616. -0.5, 0.5,
  139617. };
  139618. static long _vq_quantmap__44u0__p2_0[] = {
  139619. 1, 0, 2,
  139620. };
  139621. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  139622. _vq_quantthresh__44u0__p2_0,
  139623. _vq_quantmap__44u0__p2_0,
  139624. 3,
  139625. 3
  139626. };
  139627. static static_codebook _44u0__p2_0 = {
  139628. 4, 81,
  139629. _vq_lengthlist__44u0__p2_0,
  139630. 1, -535822336, 1611661312, 2, 0,
  139631. _vq_quantlist__44u0__p2_0,
  139632. NULL,
  139633. &_vq_auxt__44u0__p2_0,
  139634. NULL,
  139635. 0
  139636. };
  139637. static long _vq_quantlist__44u0__p3_0[] = {
  139638. 2,
  139639. 1,
  139640. 3,
  139641. 0,
  139642. 4,
  139643. };
  139644. static long _vq_lengthlist__44u0__p3_0[] = {
  139645. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  139646. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  139647. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  139648. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139649. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  139650. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  139651. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  139652. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  139653. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  139654. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  139655. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  139656. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  139657. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  139658. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  139659. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  139660. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  139661. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  139662. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  139663. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  139664. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  139665. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  139666. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  139667. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  139668. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  139669. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  139670. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  139671. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  139672. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  139673. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  139674. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  139675. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  139676. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  139677. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  139678. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  139679. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  139680. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  139681. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  139682. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  139683. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  139684. 19,
  139685. };
  139686. static float _vq_quantthresh__44u0__p3_0[] = {
  139687. -1.5, -0.5, 0.5, 1.5,
  139688. };
  139689. static long _vq_quantmap__44u0__p3_0[] = {
  139690. 3, 1, 0, 2, 4,
  139691. };
  139692. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  139693. _vq_quantthresh__44u0__p3_0,
  139694. _vq_quantmap__44u0__p3_0,
  139695. 5,
  139696. 5
  139697. };
  139698. static static_codebook _44u0__p3_0 = {
  139699. 4, 625,
  139700. _vq_lengthlist__44u0__p3_0,
  139701. 1, -533725184, 1611661312, 3, 0,
  139702. _vq_quantlist__44u0__p3_0,
  139703. NULL,
  139704. &_vq_auxt__44u0__p3_0,
  139705. NULL,
  139706. 0
  139707. };
  139708. static long _vq_quantlist__44u0__p4_0[] = {
  139709. 2,
  139710. 1,
  139711. 3,
  139712. 0,
  139713. 4,
  139714. };
  139715. static long _vq_lengthlist__44u0__p4_0[] = {
  139716. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  139717. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  139718. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  139719. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  139720. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  139721. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  139722. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  139723. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  139724. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  139725. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  139726. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  139727. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139728. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  139729. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  139730. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  139731. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  139732. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  139733. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  139734. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  139735. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  139736. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  139737. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  139738. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  139739. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  139740. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  139741. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  139742. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  139743. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  139744. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  139745. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  139746. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  139747. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  139748. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  139749. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  139750. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  139751. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  139752. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  139753. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  139754. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  139755. 12,
  139756. };
  139757. static float _vq_quantthresh__44u0__p4_0[] = {
  139758. -1.5, -0.5, 0.5, 1.5,
  139759. };
  139760. static long _vq_quantmap__44u0__p4_0[] = {
  139761. 3, 1, 0, 2, 4,
  139762. };
  139763. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  139764. _vq_quantthresh__44u0__p4_0,
  139765. _vq_quantmap__44u0__p4_0,
  139766. 5,
  139767. 5
  139768. };
  139769. static static_codebook _44u0__p4_0 = {
  139770. 4, 625,
  139771. _vq_lengthlist__44u0__p4_0,
  139772. 1, -533725184, 1611661312, 3, 0,
  139773. _vq_quantlist__44u0__p4_0,
  139774. NULL,
  139775. &_vq_auxt__44u0__p4_0,
  139776. NULL,
  139777. 0
  139778. };
  139779. static long _vq_quantlist__44u0__p5_0[] = {
  139780. 4,
  139781. 3,
  139782. 5,
  139783. 2,
  139784. 6,
  139785. 1,
  139786. 7,
  139787. 0,
  139788. 8,
  139789. };
  139790. static long _vq_lengthlist__44u0__p5_0[] = {
  139791. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139792. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  139793. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  139794. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139795. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  139796. 12,
  139797. };
  139798. static float _vq_quantthresh__44u0__p5_0[] = {
  139799. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139800. };
  139801. static long _vq_quantmap__44u0__p5_0[] = {
  139802. 7, 5, 3, 1, 0, 2, 4, 6,
  139803. 8,
  139804. };
  139805. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  139806. _vq_quantthresh__44u0__p5_0,
  139807. _vq_quantmap__44u0__p5_0,
  139808. 9,
  139809. 9
  139810. };
  139811. static static_codebook _44u0__p5_0 = {
  139812. 2, 81,
  139813. _vq_lengthlist__44u0__p5_0,
  139814. 1, -531628032, 1611661312, 4, 0,
  139815. _vq_quantlist__44u0__p5_0,
  139816. NULL,
  139817. &_vq_auxt__44u0__p5_0,
  139818. NULL,
  139819. 0
  139820. };
  139821. static long _vq_quantlist__44u0__p6_0[] = {
  139822. 6,
  139823. 5,
  139824. 7,
  139825. 4,
  139826. 8,
  139827. 3,
  139828. 9,
  139829. 2,
  139830. 10,
  139831. 1,
  139832. 11,
  139833. 0,
  139834. 12,
  139835. };
  139836. static long _vq_lengthlist__44u0__p6_0[] = {
  139837. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  139838. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  139839. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  139840. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  139841. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  139842. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  139843. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  139844. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  139845. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  139846. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  139847. 15,17,16,17,18,17,17,18, 0,
  139848. };
  139849. static float _vq_quantthresh__44u0__p6_0[] = {
  139850. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139851. 12.5, 17.5, 22.5, 27.5,
  139852. };
  139853. static long _vq_quantmap__44u0__p6_0[] = {
  139854. 11, 9, 7, 5, 3, 1, 0, 2,
  139855. 4, 6, 8, 10, 12,
  139856. };
  139857. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  139858. _vq_quantthresh__44u0__p6_0,
  139859. _vq_quantmap__44u0__p6_0,
  139860. 13,
  139861. 13
  139862. };
  139863. static static_codebook _44u0__p6_0 = {
  139864. 2, 169,
  139865. _vq_lengthlist__44u0__p6_0,
  139866. 1, -526516224, 1616117760, 4, 0,
  139867. _vq_quantlist__44u0__p6_0,
  139868. NULL,
  139869. &_vq_auxt__44u0__p6_0,
  139870. NULL,
  139871. 0
  139872. };
  139873. static long _vq_quantlist__44u0__p6_1[] = {
  139874. 2,
  139875. 1,
  139876. 3,
  139877. 0,
  139878. 4,
  139879. };
  139880. static long _vq_lengthlist__44u0__p6_1[] = {
  139881. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  139882. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  139883. };
  139884. static float _vq_quantthresh__44u0__p6_1[] = {
  139885. -1.5, -0.5, 0.5, 1.5,
  139886. };
  139887. static long _vq_quantmap__44u0__p6_1[] = {
  139888. 3, 1, 0, 2, 4,
  139889. };
  139890. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  139891. _vq_quantthresh__44u0__p6_1,
  139892. _vq_quantmap__44u0__p6_1,
  139893. 5,
  139894. 5
  139895. };
  139896. static static_codebook _44u0__p6_1 = {
  139897. 2, 25,
  139898. _vq_lengthlist__44u0__p6_1,
  139899. 1, -533725184, 1611661312, 3, 0,
  139900. _vq_quantlist__44u0__p6_1,
  139901. NULL,
  139902. &_vq_auxt__44u0__p6_1,
  139903. NULL,
  139904. 0
  139905. };
  139906. static long _vq_quantlist__44u0__p7_0[] = {
  139907. 2,
  139908. 1,
  139909. 3,
  139910. 0,
  139911. 4,
  139912. };
  139913. static long _vq_lengthlist__44u0__p7_0[] = {
  139914. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  139915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139917. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139921. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  139922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139944. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  139945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139950. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139951. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139952. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139953. 10,
  139954. };
  139955. static float _vq_quantthresh__44u0__p7_0[] = {
  139956. -253.5, -84.5, 84.5, 253.5,
  139957. };
  139958. static long _vq_quantmap__44u0__p7_0[] = {
  139959. 3, 1, 0, 2, 4,
  139960. };
  139961. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  139962. _vq_quantthresh__44u0__p7_0,
  139963. _vq_quantmap__44u0__p7_0,
  139964. 5,
  139965. 5
  139966. };
  139967. static static_codebook _44u0__p7_0 = {
  139968. 4, 625,
  139969. _vq_lengthlist__44u0__p7_0,
  139970. 1, -518709248, 1626677248, 3, 0,
  139971. _vq_quantlist__44u0__p7_0,
  139972. NULL,
  139973. &_vq_auxt__44u0__p7_0,
  139974. NULL,
  139975. 0
  139976. };
  139977. static long _vq_quantlist__44u0__p7_1[] = {
  139978. 6,
  139979. 5,
  139980. 7,
  139981. 4,
  139982. 8,
  139983. 3,
  139984. 9,
  139985. 2,
  139986. 10,
  139987. 1,
  139988. 11,
  139989. 0,
  139990. 12,
  139991. };
  139992. static long _vq_lengthlist__44u0__p7_1[] = {
  139993. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  139994. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  139995. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  139996. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  139997. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  139998. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  139999. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140000. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140001. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140002. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140003. 15,15,15,15,15,15,15,15,15,
  140004. };
  140005. static float _vq_quantthresh__44u0__p7_1[] = {
  140006. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140007. 32.5, 45.5, 58.5, 71.5,
  140008. };
  140009. static long _vq_quantmap__44u0__p7_1[] = {
  140010. 11, 9, 7, 5, 3, 1, 0, 2,
  140011. 4, 6, 8, 10, 12,
  140012. };
  140013. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  140014. _vq_quantthresh__44u0__p7_1,
  140015. _vq_quantmap__44u0__p7_1,
  140016. 13,
  140017. 13
  140018. };
  140019. static static_codebook _44u0__p7_1 = {
  140020. 2, 169,
  140021. _vq_lengthlist__44u0__p7_1,
  140022. 1, -523010048, 1618608128, 4, 0,
  140023. _vq_quantlist__44u0__p7_1,
  140024. NULL,
  140025. &_vq_auxt__44u0__p7_1,
  140026. NULL,
  140027. 0
  140028. };
  140029. static long _vq_quantlist__44u0__p7_2[] = {
  140030. 6,
  140031. 5,
  140032. 7,
  140033. 4,
  140034. 8,
  140035. 3,
  140036. 9,
  140037. 2,
  140038. 10,
  140039. 1,
  140040. 11,
  140041. 0,
  140042. 12,
  140043. };
  140044. static long _vq_lengthlist__44u0__p7_2[] = {
  140045. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140046. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140047. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140048. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140049. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140050. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140051. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140052. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140053. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140054. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140055. 9, 9, 9,10, 9, 9,10,10, 9,
  140056. };
  140057. static float _vq_quantthresh__44u0__p7_2[] = {
  140058. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140059. 2.5, 3.5, 4.5, 5.5,
  140060. };
  140061. static long _vq_quantmap__44u0__p7_2[] = {
  140062. 11, 9, 7, 5, 3, 1, 0, 2,
  140063. 4, 6, 8, 10, 12,
  140064. };
  140065. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  140066. _vq_quantthresh__44u0__p7_2,
  140067. _vq_quantmap__44u0__p7_2,
  140068. 13,
  140069. 13
  140070. };
  140071. static static_codebook _44u0__p7_2 = {
  140072. 2, 169,
  140073. _vq_lengthlist__44u0__p7_2,
  140074. 1, -531103744, 1611661312, 4, 0,
  140075. _vq_quantlist__44u0__p7_2,
  140076. NULL,
  140077. &_vq_auxt__44u0__p7_2,
  140078. NULL,
  140079. 0
  140080. };
  140081. static long _huff_lengthlist__44u0__short[] = {
  140082. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140083. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140084. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140085. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140086. };
  140087. static static_codebook _huff_book__44u0__short = {
  140088. 2, 64,
  140089. _huff_lengthlist__44u0__short,
  140090. 0, 0, 0, 0, 0,
  140091. NULL,
  140092. NULL,
  140093. NULL,
  140094. NULL,
  140095. 0
  140096. };
  140097. static long _huff_lengthlist__44u1__long[] = {
  140098. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140099. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140100. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140101. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140102. };
  140103. static static_codebook _huff_book__44u1__long = {
  140104. 2, 64,
  140105. _huff_lengthlist__44u1__long,
  140106. 0, 0, 0, 0, 0,
  140107. NULL,
  140108. NULL,
  140109. NULL,
  140110. NULL,
  140111. 0
  140112. };
  140113. static long _vq_quantlist__44u1__p1_0[] = {
  140114. 1,
  140115. 0,
  140116. 2,
  140117. };
  140118. static long _vq_lengthlist__44u1__p1_0[] = {
  140119. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140120. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140121. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140122. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140123. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140124. 13,
  140125. };
  140126. static float _vq_quantthresh__44u1__p1_0[] = {
  140127. -0.5, 0.5,
  140128. };
  140129. static long _vq_quantmap__44u1__p1_0[] = {
  140130. 1, 0, 2,
  140131. };
  140132. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  140133. _vq_quantthresh__44u1__p1_0,
  140134. _vq_quantmap__44u1__p1_0,
  140135. 3,
  140136. 3
  140137. };
  140138. static static_codebook _44u1__p1_0 = {
  140139. 4, 81,
  140140. _vq_lengthlist__44u1__p1_0,
  140141. 1, -535822336, 1611661312, 2, 0,
  140142. _vq_quantlist__44u1__p1_0,
  140143. NULL,
  140144. &_vq_auxt__44u1__p1_0,
  140145. NULL,
  140146. 0
  140147. };
  140148. static long _vq_quantlist__44u1__p2_0[] = {
  140149. 1,
  140150. 0,
  140151. 2,
  140152. };
  140153. static long _vq_lengthlist__44u1__p2_0[] = {
  140154. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140155. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140156. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140157. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140158. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140159. 9,
  140160. };
  140161. static float _vq_quantthresh__44u1__p2_0[] = {
  140162. -0.5, 0.5,
  140163. };
  140164. static long _vq_quantmap__44u1__p2_0[] = {
  140165. 1, 0, 2,
  140166. };
  140167. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  140168. _vq_quantthresh__44u1__p2_0,
  140169. _vq_quantmap__44u1__p2_0,
  140170. 3,
  140171. 3
  140172. };
  140173. static static_codebook _44u1__p2_0 = {
  140174. 4, 81,
  140175. _vq_lengthlist__44u1__p2_0,
  140176. 1, -535822336, 1611661312, 2, 0,
  140177. _vq_quantlist__44u1__p2_0,
  140178. NULL,
  140179. &_vq_auxt__44u1__p2_0,
  140180. NULL,
  140181. 0
  140182. };
  140183. static long _vq_quantlist__44u1__p3_0[] = {
  140184. 2,
  140185. 1,
  140186. 3,
  140187. 0,
  140188. 4,
  140189. };
  140190. static long _vq_lengthlist__44u1__p3_0[] = {
  140191. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140192. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140193. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140194. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140195. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140196. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140197. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140198. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140199. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140200. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140201. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140202. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140203. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140204. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140205. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140206. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140207. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140208. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140209. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140210. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140211. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140212. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140213. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140214. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140215. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140216. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140217. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140218. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140219. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140220. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140221. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140222. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140223. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140224. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140225. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140226. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140227. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140228. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140229. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140230. 19,
  140231. };
  140232. static float _vq_quantthresh__44u1__p3_0[] = {
  140233. -1.5, -0.5, 0.5, 1.5,
  140234. };
  140235. static long _vq_quantmap__44u1__p3_0[] = {
  140236. 3, 1, 0, 2, 4,
  140237. };
  140238. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  140239. _vq_quantthresh__44u1__p3_0,
  140240. _vq_quantmap__44u1__p3_0,
  140241. 5,
  140242. 5
  140243. };
  140244. static static_codebook _44u1__p3_0 = {
  140245. 4, 625,
  140246. _vq_lengthlist__44u1__p3_0,
  140247. 1, -533725184, 1611661312, 3, 0,
  140248. _vq_quantlist__44u1__p3_0,
  140249. NULL,
  140250. &_vq_auxt__44u1__p3_0,
  140251. NULL,
  140252. 0
  140253. };
  140254. static long _vq_quantlist__44u1__p4_0[] = {
  140255. 2,
  140256. 1,
  140257. 3,
  140258. 0,
  140259. 4,
  140260. };
  140261. static long _vq_lengthlist__44u1__p4_0[] = {
  140262. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140263. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140264. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140265. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140266. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140267. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140268. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140269. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140270. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140271. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140272. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140273. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140274. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140275. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140276. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140277. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140278. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140279. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140280. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140281. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140282. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140283. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140284. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140285. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140286. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140287. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140288. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140289. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140290. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140291. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140292. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140293. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140294. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140295. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140296. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140297. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140298. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140299. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140300. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140301. 12,
  140302. };
  140303. static float _vq_quantthresh__44u1__p4_0[] = {
  140304. -1.5, -0.5, 0.5, 1.5,
  140305. };
  140306. static long _vq_quantmap__44u1__p4_0[] = {
  140307. 3, 1, 0, 2, 4,
  140308. };
  140309. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  140310. _vq_quantthresh__44u1__p4_0,
  140311. _vq_quantmap__44u1__p4_0,
  140312. 5,
  140313. 5
  140314. };
  140315. static static_codebook _44u1__p4_0 = {
  140316. 4, 625,
  140317. _vq_lengthlist__44u1__p4_0,
  140318. 1, -533725184, 1611661312, 3, 0,
  140319. _vq_quantlist__44u1__p4_0,
  140320. NULL,
  140321. &_vq_auxt__44u1__p4_0,
  140322. NULL,
  140323. 0
  140324. };
  140325. static long _vq_quantlist__44u1__p5_0[] = {
  140326. 4,
  140327. 3,
  140328. 5,
  140329. 2,
  140330. 6,
  140331. 1,
  140332. 7,
  140333. 0,
  140334. 8,
  140335. };
  140336. static long _vq_lengthlist__44u1__p5_0[] = {
  140337. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140338. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140339. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  140340. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140341. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  140342. 12,
  140343. };
  140344. static float _vq_quantthresh__44u1__p5_0[] = {
  140345. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140346. };
  140347. static long _vq_quantmap__44u1__p5_0[] = {
  140348. 7, 5, 3, 1, 0, 2, 4, 6,
  140349. 8,
  140350. };
  140351. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  140352. _vq_quantthresh__44u1__p5_0,
  140353. _vq_quantmap__44u1__p5_0,
  140354. 9,
  140355. 9
  140356. };
  140357. static static_codebook _44u1__p5_0 = {
  140358. 2, 81,
  140359. _vq_lengthlist__44u1__p5_0,
  140360. 1, -531628032, 1611661312, 4, 0,
  140361. _vq_quantlist__44u1__p5_0,
  140362. NULL,
  140363. &_vq_auxt__44u1__p5_0,
  140364. NULL,
  140365. 0
  140366. };
  140367. static long _vq_quantlist__44u1__p6_0[] = {
  140368. 6,
  140369. 5,
  140370. 7,
  140371. 4,
  140372. 8,
  140373. 3,
  140374. 9,
  140375. 2,
  140376. 10,
  140377. 1,
  140378. 11,
  140379. 0,
  140380. 12,
  140381. };
  140382. static long _vq_lengthlist__44u1__p6_0[] = {
  140383. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  140384. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  140385. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  140386. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  140387. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  140388. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  140389. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  140390. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  140391. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  140392. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  140393. 15,17,16,17,18,17,17,18, 0,
  140394. };
  140395. static float _vq_quantthresh__44u1__p6_0[] = {
  140396. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140397. 12.5, 17.5, 22.5, 27.5,
  140398. };
  140399. static long _vq_quantmap__44u1__p6_0[] = {
  140400. 11, 9, 7, 5, 3, 1, 0, 2,
  140401. 4, 6, 8, 10, 12,
  140402. };
  140403. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  140404. _vq_quantthresh__44u1__p6_0,
  140405. _vq_quantmap__44u1__p6_0,
  140406. 13,
  140407. 13
  140408. };
  140409. static static_codebook _44u1__p6_0 = {
  140410. 2, 169,
  140411. _vq_lengthlist__44u1__p6_0,
  140412. 1, -526516224, 1616117760, 4, 0,
  140413. _vq_quantlist__44u1__p6_0,
  140414. NULL,
  140415. &_vq_auxt__44u1__p6_0,
  140416. NULL,
  140417. 0
  140418. };
  140419. static long _vq_quantlist__44u1__p6_1[] = {
  140420. 2,
  140421. 1,
  140422. 3,
  140423. 0,
  140424. 4,
  140425. };
  140426. static long _vq_lengthlist__44u1__p6_1[] = {
  140427. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  140428. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  140429. };
  140430. static float _vq_quantthresh__44u1__p6_1[] = {
  140431. -1.5, -0.5, 0.5, 1.5,
  140432. };
  140433. static long _vq_quantmap__44u1__p6_1[] = {
  140434. 3, 1, 0, 2, 4,
  140435. };
  140436. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  140437. _vq_quantthresh__44u1__p6_1,
  140438. _vq_quantmap__44u1__p6_1,
  140439. 5,
  140440. 5
  140441. };
  140442. static static_codebook _44u1__p6_1 = {
  140443. 2, 25,
  140444. _vq_lengthlist__44u1__p6_1,
  140445. 1, -533725184, 1611661312, 3, 0,
  140446. _vq_quantlist__44u1__p6_1,
  140447. NULL,
  140448. &_vq_auxt__44u1__p6_1,
  140449. NULL,
  140450. 0
  140451. };
  140452. static long _vq_quantlist__44u1__p7_0[] = {
  140453. 3,
  140454. 2,
  140455. 4,
  140456. 1,
  140457. 5,
  140458. 0,
  140459. 6,
  140460. };
  140461. static long _vq_lengthlist__44u1__p7_0[] = {
  140462. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140463. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140464. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140465. 8,
  140466. };
  140467. static float _vq_quantthresh__44u1__p7_0[] = {
  140468. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  140469. };
  140470. static long _vq_quantmap__44u1__p7_0[] = {
  140471. 5, 3, 1, 0, 2, 4, 6,
  140472. };
  140473. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  140474. _vq_quantthresh__44u1__p7_0,
  140475. _vq_quantmap__44u1__p7_0,
  140476. 7,
  140477. 7
  140478. };
  140479. static static_codebook _44u1__p7_0 = {
  140480. 2, 49,
  140481. _vq_lengthlist__44u1__p7_0,
  140482. 1, -518017024, 1626677248, 3, 0,
  140483. _vq_quantlist__44u1__p7_0,
  140484. NULL,
  140485. &_vq_auxt__44u1__p7_0,
  140486. NULL,
  140487. 0
  140488. };
  140489. static long _vq_quantlist__44u1__p7_1[] = {
  140490. 6,
  140491. 5,
  140492. 7,
  140493. 4,
  140494. 8,
  140495. 3,
  140496. 9,
  140497. 2,
  140498. 10,
  140499. 1,
  140500. 11,
  140501. 0,
  140502. 12,
  140503. };
  140504. static long _vq_lengthlist__44u1__p7_1[] = {
  140505. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140506. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140507. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140508. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140509. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140510. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140511. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140512. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140513. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140514. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140515. 15,15,15,15,15,15,15,15,15,
  140516. };
  140517. static float _vq_quantthresh__44u1__p7_1[] = {
  140518. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140519. 32.5, 45.5, 58.5, 71.5,
  140520. };
  140521. static long _vq_quantmap__44u1__p7_1[] = {
  140522. 11, 9, 7, 5, 3, 1, 0, 2,
  140523. 4, 6, 8, 10, 12,
  140524. };
  140525. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  140526. _vq_quantthresh__44u1__p7_1,
  140527. _vq_quantmap__44u1__p7_1,
  140528. 13,
  140529. 13
  140530. };
  140531. static static_codebook _44u1__p7_1 = {
  140532. 2, 169,
  140533. _vq_lengthlist__44u1__p7_1,
  140534. 1, -523010048, 1618608128, 4, 0,
  140535. _vq_quantlist__44u1__p7_1,
  140536. NULL,
  140537. &_vq_auxt__44u1__p7_1,
  140538. NULL,
  140539. 0
  140540. };
  140541. static long _vq_quantlist__44u1__p7_2[] = {
  140542. 6,
  140543. 5,
  140544. 7,
  140545. 4,
  140546. 8,
  140547. 3,
  140548. 9,
  140549. 2,
  140550. 10,
  140551. 1,
  140552. 11,
  140553. 0,
  140554. 12,
  140555. };
  140556. static long _vq_lengthlist__44u1__p7_2[] = {
  140557. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140558. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140559. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140560. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140561. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140562. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140563. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140564. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140565. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140566. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140567. 9, 9, 9,10, 9, 9,10,10, 9,
  140568. };
  140569. static float _vq_quantthresh__44u1__p7_2[] = {
  140570. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140571. 2.5, 3.5, 4.5, 5.5,
  140572. };
  140573. static long _vq_quantmap__44u1__p7_2[] = {
  140574. 11, 9, 7, 5, 3, 1, 0, 2,
  140575. 4, 6, 8, 10, 12,
  140576. };
  140577. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  140578. _vq_quantthresh__44u1__p7_2,
  140579. _vq_quantmap__44u1__p7_2,
  140580. 13,
  140581. 13
  140582. };
  140583. static static_codebook _44u1__p7_2 = {
  140584. 2, 169,
  140585. _vq_lengthlist__44u1__p7_2,
  140586. 1, -531103744, 1611661312, 4, 0,
  140587. _vq_quantlist__44u1__p7_2,
  140588. NULL,
  140589. &_vq_auxt__44u1__p7_2,
  140590. NULL,
  140591. 0
  140592. };
  140593. static long _huff_lengthlist__44u1__short[] = {
  140594. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140595. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140596. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140597. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140598. };
  140599. static static_codebook _huff_book__44u1__short = {
  140600. 2, 64,
  140601. _huff_lengthlist__44u1__short,
  140602. 0, 0, 0, 0, 0,
  140603. NULL,
  140604. NULL,
  140605. NULL,
  140606. NULL,
  140607. 0
  140608. };
  140609. static long _huff_lengthlist__44u2__long[] = {
  140610. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  140611. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  140612. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  140613. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  140614. };
  140615. static static_codebook _huff_book__44u2__long = {
  140616. 2, 64,
  140617. _huff_lengthlist__44u2__long,
  140618. 0, 0, 0, 0, 0,
  140619. NULL,
  140620. NULL,
  140621. NULL,
  140622. NULL,
  140623. 0
  140624. };
  140625. static long _vq_quantlist__44u2__p1_0[] = {
  140626. 1,
  140627. 0,
  140628. 2,
  140629. };
  140630. static long _vq_lengthlist__44u2__p1_0[] = {
  140631. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140632. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140633. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  140634. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  140635. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  140636. 13,
  140637. };
  140638. static float _vq_quantthresh__44u2__p1_0[] = {
  140639. -0.5, 0.5,
  140640. };
  140641. static long _vq_quantmap__44u2__p1_0[] = {
  140642. 1, 0, 2,
  140643. };
  140644. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  140645. _vq_quantthresh__44u2__p1_0,
  140646. _vq_quantmap__44u2__p1_0,
  140647. 3,
  140648. 3
  140649. };
  140650. static static_codebook _44u2__p1_0 = {
  140651. 4, 81,
  140652. _vq_lengthlist__44u2__p1_0,
  140653. 1, -535822336, 1611661312, 2, 0,
  140654. _vq_quantlist__44u2__p1_0,
  140655. NULL,
  140656. &_vq_auxt__44u2__p1_0,
  140657. NULL,
  140658. 0
  140659. };
  140660. static long _vq_quantlist__44u2__p2_0[] = {
  140661. 1,
  140662. 0,
  140663. 2,
  140664. };
  140665. static long _vq_lengthlist__44u2__p2_0[] = {
  140666. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  140667. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  140668. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140669. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  140670. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140671. 9,
  140672. };
  140673. static float _vq_quantthresh__44u2__p2_0[] = {
  140674. -0.5, 0.5,
  140675. };
  140676. static long _vq_quantmap__44u2__p2_0[] = {
  140677. 1, 0, 2,
  140678. };
  140679. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  140680. _vq_quantthresh__44u2__p2_0,
  140681. _vq_quantmap__44u2__p2_0,
  140682. 3,
  140683. 3
  140684. };
  140685. static static_codebook _44u2__p2_0 = {
  140686. 4, 81,
  140687. _vq_lengthlist__44u2__p2_0,
  140688. 1, -535822336, 1611661312, 2, 0,
  140689. _vq_quantlist__44u2__p2_0,
  140690. NULL,
  140691. &_vq_auxt__44u2__p2_0,
  140692. NULL,
  140693. 0
  140694. };
  140695. static long _vq_quantlist__44u2__p3_0[] = {
  140696. 2,
  140697. 1,
  140698. 3,
  140699. 0,
  140700. 4,
  140701. };
  140702. static long _vq_lengthlist__44u2__p3_0[] = {
  140703. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  140704. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  140705. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  140706. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  140707. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  140708. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  140709. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  140710. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  140711. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  140712. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  140713. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  140714. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  140715. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  140716. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  140717. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  140718. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  140719. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  140720. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  140721. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  140722. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  140723. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  140724. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  140725. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  140726. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  140727. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  140728. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  140729. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  140730. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  140731. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  140732. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  140733. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  140734. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  140735. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  140736. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  140737. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  140738. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  140739. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  140740. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  140741. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  140742. 0,
  140743. };
  140744. static float _vq_quantthresh__44u2__p3_0[] = {
  140745. -1.5, -0.5, 0.5, 1.5,
  140746. };
  140747. static long _vq_quantmap__44u2__p3_0[] = {
  140748. 3, 1, 0, 2, 4,
  140749. };
  140750. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  140751. _vq_quantthresh__44u2__p3_0,
  140752. _vq_quantmap__44u2__p3_0,
  140753. 5,
  140754. 5
  140755. };
  140756. static static_codebook _44u2__p3_0 = {
  140757. 4, 625,
  140758. _vq_lengthlist__44u2__p3_0,
  140759. 1, -533725184, 1611661312, 3, 0,
  140760. _vq_quantlist__44u2__p3_0,
  140761. NULL,
  140762. &_vq_auxt__44u2__p3_0,
  140763. NULL,
  140764. 0
  140765. };
  140766. static long _vq_quantlist__44u2__p4_0[] = {
  140767. 2,
  140768. 1,
  140769. 3,
  140770. 0,
  140771. 4,
  140772. };
  140773. static long _vq_lengthlist__44u2__p4_0[] = {
  140774. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  140775. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  140776. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  140777. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  140778. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  140779. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  140780. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  140781. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  140782. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  140783. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  140784. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  140785. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140786. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  140787. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  140788. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  140789. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  140790. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  140791. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  140792. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  140793. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  140794. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  140795. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  140796. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  140797. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  140798. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  140799. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  140800. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  140801. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  140802. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  140803. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  140804. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  140805. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  140806. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  140807. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  140808. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  140809. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  140810. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  140811. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  140812. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  140813. 13,
  140814. };
  140815. static float _vq_quantthresh__44u2__p4_0[] = {
  140816. -1.5, -0.5, 0.5, 1.5,
  140817. };
  140818. static long _vq_quantmap__44u2__p4_0[] = {
  140819. 3, 1, 0, 2, 4,
  140820. };
  140821. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  140822. _vq_quantthresh__44u2__p4_0,
  140823. _vq_quantmap__44u2__p4_0,
  140824. 5,
  140825. 5
  140826. };
  140827. static static_codebook _44u2__p4_0 = {
  140828. 4, 625,
  140829. _vq_lengthlist__44u2__p4_0,
  140830. 1, -533725184, 1611661312, 3, 0,
  140831. _vq_quantlist__44u2__p4_0,
  140832. NULL,
  140833. &_vq_auxt__44u2__p4_0,
  140834. NULL,
  140835. 0
  140836. };
  140837. static long _vq_quantlist__44u2__p5_0[] = {
  140838. 4,
  140839. 3,
  140840. 5,
  140841. 2,
  140842. 6,
  140843. 1,
  140844. 7,
  140845. 0,
  140846. 8,
  140847. };
  140848. static long _vq_lengthlist__44u2__p5_0[] = {
  140849. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  140850. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140851. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  140852. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  140853. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  140854. 13,
  140855. };
  140856. static float _vq_quantthresh__44u2__p5_0[] = {
  140857. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140858. };
  140859. static long _vq_quantmap__44u2__p5_0[] = {
  140860. 7, 5, 3, 1, 0, 2, 4, 6,
  140861. 8,
  140862. };
  140863. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  140864. _vq_quantthresh__44u2__p5_0,
  140865. _vq_quantmap__44u2__p5_0,
  140866. 9,
  140867. 9
  140868. };
  140869. static static_codebook _44u2__p5_0 = {
  140870. 2, 81,
  140871. _vq_lengthlist__44u2__p5_0,
  140872. 1, -531628032, 1611661312, 4, 0,
  140873. _vq_quantlist__44u2__p5_0,
  140874. NULL,
  140875. &_vq_auxt__44u2__p5_0,
  140876. NULL,
  140877. 0
  140878. };
  140879. static long _vq_quantlist__44u2__p6_0[] = {
  140880. 6,
  140881. 5,
  140882. 7,
  140883. 4,
  140884. 8,
  140885. 3,
  140886. 9,
  140887. 2,
  140888. 10,
  140889. 1,
  140890. 11,
  140891. 0,
  140892. 12,
  140893. };
  140894. static long _vq_lengthlist__44u2__p6_0[] = {
  140895. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  140896. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  140897. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  140898. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  140899. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  140900. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  140901. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  140902. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  140903. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  140904. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  140905. 15,17,17,16,18,17,18, 0, 0,
  140906. };
  140907. static float _vq_quantthresh__44u2__p6_0[] = {
  140908. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140909. 12.5, 17.5, 22.5, 27.5,
  140910. };
  140911. static long _vq_quantmap__44u2__p6_0[] = {
  140912. 11, 9, 7, 5, 3, 1, 0, 2,
  140913. 4, 6, 8, 10, 12,
  140914. };
  140915. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  140916. _vq_quantthresh__44u2__p6_0,
  140917. _vq_quantmap__44u2__p6_0,
  140918. 13,
  140919. 13
  140920. };
  140921. static static_codebook _44u2__p6_0 = {
  140922. 2, 169,
  140923. _vq_lengthlist__44u2__p6_0,
  140924. 1, -526516224, 1616117760, 4, 0,
  140925. _vq_quantlist__44u2__p6_0,
  140926. NULL,
  140927. &_vq_auxt__44u2__p6_0,
  140928. NULL,
  140929. 0
  140930. };
  140931. static long _vq_quantlist__44u2__p6_1[] = {
  140932. 2,
  140933. 1,
  140934. 3,
  140935. 0,
  140936. 4,
  140937. };
  140938. static long _vq_lengthlist__44u2__p6_1[] = {
  140939. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  140940. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  140941. };
  140942. static float _vq_quantthresh__44u2__p6_1[] = {
  140943. -1.5, -0.5, 0.5, 1.5,
  140944. };
  140945. static long _vq_quantmap__44u2__p6_1[] = {
  140946. 3, 1, 0, 2, 4,
  140947. };
  140948. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  140949. _vq_quantthresh__44u2__p6_1,
  140950. _vq_quantmap__44u2__p6_1,
  140951. 5,
  140952. 5
  140953. };
  140954. static static_codebook _44u2__p6_1 = {
  140955. 2, 25,
  140956. _vq_lengthlist__44u2__p6_1,
  140957. 1, -533725184, 1611661312, 3, 0,
  140958. _vq_quantlist__44u2__p6_1,
  140959. NULL,
  140960. &_vq_auxt__44u2__p6_1,
  140961. NULL,
  140962. 0
  140963. };
  140964. static long _vq_quantlist__44u2__p7_0[] = {
  140965. 4,
  140966. 3,
  140967. 5,
  140968. 2,
  140969. 6,
  140970. 1,
  140971. 7,
  140972. 0,
  140973. 8,
  140974. };
  140975. static long _vq_lengthlist__44u2__p7_0[] = {
  140976. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  140977. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  140978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140979. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140981. 11,
  140982. };
  140983. static float _vq_quantthresh__44u2__p7_0[] = {
  140984. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  140985. };
  140986. static long _vq_quantmap__44u2__p7_0[] = {
  140987. 7, 5, 3, 1, 0, 2, 4, 6,
  140988. 8,
  140989. };
  140990. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  140991. _vq_quantthresh__44u2__p7_0,
  140992. _vq_quantmap__44u2__p7_0,
  140993. 9,
  140994. 9
  140995. };
  140996. static static_codebook _44u2__p7_0 = {
  140997. 2, 81,
  140998. _vq_lengthlist__44u2__p7_0,
  140999. 1, -516612096, 1626677248, 4, 0,
  141000. _vq_quantlist__44u2__p7_0,
  141001. NULL,
  141002. &_vq_auxt__44u2__p7_0,
  141003. NULL,
  141004. 0
  141005. };
  141006. static long _vq_quantlist__44u2__p7_1[] = {
  141007. 6,
  141008. 5,
  141009. 7,
  141010. 4,
  141011. 8,
  141012. 3,
  141013. 9,
  141014. 2,
  141015. 10,
  141016. 1,
  141017. 11,
  141018. 0,
  141019. 12,
  141020. };
  141021. static long _vq_lengthlist__44u2__p7_1[] = {
  141022. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  141023. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  141024. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  141025. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  141026. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  141027. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  141028. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  141029. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  141030. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  141031. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  141032. 14,14,14,17,15,17,17,17,17,
  141033. };
  141034. static float _vq_quantthresh__44u2__p7_1[] = {
  141035. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141036. 32.5, 45.5, 58.5, 71.5,
  141037. };
  141038. static long _vq_quantmap__44u2__p7_1[] = {
  141039. 11, 9, 7, 5, 3, 1, 0, 2,
  141040. 4, 6, 8, 10, 12,
  141041. };
  141042. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  141043. _vq_quantthresh__44u2__p7_1,
  141044. _vq_quantmap__44u2__p7_1,
  141045. 13,
  141046. 13
  141047. };
  141048. static static_codebook _44u2__p7_1 = {
  141049. 2, 169,
  141050. _vq_lengthlist__44u2__p7_1,
  141051. 1, -523010048, 1618608128, 4, 0,
  141052. _vq_quantlist__44u2__p7_1,
  141053. NULL,
  141054. &_vq_auxt__44u2__p7_1,
  141055. NULL,
  141056. 0
  141057. };
  141058. static long _vq_quantlist__44u2__p7_2[] = {
  141059. 6,
  141060. 5,
  141061. 7,
  141062. 4,
  141063. 8,
  141064. 3,
  141065. 9,
  141066. 2,
  141067. 10,
  141068. 1,
  141069. 11,
  141070. 0,
  141071. 12,
  141072. };
  141073. static long _vq_lengthlist__44u2__p7_2[] = {
  141074. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  141075. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  141076. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  141077. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141078. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  141079. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  141080. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  141081. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141082. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  141083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  141084. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141085. };
  141086. static float _vq_quantthresh__44u2__p7_2[] = {
  141087. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141088. 2.5, 3.5, 4.5, 5.5,
  141089. };
  141090. static long _vq_quantmap__44u2__p7_2[] = {
  141091. 11, 9, 7, 5, 3, 1, 0, 2,
  141092. 4, 6, 8, 10, 12,
  141093. };
  141094. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  141095. _vq_quantthresh__44u2__p7_2,
  141096. _vq_quantmap__44u2__p7_2,
  141097. 13,
  141098. 13
  141099. };
  141100. static static_codebook _44u2__p7_2 = {
  141101. 2, 169,
  141102. _vq_lengthlist__44u2__p7_2,
  141103. 1, -531103744, 1611661312, 4, 0,
  141104. _vq_quantlist__44u2__p7_2,
  141105. NULL,
  141106. &_vq_auxt__44u2__p7_2,
  141107. NULL,
  141108. 0
  141109. };
  141110. static long _huff_lengthlist__44u2__short[] = {
  141111. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  141112. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  141113. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  141114. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  141115. };
  141116. static static_codebook _huff_book__44u2__short = {
  141117. 2, 64,
  141118. _huff_lengthlist__44u2__short,
  141119. 0, 0, 0, 0, 0,
  141120. NULL,
  141121. NULL,
  141122. NULL,
  141123. NULL,
  141124. 0
  141125. };
  141126. static long _huff_lengthlist__44u3__long[] = {
  141127. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  141128. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  141129. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  141130. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  141131. };
  141132. static static_codebook _huff_book__44u3__long = {
  141133. 2, 64,
  141134. _huff_lengthlist__44u3__long,
  141135. 0, 0, 0, 0, 0,
  141136. NULL,
  141137. NULL,
  141138. NULL,
  141139. NULL,
  141140. 0
  141141. };
  141142. static long _vq_quantlist__44u3__p1_0[] = {
  141143. 1,
  141144. 0,
  141145. 2,
  141146. };
  141147. static long _vq_lengthlist__44u3__p1_0[] = {
  141148. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141149. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141150. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  141151. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141152. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  141153. 13,
  141154. };
  141155. static float _vq_quantthresh__44u3__p1_0[] = {
  141156. -0.5, 0.5,
  141157. };
  141158. static long _vq_quantmap__44u3__p1_0[] = {
  141159. 1, 0, 2,
  141160. };
  141161. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  141162. _vq_quantthresh__44u3__p1_0,
  141163. _vq_quantmap__44u3__p1_0,
  141164. 3,
  141165. 3
  141166. };
  141167. static static_codebook _44u3__p1_0 = {
  141168. 4, 81,
  141169. _vq_lengthlist__44u3__p1_0,
  141170. 1, -535822336, 1611661312, 2, 0,
  141171. _vq_quantlist__44u3__p1_0,
  141172. NULL,
  141173. &_vq_auxt__44u3__p1_0,
  141174. NULL,
  141175. 0
  141176. };
  141177. static long _vq_quantlist__44u3__p2_0[] = {
  141178. 1,
  141179. 0,
  141180. 2,
  141181. };
  141182. static long _vq_lengthlist__44u3__p2_0[] = {
  141183. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141184. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  141185. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141186. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141187. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  141188. 9,
  141189. };
  141190. static float _vq_quantthresh__44u3__p2_0[] = {
  141191. -0.5, 0.5,
  141192. };
  141193. static long _vq_quantmap__44u3__p2_0[] = {
  141194. 1, 0, 2,
  141195. };
  141196. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  141197. _vq_quantthresh__44u3__p2_0,
  141198. _vq_quantmap__44u3__p2_0,
  141199. 3,
  141200. 3
  141201. };
  141202. static static_codebook _44u3__p2_0 = {
  141203. 4, 81,
  141204. _vq_lengthlist__44u3__p2_0,
  141205. 1, -535822336, 1611661312, 2, 0,
  141206. _vq_quantlist__44u3__p2_0,
  141207. NULL,
  141208. &_vq_auxt__44u3__p2_0,
  141209. NULL,
  141210. 0
  141211. };
  141212. static long _vq_quantlist__44u3__p3_0[] = {
  141213. 2,
  141214. 1,
  141215. 3,
  141216. 0,
  141217. 4,
  141218. };
  141219. static long _vq_lengthlist__44u3__p3_0[] = {
  141220. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141221. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141222. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141223. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141224. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  141225. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  141226. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  141227. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  141228. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141229. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141230. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  141231. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141232. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  141233. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  141234. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  141235. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  141236. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  141237. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  141238. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  141239. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  141240. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  141241. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  141242. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  141243. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  141244. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  141245. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  141246. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  141247. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  141248. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  141249. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  141250. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  141251. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  141252. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  141253. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  141254. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  141255. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  141256. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  141257. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  141258. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  141259. 0,
  141260. };
  141261. static float _vq_quantthresh__44u3__p3_0[] = {
  141262. -1.5, -0.5, 0.5, 1.5,
  141263. };
  141264. static long _vq_quantmap__44u3__p3_0[] = {
  141265. 3, 1, 0, 2, 4,
  141266. };
  141267. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  141268. _vq_quantthresh__44u3__p3_0,
  141269. _vq_quantmap__44u3__p3_0,
  141270. 5,
  141271. 5
  141272. };
  141273. static static_codebook _44u3__p3_0 = {
  141274. 4, 625,
  141275. _vq_lengthlist__44u3__p3_0,
  141276. 1, -533725184, 1611661312, 3, 0,
  141277. _vq_quantlist__44u3__p3_0,
  141278. NULL,
  141279. &_vq_auxt__44u3__p3_0,
  141280. NULL,
  141281. 0
  141282. };
  141283. static long _vq_quantlist__44u3__p4_0[] = {
  141284. 2,
  141285. 1,
  141286. 3,
  141287. 0,
  141288. 4,
  141289. };
  141290. static long _vq_lengthlist__44u3__p4_0[] = {
  141291. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141292. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141293. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  141294. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  141295. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  141296. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141297. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  141298. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  141299. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141300. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141301. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  141302. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141303. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  141304. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  141305. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  141306. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141307. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  141308. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141309. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141310. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  141311. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141312. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  141313. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  141314. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141315. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  141316. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  141317. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  141318. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  141319. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  141320. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  141321. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  141322. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  141323. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  141324. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  141325. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  141326. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  141327. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  141328. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  141329. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  141330. 13,
  141331. };
  141332. static float _vq_quantthresh__44u3__p4_0[] = {
  141333. -1.5, -0.5, 0.5, 1.5,
  141334. };
  141335. static long _vq_quantmap__44u3__p4_0[] = {
  141336. 3, 1, 0, 2, 4,
  141337. };
  141338. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  141339. _vq_quantthresh__44u3__p4_0,
  141340. _vq_quantmap__44u3__p4_0,
  141341. 5,
  141342. 5
  141343. };
  141344. static static_codebook _44u3__p4_0 = {
  141345. 4, 625,
  141346. _vq_lengthlist__44u3__p4_0,
  141347. 1, -533725184, 1611661312, 3, 0,
  141348. _vq_quantlist__44u3__p4_0,
  141349. NULL,
  141350. &_vq_auxt__44u3__p4_0,
  141351. NULL,
  141352. 0
  141353. };
  141354. static long _vq_quantlist__44u3__p5_0[] = {
  141355. 4,
  141356. 3,
  141357. 5,
  141358. 2,
  141359. 6,
  141360. 1,
  141361. 7,
  141362. 0,
  141363. 8,
  141364. };
  141365. static long _vq_lengthlist__44u3__p5_0[] = {
  141366. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  141367. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  141368. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  141369. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141370. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  141371. 12,
  141372. };
  141373. static float _vq_quantthresh__44u3__p5_0[] = {
  141374. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141375. };
  141376. static long _vq_quantmap__44u3__p5_0[] = {
  141377. 7, 5, 3, 1, 0, 2, 4, 6,
  141378. 8,
  141379. };
  141380. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  141381. _vq_quantthresh__44u3__p5_0,
  141382. _vq_quantmap__44u3__p5_0,
  141383. 9,
  141384. 9
  141385. };
  141386. static static_codebook _44u3__p5_0 = {
  141387. 2, 81,
  141388. _vq_lengthlist__44u3__p5_0,
  141389. 1, -531628032, 1611661312, 4, 0,
  141390. _vq_quantlist__44u3__p5_0,
  141391. NULL,
  141392. &_vq_auxt__44u3__p5_0,
  141393. NULL,
  141394. 0
  141395. };
  141396. static long _vq_quantlist__44u3__p6_0[] = {
  141397. 6,
  141398. 5,
  141399. 7,
  141400. 4,
  141401. 8,
  141402. 3,
  141403. 9,
  141404. 2,
  141405. 10,
  141406. 1,
  141407. 11,
  141408. 0,
  141409. 12,
  141410. };
  141411. static long _vq_lengthlist__44u3__p6_0[] = {
  141412. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  141413. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  141414. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141415. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  141416. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  141417. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  141418. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  141419. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  141420. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  141421. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  141422. 15,16,16,16,17,18,16,20,18,
  141423. };
  141424. static float _vq_quantthresh__44u3__p6_0[] = {
  141425. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141426. 12.5, 17.5, 22.5, 27.5,
  141427. };
  141428. static long _vq_quantmap__44u3__p6_0[] = {
  141429. 11, 9, 7, 5, 3, 1, 0, 2,
  141430. 4, 6, 8, 10, 12,
  141431. };
  141432. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  141433. _vq_quantthresh__44u3__p6_0,
  141434. _vq_quantmap__44u3__p6_0,
  141435. 13,
  141436. 13
  141437. };
  141438. static static_codebook _44u3__p6_0 = {
  141439. 2, 169,
  141440. _vq_lengthlist__44u3__p6_0,
  141441. 1, -526516224, 1616117760, 4, 0,
  141442. _vq_quantlist__44u3__p6_0,
  141443. NULL,
  141444. &_vq_auxt__44u3__p6_0,
  141445. NULL,
  141446. 0
  141447. };
  141448. static long _vq_quantlist__44u3__p6_1[] = {
  141449. 2,
  141450. 1,
  141451. 3,
  141452. 0,
  141453. 4,
  141454. };
  141455. static long _vq_lengthlist__44u3__p6_1[] = {
  141456. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141457. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141458. };
  141459. static float _vq_quantthresh__44u3__p6_1[] = {
  141460. -1.5, -0.5, 0.5, 1.5,
  141461. };
  141462. static long _vq_quantmap__44u3__p6_1[] = {
  141463. 3, 1, 0, 2, 4,
  141464. };
  141465. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  141466. _vq_quantthresh__44u3__p6_1,
  141467. _vq_quantmap__44u3__p6_1,
  141468. 5,
  141469. 5
  141470. };
  141471. static static_codebook _44u3__p6_1 = {
  141472. 2, 25,
  141473. _vq_lengthlist__44u3__p6_1,
  141474. 1, -533725184, 1611661312, 3, 0,
  141475. _vq_quantlist__44u3__p6_1,
  141476. NULL,
  141477. &_vq_auxt__44u3__p6_1,
  141478. NULL,
  141479. 0
  141480. };
  141481. static long _vq_quantlist__44u3__p7_0[] = {
  141482. 4,
  141483. 3,
  141484. 5,
  141485. 2,
  141486. 6,
  141487. 1,
  141488. 7,
  141489. 0,
  141490. 8,
  141491. };
  141492. static long _vq_lengthlist__44u3__p7_0[] = {
  141493. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  141494. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141495. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141496. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141497. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141498. 9,
  141499. };
  141500. static float _vq_quantthresh__44u3__p7_0[] = {
  141501. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  141502. };
  141503. static long _vq_quantmap__44u3__p7_0[] = {
  141504. 7, 5, 3, 1, 0, 2, 4, 6,
  141505. 8,
  141506. };
  141507. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  141508. _vq_quantthresh__44u3__p7_0,
  141509. _vq_quantmap__44u3__p7_0,
  141510. 9,
  141511. 9
  141512. };
  141513. static static_codebook _44u3__p7_0 = {
  141514. 2, 81,
  141515. _vq_lengthlist__44u3__p7_0,
  141516. 1, -515907584, 1627381760, 4, 0,
  141517. _vq_quantlist__44u3__p7_0,
  141518. NULL,
  141519. &_vq_auxt__44u3__p7_0,
  141520. NULL,
  141521. 0
  141522. };
  141523. static long _vq_quantlist__44u3__p7_1[] = {
  141524. 7,
  141525. 6,
  141526. 8,
  141527. 5,
  141528. 9,
  141529. 4,
  141530. 10,
  141531. 3,
  141532. 11,
  141533. 2,
  141534. 12,
  141535. 1,
  141536. 13,
  141537. 0,
  141538. 14,
  141539. };
  141540. static long _vq_lengthlist__44u3__p7_1[] = {
  141541. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  141542. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  141543. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  141544. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  141545. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  141546. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  141547. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  141548. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  141549. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  141550. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  141551. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  141552. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  141553. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  141554. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  141555. 17,
  141556. };
  141557. static float _vq_quantthresh__44u3__p7_1[] = {
  141558. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141559. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141560. };
  141561. static long _vq_quantmap__44u3__p7_1[] = {
  141562. 13, 11, 9, 7, 5, 3, 1, 0,
  141563. 2, 4, 6, 8, 10, 12, 14,
  141564. };
  141565. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  141566. _vq_quantthresh__44u3__p7_1,
  141567. _vq_quantmap__44u3__p7_1,
  141568. 15,
  141569. 15
  141570. };
  141571. static static_codebook _44u3__p7_1 = {
  141572. 2, 225,
  141573. _vq_lengthlist__44u3__p7_1,
  141574. 1, -522338304, 1620115456, 4, 0,
  141575. _vq_quantlist__44u3__p7_1,
  141576. NULL,
  141577. &_vq_auxt__44u3__p7_1,
  141578. NULL,
  141579. 0
  141580. };
  141581. static long _vq_quantlist__44u3__p7_2[] = {
  141582. 8,
  141583. 7,
  141584. 9,
  141585. 6,
  141586. 10,
  141587. 5,
  141588. 11,
  141589. 4,
  141590. 12,
  141591. 3,
  141592. 13,
  141593. 2,
  141594. 14,
  141595. 1,
  141596. 15,
  141597. 0,
  141598. 16,
  141599. };
  141600. static long _vq_lengthlist__44u3__p7_2[] = {
  141601. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141602. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141603. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  141604. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141605. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  141606. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141607. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  141608. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141609. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  141610. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141611. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141612. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  141613. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  141614. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141615. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  141616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  141617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141618. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  141619. 11,
  141620. };
  141621. static float _vq_quantthresh__44u3__p7_2[] = {
  141622. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141623. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141624. };
  141625. static long _vq_quantmap__44u3__p7_2[] = {
  141626. 15, 13, 11, 9, 7, 5, 3, 1,
  141627. 0, 2, 4, 6, 8, 10, 12, 14,
  141628. 16,
  141629. };
  141630. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  141631. _vq_quantthresh__44u3__p7_2,
  141632. _vq_quantmap__44u3__p7_2,
  141633. 17,
  141634. 17
  141635. };
  141636. static static_codebook _44u3__p7_2 = {
  141637. 2, 289,
  141638. _vq_lengthlist__44u3__p7_2,
  141639. 1, -529530880, 1611661312, 5, 0,
  141640. _vq_quantlist__44u3__p7_2,
  141641. NULL,
  141642. &_vq_auxt__44u3__p7_2,
  141643. NULL,
  141644. 0
  141645. };
  141646. static long _huff_lengthlist__44u3__short[] = {
  141647. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  141648. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  141649. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  141650. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  141651. };
  141652. static static_codebook _huff_book__44u3__short = {
  141653. 2, 64,
  141654. _huff_lengthlist__44u3__short,
  141655. 0, 0, 0, 0, 0,
  141656. NULL,
  141657. NULL,
  141658. NULL,
  141659. NULL,
  141660. 0
  141661. };
  141662. static long _huff_lengthlist__44u4__long[] = {
  141663. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  141664. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  141665. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  141666. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  141667. };
  141668. static static_codebook _huff_book__44u4__long = {
  141669. 2, 64,
  141670. _huff_lengthlist__44u4__long,
  141671. 0, 0, 0, 0, 0,
  141672. NULL,
  141673. NULL,
  141674. NULL,
  141675. NULL,
  141676. 0
  141677. };
  141678. static long _vq_quantlist__44u4__p1_0[] = {
  141679. 1,
  141680. 0,
  141681. 2,
  141682. };
  141683. static long _vq_lengthlist__44u4__p1_0[] = {
  141684. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141685. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141686. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  141687. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141688. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  141689. 13,
  141690. };
  141691. static float _vq_quantthresh__44u4__p1_0[] = {
  141692. -0.5, 0.5,
  141693. };
  141694. static long _vq_quantmap__44u4__p1_0[] = {
  141695. 1, 0, 2,
  141696. };
  141697. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  141698. _vq_quantthresh__44u4__p1_0,
  141699. _vq_quantmap__44u4__p1_0,
  141700. 3,
  141701. 3
  141702. };
  141703. static static_codebook _44u4__p1_0 = {
  141704. 4, 81,
  141705. _vq_lengthlist__44u4__p1_0,
  141706. 1, -535822336, 1611661312, 2, 0,
  141707. _vq_quantlist__44u4__p1_0,
  141708. NULL,
  141709. &_vq_auxt__44u4__p1_0,
  141710. NULL,
  141711. 0
  141712. };
  141713. static long _vq_quantlist__44u4__p2_0[] = {
  141714. 1,
  141715. 0,
  141716. 2,
  141717. };
  141718. static long _vq_lengthlist__44u4__p2_0[] = {
  141719. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141720. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  141721. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141722. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  141723. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141724. 9,
  141725. };
  141726. static float _vq_quantthresh__44u4__p2_0[] = {
  141727. -0.5, 0.5,
  141728. };
  141729. static long _vq_quantmap__44u4__p2_0[] = {
  141730. 1, 0, 2,
  141731. };
  141732. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  141733. _vq_quantthresh__44u4__p2_0,
  141734. _vq_quantmap__44u4__p2_0,
  141735. 3,
  141736. 3
  141737. };
  141738. static static_codebook _44u4__p2_0 = {
  141739. 4, 81,
  141740. _vq_lengthlist__44u4__p2_0,
  141741. 1, -535822336, 1611661312, 2, 0,
  141742. _vq_quantlist__44u4__p2_0,
  141743. NULL,
  141744. &_vq_auxt__44u4__p2_0,
  141745. NULL,
  141746. 0
  141747. };
  141748. static long _vq_quantlist__44u4__p3_0[] = {
  141749. 2,
  141750. 1,
  141751. 3,
  141752. 0,
  141753. 4,
  141754. };
  141755. static long _vq_lengthlist__44u4__p3_0[] = {
  141756. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141757. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  141758. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  141759. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  141760. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  141761. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  141762. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  141763. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  141764. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  141765. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  141766. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  141767. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  141768. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  141769. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  141770. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  141771. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  141772. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  141773. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  141774. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  141775. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  141776. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  141777. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  141778. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  141779. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  141780. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  141781. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  141782. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  141783. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  141784. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  141785. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  141786. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  141787. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  141788. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  141789. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  141790. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  141791. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  141792. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  141793. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  141794. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  141795. 0,
  141796. };
  141797. static float _vq_quantthresh__44u4__p3_0[] = {
  141798. -1.5, -0.5, 0.5, 1.5,
  141799. };
  141800. static long _vq_quantmap__44u4__p3_0[] = {
  141801. 3, 1, 0, 2, 4,
  141802. };
  141803. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  141804. _vq_quantthresh__44u4__p3_0,
  141805. _vq_quantmap__44u4__p3_0,
  141806. 5,
  141807. 5
  141808. };
  141809. static static_codebook _44u4__p3_0 = {
  141810. 4, 625,
  141811. _vq_lengthlist__44u4__p3_0,
  141812. 1, -533725184, 1611661312, 3, 0,
  141813. _vq_quantlist__44u4__p3_0,
  141814. NULL,
  141815. &_vq_auxt__44u4__p3_0,
  141816. NULL,
  141817. 0
  141818. };
  141819. static long _vq_quantlist__44u4__p4_0[] = {
  141820. 2,
  141821. 1,
  141822. 3,
  141823. 0,
  141824. 4,
  141825. };
  141826. static long _vq_lengthlist__44u4__p4_0[] = {
  141827. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141828. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141829. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  141830. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  141831. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  141832. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  141833. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  141834. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  141835. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141836. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141837. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  141838. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141839. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  141840. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  141841. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  141842. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141843. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  141844. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141845. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141846. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  141847. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141848. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  141849. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  141850. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141851. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  141852. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  141853. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  141854. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  141855. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  141856. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  141857. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  141858. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  141859. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  141860. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  141861. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  141862. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  141863. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  141864. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  141865. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  141866. 13,
  141867. };
  141868. static float _vq_quantthresh__44u4__p4_0[] = {
  141869. -1.5, -0.5, 0.5, 1.5,
  141870. };
  141871. static long _vq_quantmap__44u4__p4_0[] = {
  141872. 3, 1, 0, 2, 4,
  141873. };
  141874. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  141875. _vq_quantthresh__44u4__p4_0,
  141876. _vq_quantmap__44u4__p4_0,
  141877. 5,
  141878. 5
  141879. };
  141880. static static_codebook _44u4__p4_0 = {
  141881. 4, 625,
  141882. _vq_lengthlist__44u4__p4_0,
  141883. 1, -533725184, 1611661312, 3, 0,
  141884. _vq_quantlist__44u4__p4_0,
  141885. NULL,
  141886. &_vq_auxt__44u4__p4_0,
  141887. NULL,
  141888. 0
  141889. };
  141890. static long _vq_quantlist__44u4__p5_0[] = {
  141891. 4,
  141892. 3,
  141893. 5,
  141894. 2,
  141895. 6,
  141896. 1,
  141897. 7,
  141898. 0,
  141899. 8,
  141900. };
  141901. static long _vq_lengthlist__44u4__p5_0[] = {
  141902. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  141903. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  141904. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  141905. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141906. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  141907. 12,
  141908. };
  141909. static float _vq_quantthresh__44u4__p5_0[] = {
  141910. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141911. };
  141912. static long _vq_quantmap__44u4__p5_0[] = {
  141913. 7, 5, 3, 1, 0, 2, 4, 6,
  141914. 8,
  141915. };
  141916. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  141917. _vq_quantthresh__44u4__p5_0,
  141918. _vq_quantmap__44u4__p5_0,
  141919. 9,
  141920. 9
  141921. };
  141922. static static_codebook _44u4__p5_0 = {
  141923. 2, 81,
  141924. _vq_lengthlist__44u4__p5_0,
  141925. 1, -531628032, 1611661312, 4, 0,
  141926. _vq_quantlist__44u4__p5_0,
  141927. NULL,
  141928. &_vq_auxt__44u4__p5_0,
  141929. NULL,
  141930. 0
  141931. };
  141932. static long _vq_quantlist__44u4__p6_0[] = {
  141933. 6,
  141934. 5,
  141935. 7,
  141936. 4,
  141937. 8,
  141938. 3,
  141939. 9,
  141940. 2,
  141941. 10,
  141942. 1,
  141943. 11,
  141944. 0,
  141945. 12,
  141946. };
  141947. static long _vq_lengthlist__44u4__p6_0[] = {
  141948. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  141949. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  141950. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141951. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  141952. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  141953. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  141954. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  141955. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  141956. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  141957. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  141958. 16,16,16,17,17,18,17,20,21,
  141959. };
  141960. static float _vq_quantthresh__44u4__p6_0[] = {
  141961. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141962. 12.5, 17.5, 22.5, 27.5,
  141963. };
  141964. static long _vq_quantmap__44u4__p6_0[] = {
  141965. 11, 9, 7, 5, 3, 1, 0, 2,
  141966. 4, 6, 8, 10, 12,
  141967. };
  141968. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  141969. _vq_quantthresh__44u4__p6_0,
  141970. _vq_quantmap__44u4__p6_0,
  141971. 13,
  141972. 13
  141973. };
  141974. static static_codebook _44u4__p6_0 = {
  141975. 2, 169,
  141976. _vq_lengthlist__44u4__p6_0,
  141977. 1, -526516224, 1616117760, 4, 0,
  141978. _vq_quantlist__44u4__p6_0,
  141979. NULL,
  141980. &_vq_auxt__44u4__p6_0,
  141981. NULL,
  141982. 0
  141983. };
  141984. static long _vq_quantlist__44u4__p6_1[] = {
  141985. 2,
  141986. 1,
  141987. 3,
  141988. 0,
  141989. 4,
  141990. };
  141991. static long _vq_lengthlist__44u4__p6_1[] = {
  141992. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141993. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141994. };
  141995. static float _vq_quantthresh__44u4__p6_1[] = {
  141996. -1.5, -0.5, 0.5, 1.5,
  141997. };
  141998. static long _vq_quantmap__44u4__p6_1[] = {
  141999. 3, 1, 0, 2, 4,
  142000. };
  142001. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  142002. _vq_quantthresh__44u4__p6_1,
  142003. _vq_quantmap__44u4__p6_1,
  142004. 5,
  142005. 5
  142006. };
  142007. static static_codebook _44u4__p6_1 = {
  142008. 2, 25,
  142009. _vq_lengthlist__44u4__p6_1,
  142010. 1, -533725184, 1611661312, 3, 0,
  142011. _vq_quantlist__44u4__p6_1,
  142012. NULL,
  142013. &_vq_auxt__44u4__p6_1,
  142014. NULL,
  142015. 0
  142016. };
  142017. static long _vq_quantlist__44u4__p7_0[] = {
  142018. 6,
  142019. 5,
  142020. 7,
  142021. 4,
  142022. 8,
  142023. 3,
  142024. 9,
  142025. 2,
  142026. 10,
  142027. 1,
  142028. 11,
  142029. 0,
  142030. 12,
  142031. };
  142032. static long _vq_lengthlist__44u4__p7_0[] = {
  142033. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  142034. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  142035. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142036. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142037. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142038. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142043. 11,11,11,11,11,11,11,11,11,
  142044. };
  142045. static float _vq_quantthresh__44u4__p7_0[] = {
  142046. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142047. 637.5, 892.5, 1147.5, 1402.5,
  142048. };
  142049. static long _vq_quantmap__44u4__p7_0[] = {
  142050. 11, 9, 7, 5, 3, 1, 0, 2,
  142051. 4, 6, 8, 10, 12,
  142052. };
  142053. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  142054. _vq_quantthresh__44u4__p7_0,
  142055. _vq_quantmap__44u4__p7_0,
  142056. 13,
  142057. 13
  142058. };
  142059. static static_codebook _44u4__p7_0 = {
  142060. 2, 169,
  142061. _vq_lengthlist__44u4__p7_0,
  142062. 1, -514332672, 1627381760, 4, 0,
  142063. _vq_quantlist__44u4__p7_0,
  142064. NULL,
  142065. &_vq_auxt__44u4__p7_0,
  142066. NULL,
  142067. 0
  142068. };
  142069. static long _vq_quantlist__44u4__p7_1[] = {
  142070. 7,
  142071. 6,
  142072. 8,
  142073. 5,
  142074. 9,
  142075. 4,
  142076. 10,
  142077. 3,
  142078. 11,
  142079. 2,
  142080. 12,
  142081. 1,
  142082. 13,
  142083. 0,
  142084. 14,
  142085. };
  142086. static long _vq_lengthlist__44u4__p7_1[] = {
  142087. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  142088. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  142089. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  142090. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  142091. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  142092. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  142093. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  142094. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  142095. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  142096. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  142097. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  142098. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  142099. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  142100. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  142101. 16,
  142102. };
  142103. static float _vq_quantthresh__44u4__p7_1[] = {
  142104. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142105. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142106. };
  142107. static long _vq_quantmap__44u4__p7_1[] = {
  142108. 13, 11, 9, 7, 5, 3, 1, 0,
  142109. 2, 4, 6, 8, 10, 12, 14,
  142110. };
  142111. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  142112. _vq_quantthresh__44u4__p7_1,
  142113. _vq_quantmap__44u4__p7_1,
  142114. 15,
  142115. 15
  142116. };
  142117. static static_codebook _44u4__p7_1 = {
  142118. 2, 225,
  142119. _vq_lengthlist__44u4__p7_1,
  142120. 1, -522338304, 1620115456, 4, 0,
  142121. _vq_quantlist__44u4__p7_1,
  142122. NULL,
  142123. &_vq_auxt__44u4__p7_1,
  142124. NULL,
  142125. 0
  142126. };
  142127. static long _vq_quantlist__44u4__p7_2[] = {
  142128. 8,
  142129. 7,
  142130. 9,
  142131. 6,
  142132. 10,
  142133. 5,
  142134. 11,
  142135. 4,
  142136. 12,
  142137. 3,
  142138. 13,
  142139. 2,
  142140. 14,
  142141. 1,
  142142. 15,
  142143. 0,
  142144. 16,
  142145. };
  142146. static long _vq_lengthlist__44u4__p7_2[] = {
  142147. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142148. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142149. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142150. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142151. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142152. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142153. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142154. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142155. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  142156. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  142157. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142158. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142159. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142160. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  142161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142162. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142163. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142164. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  142165. 10,
  142166. };
  142167. static float _vq_quantthresh__44u4__p7_2[] = {
  142168. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142169. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142170. };
  142171. static long _vq_quantmap__44u4__p7_2[] = {
  142172. 15, 13, 11, 9, 7, 5, 3, 1,
  142173. 0, 2, 4, 6, 8, 10, 12, 14,
  142174. 16,
  142175. };
  142176. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  142177. _vq_quantthresh__44u4__p7_2,
  142178. _vq_quantmap__44u4__p7_2,
  142179. 17,
  142180. 17
  142181. };
  142182. static static_codebook _44u4__p7_2 = {
  142183. 2, 289,
  142184. _vq_lengthlist__44u4__p7_2,
  142185. 1, -529530880, 1611661312, 5, 0,
  142186. _vq_quantlist__44u4__p7_2,
  142187. NULL,
  142188. &_vq_auxt__44u4__p7_2,
  142189. NULL,
  142190. 0
  142191. };
  142192. static long _huff_lengthlist__44u4__short[] = {
  142193. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  142194. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  142195. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  142196. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  142197. };
  142198. static static_codebook _huff_book__44u4__short = {
  142199. 2, 64,
  142200. _huff_lengthlist__44u4__short,
  142201. 0, 0, 0, 0, 0,
  142202. NULL,
  142203. NULL,
  142204. NULL,
  142205. NULL,
  142206. 0
  142207. };
  142208. static long _huff_lengthlist__44u5__long[] = {
  142209. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  142210. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  142211. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  142212. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  142213. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  142214. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  142215. 14, 8, 7, 8,
  142216. };
  142217. static static_codebook _huff_book__44u5__long = {
  142218. 2, 100,
  142219. _huff_lengthlist__44u5__long,
  142220. 0, 0, 0, 0, 0,
  142221. NULL,
  142222. NULL,
  142223. NULL,
  142224. NULL,
  142225. 0
  142226. };
  142227. static long _vq_quantlist__44u5__p1_0[] = {
  142228. 1,
  142229. 0,
  142230. 2,
  142231. };
  142232. static long _vq_lengthlist__44u5__p1_0[] = {
  142233. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142234. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142235. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142236. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  142237. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142238. 12,
  142239. };
  142240. static float _vq_quantthresh__44u5__p1_0[] = {
  142241. -0.5, 0.5,
  142242. };
  142243. static long _vq_quantmap__44u5__p1_0[] = {
  142244. 1, 0, 2,
  142245. };
  142246. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  142247. _vq_quantthresh__44u5__p1_0,
  142248. _vq_quantmap__44u5__p1_0,
  142249. 3,
  142250. 3
  142251. };
  142252. static static_codebook _44u5__p1_0 = {
  142253. 4, 81,
  142254. _vq_lengthlist__44u5__p1_0,
  142255. 1, -535822336, 1611661312, 2, 0,
  142256. _vq_quantlist__44u5__p1_0,
  142257. NULL,
  142258. &_vq_auxt__44u5__p1_0,
  142259. NULL,
  142260. 0
  142261. };
  142262. static long _vq_quantlist__44u5__p2_0[] = {
  142263. 1,
  142264. 0,
  142265. 2,
  142266. };
  142267. static long _vq_lengthlist__44u5__p2_0[] = {
  142268. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142269. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142270. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  142271. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142272. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142273. 9,
  142274. };
  142275. static float _vq_quantthresh__44u5__p2_0[] = {
  142276. -0.5, 0.5,
  142277. };
  142278. static long _vq_quantmap__44u5__p2_0[] = {
  142279. 1, 0, 2,
  142280. };
  142281. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  142282. _vq_quantthresh__44u5__p2_0,
  142283. _vq_quantmap__44u5__p2_0,
  142284. 3,
  142285. 3
  142286. };
  142287. static static_codebook _44u5__p2_0 = {
  142288. 4, 81,
  142289. _vq_lengthlist__44u5__p2_0,
  142290. 1, -535822336, 1611661312, 2, 0,
  142291. _vq_quantlist__44u5__p2_0,
  142292. NULL,
  142293. &_vq_auxt__44u5__p2_0,
  142294. NULL,
  142295. 0
  142296. };
  142297. static long _vq_quantlist__44u5__p3_0[] = {
  142298. 2,
  142299. 1,
  142300. 3,
  142301. 0,
  142302. 4,
  142303. };
  142304. static long _vq_lengthlist__44u5__p3_0[] = {
  142305. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  142306. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  142307. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  142308. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  142309. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  142310. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  142311. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  142312. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  142313. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  142314. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  142315. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  142316. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  142317. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  142318. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  142319. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  142320. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  142321. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142322. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  142323. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  142324. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  142325. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  142326. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  142327. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  142328. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  142329. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  142330. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  142331. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  142332. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  142333. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  142334. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  142335. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  142336. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  142337. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  142338. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  142339. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  142340. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  142341. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  142342. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  142343. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  142344. 0,
  142345. };
  142346. static float _vq_quantthresh__44u5__p3_0[] = {
  142347. -1.5, -0.5, 0.5, 1.5,
  142348. };
  142349. static long _vq_quantmap__44u5__p3_0[] = {
  142350. 3, 1, 0, 2, 4,
  142351. };
  142352. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  142353. _vq_quantthresh__44u5__p3_0,
  142354. _vq_quantmap__44u5__p3_0,
  142355. 5,
  142356. 5
  142357. };
  142358. static static_codebook _44u5__p3_0 = {
  142359. 4, 625,
  142360. _vq_lengthlist__44u5__p3_0,
  142361. 1, -533725184, 1611661312, 3, 0,
  142362. _vq_quantlist__44u5__p3_0,
  142363. NULL,
  142364. &_vq_auxt__44u5__p3_0,
  142365. NULL,
  142366. 0
  142367. };
  142368. static long _vq_quantlist__44u5__p4_0[] = {
  142369. 2,
  142370. 1,
  142371. 3,
  142372. 0,
  142373. 4,
  142374. };
  142375. static long _vq_lengthlist__44u5__p4_0[] = {
  142376. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  142377. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  142378. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  142379. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  142380. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  142381. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  142382. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  142383. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  142384. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  142385. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  142386. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  142387. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142388. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  142389. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  142390. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  142391. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  142392. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  142393. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142394. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  142395. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  142396. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  142397. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  142398. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  142399. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  142400. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  142401. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  142402. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  142403. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  142404. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  142405. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  142406. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  142407. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  142408. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  142409. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  142410. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  142411. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  142412. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  142413. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  142414. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  142415. 12,
  142416. };
  142417. static float _vq_quantthresh__44u5__p4_0[] = {
  142418. -1.5, -0.5, 0.5, 1.5,
  142419. };
  142420. static long _vq_quantmap__44u5__p4_0[] = {
  142421. 3, 1, 0, 2, 4,
  142422. };
  142423. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  142424. _vq_quantthresh__44u5__p4_0,
  142425. _vq_quantmap__44u5__p4_0,
  142426. 5,
  142427. 5
  142428. };
  142429. static static_codebook _44u5__p4_0 = {
  142430. 4, 625,
  142431. _vq_lengthlist__44u5__p4_0,
  142432. 1, -533725184, 1611661312, 3, 0,
  142433. _vq_quantlist__44u5__p4_0,
  142434. NULL,
  142435. &_vq_auxt__44u5__p4_0,
  142436. NULL,
  142437. 0
  142438. };
  142439. static long _vq_quantlist__44u5__p5_0[] = {
  142440. 4,
  142441. 3,
  142442. 5,
  142443. 2,
  142444. 6,
  142445. 1,
  142446. 7,
  142447. 0,
  142448. 8,
  142449. };
  142450. static long _vq_lengthlist__44u5__p5_0[] = {
  142451. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  142452. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  142453. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  142454. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  142455. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  142456. 14,
  142457. };
  142458. static float _vq_quantthresh__44u5__p5_0[] = {
  142459. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142460. };
  142461. static long _vq_quantmap__44u5__p5_0[] = {
  142462. 7, 5, 3, 1, 0, 2, 4, 6,
  142463. 8,
  142464. };
  142465. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  142466. _vq_quantthresh__44u5__p5_0,
  142467. _vq_quantmap__44u5__p5_0,
  142468. 9,
  142469. 9
  142470. };
  142471. static static_codebook _44u5__p5_0 = {
  142472. 2, 81,
  142473. _vq_lengthlist__44u5__p5_0,
  142474. 1, -531628032, 1611661312, 4, 0,
  142475. _vq_quantlist__44u5__p5_0,
  142476. NULL,
  142477. &_vq_auxt__44u5__p5_0,
  142478. NULL,
  142479. 0
  142480. };
  142481. static long _vq_quantlist__44u5__p6_0[] = {
  142482. 4,
  142483. 3,
  142484. 5,
  142485. 2,
  142486. 6,
  142487. 1,
  142488. 7,
  142489. 0,
  142490. 8,
  142491. };
  142492. static long _vq_lengthlist__44u5__p6_0[] = {
  142493. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  142494. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  142495. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  142496. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  142497. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  142498. 11,
  142499. };
  142500. static float _vq_quantthresh__44u5__p6_0[] = {
  142501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142502. };
  142503. static long _vq_quantmap__44u5__p6_0[] = {
  142504. 7, 5, 3, 1, 0, 2, 4, 6,
  142505. 8,
  142506. };
  142507. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  142508. _vq_quantthresh__44u5__p6_0,
  142509. _vq_quantmap__44u5__p6_0,
  142510. 9,
  142511. 9
  142512. };
  142513. static static_codebook _44u5__p6_0 = {
  142514. 2, 81,
  142515. _vq_lengthlist__44u5__p6_0,
  142516. 1, -531628032, 1611661312, 4, 0,
  142517. _vq_quantlist__44u5__p6_0,
  142518. NULL,
  142519. &_vq_auxt__44u5__p6_0,
  142520. NULL,
  142521. 0
  142522. };
  142523. static long _vq_quantlist__44u5__p7_0[] = {
  142524. 1,
  142525. 0,
  142526. 2,
  142527. };
  142528. static long _vq_lengthlist__44u5__p7_0[] = {
  142529. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  142530. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  142531. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  142532. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  142533. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  142534. 12,
  142535. };
  142536. static float _vq_quantthresh__44u5__p7_0[] = {
  142537. -5.5, 5.5,
  142538. };
  142539. static long _vq_quantmap__44u5__p7_0[] = {
  142540. 1, 0, 2,
  142541. };
  142542. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  142543. _vq_quantthresh__44u5__p7_0,
  142544. _vq_quantmap__44u5__p7_0,
  142545. 3,
  142546. 3
  142547. };
  142548. static static_codebook _44u5__p7_0 = {
  142549. 4, 81,
  142550. _vq_lengthlist__44u5__p7_0,
  142551. 1, -529137664, 1618345984, 2, 0,
  142552. _vq_quantlist__44u5__p7_0,
  142553. NULL,
  142554. &_vq_auxt__44u5__p7_0,
  142555. NULL,
  142556. 0
  142557. };
  142558. static long _vq_quantlist__44u5__p7_1[] = {
  142559. 5,
  142560. 4,
  142561. 6,
  142562. 3,
  142563. 7,
  142564. 2,
  142565. 8,
  142566. 1,
  142567. 9,
  142568. 0,
  142569. 10,
  142570. };
  142571. static long _vq_lengthlist__44u5__p7_1[] = {
  142572. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  142573. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  142574. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142575. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  142576. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  142577. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142578. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  142579. 9, 9, 9, 9, 9,10,10,10,10,
  142580. };
  142581. static float _vq_quantthresh__44u5__p7_1[] = {
  142582. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142583. 3.5, 4.5,
  142584. };
  142585. static long _vq_quantmap__44u5__p7_1[] = {
  142586. 9, 7, 5, 3, 1, 0, 2, 4,
  142587. 6, 8, 10,
  142588. };
  142589. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  142590. _vq_quantthresh__44u5__p7_1,
  142591. _vq_quantmap__44u5__p7_1,
  142592. 11,
  142593. 11
  142594. };
  142595. static static_codebook _44u5__p7_1 = {
  142596. 2, 121,
  142597. _vq_lengthlist__44u5__p7_1,
  142598. 1, -531365888, 1611661312, 4, 0,
  142599. _vq_quantlist__44u5__p7_1,
  142600. NULL,
  142601. &_vq_auxt__44u5__p7_1,
  142602. NULL,
  142603. 0
  142604. };
  142605. static long _vq_quantlist__44u5__p8_0[] = {
  142606. 5,
  142607. 4,
  142608. 6,
  142609. 3,
  142610. 7,
  142611. 2,
  142612. 8,
  142613. 1,
  142614. 9,
  142615. 0,
  142616. 10,
  142617. };
  142618. static long _vq_lengthlist__44u5__p8_0[] = {
  142619. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  142620. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  142621. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  142622. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  142623. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  142624. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  142625. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  142626. 12,13,13,14,14,14,14,15,15,
  142627. };
  142628. static float _vq_quantthresh__44u5__p8_0[] = {
  142629. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142630. 38.5, 49.5,
  142631. };
  142632. static long _vq_quantmap__44u5__p8_0[] = {
  142633. 9, 7, 5, 3, 1, 0, 2, 4,
  142634. 6, 8, 10,
  142635. };
  142636. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  142637. _vq_quantthresh__44u5__p8_0,
  142638. _vq_quantmap__44u5__p8_0,
  142639. 11,
  142640. 11
  142641. };
  142642. static static_codebook _44u5__p8_0 = {
  142643. 2, 121,
  142644. _vq_lengthlist__44u5__p8_0,
  142645. 1, -524582912, 1618345984, 4, 0,
  142646. _vq_quantlist__44u5__p8_0,
  142647. NULL,
  142648. &_vq_auxt__44u5__p8_0,
  142649. NULL,
  142650. 0
  142651. };
  142652. static long _vq_quantlist__44u5__p8_1[] = {
  142653. 5,
  142654. 4,
  142655. 6,
  142656. 3,
  142657. 7,
  142658. 2,
  142659. 8,
  142660. 1,
  142661. 9,
  142662. 0,
  142663. 10,
  142664. };
  142665. static long _vq_lengthlist__44u5__p8_1[] = {
  142666. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  142667. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  142668. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  142669. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  142670. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  142671. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  142672. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142673. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142674. };
  142675. static float _vq_quantthresh__44u5__p8_1[] = {
  142676. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142677. 3.5, 4.5,
  142678. };
  142679. static long _vq_quantmap__44u5__p8_1[] = {
  142680. 9, 7, 5, 3, 1, 0, 2, 4,
  142681. 6, 8, 10,
  142682. };
  142683. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  142684. _vq_quantthresh__44u5__p8_1,
  142685. _vq_quantmap__44u5__p8_1,
  142686. 11,
  142687. 11
  142688. };
  142689. static static_codebook _44u5__p8_1 = {
  142690. 2, 121,
  142691. _vq_lengthlist__44u5__p8_1,
  142692. 1, -531365888, 1611661312, 4, 0,
  142693. _vq_quantlist__44u5__p8_1,
  142694. NULL,
  142695. &_vq_auxt__44u5__p8_1,
  142696. NULL,
  142697. 0
  142698. };
  142699. static long _vq_quantlist__44u5__p9_0[] = {
  142700. 6,
  142701. 5,
  142702. 7,
  142703. 4,
  142704. 8,
  142705. 3,
  142706. 9,
  142707. 2,
  142708. 10,
  142709. 1,
  142710. 11,
  142711. 0,
  142712. 12,
  142713. };
  142714. static long _vq_lengthlist__44u5__p9_0[] = {
  142715. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  142716. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  142717. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  142718. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  142719. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142720. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142721. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142722. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142723. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  142724. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142725. 12,12,12,12,12,12,12,12,12,
  142726. };
  142727. static float _vq_quantthresh__44u5__p9_0[] = {
  142728. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142729. 637.5, 892.5, 1147.5, 1402.5,
  142730. };
  142731. static long _vq_quantmap__44u5__p9_0[] = {
  142732. 11, 9, 7, 5, 3, 1, 0, 2,
  142733. 4, 6, 8, 10, 12,
  142734. };
  142735. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  142736. _vq_quantthresh__44u5__p9_0,
  142737. _vq_quantmap__44u5__p9_0,
  142738. 13,
  142739. 13
  142740. };
  142741. static static_codebook _44u5__p9_0 = {
  142742. 2, 169,
  142743. _vq_lengthlist__44u5__p9_0,
  142744. 1, -514332672, 1627381760, 4, 0,
  142745. _vq_quantlist__44u5__p9_0,
  142746. NULL,
  142747. &_vq_auxt__44u5__p9_0,
  142748. NULL,
  142749. 0
  142750. };
  142751. static long _vq_quantlist__44u5__p9_1[] = {
  142752. 7,
  142753. 6,
  142754. 8,
  142755. 5,
  142756. 9,
  142757. 4,
  142758. 10,
  142759. 3,
  142760. 11,
  142761. 2,
  142762. 12,
  142763. 1,
  142764. 13,
  142765. 0,
  142766. 14,
  142767. };
  142768. static long _vq_lengthlist__44u5__p9_1[] = {
  142769. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  142770. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  142771. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  142772. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  142773. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  142774. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  142775. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  142776. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  142777. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  142778. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  142779. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  142780. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  142781. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  142782. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  142783. 14,
  142784. };
  142785. static float _vq_quantthresh__44u5__p9_1[] = {
  142786. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142787. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142788. };
  142789. static long _vq_quantmap__44u5__p9_1[] = {
  142790. 13, 11, 9, 7, 5, 3, 1, 0,
  142791. 2, 4, 6, 8, 10, 12, 14,
  142792. };
  142793. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  142794. _vq_quantthresh__44u5__p9_1,
  142795. _vq_quantmap__44u5__p9_1,
  142796. 15,
  142797. 15
  142798. };
  142799. static static_codebook _44u5__p9_1 = {
  142800. 2, 225,
  142801. _vq_lengthlist__44u5__p9_1,
  142802. 1, -522338304, 1620115456, 4, 0,
  142803. _vq_quantlist__44u5__p9_1,
  142804. NULL,
  142805. &_vq_auxt__44u5__p9_1,
  142806. NULL,
  142807. 0
  142808. };
  142809. static long _vq_quantlist__44u5__p9_2[] = {
  142810. 8,
  142811. 7,
  142812. 9,
  142813. 6,
  142814. 10,
  142815. 5,
  142816. 11,
  142817. 4,
  142818. 12,
  142819. 3,
  142820. 13,
  142821. 2,
  142822. 14,
  142823. 1,
  142824. 15,
  142825. 0,
  142826. 16,
  142827. };
  142828. static long _vq_lengthlist__44u5__p9_2[] = {
  142829. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142830. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142831. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142832. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142833. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142834. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142835. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142836. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142837. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142838. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  142839. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  142840. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  142841. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142842. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142843. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142844. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142845. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  142846. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  142847. 10,
  142848. };
  142849. static float _vq_quantthresh__44u5__p9_2[] = {
  142850. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142851. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142852. };
  142853. static long _vq_quantmap__44u5__p9_2[] = {
  142854. 15, 13, 11, 9, 7, 5, 3, 1,
  142855. 0, 2, 4, 6, 8, 10, 12, 14,
  142856. 16,
  142857. };
  142858. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  142859. _vq_quantthresh__44u5__p9_2,
  142860. _vq_quantmap__44u5__p9_2,
  142861. 17,
  142862. 17
  142863. };
  142864. static static_codebook _44u5__p9_2 = {
  142865. 2, 289,
  142866. _vq_lengthlist__44u5__p9_2,
  142867. 1, -529530880, 1611661312, 5, 0,
  142868. _vq_quantlist__44u5__p9_2,
  142869. NULL,
  142870. &_vq_auxt__44u5__p9_2,
  142871. NULL,
  142872. 0
  142873. };
  142874. static long _huff_lengthlist__44u5__short[] = {
  142875. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  142876. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  142877. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  142878. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  142879. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  142880. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  142881. 6, 8,15,17,
  142882. };
  142883. static static_codebook _huff_book__44u5__short = {
  142884. 2, 100,
  142885. _huff_lengthlist__44u5__short,
  142886. 0, 0, 0, 0, 0,
  142887. NULL,
  142888. NULL,
  142889. NULL,
  142890. NULL,
  142891. 0
  142892. };
  142893. static long _huff_lengthlist__44u6__long[] = {
  142894. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  142895. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  142896. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  142897. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  142898. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  142899. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  142900. 13, 8, 7, 7,
  142901. };
  142902. static static_codebook _huff_book__44u6__long = {
  142903. 2, 100,
  142904. _huff_lengthlist__44u6__long,
  142905. 0, 0, 0, 0, 0,
  142906. NULL,
  142907. NULL,
  142908. NULL,
  142909. NULL,
  142910. 0
  142911. };
  142912. static long _vq_quantlist__44u6__p1_0[] = {
  142913. 1,
  142914. 0,
  142915. 2,
  142916. };
  142917. static long _vq_lengthlist__44u6__p1_0[] = {
  142918. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142919. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142920. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142921. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  142922. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142923. 12,
  142924. };
  142925. static float _vq_quantthresh__44u6__p1_0[] = {
  142926. -0.5, 0.5,
  142927. };
  142928. static long _vq_quantmap__44u6__p1_0[] = {
  142929. 1, 0, 2,
  142930. };
  142931. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  142932. _vq_quantthresh__44u6__p1_0,
  142933. _vq_quantmap__44u6__p1_0,
  142934. 3,
  142935. 3
  142936. };
  142937. static static_codebook _44u6__p1_0 = {
  142938. 4, 81,
  142939. _vq_lengthlist__44u6__p1_0,
  142940. 1, -535822336, 1611661312, 2, 0,
  142941. _vq_quantlist__44u6__p1_0,
  142942. NULL,
  142943. &_vq_auxt__44u6__p1_0,
  142944. NULL,
  142945. 0
  142946. };
  142947. static long _vq_quantlist__44u6__p2_0[] = {
  142948. 1,
  142949. 0,
  142950. 2,
  142951. };
  142952. static long _vq_lengthlist__44u6__p2_0[] = {
  142953. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142954. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142955. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  142956. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142957. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142958. 9,
  142959. };
  142960. static float _vq_quantthresh__44u6__p2_0[] = {
  142961. -0.5, 0.5,
  142962. };
  142963. static long _vq_quantmap__44u6__p2_0[] = {
  142964. 1, 0, 2,
  142965. };
  142966. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  142967. _vq_quantthresh__44u6__p2_0,
  142968. _vq_quantmap__44u6__p2_0,
  142969. 3,
  142970. 3
  142971. };
  142972. static static_codebook _44u6__p2_0 = {
  142973. 4, 81,
  142974. _vq_lengthlist__44u6__p2_0,
  142975. 1, -535822336, 1611661312, 2, 0,
  142976. _vq_quantlist__44u6__p2_0,
  142977. NULL,
  142978. &_vq_auxt__44u6__p2_0,
  142979. NULL,
  142980. 0
  142981. };
  142982. static long _vq_quantlist__44u6__p3_0[] = {
  142983. 2,
  142984. 1,
  142985. 3,
  142986. 0,
  142987. 4,
  142988. };
  142989. static long _vq_lengthlist__44u6__p3_0[] = {
  142990. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  142991. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  142992. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  142993. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  142994. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  142995. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  142996. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  142997. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  142998. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  142999. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143000. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  143001. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143002. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  143003. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  143004. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  143005. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  143006. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143007. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143008. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  143009. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  143010. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  143011. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  143012. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  143013. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  143014. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  143015. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  143016. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  143017. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  143018. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  143019. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  143020. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  143021. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  143022. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  143023. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  143024. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  143025. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  143026. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  143027. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  143028. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  143029. 19,
  143030. };
  143031. static float _vq_quantthresh__44u6__p3_0[] = {
  143032. -1.5, -0.5, 0.5, 1.5,
  143033. };
  143034. static long _vq_quantmap__44u6__p3_0[] = {
  143035. 3, 1, 0, 2, 4,
  143036. };
  143037. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  143038. _vq_quantthresh__44u6__p3_0,
  143039. _vq_quantmap__44u6__p3_0,
  143040. 5,
  143041. 5
  143042. };
  143043. static static_codebook _44u6__p3_0 = {
  143044. 4, 625,
  143045. _vq_lengthlist__44u6__p3_0,
  143046. 1, -533725184, 1611661312, 3, 0,
  143047. _vq_quantlist__44u6__p3_0,
  143048. NULL,
  143049. &_vq_auxt__44u6__p3_0,
  143050. NULL,
  143051. 0
  143052. };
  143053. static long _vq_quantlist__44u6__p4_0[] = {
  143054. 2,
  143055. 1,
  143056. 3,
  143057. 0,
  143058. 4,
  143059. };
  143060. static long _vq_lengthlist__44u6__p4_0[] = {
  143061. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143062. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143063. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  143064. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  143065. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143066. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  143067. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143068. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  143069. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143070. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143071. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  143072. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143073. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143074. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  143075. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  143076. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143077. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  143078. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143079. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143080. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  143081. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143082. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143083. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  143084. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143085. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  143086. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  143087. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143088. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  143089. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  143090. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  143091. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  143092. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143093. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  143094. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143095. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  143096. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143097. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  143098. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  143099. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  143100. 13,
  143101. };
  143102. static float _vq_quantthresh__44u6__p4_0[] = {
  143103. -1.5, -0.5, 0.5, 1.5,
  143104. };
  143105. static long _vq_quantmap__44u6__p4_0[] = {
  143106. 3, 1, 0, 2, 4,
  143107. };
  143108. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  143109. _vq_quantthresh__44u6__p4_0,
  143110. _vq_quantmap__44u6__p4_0,
  143111. 5,
  143112. 5
  143113. };
  143114. static static_codebook _44u6__p4_0 = {
  143115. 4, 625,
  143116. _vq_lengthlist__44u6__p4_0,
  143117. 1, -533725184, 1611661312, 3, 0,
  143118. _vq_quantlist__44u6__p4_0,
  143119. NULL,
  143120. &_vq_auxt__44u6__p4_0,
  143121. NULL,
  143122. 0
  143123. };
  143124. static long _vq_quantlist__44u6__p5_0[] = {
  143125. 4,
  143126. 3,
  143127. 5,
  143128. 2,
  143129. 6,
  143130. 1,
  143131. 7,
  143132. 0,
  143133. 8,
  143134. };
  143135. static long _vq_lengthlist__44u6__p5_0[] = {
  143136. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143137. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  143138. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143139. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  143140. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  143141. 14,
  143142. };
  143143. static float _vq_quantthresh__44u6__p5_0[] = {
  143144. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143145. };
  143146. static long _vq_quantmap__44u6__p5_0[] = {
  143147. 7, 5, 3, 1, 0, 2, 4, 6,
  143148. 8,
  143149. };
  143150. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  143151. _vq_quantthresh__44u6__p5_0,
  143152. _vq_quantmap__44u6__p5_0,
  143153. 9,
  143154. 9
  143155. };
  143156. static static_codebook _44u6__p5_0 = {
  143157. 2, 81,
  143158. _vq_lengthlist__44u6__p5_0,
  143159. 1, -531628032, 1611661312, 4, 0,
  143160. _vq_quantlist__44u6__p5_0,
  143161. NULL,
  143162. &_vq_auxt__44u6__p5_0,
  143163. NULL,
  143164. 0
  143165. };
  143166. static long _vq_quantlist__44u6__p6_0[] = {
  143167. 4,
  143168. 3,
  143169. 5,
  143170. 2,
  143171. 6,
  143172. 1,
  143173. 7,
  143174. 0,
  143175. 8,
  143176. };
  143177. static long _vq_lengthlist__44u6__p6_0[] = {
  143178. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143179. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  143180. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143181. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  143182. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  143183. 12,
  143184. };
  143185. static float _vq_quantthresh__44u6__p6_0[] = {
  143186. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143187. };
  143188. static long _vq_quantmap__44u6__p6_0[] = {
  143189. 7, 5, 3, 1, 0, 2, 4, 6,
  143190. 8,
  143191. };
  143192. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  143193. _vq_quantthresh__44u6__p6_0,
  143194. _vq_quantmap__44u6__p6_0,
  143195. 9,
  143196. 9
  143197. };
  143198. static static_codebook _44u6__p6_0 = {
  143199. 2, 81,
  143200. _vq_lengthlist__44u6__p6_0,
  143201. 1, -531628032, 1611661312, 4, 0,
  143202. _vq_quantlist__44u6__p6_0,
  143203. NULL,
  143204. &_vq_auxt__44u6__p6_0,
  143205. NULL,
  143206. 0
  143207. };
  143208. static long _vq_quantlist__44u6__p7_0[] = {
  143209. 1,
  143210. 0,
  143211. 2,
  143212. };
  143213. static long _vq_lengthlist__44u6__p7_0[] = {
  143214. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  143215. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  143216. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  143217. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  143218. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  143219. 10,
  143220. };
  143221. static float _vq_quantthresh__44u6__p7_0[] = {
  143222. -5.5, 5.5,
  143223. };
  143224. static long _vq_quantmap__44u6__p7_0[] = {
  143225. 1, 0, 2,
  143226. };
  143227. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  143228. _vq_quantthresh__44u6__p7_0,
  143229. _vq_quantmap__44u6__p7_0,
  143230. 3,
  143231. 3
  143232. };
  143233. static static_codebook _44u6__p7_0 = {
  143234. 4, 81,
  143235. _vq_lengthlist__44u6__p7_0,
  143236. 1, -529137664, 1618345984, 2, 0,
  143237. _vq_quantlist__44u6__p7_0,
  143238. NULL,
  143239. &_vq_auxt__44u6__p7_0,
  143240. NULL,
  143241. 0
  143242. };
  143243. static long _vq_quantlist__44u6__p7_1[] = {
  143244. 5,
  143245. 4,
  143246. 6,
  143247. 3,
  143248. 7,
  143249. 2,
  143250. 8,
  143251. 1,
  143252. 9,
  143253. 0,
  143254. 10,
  143255. };
  143256. static long _vq_lengthlist__44u6__p7_1[] = {
  143257. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  143258. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  143259. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143260. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  143261. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143262. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143263. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143264. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143265. };
  143266. static float _vq_quantthresh__44u6__p7_1[] = {
  143267. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143268. 3.5, 4.5,
  143269. };
  143270. static long _vq_quantmap__44u6__p7_1[] = {
  143271. 9, 7, 5, 3, 1, 0, 2, 4,
  143272. 6, 8, 10,
  143273. };
  143274. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  143275. _vq_quantthresh__44u6__p7_1,
  143276. _vq_quantmap__44u6__p7_1,
  143277. 11,
  143278. 11
  143279. };
  143280. static static_codebook _44u6__p7_1 = {
  143281. 2, 121,
  143282. _vq_lengthlist__44u6__p7_1,
  143283. 1, -531365888, 1611661312, 4, 0,
  143284. _vq_quantlist__44u6__p7_1,
  143285. NULL,
  143286. &_vq_auxt__44u6__p7_1,
  143287. NULL,
  143288. 0
  143289. };
  143290. static long _vq_quantlist__44u6__p8_0[] = {
  143291. 5,
  143292. 4,
  143293. 6,
  143294. 3,
  143295. 7,
  143296. 2,
  143297. 8,
  143298. 1,
  143299. 9,
  143300. 0,
  143301. 10,
  143302. };
  143303. static long _vq_lengthlist__44u6__p8_0[] = {
  143304. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  143305. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  143306. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  143307. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  143308. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  143309. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  143310. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  143311. 12,13,13,14,14,14,15,15,15,
  143312. };
  143313. static float _vq_quantthresh__44u6__p8_0[] = {
  143314. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143315. 38.5, 49.5,
  143316. };
  143317. static long _vq_quantmap__44u6__p8_0[] = {
  143318. 9, 7, 5, 3, 1, 0, 2, 4,
  143319. 6, 8, 10,
  143320. };
  143321. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  143322. _vq_quantthresh__44u6__p8_0,
  143323. _vq_quantmap__44u6__p8_0,
  143324. 11,
  143325. 11
  143326. };
  143327. static static_codebook _44u6__p8_0 = {
  143328. 2, 121,
  143329. _vq_lengthlist__44u6__p8_0,
  143330. 1, -524582912, 1618345984, 4, 0,
  143331. _vq_quantlist__44u6__p8_0,
  143332. NULL,
  143333. &_vq_auxt__44u6__p8_0,
  143334. NULL,
  143335. 0
  143336. };
  143337. static long _vq_quantlist__44u6__p8_1[] = {
  143338. 5,
  143339. 4,
  143340. 6,
  143341. 3,
  143342. 7,
  143343. 2,
  143344. 8,
  143345. 1,
  143346. 9,
  143347. 0,
  143348. 10,
  143349. };
  143350. static long _vq_lengthlist__44u6__p8_1[] = {
  143351. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  143352. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  143353. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  143354. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143355. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143356. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  143357. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143358. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143359. };
  143360. static float _vq_quantthresh__44u6__p8_1[] = {
  143361. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143362. 3.5, 4.5,
  143363. };
  143364. static long _vq_quantmap__44u6__p8_1[] = {
  143365. 9, 7, 5, 3, 1, 0, 2, 4,
  143366. 6, 8, 10,
  143367. };
  143368. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  143369. _vq_quantthresh__44u6__p8_1,
  143370. _vq_quantmap__44u6__p8_1,
  143371. 11,
  143372. 11
  143373. };
  143374. static static_codebook _44u6__p8_1 = {
  143375. 2, 121,
  143376. _vq_lengthlist__44u6__p8_1,
  143377. 1, -531365888, 1611661312, 4, 0,
  143378. _vq_quantlist__44u6__p8_1,
  143379. NULL,
  143380. &_vq_auxt__44u6__p8_1,
  143381. NULL,
  143382. 0
  143383. };
  143384. static long _vq_quantlist__44u6__p9_0[] = {
  143385. 7,
  143386. 6,
  143387. 8,
  143388. 5,
  143389. 9,
  143390. 4,
  143391. 10,
  143392. 3,
  143393. 11,
  143394. 2,
  143395. 12,
  143396. 1,
  143397. 13,
  143398. 0,
  143399. 14,
  143400. };
  143401. static long _vq_lengthlist__44u6__p9_0[] = {
  143402. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  143403. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  143404. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  143405. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  143406. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143407. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143408. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143409. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143410. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143411. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143412. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143413. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143414. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143415. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143416. 14,
  143417. };
  143418. static float _vq_quantthresh__44u6__p9_0[] = {
  143419. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143420. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143421. };
  143422. static long _vq_quantmap__44u6__p9_0[] = {
  143423. 13, 11, 9, 7, 5, 3, 1, 0,
  143424. 2, 4, 6, 8, 10, 12, 14,
  143425. };
  143426. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  143427. _vq_quantthresh__44u6__p9_0,
  143428. _vq_quantmap__44u6__p9_0,
  143429. 15,
  143430. 15
  143431. };
  143432. static static_codebook _44u6__p9_0 = {
  143433. 2, 225,
  143434. _vq_lengthlist__44u6__p9_0,
  143435. 1, -514071552, 1627381760, 4, 0,
  143436. _vq_quantlist__44u6__p9_0,
  143437. NULL,
  143438. &_vq_auxt__44u6__p9_0,
  143439. NULL,
  143440. 0
  143441. };
  143442. static long _vq_quantlist__44u6__p9_1[] = {
  143443. 7,
  143444. 6,
  143445. 8,
  143446. 5,
  143447. 9,
  143448. 4,
  143449. 10,
  143450. 3,
  143451. 11,
  143452. 2,
  143453. 12,
  143454. 1,
  143455. 13,
  143456. 0,
  143457. 14,
  143458. };
  143459. static long _vq_lengthlist__44u6__p9_1[] = {
  143460. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  143461. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  143462. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  143463. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  143464. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  143465. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  143466. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  143467. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  143468. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  143469. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  143470. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  143471. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  143472. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  143473. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  143474. 13,
  143475. };
  143476. static float _vq_quantthresh__44u6__p9_1[] = {
  143477. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143478. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143479. };
  143480. static long _vq_quantmap__44u6__p9_1[] = {
  143481. 13, 11, 9, 7, 5, 3, 1, 0,
  143482. 2, 4, 6, 8, 10, 12, 14,
  143483. };
  143484. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  143485. _vq_quantthresh__44u6__p9_1,
  143486. _vq_quantmap__44u6__p9_1,
  143487. 15,
  143488. 15
  143489. };
  143490. static static_codebook _44u6__p9_1 = {
  143491. 2, 225,
  143492. _vq_lengthlist__44u6__p9_1,
  143493. 1, -522338304, 1620115456, 4, 0,
  143494. _vq_quantlist__44u6__p9_1,
  143495. NULL,
  143496. &_vq_auxt__44u6__p9_1,
  143497. NULL,
  143498. 0
  143499. };
  143500. static long _vq_quantlist__44u6__p9_2[] = {
  143501. 8,
  143502. 7,
  143503. 9,
  143504. 6,
  143505. 10,
  143506. 5,
  143507. 11,
  143508. 4,
  143509. 12,
  143510. 3,
  143511. 13,
  143512. 2,
  143513. 14,
  143514. 1,
  143515. 15,
  143516. 0,
  143517. 16,
  143518. };
  143519. static long _vq_lengthlist__44u6__p9_2[] = {
  143520. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  143521. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  143522. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  143523. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143524. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143525. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143526. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143527. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143528. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  143530. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  143531. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143532. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  143533. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  143534. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  143535. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  143536. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  143537. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  143538. 10,
  143539. };
  143540. static float _vq_quantthresh__44u6__p9_2[] = {
  143541. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143542. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143543. };
  143544. static long _vq_quantmap__44u6__p9_2[] = {
  143545. 15, 13, 11, 9, 7, 5, 3, 1,
  143546. 0, 2, 4, 6, 8, 10, 12, 14,
  143547. 16,
  143548. };
  143549. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  143550. _vq_quantthresh__44u6__p9_2,
  143551. _vq_quantmap__44u6__p9_2,
  143552. 17,
  143553. 17
  143554. };
  143555. static static_codebook _44u6__p9_2 = {
  143556. 2, 289,
  143557. _vq_lengthlist__44u6__p9_2,
  143558. 1, -529530880, 1611661312, 5, 0,
  143559. _vq_quantlist__44u6__p9_2,
  143560. NULL,
  143561. &_vq_auxt__44u6__p9_2,
  143562. NULL,
  143563. 0
  143564. };
  143565. static long _huff_lengthlist__44u6__short[] = {
  143566. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  143567. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  143568. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  143569. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  143570. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  143571. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  143572. 7, 6, 9,16,
  143573. };
  143574. static static_codebook _huff_book__44u6__short = {
  143575. 2, 100,
  143576. _huff_lengthlist__44u6__short,
  143577. 0, 0, 0, 0, 0,
  143578. NULL,
  143579. NULL,
  143580. NULL,
  143581. NULL,
  143582. 0
  143583. };
  143584. static long _huff_lengthlist__44u7__long[] = {
  143585. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  143586. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  143587. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  143588. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  143589. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  143590. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  143591. 12, 8, 6, 7,
  143592. };
  143593. static static_codebook _huff_book__44u7__long = {
  143594. 2, 100,
  143595. _huff_lengthlist__44u7__long,
  143596. 0, 0, 0, 0, 0,
  143597. NULL,
  143598. NULL,
  143599. NULL,
  143600. NULL,
  143601. 0
  143602. };
  143603. static long _vq_quantlist__44u7__p1_0[] = {
  143604. 1,
  143605. 0,
  143606. 2,
  143607. };
  143608. static long _vq_lengthlist__44u7__p1_0[] = {
  143609. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143610. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  143611. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143612. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  143613. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  143614. 12,
  143615. };
  143616. static float _vq_quantthresh__44u7__p1_0[] = {
  143617. -0.5, 0.5,
  143618. };
  143619. static long _vq_quantmap__44u7__p1_0[] = {
  143620. 1, 0, 2,
  143621. };
  143622. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  143623. _vq_quantthresh__44u7__p1_0,
  143624. _vq_quantmap__44u7__p1_0,
  143625. 3,
  143626. 3
  143627. };
  143628. static static_codebook _44u7__p1_0 = {
  143629. 4, 81,
  143630. _vq_lengthlist__44u7__p1_0,
  143631. 1, -535822336, 1611661312, 2, 0,
  143632. _vq_quantlist__44u7__p1_0,
  143633. NULL,
  143634. &_vq_auxt__44u7__p1_0,
  143635. NULL,
  143636. 0
  143637. };
  143638. static long _vq_quantlist__44u7__p2_0[] = {
  143639. 1,
  143640. 0,
  143641. 2,
  143642. };
  143643. static long _vq_lengthlist__44u7__p2_0[] = {
  143644. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143645. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143646. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  143647. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143648. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143649. 9,
  143650. };
  143651. static float _vq_quantthresh__44u7__p2_0[] = {
  143652. -0.5, 0.5,
  143653. };
  143654. static long _vq_quantmap__44u7__p2_0[] = {
  143655. 1, 0, 2,
  143656. };
  143657. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  143658. _vq_quantthresh__44u7__p2_0,
  143659. _vq_quantmap__44u7__p2_0,
  143660. 3,
  143661. 3
  143662. };
  143663. static static_codebook _44u7__p2_0 = {
  143664. 4, 81,
  143665. _vq_lengthlist__44u7__p2_0,
  143666. 1, -535822336, 1611661312, 2, 0,
  143667. _vq_quantlist__44u7__p2_0,
  143668. NULL,
  143669. &_vq_auxt__44u7__p2_0,
  143670. NULL,
  143671. 0
  143672. };
  143673. static long _vq_quantlist__44u7__p3_0[] = {
  143674. 2,
  143675. 1,
  143676. 3,
  143677. 0,
  143678. 4,
  143679. };
  143680. static long _vq_lengthlist__44u7__p3_0[] = {
  143681. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143682. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143683. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143684. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  143685. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143686. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  143687. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143688. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  143689. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  143690. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143691. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  143692. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143693. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  143694. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  143695. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  143696. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  143697. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  143698. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143699. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  143700. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  143701. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  143702. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  143703. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  143704. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  143705. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  143706. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  143707. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  143708. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  143709. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  143710. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  143711. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  143712. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  143713. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  143714. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  143715. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  143716. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  143717. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  143718. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  143719. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  143720. 0,
  143721. };
  143722. static float _vq_quantthresh__44u7__p3_0[] = {
  143723. -1.5, -0.5, 0.5, 1.5,
  143724. };
  143725. static long _vq_quantmap__44u7__p3_0[] = {
  143726. 3, 1, 0, 2, 4,
  143727. };
  143728. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  143729. _vq_quantthresh__44u7__p3_0,
  143730. _vq_quantmap__44u7__p3_0,
  143731. 5,
  143732. 5
  143733. };
  143734. static static_codebook _44u7__p3_0 = {
  143735. 4, 625,
  143736. _vq_lengthlist__44u7__p3_0,
  143737. 1, -533725184, 1611661312, 3, 0,
  143738. _vq_quantlist__44u7__p3_0,
  143739. NULL,
  143740. &_vq_auxt__44u7__p3_0,
  143741. NULL,
  143742. 0
  143743. };
  143744. static long _vq_quantlist__44u7__p4_0[] = {
  143745. 2,
  143746. 1,
  143747. 3,
  143748. 0,
  143749. 4,
  143750. };
  143751. static long _vq_lengthlist__44u7__p4_0[] = {
  143752. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143753. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  143754. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  143755. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143756. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143757. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143758. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  143759. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  143760. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143761. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143762. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  143763. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143764. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143765. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  143766. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  143767. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143768. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  143769. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143770. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  143771. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  143772. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143773. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143774. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  143775. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143776. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  143777. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143778. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143779. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  143780. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  143781. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  143782. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  143783. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143784. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  143785. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143786. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  143787. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143788. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  143789. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  143790. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  143791. 14,
  143792. };
  143793. static float _vq_quantthresh__44u7__p4_0[] = {
  143794. -1.5, -0.5, 0.5, 1.5,
  143795. };
  143796. static long _vq_quantmap__44u7__p4_0[] = {
  143797. 3, 1, 0, 2, 4,
  143798. };
  143799. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  143800. _vq_quantthresh__44u7__p4_0,
  143801. _vq_quantmap__44u7__p4_0,
  143802. 5,
  143803. 5
  143804. };
  143805. static static_codebook _44u7__p4_0 = {
  143806. 4, 625,
  143807. _vq_lengthlist__44u7__p4_0,
  143808. 1, -533725184, 1611661312, 3, 0,
  143809. _vq_quantlist__44u7__p4_0,
  143810. NULL,
  143811. &_vq_auxt__44u7__p4_0,
  143812. NULL,
  143813. 0
  143814. };
  143815. static long _vq_quantlist__44u7__p5_0[] = {
  143816. 4,
  143817. 3,
  143818. 5,
  143819. 2,
  143820. 6,
  143821. 1,
  143822. 7,
  143823. 0,
  143824. 8,
  143825. };
  143826. static long _vq_lengthlist__44u7__p5_0[] = {
  143827. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143828. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  143829. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  143830. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  143831. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  143832. 14,
  143833. };
  143834. static float _vq_quantthresh__44u7__p5_0[] = {
  143835. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143836. };
  143837. static long _vq_quantmap__44u7__p5_0[] = {
  143838. 7, 5, 3, 1, 0, 2, 4, 6,
  143839. 8,
  143840. };
  143841. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  143842. _vq_quantthresh__44u7__p5_0,
  143843. _vq_quantmap__44u7__p5_0,
  143844. 9,
  143845. 9
  143846. };
  143847. static static_codebook _44u7__p5_0 = {
  143848. 2, 81,
  143849. _vq_lengthlist__44u7__p5_0,
  143850. 1, -531628032, 1611661312, 4, 0,
  143851. _vq_quantlist__44u7__p5_0,
  143852. NULL,
  143853. &_vq_auxt__44u7__p5_0,
  143854. NULL,
  143855. 0
  143856. };
  143857. static long _vq_quantlist__44u7__p6_0[] = {
  143858. 4,
  143859. 3,
  143860. 5,
  143861. 2,
  143862. 6,
  143863. 1,
  143864. 7,
  143865. 0,
  143866. 8,
  143867. };
  143868. static long _vq_lengthlist__44u7__p6_0[] = {
  143869. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  143870. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  143871. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143872. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  143873. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  143874. 12,
  143875. };
  143876. static float _vq_quantthresh__44u7__p6_0[] = {
  143877. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143878. };
  143879. static long _vq_quantmap__44u7__p6_0[] = {
  143880. 7, 5, 3, 1, 0, 2, 4, 6,
  143881. 8,
  143882. };
  143883. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  143884. _vq_quantthresh__44u7__p6_0,
  143885. _vq_quantmap__44u7__p6_0,
  143886. 9,
  143887. 9
  143888. };
  143889. static static_codebook _44u7__p6_0 = {
  143890. 2, 81,
  143891. _vq_lengthlist__44u7__p6_0,
  143892. 1, -531628032, 1611661312, 4, 0,
  143893. _vq_quantlist__44u7__p6_0,
  143894. NULL,
  143895. &_vq_auxt__44u7__p6_0,
  143896. NULL,
  143897. 0
  143898. };
  143899. static long _vq_quantlist__44u7__p7_0[] = {
  143900. 1,
  143901. 0,
  143902. 2,
  143903. };
  143904. static long _vq_lengthlist__44u7__p7_0[] = {
  143905. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  143906. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  143907. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  143908. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  143909. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  143910. 10,
  143911. };
  143912. static float _vq_quantthresh__44u7__p7_0[] = {
  143913. -5.5, 5.5,
  143914. };
  143915. static long _vq_quantmap__44u7__p7_0[] = {
  143916. 1, 0, 2,
  143917. };
  143918. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  143919. _vq_quantthresh__44u7__p7_0,
  143920. _vq_quantmap__44u7__p7_0,
  143921. 3,
  143922. 3
  143923. };
  143924. static static_codebook _44u7__p7_0 = {
  143925. 4, 81,
  143926. _vq_lengthlist__44u7__p7_0,
  143927. 1, -529137664, 1618345984, 2, 0,
  143928. _vq_quantlist__44u7__p7_0,
  143929. NULL,
  143930. &_vq_auxt__44u7__p7_0,
  143931. NULL,
  143932. 0
  143933. };
  143934. static long _vq_quantlist__44u7__p7_1[] = {
  143935. 5,
  143936. 4,
  143937. 6,
  143938. 3,
  143939. 7,
  143940. 2,
  143941. 8,
  143942. 1,
  143943. 9,
  143944. 0,
  143945. 10,
  143946. };
  143947. static long _vq_lengthlist__44u7__p7_1[] = {
  143948. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  143949. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  143950. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  143951. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  143952. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  143953. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143954. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  143955. 8, 9, 9, 9, 9, 9,10,10,10,
  143956. };
  143957. static float _vq_quantthresh__44u7__p7_1[] = {
  143958. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143959. 3.5, 4.5,
  143960. };
  143961. static long _vq_quantmap__44u7__p7_1[] = {
  143962. 9, 7, 5, 3, 1, 0, 2, 4,
  143963. 6, 8, 10,
  143964. };
  143965. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  143966. _vq_quantthresh__44u7__p7_1,
  143967. _vq_quantmap__44u7__p7_1,
  143968. 11,
  143969. 11
  143970. };
  143971. static static_codebook _44u7__p7_1 = {
  143972. 2, 121,
  143973. _vq_lengthlist__44u7__p7_1,
  143974. 1, -531365888, 1611661312, 4, 0,
  143975. _vq_quantlist__44u7__p7_1,
  143976. NULL,
  143977. &_vq_auxt__44u7__p7_1,
  143978. NULL,
  143979. 0
  143980. };
  143981. static long _vq_quantlist__44u7__p8_0[] = {
  143982. 5,
  143983. 4,
  143984. 6,
  143985. 3,
  143986. 7,
  143987. 2,
  143988. 8,
  143989. 1,
  143990. 9,
  143991. 0,
  143992. 10,
  143993. };
  143994. static long _vq_lengthlist__44u7__p8_0[] = {
  143995. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  143996. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  143997. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  143998. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  143999. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  144000. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  144001. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  144002. 12,13,13,14,14,15,15,15,16,
  144003. };
  144004. static float _vq_quantthresh__44u7__p8_0[] = {
  144005. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144006. 38.5, 49.5,
  144007. };
  144008. static long _vq_quantmap__44u7__p8_0[] = {
  144009. 9, 7, 5, 3, 1, 0, 2, 4,
  144010. 6, 8, 10,
  144011. };
  144012. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  144013. _vq_quantthresh__44u7__p8_0,
  144014. _vq_quantmap__44u7__p8_0,
  144015. 11,
  144016. 11
  144017. };
  144018. static static_codebook _44u7__p8_0 = {
  144019. 2, 121,
  144020. _vq_lengthlist__44u7__p8_0,
  144021. 1, -524582912, 1618345984, 4, 0,
  144022. _vq_quantlist__44u7__p8_0,
  144023. NULL,
  144024. &_vq_auxt__44u7__p8_0,
  144025. NULL,
  144026. 0
  144027. };
  144028. static long _vq_quantlist__44u7__p8_1[] = {
  144029. 5,
  144030. 4,
  144031. 6,
  144032. 3,
  144033. 7,
  144034. 2,
  144035. 8,
  144036. 1,
  144037. 9,
  144038. 0,
  144039. 10,
  144040. };
  144041. static long _vq_lengthlist__44u7__p8_1[] = {
  144042. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144043. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  144044. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144045. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  144046. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  144047. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144048. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144049. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144050. };
  144051. static float _vq_quantthresh__44u7__p8_1[] = {
  144052. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144053. 3.5, 4.5,
  144054. };
  144055. static long _vq_quantmap__44u7__p8_1[] = {
  144056. 9, 7, 5, 3, 1, 0, 2, 4,
  144057. 6, 8, 10,
  144058. };
  144059. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  144060. _vq_quantthresh__44u7__p8_1,
  144061. _vq_quantmap__44u7__p8_1,
  144062. 11,
  144063. 11
  144064. };
  144065. static static_codebook _44u7__p8_1 = {
  144066. 2, 121,
  144067. _vq_lengthlist__44u7__p8_1,
  144068. 1, -531365888, 1611661312, 4, 0,
  144069. _vq_quantlist__44u7__p8_1,
  144070. NULL,
  144071. &_vq_auxt__44u7__p8_1,
  144072. NULL,
  144073. 0
  144074. };
  144075. static long _vq_quantlist__44u7__p9_0[] = {
  144076. 5,
  144077. 4,
  144078. 6,
  144079. 3,
  144080. 7,
  144081. 2,
  144082. 8,
  144083. 1,
  144084. 9,
  144085. 0,
  144086. 10,
  144087. };
  144088. static long _vq_lengthlist__44u7__p9_0[] = {
  144089. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  144090. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  144091. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144095. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144096. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144097. };
  144098. static float _vq_quantthresh__44u7__p9_0[] = {
  144099. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  144100. 2229.5, 2866.5,
  144101. };
  144102. static long _vq_quantmap__44u7__p9_0[] = {
  144103. 9, 7, 5, 3, 1, 0, 2, 4,
  144104. 6, 8, 10,
  144105. };
  144106. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  144107. _vq_quantthresh__44u7__p9_0,
  144108. _vq_quantmap__44u7__p9_0,
  144109. 11,
  144110. 11
  144111. };
  144112. static static_codebook _44u7__p9_0 = {
  144113. 2, 121,
  144114. _vq_lengthlist__44u7__p9_0,
  144115. 1, -512171520, 1630791680, 4, 0,
  144116. _vq_quantlist__44u7__p9_0,
  144117. NULL,
  144118. &_vq_auxt__44u7__p9_0,
  144119. NULL,
  144120. 0
  144121. };
  144122. static long _vq_quantlist__44u7__p9_1[] = {
  144123. 6,
  144124. 5,
  144125. 7,
  144126. 4,
  144127. 8,
  144128. 3,
  144129. 9,
  144130. 2,
  144131. 10,
  144132. 1,
  144133. 11,
  144134. 0,
  144135. 12,
  144136. };
  144137. static long _vq_lengthlist__44u7__p9_1[] = {
  144138. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  144139. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  144140. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  144141. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  144142. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  144143. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  144144. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  144145. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  144146. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  144147. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  144148. 15,15,15,15,17,17,16,17,16,
  144149. };
  144150. static float _vq_quantthresh__44u7__p9_1[] = {
  144151. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  144152. 122.5, 171.5, 220.5, 269.5,
  144153. };
  144154. static long _vq_quantmap__44u7__p9_1[] = {
  144155. 11, 9, 7, 5, 3, 1, 0, 2,
  144156. 4, 6, 8, 10, 12,
  144157. };
  144158. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  144159. _vq_quantthresh__44u7__p9_1,
  144160. _vq_quantmap__44u7__p9_1,
  144161. 13,
  144162. 13
  144163. };
  144164. static static_codebook _44u7__p9_1 = {
  144165. 2, 169,
  144166. _vq_lengthlist__44u7__p9_1,
  144167. 1, -518889472, 1622704128, 4, 0,
  144168. _vq_quantlist__44u7__p9_1,
  144169. NULL,
  144170. &_vq_auxt__44u7__p9_1,
  144171. NULL,
  144172. 0
  144173. };
  144174. static long _vq_quantlist__44u7__p9_2[] = {
  144175. 24,
  144176. 23,
  144177. 25,
  144178. 22,
  144179. 26,
  144180. 21,
  144181. 27,
  144182. 20,
  144183. 28,
  144184. 19,
  144185. 29,
  144186. 18,
  144187. 30,
  144188. 17,
  144189. 31,
  144190. 16,
  144191. 32,
  144192. 15,
  144193. 33,
  144194. 14,
  144195. 34,
  144196. 13,
  144197. 35,
  144198. 12,
  144199. 36,
  144200. 11,
  144201. 37,
  144202. 10,
  144203. 38,
  144204. 9,
  144205. 39,
  144206. 8,
  144207. 40,
  144208. 7,
  144209. 41,
  144210. 6,
  144211. 42,
  144212. 5,
  144213. 43,
  144214. 4,
  144215. 44,
  144216. 3,
  144217. 45,
  144218. 2,
  144219. 46,
  144220. 1,
  144221. 47,
  144222. 0,
  144223. 48,
  144224. };
  144225. static long _vq_lengthlist__44u7__p9_2[] = {
  144226. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  144227. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144228. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  144229. 8,
  144230. };
  144231. static float _vq_quantthresh__44u7__p9_2[] = {
  144232. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144233. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144234. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144235. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144236. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144237. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144238. };
  144239. static long _vq_quantmap__44u7__p9_2[] = {
  144240. 47, 45, 43, 41, 39, 37, 35, 33,
  144241. 31, 29, 27, 25, 23, 21, 19, 17,
  144242. 15, 13, 11, 9, 7, 5, 3, 1,
  144243. 0, 2, 4, 6, 8, 10, 12, 14,
  144244. 16, 18, 20, 22, 24, 26, 28, 30,
  144245. 32, 34, 36, 38, 40, 42, 44, 46,
  144246. 48,
  144247. };
  144248. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  144249. _vq_quantthresh__44u7__p9_2,
  144250. _vq_quantmap__44u7__p9_2,
  144251. 49,
  144252. 49
  144253. };
  144254. static static_codebook _44u7__p9_2 = {
  144255. 1, 49,
  144256. _vq_lengthlist__44u7__p9_2,
  144257. 1, -526909440, 1611661312, 6, 0,
  144258. _vq_quantlist__44u7__p9_2,
  144259. NULL,
  144260. &_vq_auxt__44u7__p9_2,
  144261. NULL,
  144262. 0
  144263. };
  144264. static long _huff_lengthlist__44u7__short[] = {
  144265. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  144266. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  144267. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  144268. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  144269. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  144270. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  144271. 6, 8, 5, 9,
  144272. };
  144273. static static_codebook _huff_book__44u7__short = {
  144274. 2, 100,
  144275. _huff_lengthlist__44u7__short,
  144276. 0, 0, 0, 0, 0,
  144277. NULL,
  144278. NULL,
  144279. NULL,
  144280. NULL,
  144281. 0
  144282. };
  144283. static long _huff_lengthlist__44u8__long[] = {
  144284. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  144285. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  144286. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  144287. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  144288. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  144289. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  144290. 10, 8, 8, 9,
  144291. };
  144292. static static_codebook _huff_book__44u8__long = {
  144293. 2, 100,
  144294. _huff_lengthlist__44u8__long,
  144295. 0, 0, 0, 0, 0,
  144296. NULL,
  144297. NULL,
  144298. NULL,
  144299. NULL,
  144300. 0
  144301. };
  144302. static long _huff_lengthlist__44u8__short[] = {
  144303. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  144304. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  144305. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  144306. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  144307. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  144308. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  144309. 10,10,15,17,
  144310. };
  144311. static static_codebook _huff_book__44u8__short = {
  144312. 2, 100,
  144313. _huff_lengthlist__44u8__short,
  144314. 0, 0, 0, 0, 0,
  144315. NULL,
  144316. NULL,
  144317. NULL,
  144318. NULL,
  144319. 0
  144320. };
  144321. static long _vq_quantlist__44u8_p1_0[] = {
  144322. 1,
  144323. 0,
  144324. 2,
  144325. };
  144326. static long _vq_lengthlist__44u8_p1_0[] = {
  144327. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  144328. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  144329. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  144330. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  144331. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  144332. 10,
  144333. };
  144334. static float _vq_quantthresh__44u8_p1_0[] = {
  144335. -0.5, 0.5,
  144336. };
  144337. static long _vq_quantmap__44u8_p1_0[] = {
  144338. 1, 0, 2,
  144339. };
  144340. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  144341. _vq_quantthresh__44u8_p1_0,
  144342. _vq_quantmap__44u8_p1_0,
  144343. 3,
  144344. 3
  144345. };
  144346. static static_codebook _44u8_p1_0 = {
  144347. 4, 81,
  144348. _vq_lengthlist__44u8_p1_0,
  144349. 1, -535822336, 1611661312, 2, 0,
  144350. _vq_quantlist__44u8_p1_0,
  144351. NULL,
  144352. &_vq_auxt__44u8_p1_0,
  144353. NULL,
  144354. 0
  144355. };
  144356. static long _vq_quantlist__44u8_p2_0[] = {
  144357. 2,
  144358. 1,
  144359. 3,
  144360. 0,
  144361. 4,
  144362. };
  144363. static long _vq_lengthlist__44u8_p2_0[] = {
  144364. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144365. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144366. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  144367. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144368. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  144369. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  144370. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144371. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  144372. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144373. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144374. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  144375. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144376. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  144377. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  144378. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144379. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  144380. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144381. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144382. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144383. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  144384. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144385. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  144386. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144387. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144388. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  144389. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  144390. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  144391. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  144392. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  144393. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  144394. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  144395. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144396. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  144397. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  144398. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  144399. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  144400. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  144401. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  144402. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  144403. 14,
  144404. };
  144405. static float _vq_quantthresh__44u8_p2_0[] = {
  144406. -1.5, -0.5, 0.5, 1.5,
  144407. };
  144408. static long _vq_quantmap__44u8_p2_0[] = {
  144409. 3, 1, 0, 2, 4,
  144410. };
  144411. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  144412. _vq_quantthresh__44u8_p2_0,
  144413. _vq_quantmap__44u8_p2_0,
  144414. 5,
  144415. 5
  144416. };
  144417. static static_codebook _44u8_p2_0 = {
  144418. 4, 625,
  144419. _vq_lengthlist__44u8_p2_0,
  144420. 1, -533725184, 1611661312, 3, 0,
  144421. _vq_quantlist__44u8_p2_0,
  144422. NULL,
  144423. &_vq_auxt__44u8_p2_0,
  144424. NULL,
  144425. 0
  144426. };
  144427. static long _vq_quantlist__44u8_p3_0[] = {
  144428. 4,
  144429. 3,
  144430. 5,
  144431. 2,
  144432. 6,
  144433. 1,
  144434. 7,
  144435. 0,
  144436. 8,
  144437. };
  144438. static long _vq_lengthlist__44u8_p3_0[] = {
  144439. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144440. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144441. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144442. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144443. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  144444. 12,
  144445. };
  144446. static float _vq_quantthresh__44u8_p3_0[] = {
  144447. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144448. };
  144449. static long _vq_quantmap__44u8_p3_0[] = {
  144450. 7, 5, 3, 1, 0, 2, 4, 6,
  144451. 8,
  144452. };
  144453. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  144454. _vq_quantthresh__44u8_p3_0,
  144455. _vq_quantmap__44u8_p3_0,
  144456. 9,
  144457. 9
  144458. };
  144459. static static_codebook _44u8_p3_0 = {
  144460. 2, 81,
  144461. _vq_lengthlist__44u8_p3_0,
  144462. 1, -531628032, 1611661312, 4, 0,
  144463. _vq_quantlist__44u8_p3_0,
  144464. NULL,
  144465. &_vq_auxt__44u8_p3_0,
  144466. NULL,
  144467. 0
  144468. };
  144469. static long _vq_quantlist__44u8_p4_0[] = {
  144470. 8,
  144471. 7,
  144472. 9,
  144473. 6,
  144474. 10,
  144475. 5,
  144476. 11,
  144477. 4,
  144478. 12,
  144479. 3,
  144480. 13,
  144481. 2,
  144482. 14,
  144483. 1,
  144484. 15,
  144485. 0,
  144486. 16,
  144487. };
  144488. static long _vq_lengthlist__44u8_p4_0[] = {
  144489. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  144490. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  144491. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  144492. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144493. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144494. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  144495. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  144496. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  144497. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  144498. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  144499. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  144500. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  144501. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  144502. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  144503. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  144504. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  144505. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  144506. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  144507. 14,
  144508. };
  144509. static float _vq_quantthresh__44u8_p4_0[] = {
  144510. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144511. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144512. };
  144513. static long _vq_quantmap__44u8_p4_0[] = {
  144514. 15, 13, 11, 9, 7, 5, 3, 1,
  144515. 0, 2, 4, 6, 8, 10, 12, 14,
  144516. 16,
  144517. };
  144518. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  144519. _vq_quantthresh__44u8_p4_0,
  144520. _vq_quantmap__44u8_p4_0,
  144521. 17,
  144522. 17
  144523. };
  144524. static static_codebook _44u8_p4_0 = {
  144525. 2, 289,
  144526. _vq_lengthlist__44u8_p4_0,
  144527. 1, -529530880, 1611661312, 5, 0,
  144528. _vq_quantlist__44u8_p4_0,
  144529. NULL,
  144530. &_vq_auxt__44u8_p4_0,
  144531. NULL,
  144532. 0
  144533. };
  144534. static long _vq_quantlist__44u8_p5_0[] = {
  144535. 1,
  144536. 0,
  144537. 2,
  144538. };
  144539. static long _vq_lengthlist__44u8_p5_0[] = {
  144540. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  144541. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  144542. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  144543. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144544. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  144545. 10,
  144546. };
  144547. static float _vq_quantthresh__44u8_p5_0[] = {
  144548. -5.5, 5.5,
  144549. };
  144550. static long _vq_quantmap__44u8_p5_0[] = {
  144551. 1, 0, 2,
  144552. };
  144553. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  144554. _vq_quantthresh__44u8_p5_0,
  144555. _vq_quantmap__44u8_p5_0,
  144556. 3,
  144557. 3
  144558. };
  144559. static static_codebook _44u8_p5_0 = {
  144560. 4, 81,
  144561. _vq_lengthlist__44u8_p5_0,
  144562. 1, -529137664, 1618345984, 2, 0,
  144563. _vq_quantlist__44u8_p5_0,
  144564. NULL,
  144565. &_vq_auxt__44u8_p5_0,
  144566. NULL,
  144567. 0
  144568. };
  144569. static long _vq_quantlist__44u8_p5_1[] = {
  144570. 5,
  144571. 4,
  144572. 6,
  144573. 3,
  144574. 7,
  144575. 2,
  144576. 8,
  144577. 1,
  144578. 9,
  144579. 0,
  144580. 10,
  144581. };
  144582. static long _vq_lengthlist__44u8_p5_1[] = {
  144583. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  144584. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  144585. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  144586. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144587. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  144588. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144589. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  144590. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  144591. };
  144592. static float _vq_quantthresh__44u8_p5_1[] = {
  144593. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144594. 3.5, 4.5,
  144595. };
  144596. static long _vq_quantmap__44u8_p5_1[] = {
  144597. 9, 7, 5, 3, 1, 0, 2, 4,
  144598. 6, 8, 10,
  144599. };
  144600. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  144601. _vq_quantthresh__44u8_p5_1,
  144602. _vq_quantmap__44u8_p5_1,
  144603. 11,
  144604. 11
  144605. };
  144606. static static_codebook _44u8_p5_1 = {
  144607. 2, 121,
  144608. _vq_lengthlist__44u8_p5_1,
  144609. 1, -531365888, 1611661312, 4, 0,
  144610. _vq_quantlist__44u8_p5_1,
  144611. NULL,
  144612. &_vq_auxt__44u8_p5_1,
  144613. NULL,
  144614. 0
  144615. };
  144616. static long _vq_quantlist__44u8_p6_0[] = {
  144617. 6,
  144618. 5,
  144619. 7,
  144620. 4,
  144621. 8,
  144622. 3,
  144623. 9,
  144624. 2,
  144625. 10,
  144626. 1,
  144627. 11,
  144628. 0,
  144629. 12,
  144630. };
  144631. static long _vq_lengthlist__44u8_p6_0[] = {
  144632. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  144633. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  144634. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  144635. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  144636. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  144637. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  144638. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  144639. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  144640. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  144641. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  144642. 11,11,11,11,11,12,11,12,12,
  144643. };
  144644. static float _vq_quantthresh__44u8_p6_0[] = {
  144645. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144646. 12.5, 17.5, 22.5, 27.5,
  144647. };
  144648. static long _vq_quantmap__44u8_p6_0[] = {
  144649. 11, 9, 7, 5, 3, 1, 0, 2,
  144650. 4, 6, 8, 10, 12,
  144651. };
  144652. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  144653. _vq_quantthresh__44u8_p6_0,
  144654. _vq_quantmap__44u8_p6_0,
  144655. 13,
  144656. 13
  144657. };
  144658. static static_codebook _44u8_p6_0 = {
  144659. 2, 169,
  144660. _vq_lengthlist__44u8_p6_0,
  144661. 1, -526516224, 1616117760, 4, 0,
  144662. _vq_quantlist__44u8_p6_0,
  144663. NULL,
  144664. &_vq_auxt__44u8_p6_0,
  144665. NULL,
  144666. 0
  144667. };
  144668. static long _vq_quantlist__44u8_p6_1[] = {
  144669. 2,
  144670. 1,
  144671. 3,
  144672. 0,
  144673. 4,
  144674. };
  144675. static long _vq_lengthlist__44u8_p6_1[] = {
  144676. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  144677. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144678. };
  144679. static float _vq_quantthresh__44u8_p6_1[] = {
  144680. -1.5, -0.5, 0.5, 1.5,
  144681. };
  144682. static long _vq_quantmap__44u8_p6_1[] = {
  144683. 3, 1, 0, 2, 4,
  144684. };
  144685. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  144686. _vq_quantthresh__44u8_p6_1,
  144687. _vq_quantmap__44u8_p6_1,
  144688. 5,
  144689. 5
  144690. };
  144691. static static_codebook _44u8_p6_1 = {
  144692. 2, 25,
  144693. _vq_lengthlist__44u8_p6_1,
  144694. 1, -533725184, 1611661312, 3, 0,
  144695. _vq_quantlist__44u8_p6_1,
  144696. NULL,
  144697. &_vq_auxt__44u8_p6_1,
  144698. NULL,
  144699. 0
  144700. };
  144701. static long _vq_quantlist__44u8_p7_0[] = {
  144702. 6,
  144703. 5,
  144704. 7,
  144705. 4,
  144706. 8,
  144707. 3,
  144708. 9,
  144709. 2,
  144710. 10,
  144711. 1,
  144712. 11,
  144713. 0,
  144714. 12,
  144715. };
  144716. static long _vq_lengthlist__44u8_p7_0[] = {
  144717. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  144718. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  144719. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  144720. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  144721. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  144722. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  144723. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  144724. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  144725. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  144726. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  144727. 13,13,14,14,14,15,15,15,16,
  144728. };
  144729. static float _vq_quantthresh__44u8_p7_0[] = {
  144730. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144731. 27.5, 38.5, 49.5, 60.5,
  144732. };
  144733. static long _vq_quantmap__44u8_p7_0[] = {
  144734. 11, 9, 7, 5, 3, 1, 0, 2,
  144735. 4, 6, 8, 10, 12,
  144736. };
  144737. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  144738. _vq_quantthresh__44u8_p7_0,
  144739. _vq_quantmap__44u8_p7_0,
  144740. 13,
  144741. 13
  144742. };
  144743. static static_codebook _44u8_p7_0 = {
  144744. 2, 169,
  144745. _vq_lengthlist__44u8_p7_0,
  144746. 1, -523206656, 1618345984, 4, 0,
  144747. _vq_quantlist__44u8_p7_0,
  144748. NULL,
  144749. &_vq_auxt__44u8_p7_0,
  144750. NULL,
  144751. 0
  144752. };
  144753. static long _vq_quantlist__44u8_p7_1[] = {
  144754. 5,
  144755. 4,
  144756. 6,
  144757. 3,
  144758. 7,
  144759. 2,
  144760. 8,
  144761. 1,
  144762. 9,
  144763. 0,
  144764. 10,
  144765. };
  144766. static long _vq_lengthlist__44u8_p7_1[] = {
  144767. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144768. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  144769. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144770. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  144771. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  144772. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144773. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144774. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144775. };
  144776. static float _vq_quantthresh__44u8_p7_1[] = {
  144777. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144778. 3.5, 4.5,
  144779. };
  144780. static long _vq_quantmap__44u8_p7_1[] = {
  144781. 9, 7, 5, 3, 1, 0, 2, 4,
  144782. 6, 8, 10,
  144783. };
  144784. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  144785. _vq_quantthresh__44u8_p7_1,
  144786. _vq_quantmap__44u8_p7_1,
  144787. 11,
  144788. 11
  144789. };
  144790. static static_codebook _44u8_p7_1 = {
  144791. 2, 121,
  144792. _vq_lengthlist__44u8_p7_1,
  144793. 1, -531365888, 1611661312, 4, 0,
  144794. _vq_quantlist__44u8_p7_1,
  144795. NULL,
  144796. &_vq_auxt__44u8_p7_1,
  144797. NULL,
  144798. 0
  144799. };
  144800. static long _vq_quantlist__44u8_p8_0[] = {
  144801. 7,
  144802. 6,
  144803. 8,
  144804. 5,
  144805. 9,
  144806. 4,
  144807. 10,
  144808. 3,
  144809. 11,
  144810. 2,
  144811. 12,
  144812. 1,
  144813. 13,
  144814. 0,
  144815. 14,
  144816. };
  144817. static long _vq_lengthlist__44u8_p8_0[] = {
  144818. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  144819. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  144820. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  144821. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  144822. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  144823. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  144824. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  144825. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  144826. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  144827. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  144828. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  144829. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  144830. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  144831. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  144832. 17,
  144833. };
  144834. static float _vq_quantthresh__44u8_p8_0[] = {
  144835. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144836. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144837. };
  144838. static long _vq_quantmap__44u8_p8_0[] = {
  144839. 13, 11, 9, 7, 5, 3, 1, 0,
  144840. 2, 4, 6, 8, 10, 12, 14,
  144841. };
  144842. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  144843. _vq_quantthresh__44u8_p8_0,
  144844. _vq_quantmap__44u8_p8_0,
  144845. 15,
  144846. 15
  144847. };
  144848. static static_codebook _44u8_p8_0 = {
  144849. 2, 225,
  144850. _vq_lengthlist__44u8_p8_0,
  144851. 1, -520986624, 1620377600, 4, 0,
  144852. _vq_quantlist__44u8_p8_0,
  144853. NULL,
  144854. &_vq_auxt__44u8_p8_0,
  144855. NULL,
  144856. 0
  144857. };
  144858. static long _vq_quantlist__44u8_p8_1[] = {
  144859. 10,
  144860. 9,
  144861. 11,
  144862. 8,
  144863. 12,
  144864. 7,
  144865. 13,
  144866. 6,
  144867. 14,
  144868. 5,
  144869. 15,
  144870. 4,
  144871. 16,
  144872. 3,
  144873. 17,
  144874. 2,
  144875. 18,
  144876. 1,
  144877. 19,
  144878. 0,
  144879. 20,
  144880. };
  144881. static long _vq_lengthlist__44u8_p8_1[] = {
  144882. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144883. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  144884. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  144885. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  144886. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144887. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144888. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  144889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  144890. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  144891. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  144892. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  144893. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  144894. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  144895. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  144896. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  144897. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144898. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  144899. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  144900. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  144901. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  144902. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144903. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  144904. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  144905. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144906. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144907. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  144908. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  144909. 10,10,10,10,10,10,10,10,10,
  144910. };
  144911. static float _vq_quantthresh__44u8_p8_1[] = {
  144912. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144913. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144914. 6.5, 7.5, 8.5, 9.5,
  144915. };
  144916. static long _vq_quantmap__44u8_p8_1[] = {
  144917. 19, 17, 15, 13, 11, 9, 7, 5,
  144918. 3, 1, 0, 2, 4, 6, 8, 10,
  144919. 12, 14, 16, 18, 20,
  144920. };
  144921. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  144922. _vq_quantthresh__44u8_p8_1,
  144923. _vq_quantmap__44u8_p8_1,
  144924. 21,
  144925. 21
  144926. };
  144927. static static_codebook _44u8_p8_1 = {
  144928. 2, 441,
  144929. _vq_lengthlist__44u8_p8_1,
  144930. 1, -529268736, 1611661312, 5, 0,
  144931. _vq_quantlist__44u8_p8_1,
  144932. NULL,
  144933. &_vq_auxt__44u8_p8_1,
  144934. NULL,
  144935. 0
  144936. };
  144937. static long _vq_quantlist__44u8_p9_0[] = {
  144938. 4,
  144939. 3,
  144940. 5,
  144941. 2,
  144942. 6,
  144943. 1,
  144944. 7,
  144945. 0,
  144946. 8,
  144947. };
  144948. static long _vq_lengthlist__44u8_p9_0[] = {
  144949. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  144950. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144951. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144952. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144953. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  144954. 8,
  144955. };
  144956. static float _vq_quantthresh__44u8_p9_0[] = {
  144957. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  144958. };
  144959. static long _vq_quantmap__44u8_p9_0[] = {
  144960. 7, 5, 3, 1, 0, 2, 4, 6,
  144961. 8,
  144962. };
  144963. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  144964. _vq_quantthresh__44u8_p9_0,
  144965. _vq_quantmap__44u8_p9_0,
  144966. 9,
  144967. 9
  144968. };
  144969. static static_codebook _44u8_p9_0 = {
  144970. 2, 81,
  144971. _vq_lengthlist__44u8_p9_0,
  144972. 1, -511895552, 1631393792, 4, 0,
  144973. _vq_quantlist__44u8_p9_0,
  144974. NULL,
  144975. &_vq_auxt__44u8_p9_0,
  144976. NULL,
  144977. 0
  144978. };
  144979. static long _vq_quantlist__44u8_p9_1[] = {
  144980. 9,
  144981. 8,
  144982. 10,
  144983. 7,
  144984. 11,
  144985. 6,
  144986. 12,
  144987. 5,
  144988. 13,
  144989. 4,
  144990. 14,
  144991. 3,
  144992. 15,
  144993. 2,
  144994. 16,
  144995. 1,
  144996. 17,
  144997. 0,
  144998. 18,
  144999. };
  145000. static long _vq_lengthlist__44u8_p9_1[] = {
  145001. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  145002. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  145003. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  145004. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  145005. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  145006. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  145007. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  145008. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  145009. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  145010. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  145011. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  145012. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  145013. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  145014. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  145015. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  145016. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  145017. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  145018. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  145019. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  145020. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  145021. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  145022. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  145023. 16,15,16,16,16,16,16,16,16,
  145024. };
  145025. static float _vq_quantthresh__44u8_p9_1[] = {
  145026. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145027. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145028. 367.5, 416.5,
  145029. };
  145030. static long _vq_quantmap__44u8_p9_1[] = {
  145031. 17, 15, 13, 11, 9, 7, 5, 3,
  145032. 1, 0, 2, 4, 6, 8, 10, 12,
  145033. 14, 16, 18,
  145034. };
  145035. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  145036. _vq_quantthresh__44u8_p9_1,
  145037. _vq_quantmap__44u8_p9_1,
  145038. 19,
  145039. 19
  145040. };
  145041. static static_codebook _44u8_p9_1 = {
  145042. 2, 361,
  145043. _vq_lengthlist__44u8_p9_1,
  145044. 1, -518287360, 1622704128, 5, 0,
  145045. _vq_quantlist__44u8_p9_1,
  145046. NULL,
  145047. &_vq_auxt__44u8_p9_1,
  145048. NULL,
  145049. 0
  145050. };
  145051. static long _vq_quantlist__44u8_p9_2[] = {
  145052. 24,
  145053. 23,
  145054. 25,
  145055. 22,
  145056. 26,
  145057. 21,
  145058. 27,
  145059. 20,
  145060. 28,
  145061. 19,
  145062. 29,
  145063. 18,
  145064. 30,
  145065. 17,
  145066. 31,
  145067. 16,
  145068. 32,
  145069. 15,
  145070. 33,
  145071. 14,
  145072. 34,
  145073. 13,
  145074. 35,
  145075. 12,
  145076. 36,
  145077. 11,
  145078. 37,
  145079. 10,
  145080. 38,
  145081. 9,
  145082. 39,
  145083. 8,
  145084. 40,
  145085. 7,
  145086. 41,
  145087. 6,
  145088. 42,
  145089. 5,
  145090. 43,
  145091. 4,
  145092. 44,
  145093. 3,
  145094. 45,
  145095. 2,
  145096. 46,
  145097. 1,
  145098. 47,
  145099. 0,
  145100. 48,
  145101. };
  145102. static long _vq_lengthlist__44u8_p9_2[] = {
  145103. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  145104. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145105. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145106. 7,
  145107. };
  145108. static float _vq_quantthresh__44u8_p9_2[] = {
  145109. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145110. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145111. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145112. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145113. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145114. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145115. };
  145116. static long _vq_quantmap__44u8_p9_2[] = {
  145117. 47, 45, 43, 41, 39, 37, 35, 33,
  145118. 31, 29, 27, 25, 23, 21, 19, 17,
  145119. 15, 13, 11, 9, 7, 5, 3, 1,
  145120. 0, 2, 4, 6, 8, 10, 12, 14,
  145121. 16, 18, 20, 22, 24, 26, 28, 30,
  145122. 32, 34, 36, 38, 40, 42, 44, 46,
  145123. 48,
  145124. };
  145125. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  145126. _vq_quantthresh__44u8_p9_2,
  145127. _vq_quantmap__44u8_p9_2,
  145128. 49,
  145129. 49
  145130. };
  145131. static static_codebook _44u8_p9_2 = {
  145132. 1, 49,
  145133. _vq_lengthlist__44u8_p9_2,
  145134. 1, -526909440, 1611661312, 6, 0,
  145135. _vq_quantlist__44u8_p9_2,
  145136. NULL,
  145137. &_vq_auxt__44u8_p9_2,
  145138. NULL,
  145139. 0
  145140. };
  145141. static long _huff_lengthlist__44u9__long[] = {
  145142. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  145143. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  145144. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  145145. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  145146. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  145147. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  145148. 10, 8, 8, 9,
  145149. };
  145150. static static_codebook _huff_book__44u9__long = {
  145151. 2, 100,
  145152. _huff_lengthlist__44u9__long,
  145153. 0, 0, 0, 0, 0,
  145154. NULL,
  145155. NULL,
  145156. NULL,
  145157. NULL,
  145158. 0
  145159. };
  145160. static long _huff_lengthlist__44u9__short[] = {
  145161. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  145162. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  145163. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  145164. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  145165. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  145166. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  145167. 9, 9,12,15,
  145168. };
  145169. static static_codebook _huff_book__44u9__short = {
  145170. 2, 100,
  145171. _huff_lengthlist__44u9__short,
  145172. 0, 0, 0, 0, 0,
  145173. NULL,
  145174. NULL,
  145175. NULL,
  145176. NULL,
  145177. 0
  145178. };
  145179. static long _vq_quantlist__44u9_p1_0[] = {
  145180. 1,
  145181. 0,
  145182. 2,
  145183. };
  145184. static long _vq_lengthlist__44u9_p1_0[] = {
  145185. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  145186. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  145187. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  145188. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  145189. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  145190. 10,
  145191. };
  145192. static float _vq_quantthresh__44u9_p1_0[] = {
  145193. -0.5, 0.5,
  145194. };
  145195. static long _vq_quantmap__44u9_p1_0[] = {
  145196. 1, 0, 2,
  145197. };
  145198. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  145199. _vq_quantthresh__44u9_p1_0,
  145200. _vq_quantmap__44u9_p1_0,
  145201. 3,
  145202. 3
  145203. };
  145204. static static_codebook _44u9_p1_0 = {
  145205. 4, 81,
  145206. _vq_lengthlist__44u9_p1_0,
  145207. 1, -535822336, 1611661312, 2, 0,
  145208. _vq_quantlist__44u9_p1_0,
  145209. NULL,
  145210. &_vq_auxt__44u9_p1_0,
  145211. NULL,
  145212. 0
  145213. };
  145214. static long _vq_quantlist__44u9_p2_0[] = {
  145215. 2,
  145216. 1,
  145217. 3,
  145218. 0,
  145219. 4,
  145220. };
  145221. static long _vq_lengthlist__44u9_p2_0[] = {
  145222. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145223. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145224. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145225. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  145226. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  145227. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  145228. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  145229. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  145230. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145231. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145232. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  145233. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  145234. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  145235. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  145236. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  145237. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  145238. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  145239. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  145240. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  145241. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  145242. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  145243. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  145244. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  145245. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  145246. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  145247. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  145248. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  145249. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  145250. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  145251. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  145252. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  145253. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  145254. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  145255. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  145256. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  145257. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  145258. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  145259. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  145260. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  145261. 14,
  145262. };
  145263. static float _vq_quantthresh__44u9_p2_0[] = {
  145264. -1.5, -0.5, 0.5, 1.5,
  145265. };
  145266. static long _vq_quantmap__44u9_p2_0[] = {
  145267. 3, 1, 0, 2, 4,
  145268. };
  145269. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  145270. _vq_quantthresh__44u9_p2_0,
  145271. _vq_quantmap__44u9_p2_0,
  145272. 5,
  145273. 5
  145274. };
  145275. static static_codebook _44u9_p2_0 = {
  145276. 4, 625,
  145277. _vq_lengthlist__44u9_p2_0,
  145278. 1, -533725184, 1611661312, 3, 0,
  145279. _vq_quantlist__44u9_p2_0,
  145280. NULL,
  145281. &_vq_auxt__44u9_p2_0,
  145282. NULL,
  145283. 0
  145284. };
  145285. static long _vq_quantlist__44u9_p3_0[] = {
  145286. 4,
  145287. 3,
  145288. 5,
  145289. 2,
  145290. 6,
  145291. 1,
  145292. 7,
  145293. 0,
  145294. 8,
  145295. };
  145296. static long _vq_lengthlist__44u9_p3_0[] = {
  145297. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  145298. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145299. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145300. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  145301. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  145302. 11,
  145303. };
  145304. static float _vq_quantthresh__44u9_p3_0[] = {
  145305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145306. };
  145307. static long _vq_quantmap__44u9_p3_0[] = {
  145308. 7, 5, 3, 1, 0, 2, 4, 6,
  145309. 8,
  145310. };
  145311. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  145312. _vq_quantthresh__44u9_p3_0,
  145313. _vq_quantmap__44u9_p3_0,
  145314. 9,
  145315. 9
  145316. };
  145317. static static_codebook _44u9_p3_0 = {
  145318. 2, 81,
  145319. _vq_lengthlist__44u9_p3_0,
  145320. 1, -531628032, 1611661312, 4, 0,
  145321. _vq_quantlist__44u9_p3_0,
  145322. NULL,
  145323. &_vq_auxt__44u9_p3_0,
  145324. NULL,
  145325. 0
  145326. };
  145327. static long _vq_quantlist__44u9_p4_0[] = {
  145328. 8,
  145329. 7,
  145330. 9,
  145331. 6,
  145332. 10,
  145333. 5,
  145334. 11,
  145335. 4,
  145336. 12,
  145337. 3,
  145338. 13,
  145339. 2,
  145340. 14,
  145341. 1,
  145342. 15,
  145343. 0,
  145344. 16,
  145345. };
  145346. static long _vq_lengthlist__44u9_p4_0[] = {
  145347. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  145348. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  145349. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  145350. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  145351. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  145352. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  145353. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  145354. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  145355. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  145356. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  145357. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  145358. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  145359. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  145360. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  145361. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  145362. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  145363. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  145364. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  145365. 14,
  145366. };
  145367. static float _vq_quantthresh__44u9_p4_0[] = {
  145368. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145369. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145370. };
  145371. static long _vq_quantmap__44u9_p4_0[] = {
  145372. 15, 13, 11, 9, 7, 5, 3, 1,
  145373. 0, 2, 4, 6, 8, 10, 12, 14,
  145374. 16,
  145375. };
  145376. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  145377. _vq_quantthresh__44u9_p4_0,
  145378. _vq_quantmap__44u9_p4_0,
  145379. 17,
  145380. 17
  145381. };
  145382. static static_codebook _44u9_p4_0 = {
  145383. 2, 289,
  145384. _vq_lengthlist__44u9_p4_0,
  145385. 1, -529530880, 1611661312, 5, 0,
  145386. _vq_quantlist__44u9_p4_0,
  145387. NULL,
  145388. &_vq_auxt__44u9_p4_0,
  145389. NULL,
  145390. 0
  145391. };
  145392. static long _vq_quantlist__44u9_p5_0[] = {
  145393. 1,
  145394. 0,
  145395. 2,
  145396. };
  145397. static long _vq_lengthlist__44u9_p5_0[] = {
  145398. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  145399. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  145400. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  145401. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145402. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  145403. 10,
  145404. };
  145405. static float _vq_quantthresh__44u9_p5_0[] = {
  145406. -5.5, 5.5,
  145407. };
  145408. static long _vq_quantmap__44u9_p5_0[] = {
  145409. 1, 0, 2,
  145410. };
  145411. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  145412. _vq_quantthresh__44u9_p5_0,
  145413. _vq_quantmap__44u9_p5_0,
  145414. 3,
  145415. 3
  145416. };
  145417. static static_codebook _44u9_p5_0 = {
  145418. 4, 81,
  145419. _vq_lengthlist__44u9_p5_0,
  145420. 1, -529137664, 1618345984, 2, 0,
  145421. _vq_quantlist__44u9_p5_0,
  145422. NULL,
  145423. &_vq_auxt__44u9_p5_0,
  145424. NULL,
  145425. 0
  145426. };
  145427. static long _vq_quantlist__44u9_p5_1[] = {
  145428. 5,
  145429. 4,
  145430. 6,
  145431. 3,
  145432. 7,
  145433. 2,
  145434. 8,
  145435. 1,
  145436. 9,
  145437. 0,
  145438. 10,
  145439. };
  145440. static long _vq_lengthlist__44u9_p5_1[] = {
  145441. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  145442. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  145443. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  145444. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  145445. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  145446. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145447. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145448. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145449. };
  145450. static float _vq_quantthresh__44u9_p5_1[] = {
  145451. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145452. 3.5, 4.5,
  145453. };
  145454. static long _vq_quantmap__44u9_p5_1[] = {
  145455. 9, 7, 5, 3, 1, 0, 2, 4,
  145456. 6, 8, 10,
  145457. };
  145458. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  145459. _vq_quantthresh__44u9_p5_1,
  145460. _vq_quantmap__44u9_p5_1,
  145461. 11,
  145462. 11
  145463. };
  145464. static static_codebook _44u9_p5_1 = {
  145465. 2, 121,
  145466. _vq_lengthlist__44u9_p5_1,
  145467. 1, -531365888, 1611661312, 4, 0,
  145468. _vq_quantlist__44u9_p5_1,
  145469. NULL,
  145470. &_vq_auxt__44u9_p5_1,
  145471. NULL,
  145472. 0
  145473. };
  145474. static long _vq_quantlist__44u9_p6_0[] = {
  145475. 6,
  145476. 5,
  145477. 7,
  145478. 4,
  145479. 8,
  145480. 3,
  145481. 9,
  145482. 2,
  145483. 10,
  145484. 1,
  145485. 11,
  145486. 0,
  145487. 12,
  145488. };
  145489. static long _vq_lengthlist__44u9_p6_0[] = {
  145490. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  145491. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  145492. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145493. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  145494. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  145495. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  145496. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  145497. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  145498. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  145499. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  145500. 10,11,11,11,11,12,11,12,12,
  145501. };
  145502. static float _vq_quantthresh__44u9_p6_0[] = {
  145503. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145504. 12.5, 17.5, 22.5, 27.5,
  145505. };
  145506. static long _vq_quantmap__44u9_p6_0[] = {
  145507. 11, 9, 7, 5, 3, 1, 0, 2,
  145508. 4, 6, 8, 10, 12,
  145509. };
  145510. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  145511. _vq_quantthresh__44u9_p6_0,
  145512. _vq_quantmap__44u9_p6_0,
  145513. 13,
  145514. 13
  145515. };
  145516. static static_codebook _44u9_p6_0 = {
  145517. 2, 169,
  145518. _vq_lengthlist__44u9_p6_0,
  145519. 1, -526516224, 1616117760, 4, 0,
  145520. _vq_quantlist__44u9_p6_0,
  145521. NULL,
  145522. &_vq_auxt__44u9_p6_0,
  145523. NULL,
  145524. 0
  145525. };
  145526. static long _vq_quantlist__44u9_p6_1[] = {
  145527. 2,
  145528. 1,
  145529. 3,
  145530. 0,
  145531. 4,
  145532. };
  145533. static long _vq_lengthlist__44u9_p6_1[] = {
  145534. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  145535. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145536. };
  145537. static float _vq_quantthresh__44u9_p6_1[] = {
  145538. -1.5, -0.5, 0.5, 1.5,
  145539. };
  145540. static long _vq_quantmap__44u9_p6_1[] = {
  145541. 3, 1, 0, 2, 4,
  145542. };
  145543. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  145544. _vq_quantthresh__44u9_p6_1,
  145545. _vq_quantmap__44u9_p6_1,
  145546. 5,
  145547. 5
  145548. };
  145549. static static_codebook _44u9_p6_1 = {
  145550. 2, 25,
  145551. _vq_lengthlist__44u9_p6_1,
  145552. 1, -533725184, 1611661312, 3, 0,
  145553. _vq_quantlist__44u9_p6_1,
  145554. NULL,
  145555. &_vq_auxt__44u9_p6_1,
  145556. NULL,
  145557. 0
  145558. };
  145559. static long _vq_quantlist__44u9_p7_0[] = {
  145560. 6,
  145561. 5,
  145562. 7,
  145563. 4,
  145564. 8,
  145565. 3,
  145566. 9,
  145567. 2,
  145568. 10,
  145569. 1,
  145570. 11,
  145571. 0,
  145572. 12,
  145573. };
  145574. static long _vq_lengthlist__44u9_p7_0[] = {
  145575. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  145576. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  145577. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  145578. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  145579. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  145580. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  145581. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  145582. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  145583. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  145584. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  145585. 12,13,13,14,14,14,15,15,15,
  145586. };
  145587. static float _vq_quantthresh__44u9_p7_0[] = {
  145588. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145589. 27.5, 38.5, 49.5, 60.5,
  145590. };
  145591. static long _vq_quantmap__44u9_p7_0[] = {
  145592. 11, 9, 7, 5, 3, 1, 0, 2,
  145593. 4, 6, 8, 10, 12,
  145594. };
  145595. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  145596. _vq_quantthresh__44u9_p7_0,
  145597. _vq_quantmap__44u9_p7_0,
  145598. 13,
  145599. 13
  145600. };
  145601. static static_codebook _44u9_p7_0 = {
  145602. 2, 169,
  145603. _vq_lengthlist__44u9_p7_0,
  145604. 1, -523206656, 1618345984, 4, 0,
  145605. _vq_quantlist__44u9_p7_0,
  145606. NULL,
  145607. &_vq_auxt__44u9_p7_0,
  145608. NULL,
  145609. 0
  145610. };
  145611. static long _vq_quantlist__44u9_p7_1[] = {
  145612. 5,
  145613. 4,
  145614. 6,
  145615. 3,
  145616. 7,
  145617. 2,
  145618. 8,
  145619. 1,
  145620. 9,
  145621. 0,
  145622. 10,
  145623. };
  145624. static long _vq_lengthlist__44u9_p7_1[] = {
  145625. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  145626. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  145627. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  145628. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145629. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145630. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145631. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  145632. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145633. };
  145634. static float _vq_quantthresh__44u9_p7_1[] = {
  145635. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145636. 3.5, 4.5,
  145637. };
  145638. static long _vq_quantmap__44u9_p7_1[] = {
  145639. 9, 7, 5, 3, 1, 0, 2, 4,
  145640. 6, 8, 10,
  145641. };
  145642. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  145643. _vq_quantthresh__44u9_p7_1,
  145644. _vq_quantmap__44u9_p7_1,
  145645. 11,
  145646. 11
  145647. };
  145648. static static_codebook _44u9_p7_1 = {
  145649. 2, 121,
  145650. _vq_lengthlist__44u9_p7_1,
  145651. 1, -531365888, 1611661312, 4, 0,
  145652. _vq_quantlist__44u9_p7_1,
  145653. NULL,
  145654. &_vq_auxt__44u9_p7_1,
  145655. NULL,
  145656. 0
  145657. };
  145658. static long _vq_quantlist__44u9_p8_0[] = {
  145659. 7,
  145660. 6,
  145661. 8,
  145662. 5,
  145663. 9,
  145664. 4,
  145665. 10,
  145666. 3,
  145667. 11,
  145668. 2,
  145669. 12,
  145670. 1,
  145671. 13,
  145672. 0,
  145673. 14,
  145674. };
  145675. static long _vq_lengthlist__44u9_p8_0[] = {
  145676. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  145677. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  145678. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  145679. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  145680. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  145681. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  145682. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  145683. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  145684. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  145685. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  145686. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  145687. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  145688. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  145689. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  145690. 15,
  145691. };
  145692. static float _vq_quantthresh__44u9_p8_0[] = {
  145693. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145694. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145695. };
  145696. static long _vq_quantmap__44u9_p8_0[] = {
  145697. 13, 11, 9, 7, 5, 3, 1, 0,
  145698. 2, 4, 6, 8, 10, 12, 14,
  145699. };
  145700. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  145701. _vq_quantthresh__44u9_p8_0,
  145702. _vq_quantmap__44u9_p8_0,
  145703. 15,
  145704. 15
  145705. };
  145706. static static_codebook _44u9_p8_0 = {
  145707. 2, 225,
  145708. _vq_lengthlist__44u9_p8_0,
  145709. 1, -520986624, 1620377600, 4, 0,
  145710. _vq_quantlist__44u9_p8_0,
  145711. NULL,
  145712. &_vq_auxt__44u9_p8_0,
  145713. NULL,
  145714. 0
  145715. };
  145716. static long _vq_quantlist__44u9_p8_1[] = {
  145717. 10,
  145718. 9,
  145719. 11,
  145720. 8,
  145721. 12,
  145722. 7,
  145723. 13,
  145724. 6,
  145725. 14,
  145726. 5,
  145727. 15,
  145728. 4,
  145729. 16,
  145730. 3,
  145731. 17,
  145732. 2,
  145733. 18,
  145734. 1,
  145735. 19,
  145736. 0,
  145737. 20,
  145738. };
  145739. static long _vq_lengthlist__44u9_p8_1[] = {
  145740. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145741. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145742. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  145743. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  145744. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145745. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145746. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  145747. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  145748. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145749. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145750. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145751. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  145752. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145753. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  145754. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145755. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145756. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145757. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145758. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  145759. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145760. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145761. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  145762. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  145763. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  145764. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145765. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145766. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145767. 10,10,10,10,10,10,10,10,10,
  145768. };
  145769. static float _vq_quantthresh__44u9_p8_1[] = {
  145770. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145771. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145772. 6.5, 7.5, 8.5, 9.5,
  145773. };
  145774. static long _vq_quantmap__44u9_p8_1[] = {
  145775. 19, 17, 15, 13, 11, 9, 7, 5,
  145776. 3, 1, 0, 2, 4, 6, 8, 10,
  145777. 12, 14, 16, 18, 20,
  145778. };
  145779. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  145780. _vq_quantthresh__44u9_p8_1,
  145781. _vq_quantmap__44u9_p8_1,
  145782. 21,
  145783. 21
  145784. };
  145785. static static_codebook _44u9_p8_1 = {
  145786. 2, 441,
  145787. _vq_lengthlist__44u9_p8_1,
  145788. 1, -529268736, 1611661312, 5, 0,
  145789. _vq_quantlist__44u9_p8_1,
  145790. NULL,
  145791. &_vq_auxt__44u9_p8_1,
  145792. NULL,
  145793. 0
  145794. };
  145795. static long _vq_quantlist__44u9_p9_0[] = {
  145796. 7,
  145797. 6,
  145798. 8,
  145799. 5,
  145800. 9,
  145801. 4,
  145802. 10,
  145803. 3,
  145804. 11,
  145805. 2,
  145806. 12,
  145807. 1,
  145808. 13,
  145809. 0,
  145810. 14,
  145811. };
  145812. static long _vq_lengthlist__44u9_p9_0[] = {
  145813. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  145814. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  145815. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145826. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145827. 10,
  145828. };
  145829. static float _vq_quantthresh__44u9_p9_0[] = {
  145830. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  145831. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  145832. };
  145833. static long _vq_quantmap__44u9_p9_0[] = {
  145834. 13, 11, 9, 7, 5, 3, 1, 0,
  145835. 2, 4, 6, 8, 10, 12, 14,
  145836. };
  145837. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  145838. _vq_quantthresh__44u9_p9_0,
  145839. _vq_quantmap__44u9_p9_0,
  145840. 15,
  145841. 15
  145842. };
  145843. static static_codebook _44u9_p9_0 = {
  145844. 2, 225,
  145845. _vq_lengthlist__44u9_p9_0,
  145846. 1, -510036736, 1631393792, 4, 0,
  145847. _vq_quantlist__44u9_p9_0,
  145848. NULL,
  145849. &_vq_auxt__44u9_p9_0,
  145850. NULL,
  145851. 0
  145852. };
  145853. static long _vq_quantlist__44u9_p9_1[] = {
  145854. 9,
  145855. 8,
  145856. 10,
  145857. 7,
  145858. 11,
  145859. 6,
  145860. 12,
  145861. 5,
  145862. 13,
  145863. 4,
  145864. 14,
  145865. 3,
  145866. 15,
  145867. 2,
  145868. 16,
  145869. 1,
  145870. 17,
  145871. 0,
  145872. 18,
  145873. };
  145874. static long _vq_lengthlist__44u9_p9_1[] = {
  145875. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  145876. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  145877. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  145878. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  145879. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  145880. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  145881. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  145882. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  145883. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  145884. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  145885. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  145886. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  145887. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  145888. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  145889. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  145890. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  145891. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  145892. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  145893. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  145894. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  145895. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  145896. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  145897. 17,17,15,17,15,17,16,16,17,
  145898. };
  145899. static float _vq_quantthresh__44u9_p9_1[] = {
  145900. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145901. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145902. 367.5, 416.5,
  145903. };
  145904. static long _vq_quantmap__44u9_p9_1[] = {
  145905. 17, 15, 13, 11, 9, 7, 5, 3,
  145906. 1, 0, 2, 4, 6, 8, 10, 12,
  145907. 14, 16, 18,
  145908. };
  145909. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  145910. _vq_quantthresh__44u9_p9_1,
  145911. _vq_quantmap__44u9_p9_1,
  145912. 19,
  145913. 19
  145914. };
  145915. static static_codebook _44u9_p9_1 = {
  145916. 2, 361,
  145917. _vq_lengthlist__44u9_p9_1,
  145918. 1, -518287360, 1622704128, 5, 0,
  145919. _vq_quantlist__44u9_p9_1,
  145920. NULL,
  145921. &_vq_auxt__44u9_p9_1,
  145922. NULL,
  145923. 0
  145924. };
  145925. static long _vq_quantlist__44u9_p9_2[] = {
  145926. 24,
  145927. 23,
  145928. 25,
  145929. 22,
  145930. 26,
  145931. 21,
  145932. 27,
  145933. 20,
  145934. 28,
  145935. 19,
  145936. 29,
  145937. 18,
  145938. 30,
  145939. 17,
  145940. 31,
  145941. 16,
  145942. 32,
  145943. 15,
  145944. 33,
  145945. 14,
  145946. 34,
  145947. 13,
  145948. 35,
  145949. 12,
  145950. 36,
  145951. 11,
  145952. 37,
  145953. 10,
  145954. 38,
  145955. 9,
  145956. 39,
  145957. 8,
  145958. 40,
  145959. 7,
  145960. 41,
  145961. 6,
  145962. 42,
  145963. 5,
  145964. 43,
  145965. 4,
  145966. 44,
  145967. 3,
  145968. 45,
  145969. 2,
  145970. 46,
  145971. 1,
  145972. 47,
  145973. 0,
  145974. 48,
  145975. };
  145976. static long _vq_lengthlist__44u9_p9_2[] = {
  145977. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  145978. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145979. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145980. 7,
  145981. };
  145982. static float _vq_quantthresh__44u9_p9_2[] = {
  145983. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145984. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145985. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145986. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145987. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145988. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145989. };
  145990. static long _vq_quantmap__44u9_p9_2[] = {
  145991. 47, 45, 43, 41, 39, 37, 35, 33,
  145992. 31, 29, 27, 25, 23, 21, 19, 17,
  145993. 15, 13, 11, 9, 7, 5, 3, 1,
  145994. 0, 2, 4, 6, 8, 10, 12, 14,
  145995. 16, 18, 20, 22, 24, 26, 28, 30,
  145996. 32, 34, 36, 38, 40, 42, 44, 46,
  145997. 48,
  145998. };
  145999. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  146000. _vq_quantthresh__44u9_p9_2,
  146001. _vq_quantmap__44u9_p9_2,
  146002. 49,
  146003. 49
  146004. };
  146005. static static_codebook _44u9_p9_2 = {
  146006. 1, 49,
  146007. _vq_lengthlist__44u9_p9_2,
  146008. 1, -526909440, 1611661312, 6, 0,
  146009. _vq_quantlist__44u9_p9_2,
  146010. NULL,
  146011. &_vq_auxt__44u9_p9_2,
  146012. NULL,
  146013. 0
  146014. };
  146015. static long _huff_lengthlist__44un1__long[] = {
  146016. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  146017. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  146018. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  146019. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  146020. };
  146021. static static_codebook _huff_book__44un1__long = {
  146022. 2, 64,
  146023. _huff_lengthlist__44un1__long,
  146024. 0, 0, 0, 0, 0,
  146025. NULL,
  146026. NULL,
  146027. NULL,
  146028. NULL,
  146029. 0
  146030. };
  146031. static long _vq_quantlist__44un1__p1_0[] = {
  146032. 1,
  146033. 0,
  146034. 2,
  146035. };
  146036. static long _vq_lengthlist__44un1__p1_0[] = {
  146037. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146038. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  146039. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  146040. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  146041. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  146042. 12,
  146043. };
  146044. static float _vq_quantthresh__44un1__p1_0[] = {
  146045. -0.5, 0.5,
  146046. };
  146047. static long _vq_quantmap__44un1__p1_0[] = {
  146048. 1, 0, 2,
  146049. };
  146050. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  146051. _vq_quantthresh__44un1__p1_0,
  146052. _vq_quantmap__44un1__p1_0,
  146053. 3,
  146054. 3
  146055. };
  146056. static static_codebook _44un1__p1_0 = {
  146057. 4, 81,
  146058. _vq_lengthlist__44un1__p1_0,
  146059. 1, -535822336, 1611661312, 2, 0,
  146060. _vq_quantlist__44un1__p1_0,
  146061. NULL,
  146062. &_vq_auxt__44un1__p1_0,
  146063. NULL,
  146064. 0
  146065. };
  146066. static long _vq_quantlist__44un1__p2_0[] = {
  146067. 1,
  146068. 0,
  146069. 2,
  146070. };
  146071. static long _vq_lengthlist__44un1__p2_0[] = {
  146072. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146073. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  146074. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  146075. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  146076. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  146077. 8,
  146078. };
  146079. static float _vq_quantthresh__44un1__p2_0[] = {
  146080. -0.5, 0.5,
  146081. };
  146082. static long _vq_quantmap__44un1__p2_0[] = {
  146083. 1, 0, 2,
  146084. };
  146085. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  146086. _vq_quantthresh__44un1__p2_0,
  146087. _vq_quantmap__44un1__p2_0,
  146088. 3,
  146089. 3
  146090. };
  146091. static static_codebook _44un1__p2_0 = {
  146092. 4, 81,
  146093. _vq_lengthlist__44un1__p2_0,
  146094. 1, -535822336, 1611661312, 2, 0,
  146095. _vq_quantlist__44un1__p2_0,
  146096. NULL,
  146097. &_vq_auxt__44un1__p2_0,
  146098. NULL,
  146099. 0
  146100. };
  146101. static long _vq_quantlist__44un1__p3_0[] = {
  146102. 2,
  146103. 1,
  146104. 3,
  146105. 0,
  146106. 4,
  146107. };
  146108. static long _vq_lengthlist__44un1__p3_0[] = {
  146109. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146110. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  146111. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  146112. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  146113. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  146114. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  146115. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  146116. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  146117. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146118. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  146119. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  146120. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  146121. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  146122. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  146123. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  146124. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  146125. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146126. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  146127. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  146128. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  146129. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  146130. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  146131. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  146132. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  146133. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  146134. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  146135. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  146136. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  146137. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  146138. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  146139. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  146140. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  146141. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  146142. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  146143. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  146144. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  146145. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  146146. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  146147. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  146148. 17,
  146149. };
  146150. static float _vq_quantthresh__44un1__p3_0[] = {
  146151. -1.5, -0.5, 0.5, 1.5,
  146152. };
  146153. static long _vq_quantmap__44un1__p3_0[] = {
  146154. 3, 1, 0, 2, 4,
  146155. };
  146156. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  146157. _vq_quantthresh__44un1__p3_0,
  146158. _vq_quantmap__44un1__p3_0,
  146159. 5,
  146160. 5
  146161. };
  146162. static static_codebook _44un1__p3_0 = {
  146163. 4, 625,
  146164. _vq_lengthlist__44un1__p3_0,
  146165. 1, -533725184, 1611661312, 3, 0,
  146166. _vq_quantlist__44un1__p3_0,
  146167. NULL,
  146168. &_vq_auxt__44un1__p3_0,
  146169. NULL,
  146170. 0
  146171. };
  146172. static long _vq_quantlist__44un1__p4_0[] = {
  146173. 2,
  146174. 1,
  146175. 3,
  146176. 0,
  146177. 4,
  146178. };
  146179. static long _vq_lengthlist__44un1__p4_0[] = {
  146180. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  146181. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  146182. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  146183. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  146184. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  146185. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  146186. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  146187. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  146188. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  146189. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  146190. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  146191. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  146192. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  146193. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  146194. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  146195. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  146196. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  146197. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  146198. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  146199. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  146200. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  146201. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  146202. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  146203. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  146204. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  146205. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  146206. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  146207. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  146208. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  146209. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  146210. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  146211. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  146212. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  146213. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  146214. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  146215. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  146216. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  146217. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  146218. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  146219. 12,
  146220. };
  146221. static float _vq_quantthresh__44un1__p4_0[] = {
  146222. -1.5, -0.5, 0.5, 1.5,
  146223. };
  146224. static long _vq_quantmap__44un1__p4_0[] = {
  146225. 3, 1, 0, 2, 4,
  146226. };
  146227. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  146228. _vq_quantthresh__44un1__p4_0,
  146229. _vq_quantmap__44un1__p4_0,
  146230. 5,
  146231. 5
  146232. };
  146233. static static_codebook _44un1__p4_0 = {
  146234. 4, 625,
  146235. _vq_lengthlist__44un1__p4_0,
  146236. 1, -533725184, 1611661312, 3, 0,
  146237. _vq_quantlist__44un1__p4_0,
  146238. NULL,
  146239. &_vq_auxt__44un1__p4_0,
  146240. NULL,
  146241. 0
  146242. };
  146243. static long _vq_quantlist__44un1__p5_0[] = {
  146244. 4,
  146245. 3,
  146246. 5,
  146247. 2,
  146248. 6,
  146249. 1,
  146250. 7,
  146251. 0,
  146252. 8,
  146253. };
  146254. static long _vq_lengthlist__44un1__p5_0[] = {
  146255. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146256. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  146257. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  146258. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146259. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  146260. 12,
  146261. };
  146262. static float _vq_quantthresh__44un1__p5_0[] = {
  146263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146264. };
  146265. static long _vq_quantmap__44un1__p5_0[] = {
  146266. 7, 5, 3, 1, 0, 2, 4, 6,
  146267. 8,
  146268. };
  146269. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  146270. _vq_quantthresh__44un1__p5_0,
  146271. _vq_quantmap__44un1__p5_0,
  146272. 9,
  146273. 9
  146274. };
  146275. static static_codebook _44un1__p5_0 = {
  146276. 2, 81,
  146277. _vq_lengthlist__44un1__p5_0,
  146278. 1, -531628032, 1611661312, 4, 0,
  146279. _vq_quantlist__44un1__p5_0,
  146280. NULL,
  146281. &_vq_auxt__44un1__p5_0,
  146282. NULL,
  146283. 0
  146284. };
  146285. static long _vq_quantlist__44un1__p6_0[] = {
  146286. 6,
  146287. 5,
  146288. 7,
  146289. 4,
  146290. 8,
  146291. 3,
  146292. 9,
  146293. 2,
  146294. 10,
  146295. 1,
  146296. 11,
  146297. 0,
  146298. 12,
  146299. };
  146300. static long _vq_lengthlist__44un1__p6_0[] = {
  146301. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  146302. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  146303. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  146304. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  146305. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  146306. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  146307. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  146308. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  146309. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  146310. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  146311. 16, 0,15,18,18, 0,16, 0, 0,
  146312. };
  146313. static float _vq_quantthresh__44un1__p6_0[] = {
  146314. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146315. 12.5, 17.5, 22.5, 27.5,
  146316. };
  146317. static long _vq_quantmap__44un1__p6_0[] = {
  146318. 11, 9, 7, 5, 3, 1, 0, 2,
  146319. 4, 6, 8, 10, 12,
  146320. };
  146321. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  146322. _vq_quantthresh__44un1__p6_0,
  146323. _vq_quantmap__44un1__p6_0,
  146324. 13,
  146325. 13
  146326. };
  146327. static static_codebook _44un1__p6_0 = {
  146328. 2, 169,
  146329. _vq_lengthlist__44un1__p6_0,
  146330. 1, -526516224, 1616117760, 4, 0,
  146331. _vq_quantlist__44un1__p6_0,
  146332. NULL,
  146333. &_vq_auxt__44un1__p6_0,
  146334. NULL,
  146335. 0
  146336. };
  146337. static long _vq_quantlist__44un1__p6_1[] = {
  146338. 2,
  146339. 1,
  146340. 3,
  146341. 0,
  146342. 4,
  146343. };
  146344. static long _vq_lengthlist__44un1__p6_1[] = {
  146345. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  146346. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  146347. };
  146348. static float _vq_quantthresh__44un1__p6_1[] = {
  146349. -1.5, -0.5, 0.5, 1.5,
  146350. };
  146351. static long _vq_quantmap__44un1__p6_1[] = {
  146352. 3, 1, 0, 2, 4,
  146353. };
  146354. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  146355. _vq_quantthresh__44un1__p6_1,
  146356. _vq_quantmap__44un1__p6_1,
  146357. 5,
  146358. 5
  146359. };
  146360. static static_codebook _44un1__p6_1 = {
  146361. 2, 25,
  146362. _vq_lengthlist__44un1__p6_1,
  146363. 1, -533725184, 1611661312, 3, 0,
  146364. _vq_quantlist__44un1__p6_1,
  146365. NULL,
  146366. &_vq_auxt__44un1__p6_1,
  146367. NULL,
  146368. 0
  146369. };
  146370. static long _vq_quantlist__44un1__p7_0[] = {
  146371. 2,
  146372. 1,
  146373. 3,
  146374. 0,
  146375. 4,
  146376. };
  146377. static long _vq_lengthlist__44un1__p7_0[] = {
  146378. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  146379. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  146380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146381. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146385. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  146386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  146389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146393. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  146394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146395. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  146396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146399. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146402. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146405. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146408. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146409. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146411. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146417. 10,
  146418. };
  146419. static float _vq_quantthresh__44un1__p7_0[] = {
  146420. -253.5, -84.5, 84.5, 253.5,
  146421. };
  146422. static long _vq_quantmap__44un1__p7_0[] = {
  146423. 3, 1, 0, 2, 4,
  146424. };
  146425. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  146426. _vq_quantthresh__44un1__p7_0,
  146427. _vq_quantmap__44un1__p7_0,
  146428. 5,
  146429. 5
  146430. };
  146431. static static_codebook _44un1__p7_0 = {
  146432. 4, 625,
  146433. _vq_lengthlist__44un1__p7_0,
  146434. 1, -518709248, 1626677248, 3, 0,
  146435. _vq_quantlist__44un1__p7_0,
  146436. NULL,
  146437. &_vq_auxt__44un1__p7_0,
  146438. NULL,
  146439. 0
  146440. };
  146441. static long _vq_quantlist__44un1__p7_1[] = {
  146442. 6,
  146443. 5,
  146444. 7,
  146445. 4,
  146446. 8,
  146447. 3,
  146448. 9,
  146449. 2,
  146450. 10,
  146451. 1,
  146452. 11,
  146453. 0,
  146454. 12,
  146455. };
  146456. static long _vq_lengthlist__44un1__p7_1[] = {
  146457. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  146458. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  146459. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  146460. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  146461. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  146462. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  146463. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  146464. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  146465. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  146466. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  146467. 12,13,13,12,13,13,14,14,14,
  146468. };
  146469. static float _vq_quantthresh__44un1__p7_1[] = {
  146470. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146471. 32.5, 45.5, 58.5, 71.5,
  146472. };
  146473. static long _vq_quantmap__44un1__p7_1[] = {
  146474. 11, 9, 7, 5, 3, 1, 0, 2,
  146475. 4, 6, 8, 10, 12,
  146476. };
  146477. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  146478. _vq_quantthresh__44un1__p7_1,
  146479. _vq_quantmap__44un1__p7_1,
  146480. 13,
  146481. 13
  146482. };
  146483. static static_codebook _44un1__p7_1 = {
  146484. 2, 169,
  146485. _vq_lengthlist__44un1__p7_1,
  146486. 1, -523010048, 1618608128, 4, 0,
  146487. _vq_quantlist__44un1__p7_1,
  146488. NULL,
  146489. &_vq_auxt__44un1__p7_1,
  146490. NULL,
  146491. 0
  146492. };
  146493. static long _vq_quantlist__44un1__p7_2[] = {
  146494. 6,
  146495. 5,
  146496. 7,
  146497. 4,
  146498. 8,
  146499. 3,
  146500. 9,
  146501. 2,
  146502. 10,
  146503. 1,
  146504. 11,
  146505. 0,
  146506. 12,
  146507. };
  146508. static long _vq_lengthlist__44un1__p7_2[] = {
  146509. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  146510. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  146511. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  146512. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  146513. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  146514. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  146515. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  146516. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  146517. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  146518. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  146519. 9, 9, 9,10,10,10,10,10,10,
  146520. };
  146521. static float _vq_quantthresh__44un1__p7_2[] = {
  146522. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146523. 2.5, 3.5, 4.5, 5.5,
  146524. };
  146525. static long _vq_quantmap__44un1__p7_2[] = {
  146526. 11, 9, 7, 5, 3, 1, 0, 2,
  146527. 4, 6, 8, 10, 12,
  146528. };
  146529. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  146530. _vq_quantthresh__44un1__p7_2,
  146531. _vq_quantmap__44un1__p7_2,
  146532. 13,
  146533. 13
  146534. };
  146535. static static_codebook _44un1__p7_2 = {
  146536. 2, 169,
  146537. _vq_lengthlist__44un1__p7_2,
  146538. 1, -531103744, 1611661312, 4, 0,
  146539. _vq_quantlist__44un1__p7_2,
  146540. NULL,
  146541. &_vq_auxt__44un1__p7_2,
  146542. NULL,
  146543. 0
  146544. };
  146545. static long _huff_lengthlist__44un1__short[] = {
  146546. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  146547. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  146548. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  146549. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  146550. };
  146551. static static_codebook _huff_book__44un1__short = {
  146552. 2, 64,
  146553. _huff_lengthlist__44un1__short,
  146554. 0, 0, 0, 0, 0,
  146555. NULL,
  146556. NULL,
  146557. NULL,
  146558. NULL,
  146559. 0
  146560. };
  146561. /********* End of inlined file: res_books_uncoupled.h *********/
  146562. /***** residue backends *********************************************/
  146563. static vorbis_info_residue0 _residue_44_low_un={
  146564. 0,-1, -1, 8,-1,
  146565. {0},
  146566. {-1},
  146567. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  146568. { -1, 25, -1, 45, -1, -1, -1}
  146569. };
  146570. static vorbis_info_residue0 _residue_44_mid_un={
  146571. 0,-1, -1, 10,-1,
  146572. /* 0 1 2 3 4 5 6 7 8 9 */
  146573. {0},
  146574. {-1},
  146575. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  146576. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  146577. };
  146578. static vorbis_info_residue0 _residue_44_hi_un={
  146579. 0,-1, -1, 10,-1,
  146580. /* 0 1 2 3 4 5 6 7 8 9 */
  146581. {0},
  146582. {-1},
  146583. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  146584. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  146585. };
  146586. /* mapping conventions:
  146587. only one submap (this would change for efficient 5.1 support for example)*/
  146588. /* Four psychoacoustic profiles are used, one for each blocktype */
  146589. static vorbis_info_mapping0 _map_nominal_u[2]={
  146590. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  146591. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  146592. };
  146593. static static_bookblock _resbook_44u_n1={
  146594. {
  146595. {0},
  146596. {0,0,&_44un1__p1_0},
  146597. {0,0,&_44un1__p2_0},
  146598. {0,0,&_44un1__p3_0},
  146599. {0,0,&_44un1__p4_0},
  146600. {0,0,&_44un1__p5_0},
  146601. {&_44un1__p6_0,&_44un1__p6_1},
  146602. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  146603. }
  146604. };
  146605. static static_bookblock _resbook_44u_0={
  146606. {
  146607. {0},
  146608. {0,0,&_44u0__p1_0},
  146609. {0,0,&_44u0__p2_0},
  146610. {0,0,&_44u0__p3_0},
  146611. {0,0,&_44u0__p4_0},
  146612. {0,0,&_44u0__p5_0},
  146613. {&_44u0__p6_0,&_44u0__p6_1},
  146614. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  146615. }
  146616. };
  146617. static static_bookblock _resbook_44u_1={
  146618. {
  146619. {0},
  146620. {0,0,&_44u1__p1_0},
  146621. {0,0,&_44u1__p2_0},
  146622. {0,0,&_44u1__p3_0},
  146623. {0,0,&_44u1__p4_0},
  146624. {0,0,&_44u1__p5_0},
  146625. {&_44u1__p6_0,&_44u1__p6_1},
  146626. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  146627. }
  146628. };
  146629. static static_bookblock _resbook_44u_2={
  146630. {
  146631. {0},
  146632. {0,0,&_44u2__p1_0},
  146633. {0,0,&_44u2__p2_0},
  146634. {0,0,&_44u2__p3_0},
  146635. {0,0,&_44u2__p4_0},
  146636. {0,0,&_44u2__p5_0},
  146637. {&_44u2__p6_0,&_44u2__p6_1},
  146638. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  146639. }
  146640. };
  146641. static static_bookblock _resbook_44u_3={
  146642. {
  146643. {0},
  146644. {0,0,&_44u3__p1_0},
  146645. {0,0,&_44u3__p2_0},
  146646. {0,0,&_44u3__p3_0},
  146647. {0,0,&_44u3__p4_0},
  146648. {0,0,&_44u3__p5_0},
  146649. {&_44u3__p6_0,&_44u3__p6_1},
  146650. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  146651. }
  146652. };
  146653. static static_bookblock _resbook_44u_4={
  146654. {
  146655. {0},
  146656. {0,0,&_44u4__p1_0},
  146657. {0,0,&_44u4__p2_0},
  146658. {0,0,&_44u4__p3_0},
  146659. {0,0,&_44u4__p4_0},
  146660. {0,0,&_44u4__p5_0},
  146661. {&_44u4__p6_0,&_44u4__p6_1},
  146662. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  146663. }
  146664. };
  146665. static static_bookblock _resbook_44u_5={
  146666. {
  146667. {0},
  146668. {0,0,&_44u5__p1_0},
  146669. {0,0,&_44u5__p2_0},
  146670. {0,0,&_44u5__p3_0},
  146671. {0,0,&_44u5__p4_0},
  146672. {0,0,&_44u5__p5_0},
  146673. {0,0,&_44u5__p6_0},
  146674. {&_44u5__p7_0,&_44u5__p7_1},
  146675. {&_44u5__p8_0,&_44u5__p8_1},
  146676. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  146677. }
  146678. };
  146679. static static_bookblock _resbook_44u_6={
  146680. {
  146681. {0},
  146682. {0,0,&_44u6__p1_0},
  146683. {0,0,&_44u6__p2_0},
  146684. {0,0,&_44u6__p3_0},
  146685. {0,0,&_44u6__p4_0},
  146686. {0,0,&_44u6__p5_0},
  146687. {0,0,&_44u6__p6_0},
  146688. {&_44u6__p7_0,&_44u6__p7_1},
  146689. {&_44u6__p8_0,&_44u6__p8_1},
  146690. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  146691. }
  146692. };
  146693. static static_bookblock _resbook_44u_7={
  146694. {
  146695. {0},
  146696. {0,0,&_44u7__p1_0},
  146697. {0,0,&_44u7__p2_0},
  146698. {0,0,&_44u7__p3_0},
  146699. {0,0,&_44u7__p4_0},
  146700. {0,0,&_44u7__p5_0},
  146701. {0,0,&_44u7__p6_0},
  146702. {&_44u7__p7_0,&_44u7__p7_1},
  146703. {&_44u7__p8_0,&_44u7__p8_1},
  146704. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  146705. }
  146706. };
  146707. static static_bookblock _resbook_44u_8={
  146708. {
  146709. {0},
  146710. {0,0,&_44u8_p1_0},
  146711. {0,0,&_44u8_p2_0},
  146712. {0,0,&_44u8_p3_0},
  146713. {0,0,&_44u8_p4_0},
  146714. {&_44u8_p5_0,&_44u8_p5_1},
  146715. {&_44u8_p6_0,&_44u8_p6_1},
  146716. {&_44u8_p7_0,&_44u8_p7_1},
  146717. {&_44u8_p8_0,&_44u8_p8_1},
  146718. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  146719. }
  146720. };
  146721. static static_bookblock _resbook_44u_9={
  146722. {
  146723. {0},
  146724. {0,0,&_44u9_p1_0},
  146725. {0,0,&_44u9_p2_0},
  146726. {0,0,&_44u9_p3_0},
  146727. {0,0,&_44u9_p4_0},
  146728. {&_44u9_p5_0,&_44u9_p5_1},
  146729. {&_44u9_p6_0,&_44u9_p6_1},
  146730. {&_44u9_p7_0,&_44u9_p7_1},
  146731. {&_44u9_p8_0,&_44u9_p8_1},
  146732. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  146733. }
  146734. };
  146735. static vorbis_residue_template _res_44u_n1[]={
  146736. {1,0, &_residue_44_low_un,
  146737. &_huff_book__44un1__short,&_huff_book__44un1__short,
  146738. &_resbook_44u_n1,&_resbook_44u_n1},
  146739. {1,0, &_residue_44_low_un,
  146740. &_huff_book__44un1__long,&_huff_book__44un1__long,
  146741. &_resbook_44u_n1,&_resbook_44u_n1}
  146742. };
  146743. static vorbis_residue_template _res_44u_0[]={
  146744. {1,0, &_residue_44_low_un,
  146745. &_huff_book__44u0__short,&_huff_book__44u0__short,
  146746. &_resbook_44u_0,&_resbook_44u_0},
  146747. {1,0, &_residue_44_low_un,
  146748. &_huff_book__44u0__long,&_huff_book__44u0__long,
  146749. &_resbook_44u_0,&_resbook_44u_0}
  146750. };
  146751. static vorbis_residue_template _res_44u_1[]={
  146752. {1,0, &_residue_44_low_un,
  146753. &_huff_book__44u1__short,&_huff_book__44u1__short,
  146754. &_resbook_44u_1,&_resbook_44u_1},
  146755. {1,0, &_residue_44_low_un,
  146756. &_huff_book__44u1__long,&_huff_book__44u1__long,
  146757. &_resbook_44u_1,&_resbook_44u_1}
  146758. };
  146759. static vorbis_residue_template _res_44u_2[]={
  146760. {1,0, &_residue_44_low_un,
  146761. &_huff_book__44u2__short,&_huff_book__44u2__short,
  146762. &_resbook_44u_2,&_resbook_44u_2},
  146763. {1,0, &_residue_44_low_un,
  146764. &_huff_book__44u2__long,&_huff_book__44u2__long,
  146765. &_resbook_44u_2,&_resbook_44u_2}
  146766. };
  146767. static vorbis_residue_template _res_44u_3[]={
  146768. {1,0, &_residue_44_low_un,
  146769. &_huff_book__44u3__short,&_huff_book__44u3__short,
  146770. &_resbook_44u_3,&_resbook_44u_3},
  146771. {1,0, &_residue_44_low_un,
  146772. &_huff_book__44u3__long,&_huff_book__44u3__long,
  146773. &_resbook_44u_3,&_resbook_44u_3}
  146774. };
  146775. static vorbis_residue_template _res_44u_4[]={
  146776. {1,0, &_residue_44_low_un,
  146777. &_huff_book__44u4__short,&_huff_book__44u4__short,
  146778. &_resbook_44u_4,&_resbook_44u_4},
  146779. {1,0, &_residue_44_low_un,
  146780. &_huff_book__44u4__long,&_huff_book__44u4__long,
  146781. &_resbook_44u_4,&_resbook_44u_4}
  146782. };
  146783. static vorbis_residue_template _res_44u_5[]={
  146784. {1,0, &_residue_44_mid_un,
  146785. &_huff_book__44u5__short,&_huff_book__44u5__short,
  146786. &_resbook_44u_5,&_resbook_44u_5},
  146787. {1,0, &_residue_44_mid_un,
  146788. &_huff_book__44u5__long,&_huff_book__44u5__long,
  146789. &_resbook_44u_5,&_resbook_44u_5}
  146790. };
  146791. static vorbis_residue_template _res_44u_6[]={
  146792. {1,0, &_residue_44_mid_un,
  146793. &_huff_book__44u6__short,&_huff_book__44u6__short,
  146794. &_resbook_44u_6,&_resbook_44u_6},
  146795. {1,0, &_residue_44_mid_un,
  146796. &_huff_book__44u6__long,&_huff_book__44u6__long,
  146797. &_resbook_44u_6,&_resbook_44u_6}
  146798. };
  146799. static vorbis_residue_template _res_44u_7[]={
  146800. {1,0, &_residue_44_mid_un,
  146801. &_huff_book__44u7__short,&_huff_book__44u7__short,
  146802. &_resbook_44u_7,&_resbook_44u_7},
  146803. {1,0, &_residue_44_mid_un,
  146804. &_huff_book__44u7__long,&_huff_book__44u7__long,
  146805. &_resbook_44u_7,&_resbook_44u_7}
  146806. };
  146807. static vorbis_residue_template _res_44u_8[]={
  146808. {1,0, &_residue_44_hi_un,
  146809. &_huff_book__44u8__short,&_huff_book__44u8__short,
  146810. &_resbook_44u_8,&_resbook_44u_8},
  146811. {1,0, &_residue_44_hi_un,
  146812. &_huff_book__44u8__long,&_huff_book__44u8__long,
  146813. &_resbook_44u_8,&_resbook_44u_8}
  146814. };
  146815. static vorbis_residue_template _res_44u_9[]={
  146816. {1,0, &_residue_44_hi_un,
  146817. &_huff_book__44u9__short,&_huff_book__44u9__short,
  146818. &_resbook_44u_9,&_resbook_44u_9},
  146819. {1,0, &_residue_44_hi_un,
  146820. &_huff_book__44u9__long,&_huff_book__44u9__long,
  146821. &_resbook_44u_9,&_resbook_44u_9}
  146822. };
  146823. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  146824. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  146825. { _map_nominal_u, _res_44u_0 }, /* 0 */
  146826. { _map_nominal_u, _res_44u_1 }, /* 1 */
  146827. { _map_nominal_u, _res_44u_2 }, /* 2 */
  146828. { _map_nominal_u, _res_44u_3 }, /* 3 */
  146829. { _map_nominal_u, _res_44u_4 }, /* 4 */
  146830. { _map_nominal_u, _res_44u_5 }, /* 5 */
  146831. { _map_nominal_u, _res_44u_6 }, /* 6 */
  146832. { _map_nominal_u, _res_44u_7 }, /* 7 */
  146833. { _map_nominal_u, _res_44u_8 }, /* 8 */
  146834. { _map_nominal_u, _res_44u_9 }, /* 9 */
  146835. };
  146836. /********* End of inlined file: residue_44u.h *********/
  146837. static double rate_mapping_44_un[12]={
  146838. 32000.,48000.,60000.,70000.,80000.,86000.,
  146839. 96000.,110000.,120000.,140000.,160000.,240001.
  146840. };
  146841. ve_setup_data_template ve_setup_44_uncoupled={
  146842. 11,
  146843. rate_mapping_44_un,
  146844. quality_mapping_44,
  146845. -1,
  146846. 40000,
  146847. 50000,
  146848. blocksize_short_44,
  146849. blocksize_long_44,
  146850. _psy_tone_masteratt_44,
  146851. _psy_tone_0dB,
  146852. _psy_tone_suppress,
  146853. _vp_tonemask_adj_otherblock,
  146854. _vp_tonemask_adj_longblock,
  146855. _vp_tonemask_adj_otherblock,
  146856. _psy_noiseguards_44,
  146857. _psy_noisebias_impulse,
  146858. _psy_noisebias_padding,
  146859. _psy_noisebias_trans,
  146860. _psy_noisebias_long,
  146861. _psy_noise_suppress,
  146862. _psy_compand_44,
  146863. _psy_compand_short_mapping,
  146864. _psy_compand_long_mapping,
  146865. {_noise_start_short_44,_noise_start_long_44},
  146866. {_noise_part_short_44,_noise_part_long_44},
  146867. _noise_thresh_44,
  146868. _psy_ath_floater,
  146869. _psy_ath_abs,
  146870. _psy_lowpass_44,
  146871. _psy_global_44,
  146872. _global_mapping_44,
  146873. NULL,
  146874. _floor_books,
  146875. _floor,
  146876. _floor_short_mapping_44,
  146877. _floor_long_mapping_44,
  146878. _mapres_template_44_uncoupled
  146879. };
  146880. /********* End of inlined file: setup_44u.h *********/
  146881. /********* Start of inlined file: setup_32.h *********/
  146882. static double rate_mapping_32[12]={
  146883. 18000.,28000.,35000.,45000.,56000.,60000.,
  146884. 75000.,90000.,100000.,115000.,150000.,190000.,
  146885. };
  146886. static double rate_mapping_32_un[12]={
  146887. 30000.,42000.,52000.,64000.,72000.,78000.,
  146888. 86000.,92000.,110000.,120000.,140000.,190000.,
  146889. };
  146890. static double _psy_lowpass_32[12]={
  146891. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  146892. };
  146893. ve_setup_data_template ve_setup_32_stereo={
  146894. 11,
  146895. rate_mapping_32,
  146896. quality_mapping_44,
  146897. 2,
  146898. 26000,
  146899. 40000,
  146900. blocksize_short_44,
  146901. blocksize_long_44,
  146902. _psy_tone_masteratt_44,
  146903. _psy_tone_0dB,
  146904. _psy_tone_suppress,
  146905. _vp_tonemask_adj_otherblock,
  146906. _vp_tonemask_adj_longblock,
  146907. _vp_tonemask_adj_otherblock,
  146908. _psy_noiseguards_44,
  146909. _psy_noisebias_impulse,
  146910. _psy_noisebias_padding,
  146911. _psy_noisebias_trans,
  146912. _psy_noisebias_long,
  146913. _psy_noise_suppress,
  146914. _psy_compand_44,
  146915. _psy_compand_short_mapping,
  146916. _psy_compand_long_mapping,
  146917. {_noise_start_short_44,_noise_start_long_44},
  146918. {_noise_part_short_44,_noise_part_long_44},
  146919. _noise_thresh_44,
  146920. _psy_ath_floater,
  146921. _psy_ath_abs,
  146922. _psy_lowpass_32,
  146923. _psy_global_44,
  146924. _global_mapping_44,
  146925. _psy_stereo_modes_44,
  146926. _floor_books,
  146927. _floor,
  146928. _floor_short_mapping_44,
  146929. _floor_long_mapping_44,
  146930. _mapres_template_44_stereo
  146931. };
  146932. ve_setup_data_template ve_setup_32_uncoupled={
  146933. 11,
  146934. rate_mapping_32_un,
  146935. quality_mapping_44,
  146936. -1,
  146937. 26000,
  146938. 40000,
  146939. blocksize_short_44,
  146940. blocksize_long_44,
  146941. _psy_tone_masteratt_44,
  146942. _psy_tone_0dB,
  146943. _psy_tone_suppress,
  146944. _vp_tonemask_adj_otherblock,
  146945. _vp_tonemask_adj_longblock,
  146946. _vp_tonemask_adj_otherblock,
  146947. _psy_noiseguards_44,
  146948. _psy_noisebias_impulse,
  146949. _psy_noisebias_padding,
  146950. _psy_noisebias_trans,
  146951. _psy_noisebias_long,
  146952. _psy_noise_suppress,
  146953. _psy_compand_44,
  146954. _psy_compand_short_mapping,
  146955. _psy_compand_long_mapping,
  146956. {_noise_start_short_44,_noise_start_long_44},
  146957. {_noise_part_short_44,_noise_part_long_44},
  146958. _noise_thresh_44,
  146959. _psy_ath_floater,
  146960. _psy_ath_abs,
  146961. _psy_lowpass_32,
  146962. _psy_global_44,
  146963. _global_mapping_44,
  146964. NULL,
  146965. _floor_books,
  146966. _floor,
  146967. _floor_short_mapping_44,
  146968. _floor_long_mapping_44,
  146969. _mapres_template_44_uncoupled
  146970. };
  146971. /********* End of inlined file: setup_32.h *********/
  146972. /********* Start of inlined file: setup_8.h *********/
  146973. /********* Start of inlined file: psych_8.h *********/
  146974. static att3 _psy_tone_masteratt_8[3]={
  146975. {{ 32, 25, 12}, 0, 0}, /* 0 */
  146976. {{ 30, 25, 12}, 0, 0}, /* 0 */
  146977. {{ 20, 0, -14}, 0, 0}, /* 0 */
  146978. };
  146979. static vp_adjblock _vp_tonemask_adj_8[3]={
  146980. /* adjust for mode zero */
  146981. /* 63 125 250 500 1 2 4 8 16 */
  146982. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  146983. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  146984. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  146985. };
  146986. static noise3 _psy_noisebias_8[3]={
  146987. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  146988. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  146989. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  146990. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  146991. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  146992. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  146993. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  146994. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  146995. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  146996. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  146997. };
  146998. /* stereo mode by base quality level */
  146999. static adj_stereo _psy_stereo_modes_8[3]={
  147000. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147001. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147002. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147003. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147004. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147005. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147006. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147007. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147008. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147009. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147010. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147011. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147012. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147013. };
  147014. static noiseguard _psy_noiseguards_8[2]={
  147015. {10,10,-1},
  147016. {10,10,-1},
  147017. };
  147018. static compandblock _psy_compand_8[2]={
  147019. {{
  147020. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  147021. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  147022. 12,12,13,13,14,14,15, 15, /* 23dB */
  147023. 16,16,17,17,17,18,18, 19, /* 31dB */
  147024. 19,19,20,21,22,23,24, 25, /* 39dB */
  147025. }},
  147026. {{
  147027. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  147028. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  147029. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  147030. 9,10,11,12,13,14,15, 16, /* 31dB */
  147031. 17,18,19,20,21,22,23, 24, /* 39dB */
  147032. }},
  147033. };
  147034. static double _psy_lowpass_8[3]={3.,4.,4.};
  147035. static int _noise_start_8[2]={
  147036. 64,64,
  147037. };
  147038. static int _noise_part_8[2]={
  147039. 8,8,
  147040. };
  147041. static int _psy_ath_floater_8[3]={
  147042. -100,-100,-105,
  147043. };
  147044. static int _psy_ath_abs_8[3]={
  147045. -130,-130,-140,
  147046. };
  147047. /********* End of inlined file: psych_8.h *********/
  147048. /********* Start of inlined file: residue_8.h *********/
  147049. /***** residue backends *********************************************/
  147050. static static_bookblock _resbook_8s_0={
  147051. {
  147052. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  147053. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  147054. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  147055. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  147056. }
  147057. };
  147058. static static_bookblock _resbook_8s_1={
  147059. {
  147060. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  147061. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  147062. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  147063. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  147064. }
  147065. };
  147066. static vorbis_residue_template _res_8s_0[]={
  147067. {2,0, &_residue_44_mid,
  147068. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  147069. &_resbook_8s_0,&_resbook_8s_0},
  147070. };
  147071. static vorbis_residue_template _res_8s_1[]={
  147072. {2,0, &_residue_44_mid,
  147073. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  147074. &_resbook_8s_1,&_resbook_8s_1},
  147075. };
  147076. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  147077. { _map_nominal, _res_8s_0 }, /* 0 */
  147078. { _map_nominal, _res_8s_1 }, /* 1 */
  147079. };
  147080. static static_bookblock _resbook_8u_0={
  147081. {
  147082. {0},
  147083. {0,0,&_8u0__p1_0},
  147084. {0,0,&_8u0__p2_0},
  147085. {0,0,&_8u0__p3_0},
  147086. {0,0,&_8u0__p4_0},
  147087. {0,0,&_8u0__p5_0},
  147088. {&_8u0__p6_0,&_8u0__p6_1},
  147089. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  147090. }
  147091. };
  147092. static static_bookblock _resbook_8u_1={
  147093. {
  147094. {0},
  147095. {0,0,&_8u1__p1_0},
  147096. {0,0,&_8u1__p2_0},
  147097. {0,0,&_8u1__p3_0},
  147098. {0,0,&_8u1__p4_0},
  147099. {0,0,&_8u1__p5_0},
  147100. {0,0,&_8u1__p6_0},
  147101. {&_8u1__p7_0,&_8u1__p7_1},
  147102. {&_8u1__p8_0,&_8u1__p8_1},
  147103. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  147104. }
  147105. };
  147106. static vorbis_residue_template _res_8u_0[]={
  147107. {1,0, &_residue_44_low_un,
  147108. &_huff_book__8u0__single,&_huff_book__8u0__single,
  147109. &_resbook_8u_0,&_resbook_8u_0},
  147110. };
  147111. static vorbis_residue_template _res_8u_1[]={
  147112. {1,0, &_residue_44_mid_un,
  147113. &_huff_book__8u1__single,&_huff_book__8u1__single,
  147114. &_resbook_8u_1,&_resbook_8u_1},
  147115. };
  147116. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  147117. { _map_nominal_u, _res_8u_0 }, /* 0 */
  147118. { _map_nominal_u, _res_8u_1 }, /* 1 */
  147119. };
  147120. /********* End of inlined file: residue_8.h *********/
  147121. static int blocksize_8[2]={
  147122. 512,512
  147123. };
  147124. static int _floor_mapping_8[2]={
  147125. 6,6,
  147126. };
  147127. static double rate_mapping_8[3]={
  147128. 6000.,9000.,32000.,
  147129. };
  147130. static double rate_mapping_8_uncoupled[3]={
  147131. 8000.,14000.,42000.,
  147132. };
  147133. static double quality_mapping_8[3]={
  147134. -.1,.0,1.
  147135. };
  147136. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  147137. static double _global_mapping_8[3]={ 1., 2., 3. };
  147138. ve_setup_data_template ve_setup_8_stereo={
  147139. 2,
  147140. rate_mapping_8,
  147141. quality_mapping_8,
  147142. 2,
  147143. 8000,
  147144. 9000,
  147145. blocksize_8,
  147146. blocksize_8,
  147147. _psy_tone_masteratt_8,
  147148. _psy_tone_0dB,
  147149. _psy_tone_suppress,
  147150. _vp_tonemask_adj_8,
  147151. NULL,
  147152. _vp_tonemask_adj_8,
  147153. _psy_noiseguards_8,
  147154. _psy_noisebias_8,
  147155. _psy_noisebias_8,
  147156. NULL,
  147157. NULL,
  147158. _psy_noise_suppress,
  147159. _psy_compand_8,
  147160. _psy_compand_8_mapping,
  147161. NULL,
  147162. {_noise_start_8,_noise_start_8},
  147163. {_noise_part_8,_noise_part_8},
  147164. _noise_thresh_5only,
  147165. _psy_ath_floater_8,
  147166. _psy_ath_abs_8,
  147167. _psy_lowpass_8,
  147168. _psy_global_44,
  147169. _global_mapping_8,
  147170. _psy_stereo_modes_8,
  147171. _floor_books,
  147172. _floor,
  147173. _floor_mapping_8,
  147174. NULL,
  147175. _mapres_template_8_stereo
  147176. };
  147177. ve_setup_data_template ve_setup_8_uncoupled={
  147178. 2,
  147179. rate_mapping_8_uncoupled,
  147180. quality_mapping_8,
  147181. -1,
  147182. 8000,
  147183. 9000,
  147184. blocksize_8,
  147185. blocksize_8,
  147186. _psy_tone_masteratt_8,
  147187. _psy_tone_0dB,
  147188. _psy_tone_suppress,
  147189. _vp_tonemask_adj_8,
  147190. NULL,
  147191. _vp_tonemask_adj_8,
  147192. _psy_noiseguards_8,
  147193. _psy_noisebias_8,
  147194. _psy_noisebias_8,
  147195. NULL,
  147196. NULL,
  147197. _psy_noise_suppress,
  147198. _psy_compand_8,
  147199. _psy_compand_8_mapping,
  147200. NULL,
  147201. {_noise_start_8,_noise_start_8},
  147202. {_noise_part_8,_noise_part_8},
  147203. _noise_thresh_5only,
  147204. _psy_ath_floater_8,
  147205. _psy_ath_abs_8,
  147206. _psy_lowpass_8,
  147207. _psy_global_44,
  147208. _global_mapping_8,
  147209. _psy_stereo_modes_8,
  147210. _floor_books,
  147211. _floor,
  147212. _floor_mapping_8,
  147213. NULL,
  147214. _mapres_template_8_uncoupled
  147215. };
  147216. /********* End of inlined file: setup_8.h *********/
  147217. /********* Start of inlined file: setup_11.h *********/
  147218. /********* Start of inlined file: psych_11.h *********/
  147219. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  147220. static att3 _psy_tone_masteratt_11[3]={
  147221. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147222. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147223. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147224. };
  147225. static vp_adjblock _vp_tonemask_adj_11[3]={
  147226. /* adjust for mode zero */
  147227. /* 63 125 250 500 1 2 4 8 16 */
  147228. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  147229. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  147230. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  147231. };
  147232. static noise3 _psy_noisebias_11[3]={
  147233. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147234. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147235. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  147236. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147237. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147238. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147239. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147240. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147241. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147242. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147243. };
  147244. static double _noise_thresh_11[3]={ .3,.5,.5 };
  147245. /********* End of inlined file: psych_11.h *********/
  147246. static int blocksize_11[2]={
  147247. 512,512
  147248. };
  147249. static int _floor_mapping_11[2]={
  147250. 6,6,
  147251. };
  147252. static double rate_mapping_11[3]={
  147253. 8000.,13000.,44000.,
  147254. };
  147255. static double rate_mapping_11_uncoupled[3]={
  147256. 12000.,20000.,50000.,
  147257. };
  147258. static double quality_mapping_11[3]={
  147259. -.1,.0,1.
  147260. };
  147261. ve_setup_data_template ve_setup_11_stereo={
  147262. 2,
  147263. rate_mapping_11,
  147264. quality_mapping_11,
  147265. 2,
  147266. 9000,
  147267. 15000,
  147268. blocksize_11,
  147269. blocksize_11,
  147270. _psy_tone_masteratt_11,
  147271. _psy_tone_0dB,
  147272. _psy_tone_suppress,
  147273. _vp_tonemask_adj_11,
  147274. NULL,
  147275. _vp_tonemask_adj_11,
  147276. _psy_noiseguards_8,
  147277. _psy_noisebias_11,
  147278. _psy_noisebias_11,
  147279. NULL,
  147280. NULL,
  147281. _psy_noise_suppress,
  147282. _psy_compand_8,
  147283. _psy_compand_8_mapping,
  147284. NULL,
  147285. {_noise_start_8,_noise_start_8},
  147286. {_noise_part_8,_noise_part_8},
  147287. _noise_thresh_11,
  147288. _psy_ath_floater_8,
  147289. _psy_ath_abs_8,
  147290. _psy_lowpass_11,
  147291. _psy_global_44,
  147292. _global_mapping_8,
  147293. _psy_stereo_modes_8,
  147294. _floor_books,
  147295. _floor,
  147296. _floor_mapping_11,
  147297. NULL,
  147298. _mapres_template_8_stereo
  147299. };
  147300. ve_setup_data_template ve_setup_11_uncoupled={
  147301. 2,
  147302. rate_mapping_11_uncoupled,
  147303. quality_mapping_11,
  147304. -1,
  147305. 9000,
  147306. 15000,
  147307. blocksize_11,
  147308. blocksize_11,
  147309. _psy_tone_masteratt_11,
  147310. _psy_tone_0dB,
  147311. _psy_tone_suppress,
  147312. _vp_tonemask_adj_11,
  147313. NULL,
  147314. _vp_tonemask_adj_11,
  147315. _psy_noiseguards_8,
  147316. _psy_noisebias_11,
  147317. _psy_noisebias_11,
  147318. NULL,
  147319. NULL,
  147320. _psy_noise_suppress,
  147321. _psy_compand_8,
  147322. _psy_compand_8_mapping,
  147323. NULL,
  147324. {_noise_start_8,_noise_start_8},
  147325. {_noise_part_8,_noise_part_8},
  147326. _noise_thresh_11,
  147327. _psy_ath_floater_8,
  147328. _psy_ath_abs_8,
  147329. _psy_lowpass_11,
  147330. _psy_global_44,
  147331. _global_mapping_8,
  147332. _psy_stereo_modes_8,
  147333. _floor_books,
  147334. _floor,
  147335. _floor_mapping_11,
  147336. NULL,
  147337. _mapres_template_8_uncoupled
  147338. };
  147339. /********* End of inlined file: setup_11.h *********/
  147340. /********* Start of inlined file: setup_16.h *********/
  147341. /********* Start of inlined file: psych_16.h *********/
  147342. /* stereo mode by base quality level */
  147343. static adj_stereo _psy_stereo_modes_16[4]={
  147344. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147345. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147346. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147347. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  147348. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147349. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147350. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147351. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  147352. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147353. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147354. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147355. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147356. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147357. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  147358. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  147359. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  147360. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147361. };
  147362. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  147363. static att3 _psy_tone_masteratt_16[4]={
  147364. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147365. {{ 25, 22, 12}, 0, 0}, /* 0 */
  147366. {{ 20, 12, 0}, 0, 0}, /* 0 */
  147367. {{ 15, 0, -14}, 0, 0}, /* 0 */
  147368. };
  147369. static vp_adjblock _vp_tonemask_adj_16[4]={
  147370. /* adjust for mode zero */
  147371. /* 63 125 250 500 1 2 4 8 16 */
  147372. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  147373. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  147374. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  147375. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  147376. };
  147377. static noise3 _psy_noisebias_16_short[4]={
  147378. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147379. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  147380. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  147381. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147382. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  147383. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  147384. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  147385. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  147386. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  147387. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147388. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147389. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  147390. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147391. };
  147392. static noise3 _psy_noisebias_16_impulse[4]={
  147393. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147394. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  147395. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  147396. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147397. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  147398. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  147399. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  147400. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  147401. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  147402. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147403. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147404. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  147405. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147406. };
  147407. static noise3 _psy_noisebias_16[4]={
  147408. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147409. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  147410. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  147411. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147412. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  147413. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  147414. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147415. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  147416. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  147417. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147418. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147419. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  147420. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147421. };
  147422. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  147423. static int _noise_start_16[3]={ 256,256,9999 };
  147424. static int _noise_part_16[4]={ 8,8,8,8 };
  147425. static int _psy_ath_floater_16[4]={
  147426. -100,-100,-100,-105,
  147427. };
  147428. static int _psy_ath_abs_16[4]={
  147429. -130,-130,-130,-140,
  147430. };
  147431. /********* End of inlined file: psych_16.h *********/
  147432. /********* Start of inlined file: residue_16.h *********/
  147433. /***** residue backends *********************************************/
  147434. static static_bookblock _resbook_16s_0={
  147435. {
  147436. {0},
  147437. {0,0,&_16c0_s_p1_0},
  147438. {0,0,&_16c0_s_p2_0},
  147439. {0,0,&_16c0_s_p3_0},
  147440. {0,0,&_16c0_s_p4_0},
  147441. {0,0,&_16c0_s_p5_0},
  147442. {0,0,&_16c0_s_p6_0},
  147443. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  147444. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  147445. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  147446. }
  147447. };
  147448. static static_bookblock _resbook_16s_1={
  147449. {
  147450. {0},
  147451. {0,0,&_16c1_s_p1_0},
  147452. {0,0,&_16c1_s_p2_0},
  147453. {0,0,&_16c1_s_p3_0},
  147454. {0,0,&_16c1_s_p4_0},
  147455. {0,0,&_16c1_s_p5_0},
  147456. {0,0,&_16c1_s_p6_0},
  147457. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  147458. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  147459. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  147460. }
  147461. };
  147462. static static_bookblock _resbook_16s_2={
  147463. {
  147464. {0},
  147465. {0,0,&_16c2_s_p1_0},
  147466. {0,0,&_16c2_s_p2_0},
  147467. {0,0,&_16c2_s_p3_0},
  147468. {0,0,&_16c2_s_p4_0},
  147469. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  147470. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  147471. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  147472. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  147473. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  147474. }
  147475. };
  147476. static vorbis_residue_template _res_16s_0[]={
  147477. {2,0, &_residue_44_mid,
  147478. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  147479. &_resbook_16s_0,&_resbook_16s_0},
  147480. };
  147481. static vorbis_residue_template _res_16s_1[]={
  147482. {2,0, &_residue_44_mid,
  147483. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  147484. &_resbook_16s_1,&_resbook_16s_1},
  147485. {2,0, &_residue_44_mid,
  147486. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  147487. &_resbook_16s_1,&_resbook_16s_1}
  147488. };
  147489. static vorbis_residue_template _res_16s_2[]={
  147490. {2,0, &_residue_44_high,
  147491. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  147492. &_resbook_16s_2,&_resbook_16s_2},
  147493. {2,0, &_residue_44_high,
  147494. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  147495. &_resbook_16s_2,&_resbook_16s_2}
  147496. };
  147497. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  147498. { _map_nominal, _res_16s_0 }, /* 0 */
  147499. { _map_nominal, _res_16s_1 }, /* 1 */
  147500. { _map_nominal, _res_16s_2 }, /* 2 */
  147501. };
  147502. static static_bookblock _resbook_16u_0={
  147503. {
  147504. {0},
  147505. {0,0,&_16u0__p1_0},
  147506. {0,0,&_16u0__p2_0},
  147507. {0,0,&_16u0__p3_0},
  147508. {0,0,&_16u0__p4_0},
  147509. {0,0,&_16u0__p5_0},
  147510. {&_16u0__p6_0,&_16u0__p6_1},
  147511. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  147512. }
  147513. };
  147514. static static_bookblock _resbook_16u_1={
  147515. {
  147516. {0},
  147517. {0,0,&_16u1__p1_0},
  147518. {0,0,&_16u1__p2_0},
  147519. {0,0,&_16u1__p3_0},
  147520. {0,0,&_16u1__p4_0},
  147521. {0,0,&_16u1__p5_0},
  147522. {0,0,&_16u1__p6_0},
  147523. {&_16u1__p7_0,&_16u1__p7_1},
  147524. {&_16u1__p8_0,&_16u1__p8_1},
  147525. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  147526. }
  147527. };
  147528. static static_bookblock _resbook_16u_2={
  147529. {
  147530. {0},
  147531. {0,0,&_16u2_p1_0},
  147532. {0,0,&_16u2_p2_0},
  147533. {0,0,&_16u2_p3_0},
  147534. {0,0,&_16u2_p4_0},
  147535. {&_16u2_p5_0,&_16u2_p5_1},
  147536. {&_16u2_p6_0,&_16u2_p6_1},
  147537. {&_16u2_p7_0,&_16u2_p7_1},
  147538. {&_16u2_p8_0,&_16u2_p8_1},
  147539. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  147540. }
  147541. };
  147542. static vorbis_residue_template _res_16u_0[]={
  147543. {1,0, &_residue_44_low_un,
  147544. &_huff_book__16u0__single,&_huff_book__16u0__single,
  147545. &_resbook_16u_0,&_resbook_16u_0},
  147546. };
  147547. static vorbis_residue_template _res_16u_1[]={
  147548. {1,0, &_residue_44_mid_un,
  147549. &_huff_book__16u1__short,&_huff_book__16u1__short,
  147550. &_resbook_16u_1,&_resbook_16u_1},
  147551. {1,0, &_residue_44_mid_un,
  147552. &_huff_book__16u1__long,&_huff_book__16u1__long,
  147553. &_resbook_16u_1,&_resbook_16u_1}
  147554. };
  147555. static vorbis_residue_template _res_16u_2[]={
  147556. {1,0, &_residue_44_hi_un,
  147557. &_huff_book__16u2__short,&_huff_book__16u2__short,
  147558. &_resbook_16u_2,&_resbook_16u_2},
  147559. {1,0, &_residue_44_hi_un,
  147560. &_huff_book__16u2__long,&_huff_book__16u2__long,
  147561. &_resbook_16u_2,&_resbook_16u_2}
  147562. };
  147563. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  147564. { _map_nominal_u, _res_16u_0 }, /* 0 */
  147565. { _map_nominal_u, _res_16u_1 }, /* 1 */
  147566. { _map_nominal_u, _res_16u_2 }, /* 2 */
  147567. };
  147568. /********* End of inlined file: residue_16.h *********/
  147569. static int blocksize_16_short[3]={
  147570. 1024,512,512
  147571. };
  147572. static int blocksize_16_long[3]={
  147573. 1024,1024,1024
  147574. };
  147575. static int _floor_mapping_16_short[3]={
  147576. 9,3,3
  147577. };
  147578. static int _floor_mapping_16[3]={
  147579. 9,9,9
  147580. };
  147581. static double rate_mapping_16[4]={
  147582. 12000.,20000.,44000.,86000.
  147583. };
  147584. static double rate_mapping_16_uncoupled[4]={
  147585. 16000.,28000.,64000.,100000.
  147586. };
  147587. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  147588. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  147589. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  147590. ve_setup_data_template ve_setup_16_stereo={
  147591. 3,
  147592. rate_mapping_16,
  147593. quality_mapping_16,
  147594. 2,
  147595. 15000,
  147596. 19000,
  147597. blocksize_16_short,
  147598. blocksize_16_long,
  147599. _psy_tone_masteratt_16,
  147600. _psy_tone_0dB,
  147601. _psy_tone_suppress,
  147602. _vp_tonemask_adj_16,
  147603. _vp_tonemask_adj_16,
  147604. _vp_tonemask_adj_16,
  147605. _psy_noiseguards_8,
  147606. _psy_noisebias_16_impulse,
  147607. _psy_noisebias_16_short,
  147608. _psy_noisebias_16_short,
  147609. _psy_noisebias_16,
  147610. _psy_noise_suppress,
  147611. _psy_compand_8,
  147612. _psy_compand_16_mapping,
  147613. _psy_compand_16_mapping,
  147614. {_noise_start_16,_noise_start_16},
  147615. { _noise_part_16, _noise_part_16},
  147616. _noise_thresh_16,
  147617. _psy_ath_floater_16,
  147618. _psy_ath_abs_16,
  147619. _psy_lowpass_16,
  147620. _psy_global_44,
  147621. _global_mapping_16,
  147622. _psy_stereo_modes_16,
  147623. _floor_books,
  147624. _floor,
  147625. _floor_mapping_16_short,
  147626. _floor_mapping_16,
  147627. _mapres_template_16_stereo
  147628. };
  147629. ve_setup_data_template ve_setup_16_uncoupled={
  147630. 3,
  147631. rate_mapping_16_uncoupled,
  147632. quality_mapping_16,
  147633. -1,
  147634. 15000,
  147635. 19000,
  147636. blocksize_16_short,
  147637. blocksize_16_long,
  147638. _psy_tone_masteratt_16,
  147639. _psy_tone_0dB,
  147640. _psy_tone_suppress,
  147641. _vp_tonemask_adj_16,
  147642. _vp_tonemask_adj_16,
  147643. _vp_tonemask_adj_16,
  147644. _psy_noiseguards_8,
  147645. _psy_noisebias_16_impulse,
  147646. _psy_noisebias_16_short,
  147647. _psy_noisebias_16_short,
  147648. _psy_noisebias_16,
  147649. _psy_noise_suppress,
  147650. _psy_compand_8,
  147651. _psy_compand_16_mapping,
  147652. _psy_compand_16_mapping,
  147653. {_noise_start_16,_noise_start_16},
  147654. { _noise_part_16, _noise_part_16},
  147655. _noise_thresh_16,
  147656. _psy_ath_floater_16,
  147657. _psy_ath_abs_16,
  147658. _psy_lowpass_16,
  147659. _psy_global_44,
  147660. _global_mapping_16,
  147661. _psy_stereo_modes_16,
  147662. _floor_books,
  147663. _floor,
  147664. _floor_mapping_16_short,
  147665. _floor_mapping_16,
  147666. _mapres_template_16_uncoupled
  147667. };
  147668. /********* End of inlined file: setup_16.h *********/
  147669. /********* Start of inlined file: setup_22.h *********/
  147670. static double rate_mapping_22[4]={
  147671. 15000.,20000.,44000.,86000.
  147672. };
  147673. static double rate_mapping_22_uncoupled[4]={
  147674. 16000.,28000.,50000.,90000.
  147675. };
  147676. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  147677. ve_setup_data_template ve_setup_22_stereo={
  147678. 3,
  147679. rate_mapping_22,
  147680. quality_mapping_16,
  147681. 2,
  147682. 19000,
  147683. 26000,
  147684. blocksize_16_short,
  147685. blocksize_16_long,
  147686. _psy_tone_masteratt_16,
  147687. _psy_tone_0dB,
  147688. _psy_tone_suppress,
  147689. _vp_tonemask_adj_16,
  147690. _vp_tonemask_adj_16,
  147691. _vp_tonemask_adj_16,
  147692. _psy_noiseguards_8,
  147693. _psy_noisebias_16_impulse,
  147694. _psy_noisebias_16_short,
  147695. _psy_noisebias_16_short,
  147696. _psy_noisebias_16,
  147697. _psy_noise_suppress,
  147698. _psy_compand_8,
  147699. _psy_compand_8_mapping,
  147700. _psy_compand_8_mapping,
  147701. {_noise_start_16,_noise_start_16},
  147702. { _noise_part_16, _noise_part_16},
  147703. _noise_thresh_16,
  147704. _psy_ath_floater_16,
  147705. _psy_ath_abs_16,
  147706. _psy_lowpass_22,
  147707. _psy_global_44,
  147708. _global_mapping_16,
  147709. _psy_stereo_modes_16,
  147710. _floor_books,
  147711. _floor,
  147712. _floor_mapping_16_short,
  147713. _floor_mapping_16,
  147714. _mapres_template_16_stereo
  147715. };
  147716. ve_setup_data_template ve_setup_22_uncoupled={
  147717. 3,
  147718. rate_mapping_22_uncoupled,
  147719. quality_mapping_16,
  147720. -1,
  147721. 19000,
  147722. 26000,
  147723. blocksize_16_short,
  147724. blocksize_16_long,
  147725. _psy_tone_masteratt_16,
  147726. _psy_tone_0dB,
  147727. _psy_tone_suppress,
  147728. _vp_tonemask_adj_16,
  147729. _vp_tonemask_adj_16,
  147730. _vp_tonemask_adj_16,
  147731. _psy_noiseguards_8,
  147732. _psy_noisebias_16_impulse,
  147733. _psy_noisebias_16_short,
  147734. _psy_noisebias_16_short,
  147735. _psy_noisebias_16,
  147736. _psy_noise_suppress,
  147737. _psy_compand_8,
  147738. _psy_compand_8_mapping,
  147739. _psy_compand_8_mapping,
  147740. {_noise_start_16,_noise_start_16},
  147741. { _noise_part_16, _noise_part_16},
  147742. _noise_thresh_16,
  147743. _psy_ath_floater_16,
  147744. _psy_ath_abs_16,
  147745. _psy_lowpass_22,
  147746. _psy_global_44,
  147747. _global_mapping_16,
  147748. _psy_stereo_modes_16,
  147749. _floor_books,
  147750. _floor,
  147751. _floor_mapping_16_short,
  147752. _floor_mapping_16,
  147753. _mapres_template_16_uncoupled
  147754. };
  147755. /********* End of inlined file: setup_22.h *********/
  147756. /********* Start of inlined file: setup_X.h *********/
  147757. static double rate_mapping_X[12]={
  147758. -1.,-1.,-1.,-1.,-1.,-1.,
  147759. -1.,-1.,-1.,-1.,-1.,-1.
  147760. };
  147761. ve_setup_data_template ve_setup_X_stereo={
  147762. 11,
  147763. rate_mapping_X,
  147764. quality_mapping_44,
  147765. 2,
  147766. 50000,
  147767. 200000,
  147768. blocksize_short_44,
  147769. blocksize_long_44,
  147770. _psy_tone_masteratt_44,
  147771. _psy_tone_0dB,
  147772. _psy_tone_suppress,
  147773. _vp_tonemask_adj_otherblock,
  147774. _vp_tonemask_adj_longblock,
  147775. _vp_tonemask_adj_otherblock,
  147776. _psy_noiseguards_44,
  147777. _psy_noisebias_impulse,
  147778. _psy_noisebias_padding,
  147779. _psy_noisebias_trans,
  147780. _psy_noisebias_long,
  147781. _psy_noise_suppress,
  147782. _psy_compand_44,
  147783. _psy_compand_short_mapping,
  147784. _psy_compand_long_mapping,
  147785. {_noise_start_short_44,_noise_start_long_44},
  147786. {_noise_part_short_44,_noise_part_long_44},
  147787. _noise_thresh_44,
  147788. _psy_ath_floater,
  147789. _psy_ath_abs,
  147790. _psy_lowpass_44,
  147791. _psy_global_44,
  147792. _global_mapping_44,
  147793. _psy_stereo_modes_44,
  147794. _floor_books,
  147795. _floor,
  147796. _floor_short_mapping_44,
  147797. _floor_long_mapping_44,
  147798. _mapres_template_44_stereo
  147799. };
  147800. ve_setup_data_template ve_setup_X_uncoupled={
  147801. 11,
  147802. rate_mapping_X,
  147803. quality_mapping_44,
  147804. -1,
  147805. 50000,
  147806. 200000,
  147807. blocksize_short_44,
  147808. blocksize_long_44,
  147809. _psy_tone_masteratt_44,
  147810. _psy_tone_0dB,
  147811. _psy_tone_suppress,
  147812. _vp_tonemask_adj_otherblock,
  147813. _vp_tonemask_adj_longblock,
  147814. _vp_tonemask_adj_otherblock,
  147815. _psy_noiseguards_44,
  147816. _psy_noisebias_impulse,
  147817. _psy_noisebias_padding,
  147818. _psy_noisebias_trans,
  147819. _psy_noisebias_long,
  147820. _psy_noise_suppress,
  147821. _psy_compand_44,
  147822. _psy_compand_short_mapping,
  147823. _psy_compand_long_mapping,
  147824. {_noise_start_short_44,_noise_start_long_44},
  147825. {_noise_part_short_44,_noise_part_long_44},
  147826. _noise_thresh_44,
  147827. _psy_ath_floater,
  147828. _psy_ath_abs,
  147829. _psy_lowpass_44,
  147830. _psy_global_44,
  147831. _global_mapping_44,
  147832. NULL,
  147833. _floor_books,
  147834. _floor,
  147835. _floor_short_mapping_44,
  147836. _floor_long_mapping_44,
  147837. _mapres_template_44_uncoupled
  147838. };
  147839. ve_setup_data_template ve_setup_XX_stereo={
  147840. 2,
  147841. rate_mapping_X,
  147842. quality_mapping_8,
  147843. 2,
  147844. 0,
  147845. 8000,
  147846. blocksize_8,
  147847. blocksize_8,
  147848. _psy_tone_masteratt_8,
  147849. _psy_tone_0dB,
  147850. _psy_tone_suppress,
  147851. _vp_tonemask_adj_8,
  147852. NULL,
  147853. _vp_tonemask_adj_8,
  147854. _psy_noiseguards_8,
  147855. _psy_noisebias_8,
  147856. _psy_noisebias_8,
  147857. NULL,
  147858. NULL,
  147859. _psy_noise_suppress,
  147860. _psy_compand_8,
  147861. _psy_compand_8_mapping,
  147862. NULL,
  147863. {_noise_start_8,_noise_start_8},
  147864. {_noise_part_8,_noise_part_8},
  147865. _noise_thresh_5only,
  147866. _psy_ath_floater_8,
  147867. _psy_ath_abs_8,
  147868. _psy_lowpass_8,
  147869. _psy_global_44,
  147870. _global_mapping_8,
  147871. _psy_stereo_modes_8,
  147872. _floor_books,
  147873. _floor,
  147874. _floor_mapping_8,
  147875. NULL,
  147876. _mapres_template_8_stereo
  147877. };
  147878. ve_setup_data_template ve_setup_XX_uncoupled={
  147879. 2,
  147880. rate_mapping_X,
  147881. quality_mapping_8,
  147882. -1,
  147883. 0,
  147884. 8000,
  147885. blocksize_8,
  147886. blocksize_8,
  147887. _psy_tone_masteratt_8,
  147888. _psy_tone_0dB,
  147889. _psy_tone_suppress,
  147890. _vp_tonemask_adj_8,
  147891. NULL,
  147892. _vp_tonemask_adj_8,
  147893. _psy_noiseguards_8,
  147894. _psy_noisebias_8,
  147895. _psy_noisebias_8,
  147896. NULL,
  147897. NULL,
  147898. _psy_noise_suppress,
  147899. _psy_compand_8,
  147900. _psy_compand_8_mapping,
  147901. NULL,
  147902. {_noise_start_8,_noise_start_8},
  147903. {_noise_part_8,_noise_part_8},
  147904. _noise_thresh_5only,
  147905. _psy_ath_floater_8,
  147906. _psy_ath_abs_8,
  147907. _psy_lowpass_8,
  147908. _psy_global_44,
  147909. _global_mapping_8,
  147910. _psy_stereo_modes_8,
  147911. _floor_books,
  147912. _floor,
  147913. _floor_mapping_8,
  147914. NULL,
  147915. _mapres_template_8_uncoupled
  147916. };
  147917. /********* End of inlined file: setup_X.h *********/
  147918. static ve_setup_data_template *setup_list[]={
  147919. &ve_setup_44_stereo,
  147920. &ve_setup_44_uncoupled,
  147921. &ve_setup_32_stereo,
  147922. &ve_setup_32_uncoupled,
  147923. &ve_setup_22_stereo,
  147924. &ve_setup_22_uncoupled,
  147925. &ve_setup_16_stereo,
  147926. &ve_setup_16_uncoupled,
  147927. &ve_setup_11_stereo,
  147928. &ve_setup_11_uncoupled,
  147929. &ve_setup_8_stereo,
  147930. &ve_setup_8_uncoupled,
  147931. &ve_setup_X_stereo,
  147932. &ve_setup_X_uncoupled,
  147933. &ve_setup_XX_stereo,
  147934. &ve_setup_XX_uncoupled,
  147935. 0
  147936. };
  147937. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  147938. if(vi && vi->codec_setup){
  147939. vi->version=0;
  147940. vi->channels=ch;
  147941. vi->rate=rate;
  147942. return(0);
  147943. }
  147944. return(OV_EINVAL);
  147945. }
  147946. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  147947. static_codebook ***books,
  147948. vorbis_info_floor1 *in,
  147949. int *x){
  147950. int i,k,is=s;
  147951. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  147952. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  147953. memcpy(f,in+x[is],sizeof(*f));
  147954. /* fill in the lowpass field, even if it's temporary */
  147955. f->n=ci->blocksizes[block]>>1;
  147956. /* books */
  147957. {
  147958. int partitions=f->partitions;
  147959. int maxclass=-1;
  147960. int maxbook=-1;
  147961. for(i=0;i<partitions;i++)
  147962. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  147963. for(i=0;i<=maxclass;i++){
  147964. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  147965. f->class_book[i]+=ci->books;
  147966. for(k=0;k<(1<<f->class_subs[i]);k++){
  147967. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  147968. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  147969. }
  147970. }
  147971. for(i=0;i<=maxbook;i++)
  147972. ci->book_param[ci->books++]=books[x[is]][i];
  147973. }
  147974. /* for now, we're only using floor 1 */
  147975. ci->floor_type[ci->floors]=1;
  147976. ci->floor_param[ci->floors]=f;
  147977. ci->floors++;
  147978. return;
  147979. }
  147980. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  147981. vorbis_info_psy_global *in,
  147982. double *x){
  147983. int i,is=s;
  147984. double ds=s-is;
  147985. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  147986. vorbis_info_psy_global *g=&ci->psy_g_param;
  147987. memcpy(g,in+(int)x[is],sizeof(*g));
  147988. ds=x[is]*(1.-ds)+x[is+1]*ds;
  147989. is=(int)ds;
  147990. ds-=is;
  147991. if(ds==0 && is>0){
  147992. is--;
  147993. ds=1.;
  147994. }
  147995. /* interpolate the trigger threshholds */
  147996. for(i=0;i<4;i++){
  147997. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  147998. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  147999. }
  148000. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  148001. return;
  148002. }
  148003. static void vorbis_encode_global_stereo(vorbis_info *vi,
  148004. highlevel_encode_setup *hi,
  148005. adj_stereo *p){
  148006. float s=hi->stereo_point_setting;
  148007. int i,is=s;
  148008. double ds=s-is;
  148009. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148010. vorbis_info_psy_global *g=&ci->psy_g_param;
  148011. if(p){
  148012. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  148013. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  148014. if(hi->managed){
  148015. /* interpolate the kHz threshholds */
  148016. for(i=0;i<PACKETBLOBS;i++){
  148017. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  148018. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148019. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148020. g->coupling_pkHz[i]=kHz;
  148021. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  148022. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148023. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148024. }
  148025. }else{
  148026. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  148027. for(i=0;i<PACKETBLOBS;i++){
  148028. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148029. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148030. g->coupling_pkHz[i]=kHz;
  148031. }
  148032. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  148033. for(i=0;i<PACKETBLOBS;i++){
  148034. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148035. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148036. }
  148037. }
  148038. }else{
  148039. for(i=0;i<PACKETBLOBS;i++){
  148040. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  148041. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  148042. }
  148043. }
  148044. return;
  148045. }
  148046. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  148047. int *nn_start,
  148048. int *nn_partition,
  148049. double *nn_thresh,
  148050. int block){
  148051. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148052. vorbis_info_psy *p=ci->psy_param[block];
  148053. highlevel_encode_setup *hi=&ci->hi;
  148054. int is=s;
  148055. if(block>=ci->psys)
  148056. ci->psys=block+1;
  148057. if(!p){
  148058. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  148059. ci->psy_param[block]=p;
  148060. }
  148061. memcpy(p,&_psy_info_template,sizeof(*p));
  148062. p->blockflag=block>>1;
  148063. if(hi->noise_normalize_p){
  148064. p->normal_channel_p=1;
  148065. p->normal_point_p=1;
  148066. p->normal_start=nn_start[is];
  148067. p->normal_partition=nn_partition[is];
  148068. p->normal_thresh=nn_thresh[is];
  148069. }
  148070. return;
  148071. }
  148072. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  148073. att3 *att,
  148074. int *max,
  148075. vp_adjblock *in){
  148076. int i,is=s;
  148077. double ds=s-is;
  148078. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148079. vorbis_info_psy *p=ci->psy_param[block];
  148080. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  148081. filling the values in here */
  148082. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  148083. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  148084. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  148085. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  148086. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  148087. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  148088. for(i=0;i<P_BANDS;i++)
  148089. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  148090. return;
  148091. }
  148092. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  148093. compandblock *in, double *x){
  148094. int i,is=s;
  148095. double ds=s-is;
  148096. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148097. vorbis_info_psy *p=ci->psy_param[block];
  148098. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148099. is=(int)ds;
  148100. ds-=is;
  148101. if(ds==0 && is>0){
  148102. is--;
  148103. ds=1.;
  148104. }
  148105. /* interpolate the compander settings */
  148106. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  148107. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  148108. return;
  148109. }
  148110. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  148111. int *suppress){
  148112. int is=s;
  148113. double ds=s-is;
  148114. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148115. vorbis_info_psy *p=ci->psy_param[block];
  148116. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148117. return;
  148118. }
  148119. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  148120. int *suppress,
  148121. noise3 *in,
  148122. noiseguard *guard,
  148123. double userbias){
  148124. int i,is=s,j;
  148125. double ds=s-is;
  148126. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148127. vorbis_info_psy *p=ci->psy_param[block];
  148128. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148129. p->noisewindowlomin=guard[block].lo;
  148130. p->noisewindowhimin=guard[block].hi;
  148131. p->noisewindowfixed=guard[block].fixed;
  148132. for(j=0;j<P_NOISECURVES;j++)
  148133. for(i=0;i<P_BANDS;i++)
  148134. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  148135. /* impulse blocks may take a user specified bias to boost the
  148136. nominal/high noise encoding depth */
  148137. for(j=0;j<P_NOISECURVES;j++){
  148138. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  148139. for(i=0;i<P_BANDS;i++){
  148140. p->noiseoff[j][i]+=userbias;
  148141. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  148142. }
  148143. }
  148144. return;
  148145. }
  148146. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  148147. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148148. vorbis_info_psy *p=ci->psy_param[block];
  148149. p->ath_adjatt=ci->hi.ath_floating_dB;
  148150. p->ath_maxatt=ci->hi.ath_absolute_dB;
  148151. return;
  148152. }
  148153. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  148154. int i;
  148155. for(i=0;i<ci->books;i++)
  148156. if(ci->book_param[i]==book)return(i);
  148157. return(ci->books++);
  148158. }
  148159. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  148160. int *shortb,int *longb){
  148161. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148162. int is=s;
  148163. int blockshort=shortb[is];
  148164. int blocklong=longb[is];
  148165. ci->blocksizes[0]=blockshort;
  148166. ci->blocksizes[1]=blocklong;
  148167. }
  148168. static void vorbis_encode_residue_setup(vorbis_info *vi,
  148169. int number, int block,
  148170. vorbis_residue_template *res){
  148171. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148172. int i,n;
  148173. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  148174. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  148175. memcpy(r,res->res,sizeof(*r));
  148176. if(ci->residues<=number)ci->residues=number+1;
  148177. switch(ci->blocksizes[block]){
  148178. case 64:case 128:case 256:
  148179. r->grouping=16;
  148180. break;
  148181. default:
  148182. r->grouping=32;
  148183. break;
  148184. }
  148185. ci->residue_type[number]=res->res_type;
  148186. /* to be adjusted by lowpass/pointlimit later */
  148187. n=r->end=ci->blocksizes[block]>>1;
  148188. if(res->res_type==2)
  148189. n=r->end*=vi->channels;
  148190. /* fill in all the books */
  148191. {
  148192. int booklist=0,k;
  148193. if(ci->hi.managed){
  148194. for(i=0;i<r->partitions;i++)
  148195. for(k=0;k<3;k++)
  148196. if(res->books_base_managed->books[i][k])
  148197. r->secondstages[i]|=(1<<k);
  148198. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  148199. ci->book_param[r->groupbook]=res->book_aux_managed;
  148200. for(i=0;i<r->partitions;i++){
  148201. for(k=0;k<3;k++){
  148202. if(res->books_base_managed->books[i][k]){
  148203. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  148204. r->booklist[booklist++]=bookid;
  148205. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  148206. }
  148207. }
  148208. }
  148209. }else{
  148210. for(i=0;i<r->partitions;i++)
  148211. for(k=0;k<3;k++)
  148212. if(res->books_base->books[i][k])
  148213. r->secondstages[i]|=(1<<k);
  148214. r->groupbook=book_dup_or_new(ci,res->book_aux);
  148215. ci->book_param[r->groupbook]=res->book_aux;
  148216. for(i=0;i<r->partitions;i++){
  148217. for(k=0;k<3;k++){
  148218. if(res->books_base->books[i][k]){
  148219. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  148220. r->booklist[booklist++]=bookid;
  148221. ci->book_param[bookid]=res->books_base->books[i][k];
  148222. }
  148223. }
  148224. }
  148225. }
  148226. }
  148227. /* lowpass setup/pointlimit */
  148228. {
  148229. double freq=ci->hi.lowpass_kHz*1000.;
  148230. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  148231. double nyq=vi->rate/2.;
  148232. long blocksize=ci->blocksizes[block]>>1;
  148233. /* lowpass needs to be set in the floor and the residue. */
  148234. if(freq>nyq)freq=nyq;
  148235. /* in the floor, the granularity can be very fine; it doesn't alter
  148236. the encoding structure, only the samples used to fit the floor
  148237. approximation */
  148238. f->n=freq/nyq*blocksize;
  148239. /* this res may by limited by the maximum pointlimit of the mode,
  148240. not the lowpass. the floor is always lowpass limited. */
  148241. if(res->limit_type){
  148242. if(ci->hi.managed)
  148243. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  148244. else
  148245. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  148246. if(freq>nyq)freq=nyq;
  148247. }
  148248. /* in the residue, we're constrained, physically, by partition
  148249. boundaries. We still lowpass 'wherever', but we have to round up
  148250. here to next boundary, or the vorbis spec will round it *down* to
  148251. previous boundary in encode/decode */
  148252. if(ci->residue_type[block]==2)
  148253. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  148254. r->grouping;
  148255. else
  148256. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  148257. r->grouping;
  148258. }
  148259. }
  148260. /* we assume two maps in this encoder */
  148261. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  148262. vorbis_mapping_template *maps){
  148263. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148264. int i,j,is=s,modes=2;
  148265. vorbis_info_mapping0 *map=maps[is].map;
  148266. vorbis_info_mode *mode=_mode_template;
  148267. vorbis_residue_template *res=maps[is].res;
  148268. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  148269. for(i=0;i<modes;i++){
  148270. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  148271. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  148272. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  148273. if(i>=ci->modes)ci->modes=i+1;
  148274. ci->map_type[i]=0;
  148275. memcpy(ci->map_param[i],map+i,sizeof(*map));
  148276. if(i>=ci->maps)ci->maps=i+1;
  148277. for(j=0;j<map[i].submaps;j++)
  148278. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  148279. ,res+map[i].residuesubmap[j]);
  148280. }
  148281. }
  148282. static double setting_to_approx_bitrate(vorbis_info *vi){
  148283. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148284. highlevel_encode_setup *hi=&ci->hi;
  148285. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  148286. int is=hi->base_setting;
  148287. double ds=hi->base_setting-is;
  148288. int ch=vi->channels;
  148289. double *r=setup->rate_mapping;
  148290. if(r==NULL)
  148291. return(-1);
  148292. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  148293. }
  148294. static void get_setup_template(vorbis_info *vi,
  148295. long ch,long srate,
  148296. double req,int q_or_bitrate){
  148297. int i=0,j;
  148298. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148299. highlevel_encode_setup *hi=&ci->hi;
  148300. if(q_or_bitrate)req/=ch;
  148301. while(setup_list[i]){
  148302. if(setup_list[i]->coupling_restriction==-1 ||
  148303. setup_list[i]->coupling_restriction==ch){
  148304. if(srate>=setup_list[i]->samplerate_min_restriction &&
  148305. srate<=setup_list[i]->samplerate_max_restriction){
  148306. int mappings=setup_list[i]->mappings;
  148307. double *map=(q_or_bitrate?
  148308. setup_list[i]->rate_mapping:
  148309. setup_list[i]->quality_mapping);
  148310. /* the template matches. Does the requested quality mode
  148311. fall within this template's modes? */
  148312. if(req<map[0]){++i;continue;}
  148313. if(req>map[setup_list[i]->mappings]){++i;continue;}
  148314. for(j=0;j<mappings;j++)
  148315. if(req>=map[j] && req<map[j+1])break;
  148316. /* an all-points match */
  148317. hi->setup=setup_list[i];
  148318. if(j==mappings)
  148319. hi->base_setting=j-.001;
  148320. else{
  148321. float low=map[j];
  148322. float high=map[j+1];
  148323. float del=(req-low)/(high-low);
  148324. hi->base_setting=j+del;
  148325. }
  148326. return;
  148327. }
  148328. }
  148329. i++;
  148330. }
  148331. hi->setup=NULL;
  148332. }
  148333. /* encoders will need to use vorbis_info_init beforehand and call
  148334. vorbis_info clear when all done */
  148335. /* two interfaces; this, more detailed one, and later a convenience
  148336. layer on top */
  148337. /* the final setup call */
  148338. int vorbis_encode_setup_init(vorbis_info *vi){
  148339. int i0=0,singleblock=0;
  148340. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148341. ve_setup_data_template *setup=NULL;
  148342. highlevel_encode_setup *hi=&ci->hi;
  148343. if(ci==NULL)return(OV_EINVAL);
  148344. if(!hi->impulse_block_p)i0=1;
  148345. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  148346. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  148347. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  148348. /* again, bound this to avoid the app shooting itself int he foot
  148349. too badly */
  148350. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  148351. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  148352. /* get the appropriate setup template; matches the fetch in previous
  148353. stages */
  148354. setup=(ve_setup_data_template *)hi->setup;
  148355. if(setup==NULL)return(OV_EINVAL);
  148356. hi->set_in_stone=1;
  148357. /* choose block sizes from configured sizes as well as paying
  148358. attention to long_block_p and short_block_p. If the configured
  148359. short and long blocks are the same length, we set long_block_p
  148360. and unset short_block_p */
  148361. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  148362. setup->blocksize_short,
  148363. setup->blocksize_long);
  148364. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  148365. /* floor setup; choose proper floor params. Allocated on the floor
  148366. stack in order; if we alloc only long floor, it's 0 */
  148367. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  148368. setup->floor_books,
  148369. setup->floor_params,
  148370. setup->floor_short_mapping);
  148371. if(!singleblock)
  148372. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  148373. setup->floor_books,
  148374. setup->floor_params,
  148375. setup->floor_long_mapping);
  148376. /* setup of [mostly] short block detection and stereo*/
  148377. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  148378. setup->global_params,
  148379. setup->global_mapping);
  148380. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  148381. /* basic psych setup and noise normalization */
  148382. vorbis_encode_psyset_setup(vi,hi->short_setting,
  148383. setup->psy_noise_normal_start[0],
  148384. setup->psy_noise_normal_partition[0],
  148385. setup->psy_noise_normal_thresh,
  148386. 0);
  148387. vorbis_encode_psyset_setup(vi,hi->short_setting,
  148388. setup->psy_noise_normal_start[0],
  148389. setup->psy_noise_normal_partition[0],
  148390. setup->psy_noise_normal_thresh,
  148391. 1);
  148392. if(!singleblock){
  148393. vorbis_encode_psyset_setup(vi,hi->long_setting,
  148394. setup->psy_noise_normal_start[1],
  148395. setup->psy_noise_normal_partition[1],
  148396. setup->psy_noise_normal_thresh,
  148397. 2);
  148398. vorbis_encode_psyset_setup(vi,hi->long_setting,
  148399. setup->psy_noise_normal_start[1],
  148400. setup->psy_noise_normal_partition[1],
  148401. setup->psy_noise_normal_thresh,
  148402. 3);
  148403. }
  148404. /* tone masking setup */
  148405. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  148406. setup->psy_tone_masteratt,
  148407. setup->psy_tone_0dB,
  148408. setup->psy_tone_adj_impulse);
  148409. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  148410. setup->psy_tone_masteratt,
  148411. setup->psy_tone_0dB,
  148412. setup->psy_tone_adj_other);
  148413. if(!singleblock){
  148414. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  148415. setup->psy_tone_masteratt,
  148416. setup->psy_tone_0dB,
  148417. setup->psy_tone_adj_other);
  148418. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  148419. setup->psy_tone_masteratt,
  148420. setup->psy_tone_0dB,
  148421. setup->psy_tone_adj_long);
  148422. }
  148423. /* noise companding setup */
  148424. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  148425. setup->psy_noise_compand,
  148426. setup->psy_noise_compand_short_mapping);
  148427. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  148428. setup->psy_noise_compand,
  148429. setup->psy_noise_compand_short_mapping);
  148430. if(!singleblock){
  148431. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  148432. setup->psy_noise_compand,
  148433. setup->psy_noise_compand_long_mapping);
  148434. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  148435. setup->psy_noise_compand,
  148436. setup->psy_noise_compand_long_mapping);
  148437. }
  148438. /* peak guarding setup */
  148439. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  148440. setup->psy_tone_dBsuppress);
  148441. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  148442. setup->psy_tone_dBsuppress);
  148443. if(!singleblock){
  148444. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  148445. setup->psy_tone_dBsuppress);
  148446. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  148447. setup->psy_tone_dBsuppress);
  148448. }
  148449. /* noise bias setup */
  148450. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  148451. setup->psy_noise_dBsuppress,
  148452. setup->psy_noise_bias_impulse,
  148453. setup->psy_noiseguards,
  148454. (i0==0?hi->impulse_noisetune:0.));
  148455. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  148456. setup->psy_noise_dBsuppress,
  148457. setup->psy_noise_bias_padding,
  148458. setup->psy_noiseguards,0.);
  148459. if(!singleblock){
  148460. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  148461. setup->psy_noise_dBsuppress,
  148462. setup->psy_noise_bias_trans,
  148463. setup->psy_noiseguards,0.);
  148464. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  148465. setup->psy_noise_dBsuppress,
  148466. setup->psy_noise_bias_long,
  148467. setup->psy_noiseguards,0.);
  148468. }
  148469. vorbis_encode_ath_setup(vi,0);
  148470. vorbis_encode_ath_setup(vi,1);
  148471. if(!singleblock){
  148472. vorbis_encode_ath_setup(vi,2);
  148473. vorbis_encode_ath_setup(vi,3);
  148474. }
  148475. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  148476. /* set bitrate readonlies and management */
  148477. if(hi->bitrate_av>0)
  148478. vi->bitrate_nominal=hi->bitrate_av;
  148479. else{
  148480. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  148481. }
  148482. vi->bitrate_lower=hi->bitrate_min;
  148483. vi->bitrate_upper=hi->bitrate_max;
  148484. if(hi->bitrate_av)
  148485. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  148486. else
  148487. vi->bitrate_window=0.;
  148488. if(hi->managed){
  148489. ci->bi.avg_rate=hi->bitrate_av;
  148490. ci->bi.min_rate=hi->bitrate_min;
  148491. ci->bi.max_rate=hi->bitrate_max;
  148492. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  148493. ci->bi.reservoir_bias=
  148494. hi->bitrate_reservoir_bias;
  148495. ci->bi.slew_damp=hi->bitrate_av_damp;
  148496. }
  148497. return(0);
  148498. }
  148499. static int vorbis_encode_setup_setting(vorbis_info *vi,
  148500. long channels,
  148501. long rate){
  148502. int ret=0,i,is;
  148503. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148504. highlevel_encode_setup *hi=&ci->hi;
  148505. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  148506. double ds;
  148507. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  148508. if(ret)return(ret);
  148509. is=hi->base_setting;
  148510. ds=hi->base_setting-is;
  148511. hi->short_setting=hi->base_setting;
  148512. hi->long_setting=hi->base_setting;
  148513. hi->managed=0;
  148514. hi->impulse_block_p=1;
  148515. hi->noise_normalize_p=1;
  148516. hi->stereo_point_setting=hi->base_setting;
  148517. hi->lowpass_kHz=
  148518. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  148519. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  148520. setup->psy_ath_float[is+1]*ds;
  148521. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  148522. setup->psy_ath_abs[is+1]*ds;
  148523. hi->amplitude_track_dBpersec=-6.;
  148524. hi->trigger_setting=hi->base_setting;
  148525. for(i=0;i<4;i++){
  148526. hi->block[i].tone_mask_setting=hi->base_setting;
  148527. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  148528. hi->block[i].noise_bias_setting=hi->base_setting;
  148529. hi->block[i].noise_compand_setting=hi->base_setting;
  148530. }
  148531. return(ret);
  148532. }
  148533. int vorbis_encode_setup_vbr(vorbis_info *vi,
  148534. long channels,
  148535. long rate,
  148536. float quality){
  148537. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148538. highlevel_encode_setup *hi=&ci->hi;
  148539. quality+=.0000001;
  148540. if(quality>=1.)quality=.9999;
  148541. get_setup_template(vi,channels,rate,quality,0);
  148542. if(!hi->setup)return OV_EIMPL;
  148543. return vorbis_encode_setup_setting(vi,channels,rate);
  148544. }
  148545. int vorbis_encode_init_vbr(vorbis_info *vi,
  148546. long channels,
  148547. long rate,
  148548. float base_quality /* 0. to 1. */
  148549. ){
  148550. int ret=0;
  148551. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  148552. if(ret){
  148553. vorbis_info_clear(vi);
  148554. return ret;
  148555. }
  148556. ret=vorbis_encode_setup_init(vi);
  148557. if(ret)
  148558. vorbis_info_clear(vi);
  148559. return(ret);
  148560. }
  148561. int vorbis_encode_setup_managed(vorbis_info *vi,
  148562. long channels,
  148563. long rate,
  148564. long max_bitrate,
  148565. long nominal_bitrate,
  148566. long min_bitrate){
  148567. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148568. highlevel_encode_setup *hi=&ci->hi;
  148569. double tnominal=nominal_bitrate;
  148570. int ret=0;
  148571. if(nominal_bitrate<=0.){
  148572. if(max_bitrate>0.){
  148573. if(min_bitrate>0.)
  148574. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  148575. else
  148576. nominal_bitrate=max_bitrate*.875;
  148577. }else{
  148578. if(min_bitrate>0.){
  148579. nominal_bitrate=min_bitrate;
  148580. }else{
  148581. return(OV_EINVAL);
  148582. }
  148583. }
  148584. }
  148585. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  148586. if(!hi->setup)return OV_EIMPL;
  148587. ret=vorbis_encode_setup_setting(vi,channels,rate);
  148588. if(ret){
  148589. vorbis_info_clear(vi);
  148590. return ret;
  148591. }
  148592. /* initialize management with sane defaults */
  148593. hi->managed=1;
  148594. hi->bitrate_min=min_bitrate;
  148595. hi->bitrate_max=max_bitrate;
  148596. hi->bitrate_av=tnominal;
  148597. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  148598. hi->bitrate_reservoir=nominal_bitrate*2;
  148599. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  148600. return(ret);
  148601. }
  148602. int vorbis_encode_init(vorbis_info *vi,
  148603. long channels,
  148604. long rate,
  148605. long max_bitrate,
  148606. long nominal_bitrate,
  148607. long min_bitrate){
  148608. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  148609. max_bitrate,
  148610. nominal_bitrate,
  148611. min_bitrate);
  148612. if(ret){
  148613. vorbis_info_clear(vi);
  148614. return(ret);
  148615. }
  148616. ret=vorbis_encode_setup_init(vi);
  148617. if(ret)
  148618. vorbis_info_clear(vi);
  148619. return(ret);
  148620. }
  148621. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  148622. if(vi){
  148623. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148624. highlevel_encode_setup *hi=&ci->hi;
  148625. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  148626. if(setp && hi->set_in_stone)return(OV_EINVAL);
  148627. switch(number){
  148628. /* now deprecated *****************/
  148629. case OV_ECTL_RATEMANAGE_GET:
  148630. {
  148631. struct ovectl_ratemanage_arg *ai=
  148632. (struct ovectl_ratemanage_arg *)arg;
  148633. ai->management_active=hi->managed;
  148634. ai->bitrate_hard_window=ai->bitrate_av_window=
  148635. (double)hi->bitrate_reservoir/vi->rate;
  148636. ai->bitrate_av_window_center=1.;
  148637. ai->bitrate_hard_min=hi->bitrate_min;
  148638. ai->bitrate_hard_max=hi->bitrate_max;
  148639. ai->bitrate_av_lo=hi->bitrate_av;
  148640. ai->bitrate_av_hi=hi->bitrate_av;
  148641. }
  148642. return(0);
  148643. /* now deprecated *****************/
  148644. case OV_ECTL_RATEMANAGE_SET:
  148645. {
  148646. struct ovectl_ratemanage_arg *ai=
  148647. (struct ovectl_ratemanage_arg *)arg;
  148648. if(ai==NULL){
  148649. hi->managed=0;
  148650. }else{
  148651. hi->managed=ai->management_active;
  148652. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  148653. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  148654. }
  148655. }
  148656. return 0;
  148657. /* now deprecated *****************/
  148658. case OV_ECTL_RATEMANAGE_AVG:
  148659. {
  148660. struct ovectl_ratemanage_arg *ai=
  148661. (struct ovectl_ratemanage_arg *)arg;
  148662. if(ai==NULL){
  148663. hi->bitrate_av=0;
  148664. }else{
  148665. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  148666. }
  148667. }
  148668. return(0);
  148669. /* now deprecated *****************/
  148670. case OV_ECTL_RATEMANAGE_HARD:
  148671. {
  148672. struct ovectl_ratemanage_arg *ai=
  148673. (struct ovectl_ratemanage_arg *)arg;
  148674. if(ai==NULL){
  148675. hi->bitrate_min=0;
  148676. hi->bitrate_max=0;
  148677. }else{
  148678. hi->bitrate_min=ai->bitrate_hard_min;
  148679. hi->bitrate_max=ai->bitrate_hard_max;
  148680. hi->bitrate_reservoir=ai->bitrate_hard_window*
  148681. (hi->bitrate_max+hi->bitrate_min)*.5;
  148682. }
  148683. if(hi->bitrate_reservoir<128.)
  148684. hi->bitrate_reservoir=128.;
  148685. }
  148686. return(0);
  148687. /* replacement ratemanage interface */
  148688. case OV_ECTL_RATEMANAGE2_GET:
  148689. {
  148690. struct ovectl_ratemanage2_arg *ai=
  148691. (struct ovectl_ratemanage2_arg *)arg;
  148692. if(ai==NULL)return OV_EINVAL;
  148693. ai->management_active=hi->managed;
  148694. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  148695. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  148696. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  148697. ai->bitrate_average_damping=hi->bitrate_av_damp;
  148698. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  148699. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  148700. }
  148701. return (0);
  148702. case OV_ECTL_RATEMANAGE2_SET:
  148703. {
  148704. struct ovectl_ratemanage2_arg *ai=
  148705. (struct ovectl_ratemanage2_arg *)arg;
  148706. if(ai==NULL){
  148707. hi->managed=0;
  148708. }else{
  148709. /* sanity check; only catch invariant violations */
  148710. if(ai->bitrate_limit_min_kbps>0 &&
  148711. ai->bitrate_average_kbps>0 &&
  148712. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  148713. return OV_EINVAL;
  148714. if(ai->bitrate_limit_max_kbps>0 &&
  148715. ai->bitrate_average_kbps>0 &&
  148716. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  148717. return OV_EINVAL;
  148718. if(ai->bitrate_limit_min_kbps>0 &&
  148719. ai->bitrate_limit_max_kbps>0 &&
  148720. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  148721. return OV_EINVAL;
  148722. if(ai->bitrate_average_damping <= 0.)
  148723. return OV_EINVAL;
  148724. if(ai->bitrate_limit_reservoir_bits < 0)
  148725. return OV_EINVAL;
  148726. if(ai->bitrate_limit_reservoir_bias < 0.)
  148727. return OV_EINVAL;
  148728. if(ai->bitrate_limit_reservoir_bias > 1.)
  148729. return OV_EINVAL;
  148730. hi->managed=ai->management_active;
  148731. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  148732. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  148733. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  148734. hi->bitrate_av_damp=ai->bitrate_average_damping;
  148735. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  148736. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  148737. }
  148738. }
  148739. return 0;
  148740. case OV_ECTL_LOWPASS_GET:
  148741. {
  148742. double *farg=(double *)arg;
  148743. *farg=hi->lowpass_kHz;
  148744. }
  148745. return(0);
  148746. case OV_ECTL_LOWPASS_SET:
  148747. {
  148748. double *farg=(double *)arg;
  148749. hi->lowpass_kHz=*farg;
  148750. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  148751. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  148752. }
  148753. return(0);
  148754. case OV_ECTL_IBLOCK_GET:
  148755. {
  148756. double *farg=(double *)arg;
  148757. *farg=hi->impulse_noisetune;
  148758. }
  148759. return(0);
  148760. case OV_ECTL_IBLOCK_SET:
  148761. {
  148762. double *farg=(double *)arg;
  148763. hi->impulse_noisetune=*farg;
  148764. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  148765. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  148766. }
  148767. return(0);
  148768. }
  148769. return(OV_EIMPL);
  148770. }
  148771. return(OV_EINVAL);
  148772. }
  148773. #endif
  148774. /********* End of inlined file: vorbisenc.c *********/
  148775. /********* Start of inlined file: vorbisfile.c *********/
  148776. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  148777. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  148778. // tasks..
  148779. #ifdef _MSC_VER
  148780. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  148781. #endif
  148782. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  148783. #if JUCE_USE_OGGVORBIS
  148784. #include <stdlib.h>
  148785. #include <stdio.h>
  148786. #include <errno.h>
  148787. #include <string.h>
  148788. #include <math.h>
  148789. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  148790. one logical bitstream arranged end to end (the only form of Ogg
  148791. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  148792. multiplexing] is not allowed in Vorbis) */
  148793. /* A Vorbis file can be played beginning to end (streamed) without
  148794. worrying ahead of time about chaining (see decoder_example.c). If
  148795. we have the whole file, however, and want random access
  148796. (seeking/scrubbing) or desire to know the total length/time of a
  148797. file, we need to account for the possibility of chaining. */
  148798. /* We can handle things a number of ways; we can determine the entire
  148799. bitstream structure right off the bat, or find pieces on demand.
  148800. This example determines and caches structure for the entire
  148801. bitstream, but builds a virtual decoder on the fly when moving
  148802. between links in the chain. */
  148803. /* There are also different ways to implement seeking. Enough
  148804. information exists in an Ogg bitstream to seek to
  148805. sample-granularity positions in the output. Or, one can seek by
  148806. picking some portion of the stream roughly in the desired area if
  148807. we only want coarse navigation through the stream. */
  148808. /*************************************************************************
  148809. * Many, many internal helpers. The intention is not to be confusing;
  148810. * rampant duplication and monolithic function implementation would be
  148811. * harder to understand anyway. The high level functions are last. Begin
  148812. * grokking near the end of the file */
  148813. /* read a little more data from the file/pipe into the ogg_sync framer
  148814. */
  148815. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  148816. over 8k gets what they deserve */
  148817. static long _get_data(OggVorbis_File *vf){
  148818. errno=0;
  148819. if(vf->datasource){
  148820. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  148821. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  148822. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  148823. if(bytes==0 && errno)return(-1);
  148824. return(bytes);
  148825. }else
  148826. return(0);
  148827. }
  148828. /* save a tiny smidge of verbosity to make the code more readable */
  148829. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  148830. if(vf->datasource){
  148831. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  148832. vf->offset=offset;
  148833. ogg_sync_reset(&vf->oy);
  148834. }else{
  148835. /* shouldn't happen unless someone writes a broken callback */
  148836. return;
  148837. }
  148838. }
  148839. /* The read/seek functions track absolute position within the stream */
  148840. /* from the head of the stream, get the next page. boundary specifies
  148841. if the function is allowed to fetch more data from the stream (and
  148842. how much) or only use internally buffered data.
  148843. boundary: -1) unbounded search
  148844. 0) read no additional data; use cached only
  148845. n) search for a new page beginning for n bytes
  148846. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  148847. n) found a page at absolute offset n */
  148848. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  148849. ogg_int64_t boundary){
  148850. if(boundary>0)boundary+=vf->offset;
  148851. while(1){
  148852. long more;
  148853. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  148854. more=ogg_sync_pageseek(&vf->oy,og);
  148855. if(more<0){
  148856. /* skipped n bytes */
  148857. vf->offset-=more;
  148858. }else{
  148859. if(more==0){
  148860. /* send more paramedics */
  148861. if(!boundary)return(OV_FALSE);
  148862. {
  148863. long ret=_get_data(vf);
  148864. if(ret==0)return(OV_EOF);
  148865. if(ret<0)return(OV_EREAD);
  148866. }
  148867. }else{
  148868. /* got a page. Return the offset at the page beginning,
  148869. advance the internal offset past the page end */
  148870. ogg_int64_t ret=vf->offset;
  148871. vf->offset+=more;
  148872. return(ret);
  148873. }
  148874. }
  148875. }
  148876. }
  148877. /* find the latest page beginning before the current stream cursor
  148878. position. Much dirtier than the above as Ogg doesn't have any
  148879. backward search linkage. no 'readp' as it will certainly have to
  148880. read. */
  148881. /* returns offset or OV_EREAD, OV_FAULT */
  148882. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  148883. ogg_int64_t begin=vf->offset;
  148884. ogg_int64_t end=begin;
  148885. ogg_int64_t ret;
  148886. ogg_int64_t offset=-1;
  148887. while(offset==-1){
  148888. begin-=CHUNKSIZE;
  148889. if(begin<0)
  148890. begin=0;
  148891. _seek_helper(vf,begin);
  148892. while(vf->offset<end){
  148893. ret=_get_next_page(vf,og,end-vf->offset);
  148894. if(ret==OV_EREAD)return(OV_EREAD);
  148895. if(ret<0){
  148896. break;
  148897. }else{
  148898. offset=ret;
  148899. }
  148900. }
  148901. }
  148902. /* we have the offset. Actually snork and hold the page now */
  148903. _seek_helper(vf,offset);
  148904. ret=_get_next_page(vf,og,CHUNKSIZE);
  148905. if(ret<0)
  148906. /* this shouldn't be possible */
  148907. return(OV_EFAULT);
  148908. return(offset);
  148909. }
  148910. /* finds each bitstream link one at a time using a bisection search
  148911. (has to begin by knowing the offset of the lb's initial page).
  148912. Recurses for each link so it can alloc the link storage after
  148913. finding them all, then unroll and fill the cache at the same time */
  148914. static int _bisect_forward_serialno(OggVorbis_File *vf,
  148915. ogg_int64_t begin,
  148916. ogg_int64_t searched,
  148917. ogg_int64_t end,
  148918. long currentno,
  148919. long m){
  148920. ogg_int64_t endsearched=end;
  148921. ogg_int64_t next=end;
  148922. ogg_page og;
  148923. ogg_int64_t ret;
  148924. /* the below guards against garbage seperating the last and
  148925. first pages of two links. */
  148926. while(searched<endsearched){
  148927. ogg_int64_t bisect;
  148928. if(endsearched-searched<CHUNKSIZE){
  148929. bisect=searched;
  148930. }else{
  148931. bisect=(searched+endsearched)/2;
  148932. }
  148933. _seek_helper(vf,bisect);
  148934. ret=_get_next_page(vf,&og,-1);
  148935. if(ret==OV_EREAD)return(OV_EREAD);
  148936. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  148937. endsearched=bisect;
  148938. if(ret>=0)next=ret;
  148939. }else{
  148940. searched=ret+og.header_len+og.body_len;
  148941. }
  148942. }
  148943. _seek_helper(vf,next);
  148944. ret=_get_next_page(vf,&og,-1);
  148945. if(ret==OV_EREAD)return(OV_EREAD);
  148946. if(searched>=end || ret<0){
  148947. vf->links=m+1;
  148948. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  148949. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  148950. vf->offsets[m+1]=searched;
  148951. }else{
  148952. ret=_bisect_forward_serialno(vf,next,vf->offset,
  148953. end,ogg_page_serialno(&og),m+1);
  148954. if(ret==OV_EREAD)return(OV_EREAD);
  148955. }
  148956. vf->offsets[m]=begin;
  148957. vf->serialnos[m]=currentno;
  148958. return(0);
  148959. }
  148960. /* uses the local ogg_stream storage in vf; this is important for
  148961. non-streaming input sources */
  148962. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  148963. long *serialno,ogg_page *og_ptr){
  148964. ogg_page og;
  148965. ogg_packet op;
  148966. int i,ret;
  148967. if(!og_ptr){
  148968. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  148969. if(llret==OV_EREAD)return(OV_EREAD);
  148970. if(llret<0)return OV_ENOTVORBIS;
  148971. og_ptr=&og;
  148972. }
  148973. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  148974. if(serialno)*serialno=vf->os.serialno;
  148975. vf->ready_state=STREAMSET;
  148976. /* extract the initial header from the first page and verify that the
  148977. Ogg bitstream is in fact Vorbis data */
  148978. vorbis_info_init(vi);
  148979. vorbis_comment_init(vc);
  148980. i=0;
  148981. while(i<3){
  148982. ogg_stream_pagein(&vf->os,og_ptr);
  148983. while(i<3){
  148984. int result=ogg_stream_packetout(&vf->os,&op);
  148985. if(result==0)break;
  148986. if(result==-1){
  148987. ret=OV_EBADHEADER;
  148988. goto bail_header;
  148989. }
  148990. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  148991. goto bail_header;
  148992. }
  148993. i++;
  148994. }
  148995. if(i<3)
  148996. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  148997. ret=OV_EBADHEADER;
  148998. goto bail_header;
  148999. }
  149000. }
  149001. return 0;
  149002. bail_header:
  149003. vorbis_info_clear(vi);
  149004. vorbis_comment_clear(vc);
  149005. vf->ready_state=OPENED;
  149006. return ret;
  149007. }
  149008. /* last step of the OggVorbis_File initialization; get all the
  149009. vorbis_info structs and PCM positions. Only called by the seekable
  149010. initialization (local stream storage is hacked slightly; pay
  149011. attention to how that's done) */
  149012. /* this is void and does not propogate errors up because we want to be
  149013. able to open and use damaged bitstreams as well as we can. Just
  149014. watch out for missing information for links in the OggVorbis_File
  149015. struct */
  149016. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  149017. ogg_page og;
  149018. int i;
  149019. ogg_int64_t ret;
  149020. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  149021. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  149022. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  149023. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  149024. for(i=0;i<vf->links;i++){
  149025. if(i==0){
  149026. /* we already grabbed the initial header earlier. Just set the offset */
  149027. vf->dataoffsets[i]=dataoffset;
  149028. _seek_helper(vf,dataoffset);
  149029. }else{
  149030. /* seek to the location of the initial header */
  149031. _seek_helper(vf,vf->offsets[i]);
  149032. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  149033. vf->dataoffsets[i]=-1;
  149034. }else{
  149035. vf->dataoffsets[i]=vf->offset;
  149036. }
  149037. }
  149038. /* fetch beginning PCM offset */
  149039. if(vf->dataoffsets[i]!=-1){
  149040. ogg_int64_t accumulated=0;
  149041. long lastblock=-1;
  149042. int result;
  149043. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  149044. while(1){
  149045. ogg_packet op;
  149046. ret=_get_next_page(vf,&og,-1);
  149047. if(ret<0)
  149048. /* this should not be possible unless the file is
  149049. truncated/mangled */
  149050. break;
  149051. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  149052. break;
  149053. /* count blocksizes of all frames in the page */
  149054. ogg_stream_pagein(&vf->os,&og);
  149055. while((result=ogg_stream_packetout(&vf->os,&op))){
  149056. if(result>0){ /* ignore holes */
  149057. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  149058. if(lastblock!=-1)
  149059. accumulated+=(lastblock+thisblock)>>2;
  149060. lastblock=thisblock;
  149061. }
  149062. }
  149063. if(ogg_page_granulepos(&og)!=-1){
  149064. /* pcm offset of last packet on the first audio page */
  149065. accumulated= ogg_page_granulepos(&og)-accumulated;
  149066. break;
  149067. }
  149068. }
  149069. /* less than zero? This is a stream with samples trimmed off
  149070. the beginning, a normal occurrence; set the offset to zero */
  149071. if(accumulated<0)accumulated=0;
  149072. vf->pcmlengths[i*2]=accumulated;
  149073. }
  149074. /* get the PCM length of this link. To do this,
  149075. get the last page of the stream */
  149076. {
  149077. ogg_int64_t end=vf->offsets[i+1];
  149078. _seek_helper(vf,end);
  149079. while(1){
  149080. ret=_get_prev_page(vf,&og);
  149081. if(ret<0){
  149082. /* this should not be possible */
  149083. vorbis_info_clear(vf->vi+i);
  149084. vorbis_comment_clear(vf->vc+i);
  149085. break;
  149086. }
  149087. if(ogg_page_granulepos(&og)!=-1){
  149088. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  149089. break;
  149090. }
  149091. vf->offset=ret;
  149092. }
  149093. }
  149094. }
  149095. }
  149096. static int _make_decode_ready(OggVorbis_File *vf){
  149097. if(vf->ready_state>STREAMSET)return 0;
  149098. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  149099. if(vf->seekable){
  149100. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  149101. return OV_EBADLINK;
  149102. }else{
  149103. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  149104. return OV_EBADLINK;
  149105. }
  149106. vorbis_block_init(&vf->vd,&vf->vb);
  149107. vf->ready_state=INITSET;
  149108. vf->bittrack=0.f;
  149109. vf->samptrack=0.f;
  149110. return 0;
  149111. }
  149112. static int _open_seekable2(OggVorbis_File *vf){
  149113. long serialno=vf->current_serialno;
  149114. ogg_int64_t dataoffset=vf->offset, end;
  149115. ogg_page og;
  149116. /* we're partially open and have a first link header state in
  149117. storage in vf */
  149118. /* we can seek, so set out learning all about this file */
  149119. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  149120. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  149121. /* We get the offset for the last page of the physical bitstream.
  149122. Most OggVorbis files will contain a single logical bitstream */
  149123. end=_get_prev_page(vf,&og);
  149124. if(end<0)return(end);
  149125. /* more than one logical bitstream? */
  149126. if(ogg_page_serialno(&og)!=serialno){
  149127. /* Chained bitstream. Bisect-search each logical bitstream
  149128. section. Do so based on serial number only */
  149129. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  149130. }else{
  149131. /* Only one logical bitstream */
  149132. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  149133. }
  149134. /* the initial header memory is referenced by vf after; don't free it */
  149135. _prefetch_all_headers(vf,dataoffset);
  149136. return(ov_raw_seek(vf,0));
  149137. }
  149138. /* clear out the current logical bitstream decoder */
  149139. static void _decode_clear(OggVorbis_File *vf){
  149140. vorbis_dsp_clear(&vf->vd);
  149141. vorbis_block_clear(&vf->vb);
  149142. vf->ready_state=OPENED;
  149143. }
  149144. /* fetch and process a packet. Handles the case where we're at a
  149145. bitstream boundary and dumps the decoding machine. If the decoding
  149146. machine is unloaded, it loads it. It also keeps pcm_offset up to
  149147. date (seek and read both use this. seek uses a special hack with
  149148. readp).
  149149. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  149150. 0) need more data (only if readp==0)
  149151. 1) got a packet
  149152. */
  149153. static int _fetch_and_process_packet(OggVorbis_File *vf,
  149154. ogg_packet *op_in,
  149155. int readp,
  149156. int spanp){
  149157. ogg_page og;
  149158. /* handle one packet. Try to fetch it from current stream state */
  149159. /* extract packets from page */
  149160. while(1){
  149161. /* process a packet if we can. If the machine isn't loaded,
  149162. neither is a page */
  149163. if(vf->ready_state==INITSET){
  149164. while(1) {
  149165. ogg_packet op;
  149166. ogg_packet *op_ptr=(op_in?op_in:&op);
  149167. int result=ogg_stream_packetout(&vf->os,op_ptr);
  149168. ogg_int64_t granulepos;
  149169. op_in=NULL;
  149170. if(result==-1)return(OV_HOLE); /* hole in the data. */
  149171. if(result>0){
  149172. /* got a packet. process it */
  149173. granulepos=op_ptr->granulepos;
  149174. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  149175. header handling. The
  149176. header packets aren't
  149177. audio, so if/when we
  149178. submit them,
  149179. vorbis_synthesis will
  149180. reject them */
  149181. /* suck in the synthesis data and track bitrate */
  149182. {
  149183. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149184. /* for proper use of libvorbis within libvorbisfile,
  149185. oldsamples will always be zero. */
  149186. if(oldsamples)return(OV_EFAULT);
  149187. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149188. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  149189. vf->bittrack+=op_ptr->bytes*8;
  149190. }
  149191. /* update the pcm offset. */
  149192. if(granulepos!=-1 && !op_ptr->e_o_s){
  149193. int link=(vf->seekable?vf->current_link:0);
  149194. int i,samples;
  149195. /* this packet has a pcm_offset on it (the last packet
  149196. completed on a page carries the offset) After processing
  149197. (above), we know the pcm position of the *last* sample
  149198. ready to be returned. Find the offset of the *first*
  149199. As an aside, this trick is inaccurate if we begin
  149200. reading anew right at the last page; the end-of-stream
  149201. granulepos declares the last frame in the stream, and the
  149202. last packet of the last page may be a partial frame.
  149203. So, we need a previous granulepos from an in-sequence page
  149204. to have a reference point. Thus the !op_ptr->e_o_s clause
  149205. above */
  149206. if(vf->seekable && link>0)
  149207. granulepos-=vf->pcmlengths[link*2];
  149208. if(granulepos<0)granulepos=0; /* actually, this
  149209. shouldn't be possible
  149210. here unless the stream
  149211. is very broken */
  149212. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149213. granulepos-=samples;
  149214. for(i=0;i<link;i++)
  149215. granulepos+=vf->pcmlengths[i*2+1];
  149216. vf->pcm_offset=granulepos;
  149217. }
  149218. return(1);
  149219. }
  149220. }
  149221. else
  149222. break;
  149223. }
  149224. }
  149225. if(vf->ready_state>=OPENED){
  149226. ogg_int64_t ret;
  149227. if(!readp)return(0);
  149228. if((ret=_get_next_page(vf,&og,-1))<0){
  149229. return(OV_EOF); /* eof.
  149230. leave unitialized */
  149231. }
  149232. /* bitrate tracking; add the header's bytes here, the body bytes
  149233. are done by packet above */
  149234. vf->bittrack+=og.header_len*8;
  149235. /* has our decoding just traversed a bitstream boundary? */
  149236. if(vf->ready_state==INITSET){
  149237. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149238. if(!spanp)
  149239. return(OV_EOF);
  149240. _decode_clear(vf);
  149241. if(!vf->seekable){
  149242. vorbis_info_clear(vf->vi);
  149243. vorbis_comment_clear(vf->vc);
  149244. }
  149245. }
  149246. }
  149247. }
  149248. /* Do we need to load a new machine before submitting the page? */
  149249. /* This is different in the seekable and non-seekable cases.
  149250. In the seekable case, we already have all the header
  149251. information loaded and cached; we just initialize the machine
  149252. with it and continue on our merry way.
  149253. In the non-seekable (streaming) case, we'll only be at a
  149254. boundary if we just left the previous logical bitstream and
  149255. we're now nominally at the header of the next bitstream
  149256. */
  149257. if(vf->ready_state!=INITSET){
  149258. int link;
  149259. if(vf->ready_state<STREAMSET){
  149260. if(vf->seekable){
  149261. vf->current_serialno=ogg_page_serialno(&og);
  149262. /* match the serialno to bitstream section. We use this rather than
  149263. offset positions to avoid problems near logical bitstream
  149264. boundaries */
  149265. for(link=0;link<vf->links;link++)
  149266. if(vf->serialnos[link]==vf->current_serialno)break;
  149267. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  149268. stream. error out,
  149269. leave machine
  149270. uninitialized */
  149271. vf->current_link=link;
  149272. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149273. vf->ready_state=STREAMSET;
  149274. }else{
  149275. /* we're streaming */
  149276. /* fetch the three header packets, build the info struct */
  149277. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  149278. if(ret)return(ret);
  149279. vf->current_link++;
  149280. link=0;
  149281. }
  149282. }
  149283. {
  149284. int ret=_make_decode_ready(vf);
  149285. if(ret<0)return ret;
  149286. }
  149287. }
  149288. ogg_stream_pagein(&vf->os,&og);
  149289. }
  149290. }
  149291. /* if, eg, 64 bit stdio is configured by default, this will build with
  149292. fseek64 */
  149293. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  149294. if(f==NULL)return(-1);
  149295. return fseek(f,off,whence);
  149296. }
  149297. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  149298. long ibytes, ov_callbacks callbacks){
  149299. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  149300. int ret;
  149301. memset(vf,0,sizeof(*vf));
  149302. vf->datasource=f;
  149303. vf->callbacks = callbacks;
  149304. /* init the framing state */
  149305. ogg_sync_init(&vf->oy);
  149306. /* perhaps some data was previously read into a buffer for testing
  149307. against other stream types. Allow initialization from this
  149308. previously read data (as we may be reading from a non-seekable
  149309. stream) */
  149310. if(initial){
  149311. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  149312. memcpy(buffer,initial,ibytes);
  149313. ogg_sync_wrote(&vf->oy,ibytes);
  149314. }
  149315. /* can we seek? Stevens suggests the seek test was portable */
  149316. if(offsettest!=-1)vf->seekable=1;
  149317. /* No seeking yet; Set up a 'single' (current) logical bitstream
  149318. entry for partial open */
  149319. vf->links=1;
  149320. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  149321. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  149322. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  149323. /* Try to fetch the headers, maintaining all the storage */
  149324. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  149325. vf->datasource=NULL;
  149326. ov_clear(vf);
  149327. }else
  149328. vf->ready_state=PARTOPEN;
  149329. return(ret);
  149330. }
  149331. static int _ov_open2(OggVorbis_File *vf){
  149332. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  149333. vf->ready_state=OPENED;
  149334. if(vf->seekable){
  149335. int ret=_open_seekable2(vf);
  149336. if(ret){
  149337. vf->datasource=NULL;
  149338. ov_clear(vf);
  149339. }
  149340. return(ret);
  149341. }else
  149342. vf->ready_state=STREAMSET;
  149343. return 0;
  149344. }
  149345. /* clear out the OggVorbis_File struct */
  149346. int ov_clear(OggVorbis_File *vf){
  149347. if(vf){
  149348. vorbis_block_clear(&vf->vb);
  149349. vorbis_dsp_clear(&vf->vd);
  149350. ogg_stream_clear(&vf->os);
  149351. if(vf->vi && vf->links){
  149352. int i;
  149353. for(i=0;i<vf->links;i++){
  149354. vorbis_info_clear(vf->vi+i);
  149355. vorbis_comment_clear(vf->vc+i);
  149356. }
  149357. _ogg_free(vf->vi);
  149358. _ogg_free(vf->vc);
  149359. }
  149360. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  149361. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  149362. if(vf->serialnos)_ogg_free(vf->serialnos);
  149363. if(vf->offsets)_ogg_free(vf->offsets);
  149364. ogg_sync_clear(&vf->oy);
  149365. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  149366. memset(vf,0,sizeof(*vf));
  149367. }
  149368. #ifdef DEBUG_LEAKS
  149369. _VDBG_dump();
  149370. #endif
  149371. return(0);
  149372. }
  149373. /* inspects the OggVorbis file and finds/documents all the logical
  149374. bitstreams contained in it. Tries to be tolerant of logical
  149375. bitstream sections that are truncated/woogie.
  149376. return: -1) error
  149377. 0) OK
  149378. */
  149379. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  149380. ov_callbacks callbacks){
  149381. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  149382. if(ret)return ret;
  149383. return _ov_open2(vf);
  149384. }
  149385. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  149386. ov_callbacks callbacks = {
  149387. (size_t (*)(void *, size_t, size_t, void *)) fread,
  149388. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  149389. (int (*)(void *)) fclose,
  149390. (long (*)(void *)) ftell
  149391. };
  149392. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  149393. }
  149394. /* cheap hack for game usage where downsampling is desirable; there's
  149395. no need for SRC as we can just do it cheaply in libvorbis. */
  149396. int ov_halfrate(OggVorbis_File *vf,int flag){
  149397. int i;
  149398. if(vf->vi==NULL)return OV_EINVAL;
  149399. if(!vf->seekable)return OV_EINVAL;
  149400. if(vf->ready_state>=STREAMSET)
  149401. _decode_clear(vf); /* clear out stream state; later on libvorbis
  149402. will be able to swap this on the fly, but
  149403. for now dumping the decode machine is needed
  149404. to reinit the MDCT lookups. 1.1 libvorbis
  149405. is planned to be able to switch on the fly */
  149406. for(i=0;i<vf->links;i++){
  149407. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  149408. ov_halfrate(vf,0);
  149409. return OV_EINVAL;
  149410. }
  149411. }
  149412. return 0;
  149413. }
  149414. int ov_halfrate_p(OggVorbis_File *vf){
  149415. if(vf->vi==NULL)return OV_EINVAL;
  149416. return vorbis_synthesis_halfrate_p(vf->vi);
  149417. }
  149418. /* Only partially open the vorbis file; test for Vorbisness, and load
  149419. the headers for the first chain. Do not seek (although test for
  149420. seekability). Use ov_test_open to finish opening the file, else
  149421. ov_clear to close/free it. Same return codes as open. */
  149422. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  149423. ov_callbacks callbacks)
  149424. {
  149425. return _ov_open1(f,vf,initial,ibytes,callbacks);
  149426. }
  149427. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  149428. ov_callbacks callbacks = {
  149429. (size_t (*)(void *, size_t, size_t, void *)) fread,
  149430. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  149431. (int (*)(void *)) fclose,
  149432. (long (*)(void *)) ftell
  149433. };
  149434. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  149435. }
  149436. int ov_test_open(OggVorbis_File *vf){
  149437. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  149438. return _ov_open2(vf);
  149439. }
  149440. /* How many logical bitstreams in this physical bitstream? */
  149441. long ov_streams(OggVorbis_File *vf){
  149442. return vf->links;
  149443. }
  149444. /* Is the FILE * associated with vf seekable? */
  149445. long ov_seekable(OggVorbis_File *vf){
  149446. return vf->seekable;
  149447. }
  149448. /* returns the bitrate for a given logical bitstream or the entire
  149449. physical bitstream. If the file is open for random access, it will
  149450. find the *actual* average bitrate. If the file is streaming, it
  149451. returns the nominal bitrate (if set) else the average of the
  149452. upper/lower bounds (if set) else -1 (unset).
  149453. If you want the actual bitrate field settings, get them from the
  149454. vorbis_info structs */
  149455. long ov_bitrate(OggVorbis_File *vf,int i){
  149456. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149457. if(i>=vf->links)return(OV_EINVAL);
  149458. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  149459. if(i<0){
  149460. ogg_int64_t bits=0;
  149461. int i;
  149462. float br;
  149463. for(i=0;i<vf->links;i++)
  149464. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  149465. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  149466. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  149467. * so this is slightly transformed to make it work.
  149468. */
  149469. br = bits/ov_time_total(vf,-1);
  149470. return(rint(br));
  149471. }else{
  149472. if(vf->seekable){
  149473. /* return the actual bitrate */
  149474. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  149475. }else{
  149476. /* return nominal if set */
  149477. if(vf->vi[i].bitrate_nominal>0){
  149478. return vf->vi[i].bitrate_nominal;
  149479. }else{
  149480. if(vf->vi[i].bitrate_upper>0){
  149481. if(vf->vi[i].bitrate_lower>0){
  149482. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  149483. }else{
  149484. return vf->vi[i].bitrate_upper;
  149485. }
  149486. }
  149487. return(OV_FALSE);
  149488. }
  149489. }
  149490. }
  149491. }
  149492. /* returns the actual bitrate since last call. returns -1 if no
  149493. additional data to offer since last call (or at beginning of stream),
  149494. EINVAL if stream is only partially open
  149495. */
  149496. long ov_bitrate_instant(OggVorbis_File *vf){
  149497. int link=(vf->seekable?vf->current_link:0);
  149498. long ret;
  149499. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149500. if(vf->samptrack==0)return(OV_FALSE);
  149501. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  149502. vf->bittrack=0.f;
  149503. vf->samptrack=0.f;
  149504. return(ret);
  149505. }
  149506. /* Guess */
  149507. long ov_serialnumber(OggVorbis_File *vf,int i){
  149508. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  149509. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  149510. if(i<0){
  149511. return(vf->current_serialno);
  149512. }else{
  149513. return(vf->serialnos[i]);
  149514. }
  149515. }
  149516. /* returns: total raw (compressed) length of content if i==-1
  149517. raw (compressed) length of that logical bitstream for i==0 to n
  149518. OV_EINVAL if the stream is not seekable (we can't know the length)
  149519. or if stream is only partially open
  149520. */
  149521. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  149522. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149523. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149524. if(i<0){
  149525. ogg_int64_t acc=0;
  149526. int i;
  149527. for(i=0;i<vf->links;i++)
  149528. acc+=ov_raw_total(vf,i);
  149529. return(acc);
  149530. }else{
  149531. return(vf->offsets[i+1]-vf->offsets[i]);
  149532. }
  149533. }
  149534. /* returns: total PCM length (samples) of content if i==-1 PCM length
  149535. (samples) of that logical bitstream for i==0 to n
  149536. OV_EINVAL if the stream is not seekable (we can't know the
  149537. length) or only partially open
  149538. */
  149539. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  149540. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149541. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149542. if(i<0){
  149543. ogg_int64_t acc=0;
  149544. int i;
  149545. for(i=0;i<vf->links;i++)
  149546. acc+=ov_pcm_total(vf,i);
  149547. return(acc);
  149548. }else{
  149549. return(vf->pcmlengths[i*2+1]);
  149550. }
  149551. }
  149552. /* returns: total seconds of content if i==-1
  149553. seconds in that logical bitstream for i==0 to n
  149554. OV_EINVAL if the stream is not seekable (we can't know the
  149555. length) or only partially open
  149556. */
  149557. double ov_time_total(OggVorbis_File *vf,int i){
  149558. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149559. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149560. if(i<0){
  149561. double acc=0;
  149562. int i;
  149563. for(i=0;i<vf->links;i++)
  149564. acc+=ov_time_total(vf,i);
  149565. return(acc);
  149566. }else{
  149567. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  149568. }
  149569. }
  149570. /* seek to an offset relative to the *compressed* data. This also
  149571. scans packets to update the PCM cursor. It will cross a logical
  149572. bitstream boundary, but only if it can't get any packets out of the
  149573. tail of the bitstream we seek to (so no surprises).
  149574. returns zero on success, nonzero on failure */
  149575. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  149576. ogg_stream_state work_os;
  149577. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149578. if(!vf->seekable)
  149579. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  149580. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  149581. /* don't yet clear out decoding machine (if it's initialized), in
  149582. the case we're in the same link. Restart the decode lapping, and
  149583. let _fetch_and_process_packet deal with a potential bitstream
  149584. boundary */
  149585. vf->pcm_offset=-1;
  149586. ogg_stream_reset_serialno(&vf->os,
  149587. vf->current_serialno); /* must set serialno */
  149588. vorbis_synthesis_restart(&vf->vd);
  149589. _seek_helper(vf,pos);
  149590. /* we need to make sure the pcm_offset is set, but we don't want to
  149591. advance the raw cursor past good packets just to get to the first
  149592. with a granulepos. That's not equivalent behavior to beginning
  149593. decoding as immediately after the seek position as possible.
  149594. So, a hack. We use two stream states; a local scratch state and
  149595. the shared vf->os stream state. We use the local state to
  149596. scan, and the shared state as a buffer for later decode.
  149597. Unfortuantely, on the last page we still advance to last packet
  149598. because the granulepos on the last page is not necessarily on a
  149599. packet boundary, and we need to make sure the granpos is
  149600. correct.
  149601. */
  149602. {
  149603. ogg_page og;
  149604. ogg_packet op;
  149605. int lastblock=0;
  149606. int accblock=0;
  149607. int thisblock;
  149608. int eosflag;
  149609. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  149610. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  149611. return from not necessarily
  149612. starting from the beginning */
  149613. while(1){
  149614. if(vf->ready_state>=STREAMSET){
  149615. /* snarf/scan a packet if we can */
  149616. int result=ogg_stream_packetout(&work_os,&op);
  149617. if(result>0){
  149618. if(vf->vi[vf->current_link].codec_setup){
  149619. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  149620. if(thisblock<0){
  149621. ogg_stream_packetout(&vf->os,NULL);
  149622. thisblock=0;
  149623. }else{
  149624. if(eosflag)
  149625. ogg_stream_packetout(&vf->os,NULL);
  149626. else
  149627. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  149628. }
  149629. if(op.granulepos!=-1){
  149630. int i,link=vf->current_link;
  149631. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  149632. if(granulepos<0)granulepos=0;
  149633. for(i=0;i<link;i++)
  149634. granulepos+=vf->pcmlengths[i*2+1];
  149635. vf->pcm_offset=granulepos-accblock;
  149636. break;
  149637. }
  149638. lastblock=thisblock;
  149639. continue;
  149640. }else
  149641. ogg_stream_packetout(&vf->os,NULL);
  149642. }
  149643. }
  149644. if(!lastblock){
  149645. if(_get_next_page(vf,&og,-1)<0){
  149646. vf->pcm_offset=ov_pcm_total(vf,-1);
  149647. break;
  149648. }
  149649. }else{
  149650. /* huh? Bogus stream with packets but no granulepos */
  149651. vf->pcm_offset=-1;
  149652. break;
  149653. }
  149654. /* has our decoding just traversed a bitstream boundary? */
  149655. if(vf->ready_state>=STREAMSET)
  149656. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149657. _decode_clear(vf); /* clear out stream state */
  149658. ogg_stream_clear(&work_os);
  149659. }
  149660. if(vf->ready_state<STREAMSET){
  149661. int link;
  149662. vf->current_serialno=ogg_page_serialno(&og);
  149663. for(link=0;link<vf->links;link++)
  149664. if(vf->serialnos[link]==vf->current_serialno)break;
  149665. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  149666. error out, leave
  149667. machine uninitialized */
  149668. vf->current_link=link;
  149669. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149670. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  149671. vf->ready_state=STREAMSET;
  149672. }
  149673. ogg_stream_pagein(&vf->os,&og);
  149674. ogg_stream_pagein(&work_os,&og);
  149675. eosflag=ogg_page_eos(&og);
  149676. }
  149677. }
  149678. ogg_stream_clear(&work_os);
  149679. vf->bittrack=0.f;
  149680. vf->samptrack=0.f;
  149681. return(0);
  149682. seek_error:
  149683. /* dump the machine so we're in a known state */
  149684. vf->pcm_offset=-1;
  149685. ogg_stream_clear(&work_os);
  149686. _decode_clear(vf);
  149687. return OV_EBADLINK;
  149688. }
  149689. /* Page granularity seek (faster than sample granularity because we
  149690. don't do the last bit of decode to find a specific sample).
  149691. Seek to the last [granule marked] page preceeding the specified pos
  149692. location, such that decoding past the returned point will quickly
  149693. arrive at the requested position. */
  149694. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  149695. int link=-1;
  149696. ogg_int64_t result=0;
  149697. ogg_int64_t total=ov_pcm_total(vf,-1);
  149698. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149699. if(!vf->seekable)return(OV_ENOSEEK);
  149700. if(pos<0 || pos>total)return(OV_EINVAL);
  149701. /* which bitstream section does this pcm offset occur in? */
  149702. for(link=vf->links-1;link>=0;link--){
  149703. total-=vf->pcmlengths[link*2+1];
  149704. if(pos>=total)break;
  149705. }
  149706. /* search within the logical bitstream for the page with the highest
  149707. pcm_pos preceeding (or equal to) pos. There is a danger here;
  149708. missing pages or incorrect frame number information in the
  149709. bitstream could make our task impossible. Account for that (it
  149710. would be an error condition) */
  149711. /* new search algorithm by HB (Nicholas Vinen) */
  149712. {
  149713. ogg_int64_t end=vf->offsets[link+1];
  149714. ogg_int64_t begin=vf->offsets[link];
  149715. ogg_int64_t begintime = vf->pcmlengths[link*2];
  149716. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  149717. ogg_int64_t target=pos-total+begintime;
  149718. ogg_int64_t best=begin;
  149719. ogg_page og;
  149720. while(begin<end){
  149721. ogg_int64_t bisect;
  149722. if(end-begin<CHUNKSIZE){
  149723. bisect=begin;
  149724. }else{
  149725. /* take a (pretty decent) guess. */
  149726. bisect=begin +
  149727. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  149728. if(bisect<=begin)
  149729. bisect=begin+1;
  149730. }
  149731. _seek_helper(vf,bisect);
  149732. while(begin<end){
  149733. result=_get_next_page(vf,&og,end-vf->offset);
  149734. if(result==OV_EREAD) goto seek_error;
  149735. if(result<0){
  149736. if(bisect<=begin+1)
  149737. end=begin; /* found it */
  149738. else{
  149739. if(bisect==0) goto seek_error;
  149740. bisect-=CHUNKSIZE;
  149741. if(bisect<=begin)bisect=begin+1;
  149742. _seek_helper(vf,bisect);
  149743. }
  149744. }else{
  149745. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  149746. if(granulepos==-1)continue;
  149747. if(granulepos<target){
  149748. best=result; /* raw offset of packet with granulepos */
  149749. begin=vf->offset; /* raw offset of next page */
  149750. begintime=granulepos;
  149751. if(target-begintime>44100)break;
  149752. bisect=begin; /* *not* begin + 1 */
  149753. }else{
  149754. if(bisect<=begin+1)
  149755. end=begin; /* found it */
  149756. else{
  149757. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  149758. end=result;
  149759. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  149760. if(bisect<=begin)bisect=begin+1;
  149761. _seek_helper(vf,bisect);
  149762. }else{
  149763. end=result;
  149764. endtime=granulepos;
  149765. break;
  149766. }
  149767. }
  149768. }
  149769. }
  149770. }
  149771. }
  149772. /* found our page. seek to it, update pcm offset. Easier case than
  149773. raw_seek, don't keep packets preceeding granulepos. */
  149774. {
  149775. ogg_page og;
  149776. ogg_packet op;
  149777. /* seek */
  149778. _seek_helper(vf,best);
  149779. vf->pcm_offset=-1;
  149780. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  149781. if(link!=vf->current_link){
  149782. /* Different link; dump entire decode machine */
  149783. _decode_clear(vf);
  149784. vf->current_link=link;
  149785. vf->current_serialno=ogg_page_serialno(&og);
  149786. vf->ready_state=STREAMSET;
  149787. }else{
  149788. vorbis_synthesis_restart(&vf->vd);
  149789. }
  149790. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149791. ogg_stream_pagein(&vf->os,&og);
  149792. /* pull out all but last packet; the one with granulepos */
  149793. while(1){
  149794. result=ogg_stream_packetpeek(&vf->os,&op);
  149795. if(result==0){
  149796. /* !!! the packet finishing this page originated on a
  149797. preceeding page. Keep fetching previous pages until we
  149798. get one with a granulepos or without the 'continued' flag
  149799. set. Then just use raw_seek for simplicity. */
  149800. _seek_helper(vf,best);
  149801. while(1){
  149802. result=_get_prev_page(vf,&og);
  149803. if(result<0) goto seek_error;
  149804. if(ogg_page_granulepos(&og)>-1 ||
  149805. !ogg_page_continued(&og)){
  149806. return ov_raw_seek(vf,result);
  149807. }
  149808. vf->offset=result;
  149809. }
  149810. }
  149811. if(result<0){
  149812. result = OV_EBADPACKET;
  149813. goto seek_error;
  149814. }
  149815. if(op.granulepos!=-1){
  149816. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  149817. if(vf->pcm_offset<0)vf->pcm_offset=0;
  149818. vf->pcm_offset+=total;
  149819. break;
  149820. }else
  149821. result=ogg_stream_packetout(&vf->os,NULL);
  149822. }
  149823. }
  149824. }
  149825. /* verify result */
  149826. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  149827. result=OV_EFAULT;
  149828. goto seek_error;
  149829. }
  149830. vf->bittrack=0.f;
  149831. vf->samptrack=0.f;
  149832. return(0);
  149833. seek_error:
  149834. /* dump machine so we're in a known state */
  149835. vf->pcm_offset=-1;
  149836. _decode_clear(vf);
  149837. return (int)result;
  149838. }
  149839. /* seek to a sample offset relative to the decompressed pcm stream
  149840. returns zero on success, nonzero on failure */
  149841. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  149842. int thisblock,lastblock=0;
  149843. int ret=ov_pcm_seek_page(vf,pos);
  149844. if(ret<0)return(ret);
  149845. if((ret=_make_decode_ready(vf)))return ret;
  149846. /* discard leading packets we don't need for the lapping of the
  149847. position we want; don't decode them */
  149848. while(1){
  149849. ogg_packet op;
  149850. ogg_page og;
  149851. int ret=ogg_stream_packetpeek(&vf->os,&op);
  149852. if(ret>0){
  149853. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  149854. if(thisblock<0){
  149855. ogg_stream_packetout(&vf->os,NULL);
  149856. continue; /* non audio packet */
  149857. }
  149858. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  149859. if(vf->pcm_offset+((thisblock+
  149860. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  149861. /* remove the packet from packet queue and track its granulepos */
  149862. ogg_stream_packetout(&vf->os,NULL);
  149863. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  149864. only tracking, no
  149865. pcm_decode */
  149866. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149867. /* end of logical stream case is hard, especially with exact
  149868. length positioning. */
  149869. if(op.granulepos>-1){
  149870. int i;
  149871. /* always believe the stream markers */
  149872. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  149873. if(vf->pcm_offset<0)vf->pcm_offset=0;
  149874. for(i=0;i<vf->current_link;i++)
  149875. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  149876. }
  149877. lastblock=thisblock;
  149878. }else{
  149879. if(ret<0 && ret!=OV_HOLE)break;
  149880. /* suck in a new page */
  149881. if(_get_next_page(vf,&og,-1)<0)break;
  149882. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  149883. if(vf->ready_state<STREAMSET){
  149884. int link;
  149885. vf->current_serialno=ogg_page_serialno(&og);
  149886. for(link=0;link<vf->links;link++)
  149887. if(vf->serialnos[link]==vf->current_serialno)break;
  149888. if(link==vf->links)return(OV_EBADLINK);
  149889. vf->current_link=link;
  149890. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149891. vf->ready_state=STREAMSET;
  149892. ret=_make_decode_ready(vf);
  149893. if(ret)return ret;
  149894. lastblock=0;
  149895. }
  149896. ogg_stream_pagein(&vf->os,&og);
  149897. }
  149898. }
  149899. vf->bittrack=0.f;
  149900. vf->samptrack=0.f;
  149901. /* discard samples until we reach the desired position. Crossing a
  149902. logical bitstream boundary with abandon is OK. */
  149903. while(vf->pcm_offset<pos){
  149904. ogg_int64_t target=pos-vf->pcm_offset;
  149905. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149906. if(samples>target)samples=target;
  149907. vorbis_synthesis_read(&vf->vd,samples);
  149908. vf->pcm_offset+=samples;
  149909. if(samples<target)
  149910. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  149911. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  149912. }
  149913. return 0;
  149914. }
  149915. /* seek to a playback time relative to the decompressed pcm stream
  149916. returns zero on success, nonzero on failure */
  149917. int ov_time_seek(OggVorbis_File *vf,double seconds){
  149918. /* translate time to PCM position and call ov_pcm_seek */
  149919. int link=-1;
  149920. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  149921. double time_total=ov_time_total(vf,-1);
  149922. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149923. if(!vf->seekable)return(OV_ENOSEEK);
  149924. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  149925. /* which bitstream section does this time offset occur in? */
  149926. for(link=vf->links-1;link>=0;link--){
  149927. pcm_total-=vf->pcmlengths[link*2+1];
  149928. time_total-=ov_time_total(vf,link);
  149929. if(seconds>=time_total)break;
  149930. }
  149931. /* enough information to convert time offset to pcm offset */
  149932. {
  149933. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  149934. return(ov_pcm_seek(vf,target));
  149935. }
  149936. }
  149937. /* page-granularity version of ov_time_seek
  149938. returns zero on success, nonzero on failure */
  149939. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  149940. /* translate time to PCM position and call ov_pcm_seek */
  149941. int link=-1;
  149942. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  149943. double time_total=ov_time_total(vf,-1);
  149944. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149945. if(!vf->seekable)return(OV_ENOSEEK);
  149946. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  149947. /* which bitstream section does this time offset occur in? */
  149948. for(link=vf->links-1;link>=0;link--){
  149949. pcm_total-=vf->pcmlengths[link*2+1];
  149950. time_total-=ov_time_total(vf,link);
  149951. if(seconds>=time_total)break;
  149952. }
  149953. /* enough information to convert time offset to pcm offset */
  149954. {
  149955. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  149956. return(ov_pcm_seek_page(vf,target));
  149957. }
  149958. }
  149959. /* tell the current stream offset cursor. Note that seek followed by
  149960. tell will likely not give the set offset due to caching */
  149961. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  149962. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149963. return(vf->offset);
  149964. }
  149965. /* return PCM offset (sample) of next PCM sample to be read */
  149966. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  149967. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149968. return(vf->pcm_offset);
  149969. }
  149970. /* return time offset (seconds) of next PCM sample to be read */
  149971. double ov_time_tell(OggVorbis_File *vf){
  149972. int link=0;
  149973. ogg_int64_t pcm_total=0;
  149974. double time_total=0.f;
  149975. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149976. if(vf->seekable){
  149977. pcm_total=ov_pcm_total(vf,-1);
  149978. time_total=ov_time_total(vf,-1);
  149979. /* which bitstream section does this time offset occur in? */
  149980. for(link=vf->links-1;link>=0;link--){
  149981. pcm_total-=vf->pcmlengths[link*2+1];
  149982. time_total-=ov_time_total(vf,link);
  149983. if(vf->pcm_offset>=pcm_total)break;
  149984. }
  149985. }
  149986. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  149987. }
  149988. /* link: -1) return the vorbis_info struct for the bitstream section
  149989. currently being decoded
  149990. 0-n) to request information for a specific bitstream section
  149991. In the case of a non-seekable bitstream, any call returns the
  149992. current bitstream. NULL in the case that the machine is not
  149993. initialized */
  149994. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  149995. if(vf->seekable){
  149996. if(link<0)
  149997. if(vf->ready_state>=STREAMSET)
  149998. return vf->vi+vf->current_link;
  149999. else
  150000. return vf->vi;
  150001. else
  150002. if(link>=vf->links)
  150003. return NULL;
  150004. else
  150005. return vf->vi+link;
  150006. }else{
  150007. return vf->vi;
  150008. }
  150009. }
  150010. /* grr, strong typing, grr, no templates/inheritence, grr */
  150011. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  150012. if(vf->seekable){
  150013. if(link<0)
  150014. if(vf->ready_state>=STREAMSET)
  150015. return vf->vc+vf->current_link;
  150016. else
  150017. return vf->vc;
  150018. else
  150019. if(link>=vf->links)
  150020. return NULL;
  150021. else
  150022. return vf->vc+link;
  150023. }else{
  150024. return vf->vc;
  150025. }
  150026. }
  150027. static int host_is_big_endian() {
  150028. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  150029. unsigned char *bytewise = (unsigned char *)&pattern;
  150030. if (bytewise[0] == 0xfe) return 1;
  150031. return 0;
  150032. }
  150033. /* up to this point, everything could more or less hide the multiple
  150034. logical bitstream nature of chaining from the toplevel application
  150035. if the toplevel application didn't particularly care. However, at
  150036. the point that we actually read audio back, the multiple-section
  150037. nature must surface: Multiple bitstream sections do not necessarily
  150038. have to have the same number of channels or sampling rate.
  150039. ov_read returns the sequential logical bitstream number currently
  150040. being decoded along with the PCM data in order that the toplevel
  150041. application can take action on channel/sample rate changes. This
  150042. number will be incremented even for streamed (non-seekable) streams
  150043. (for seekable streams, it represents the actual logical bitstream
  150044. index within the physical bitstream. Note that the accessor
  150045. functions above are aware of this dichotomy).
  150046. input values: buffer) a buffer to hold packed PCM data for return
  150047. length) the byte length requested to be placed into buffer
  150048. bigendianp) should the data be packed LSB first (0) or
  150049. MSB first (1)
  150050. word) word size for output. currently 1 (byte) or
  150051. 2 (16 bit short)
  150052. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150053. 0) EOF
  150054. n) number of bytes of PCM actually returned. The
  150055. below works on a packet-by-packet basis, so the
  150056. return length is not related to the 'length' passed
  150057. in, just guaranteed to fit.
  150058. *section) set to the logical bitstream number */
  150059. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  150060. int bigendianp,int word,int sgned,int *bitstream){
  150061. int i,j;
  150062. int host_endian = host_is_big_endian();
  150063. float **pcm;
  150064. long samples;
  150065. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150066. while(1){
  150067. if(vf->ready_state==INITSET){
  150068. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150069. if(samples)break;
  150070. }
  150071. /* suck in another packet */
  150072. {
  150073. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150074. if(ret==OV_EOF)
  150075. return(0);
  150076. if(ret<=0)
  150077. return(ret);
  150078. }
  150079. }
  150080. if(samples>0){
  150081. /* yay! proceed to pack data into the byte buffer */
  150082. long channels=ov_info(vf,-1)->channels;
  150083. long bytespersample=word * channels;
  150084. vorbis_fpu_control fpu;
  150085. (void) fpu; // (to avoid a warning about it being unused)
  150086. if(samples>length/bytespersample)samples=length/bytespersample;
  150087. if(samples <= 0)
  150088. return OV_EINVAL;
  150089. /* a tight loop to pack each size */
  150090. {
  150091. int val;
  150092. if(word==1){
  150093. int off=(sgned?0:128);
  150094. vorbis_fpu_setround(&fpu);
  150095. for(j=0;j<samples;j++)
  150096. for(i=0;i<channels;i++){
  150097. val=vorbis_ftoi(pcm[i][j]*128.f);
  150098. if(val>127)val=127;
  150099. else if(val<-128)val=-128;
  150100. *buffer++=val+off;
  150101. }
  150102. vorbis_fpu_restore(fpu);
  150103. }else{
  150104. int off=(sgned?0:32768);
  150105. if(host_endian==bigendianp){
  150106. if(sgned){
  150107. vorbis_fpu_setround(&fpu);
  150108. for(i=0;i<channels;i++) { /* It's faster in this order */
  150109. float *src=pcm[i];
  150110. short *dest=((short *)buffer)+i;
  150111. for(j=0;j<samples;j++) {
  150112. val=vorbis_ftoi(src[j]*32768.f);
  150113. if(val>32767)val=32767;
  150114. else if(val<-32768)val=-32768;
  150115. *dest=val;
  150116. dest+=channels;
  150117. }
  150118. }
  150119. vorbis_fpu_restore(fpu);
  150120. }else{
  150121. vorbis_fpu_setround(&fpu);
  150122. for(i=0;i<channels;i++) {
  150123. float *src=pcm[i];
  150124. short *dest=((short *)buffer)+i;
  150125. for(j=0;j<samples;j++) {
  150126. val=vorbis_ftoi(src[j]*32768.f);
  150127. if(val>32767)val=32767;
  150128. else if(val<-32768)val=-32768;
  150129. *dest=val+off;
  150130. dest+=channels;
  150131. }
  150132. }
  150133. vorbis_fpu_restore(fpu);
  150134. }
  150135. }else if(bigendianp){
  150136. vorbis_fpu_setround(&fpu);
  150137. for(j=0;j<samples;j++)
  150138. for(i=0;i<channels;i++){
  150139. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150140. if(val>32767)val=32767;
  150141. else if(val<-32768)val=-32768;
  150142. val+=off;
  150143. *buffer++=(val>>8);
  150144. *buffer++=(val&0xff);
  150145. }
  150146. vorbis_fpu_restore(fpu);
  150147. }else{
  150148. int val;
  150149. vorbis_fpu_setround(&fpu);
  150150. for(j=0;j<samples;j++)
  150151. for(i=0;i<channels;i++){
  150152. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150153. if(val>32767)val=32767;
  150154. else if(val<-32768)val=-32768;
  150155. val+=off;
  150156. *buffer++=(val&0xff);
  150157. *buffer++=(val>>8);
  150158. }
  150159. vorbis_fpu_restore(fpu);
  150160. }
  150161. }
  150162. }
  150163. vorbis_synthesis_read(&vf->vd,samples);
  150164. vf->pcm_offset+=samples;
  150165. if(bitstream)*bitstream=vf->current_link;
  150166. return(samples*bytespersample);
  150167. }else{
  150168. return(samples);
  150169. }
  150170. }
  150171. /* input values: pcm_channels) a float vector per channel of output
  150172. length) the sample length being read by the app
  150173. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150174. 0) EOF
  150175. n) number of samples of PCM actually returned. The
  150176. below works on a packet-by-packet basis, so the
  150177. return length is not related to the 'length' passed
  150178. in, just guaranteed to fit.
  150179. *section) set to the logical bitstream number */
  150180. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  150181. int *bitstream){
  150182. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150183. while(1){
  150184. if(vf->ready_state==INITSET){
  150185. float **pcm;
  150186. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150187. if(samples){
  150188. if(pcm_channels)*pcm_channels=pcm;
  150189. if(samples>length)samples=length;
  150190. vorbis_synthesis_read(&vf->vd,samples);
  150191. vf->pcm_offset+=samples;
  150192. if(bitstream)*bitstream=vf->current_link;
  150193. return samples;
  150194. }
  150195. }
  150196. /* suck in another packet */
  150197. {
  150198. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150199. if(ret==OV_EOF)return(0);
  150200. if(ret<=0)return(ret);
  150201. }
  150202. }
  150203. }
  150204. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  150205. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  150206. ogg_int64_t off);
  150207. static void _ov_splice(float **pcm,float **lappcm,
  150208. int n1, int n2,
  150209. int ch1, int ch2,
  150210. float *w1, float *w2){
  150211. int i,j;
  150212. float *w=w1;
  150213. int n=n1;
  150214. if(n1>n2){
  150215. n=n2;
  150216. w=w2;
  150217. }
  150218. /* splice */
  150219. for(j=0;j<ch1 && j<ch2;j++){
  150220. float *s=lappcm[j];
  150221. float *d=pcm[j];
  150222. for(i=0;i<n;i++){
  150223. float wd=w[i]*w[i];
  150224. float ws=1.-wd;
  150225. d[i]=d[i]*wd + s[i]*ws;
  150226. }
  150227. }
  150228. /* window from zero */
  150229. for(;j<ch2;j++){
  150230. float *d=pcm[j];
  150231. for(i=0;i<n;i++){
  150232. float wd=w[i]*w[i];
  150233. d[i]=d[i]*wd;
  150234. }
  150235. }
  150236. }
  150237. /* make sure vf is INITSET */
  150238. static int _ov_initset(OggVorbis_File *vf){
  150239. while(1){
  150240. if(vf->ready_state==INITSET)break;
  150241. /* suck in another packet */
  150242. {
  150243. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150244. if(ret<0 && ret!=OV_HOLE)return(ret);
  150245. }
  150246. }
  150247. return 0;
  150248. }
  150249. /* make sure vf is INITSET and that we have a primed buffer; if
  150250. we're crosslapping at a stream section boundary, this also makes
  150251. sure we're sanity checking against the right stream information */
  150252. static int _ov_initprime(OggVorbis_File *vf){
  150253. vorbis_dsp_state *vd=&vf->vd;
  150254. while(1){
  150255. if(vf->ready_state==INITSET)
  150256. if(vorbis_synthesis_pcmout(vd,NULL))break;
  150257. /* suck in another packet */
  150258. {
  150259. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150260. if(ret<0 && ret!=OV_HOLE)return(ret);
  150261. }
  150262. }
  150263. return 0;
  150264. }
  150265. /* grab enough data for lapping from vf; this may be in the form of
  150266. unreturned, already-decoded pcm, remaining PCM we will need to
  150267. decode, or synthetic postextrapolation from last packets. */
  150268. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  150269. float **lappcm,int lapsize){
  150270. int lapcount=0,i;
  150271. float **pcm;
  150272. /* try first to decode the lapping data */
  150273. while(lapcount<lapsize){
  150274. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  150275. if(samples){
  150276. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150277. for(i=0;i<vi->channels;i++)
  150278. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150279. lapcount+=samples;
  150280. vorbis_synthesis_read(vd,samples);
  150281. }else{
  150282. /* suck in another packet */
  150283. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  150284. if(ret==OV_EOF)break;
  150285. }
  150286. }
  150287. if(lapcount<lapsize){
  150288. /* failed to get lapping data from normal decode; pry it from the
  150289. postextrapolation buffering, or the second half of the MDCT
  150290. from the last packet */
  150291. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  150292. if(samples==0){
  150293. for(i=0;i<vi->channels;i++)
  150294. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  150295. lapcount=lapsize;
  150296. }else{
  150297. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150298. for(i=0;i<vi->channels;i++)
  150299. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150300. lapcount+=samples;
  150301. }
  150302. }
  150303. }
  150304. /* this sets up crosslapping of a sample by using trailing data from
  150305. sample 1 and lapping it into the windowing buffer of sample 2 */
  150306. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  150307. vorbis_info *vi1,*vi2;
  150308. float **lappcm;
  150309. float **pcm;
  150310. float *w1,*w2;
  150311. int n1,n2,i,ret,hs1,hs2;
  150312. if(vf1==vf2)return(0); /* degenerate case */
  150313. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  150314. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  150315. /* the relevant overlap buffers must be pre-checked and pre-primed
  150316. before looking at settings in the event that priming would cross
  150317. a bitstream boundary. So, do it now */
  150318. ret=_ov_initset(vf1);
  150319. if(ret)return(ret);
  150320. ret=_ov_initprime(vf2);
  150321. if(ret)return(ret);
  150322. vi1=ov_info(vf1,-1);
  150323. vi2=ov_info(vf2,-1);
  150324. hs1=ov_halfrate_p(vf1);
  150325. hs2=ov_halfrate_p(vf2);
  150326. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  150327. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  150328. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  150329. w1=vorbis_window(&vf1->vd,0);
  150330. w2=vorbis_window(&vf2->vd,0);
  150331. for(i=0;i<vi1->channels;i++)
  150332. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150333. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  150334. /* have a lapping buffer from vf1; now to splice it into the lapping
  150335. buffer of vf2 */
  150336. /* consolidate and expose the buffer. */
  150337. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  150338. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  150339. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  150340. /* splice */
  150341. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  150342. /* done */
  150343. return(0);
  150344. }
  150345. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  150346. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  150347. vorbis_info *vi;
  150348. float **lappcm;
  150349. float **pcm;
  150350. float *w1,*w2;
  150351. int n1,n2,ch1,ch2,hs;
  150352. int i,ret;
  150353. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150354. ret=_ov_initset(vf);
  150355. if(ret)return(ret);
  150356. vi=ov_info(vf,-1);
  150357. hs=ov_halfrate_p(vf);
  150358. ch1=vi->channels;
  150359. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  150360. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  150361. persistent; even if the decode state
  150362. from this link gets dumped, this
  150363. window array continues to exist */
  150364. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  150365. for(i=0;i<ch1;i++)
  150366. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150367. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  150368. /* have lapping data; seek and prime the buffer */
  150369. ret=localseek(vf,pos);
  150370. if(ret)return ret;
  150371. ret=_ov_initprime(vf);
  150372. if(ret)return(ret);
  150373. /* Guard against cross-link changes; they're perfectly legal */
  150374. vi=ov_info(vf,-1);
  150375. ch2=vi->channels;
  150376. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  150377. w2=vorbis_window(&vf->vd,0);
  150378. /* consolidate and expose the buffer. */
  150379. vorbis_synthesis_lapout(&vf->vd,&pcm);
  150380. /* splice */
  150381. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  150382. /* done */
  150383. return(0);
  150384. }
  150385. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150386. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  150387. }
  150388. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150389. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  150390. }
  150391. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150392. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  150393. }
  150394. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  150395. int (*localseek)(OggVorbis_File *,double)){
  150396. vorbis_info *vi;
  150397. float **lappcm;
  150398. float **pcm;
  150399. float *w1,*w2;
  150400. int n1,n2,ch1,ch2,hs;
  150401. int i,ret;
  150402. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150403. ret=_ov_initset(vf);
  150404. if(ret)return(ret);
  150405. vi=ov_info(vf,-1);
  150406. hs=ov_halfrate_p(vf);
  150407. ch1=vi->channels;
  150408. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  150409. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  150410. persistent; even if the decode state
  150411. from this link gets dumped, this
  150412. window array continues to exist */
  150413. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  150414. for(i=0;i<ch1;i++)
  150415. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150416. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  150417. /* have lapping data; seek and prime the buffer */
  150418. ret=localseek(vf,pos);
  150419. if(ret)return ret;
  150420. ret=_ov_initprime(vf);
  150421. if(ret)return(ret);
  150422. /* Guard against cross-link changes; they're perfectly legal */
  150423. vi=ov_info(vf,-1);
  150424. ch2=vi->channels;
  150425. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  150426. w2=vorbis_window(&vf->vd,0);
  150427. /* consolidate and expose the buffer. */
  150428. vorbis_synthesis_lapout(&vf->vd,&pcm);
  150429. /* splice */
  150430. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  150431. /* done */
  150432. return(0);
  150433. }
  150434. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  150435. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  150436. }
  150437. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  150438. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  150439. }
  150440. #endif
  150441. /********* End of inlined file: vorbisfile.c *********/
  150442. /********* Start of inlined file: window.c *********/
  150443. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  150444. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  150445. // tasks..
  150446. #ifdef _MSC_VER
  150447. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  150448. #endif
  150449. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  150450. #if JUCE_USE_OGGVORBIS
  150451. #include <stdlib.h>
  150452. #include <math.h>
  150453. static float vwin64[32] = {
  150454. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  150455. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  150456. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  150457. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  150458. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  150459. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  150460. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  150461. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  150462. };
  150463. static float vwin128[64] = {
  150464. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  150465. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  150466. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  150467. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  150468. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  150469. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  150470. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  150471. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  150472. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  150473. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  150474. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  150475. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  150476. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  150477. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  150478. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  150479. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  150480. };
  150481. static float vwin256[128] = {
  150482. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  150483. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  150484. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  150485. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  150486. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  150487. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  150488. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  150489. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  150490. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  150491. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  150492. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  150493. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  150494. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  150495. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  150496. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  150497. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  150498. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  150499. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  150500. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  150501. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  150502. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  150503. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  150504. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  150505. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  150506. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  150507. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  150508. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  150509. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  150510. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  150511. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  150512. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  150513. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  150514. };
  150515. static float vwin512[256] = {
  150516. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  150517. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  150518. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  150519. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  150520. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  150521. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  150522. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  150523. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  150524. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  150525. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  150526. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  150527. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  150528. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  150529. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  150530. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  150531. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  150532. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  150533. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  150534. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  150535. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  150536. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  150537. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  150538. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  150539. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  150540. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  150541. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  150542. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  150543. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  150544. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  150545. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  150546. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  150547. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  150548. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  150549. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  150550. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  150551. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  150552. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  150553. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  150554. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  150555. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  150556. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  150557. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  150558. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  150559. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  150560. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  150561. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  150562. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  150563. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  150564. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  150565. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  150566. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  150567. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  150568. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  150569. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  150570. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  150571. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  150572. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  150573. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  150574. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  150575. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  150576. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  150577. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  150578. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  150579. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  150580. };
  150581. static float vwin1024[512] = {
  150582. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  150583. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  150584. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  150585. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  150586. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  150587. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  150588. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  150589. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  150590. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  150591. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  150592. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  150593. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  150594. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  150595. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  150596. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  150597. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  150598. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  150599. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  150600. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  150601. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  150602. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  150603. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  150604. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  150605. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  150606. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  150607. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  150608. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  150609. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  150610. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  150611. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  150612. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  150613. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  150614. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  150615. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  150616. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  150617. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  150618. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  150619. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  150620. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  150621. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  150622. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  150623. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  150624. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  150625. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  150626. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  150627. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  150628. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  150629. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  150630. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  150631. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  150632. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  150633. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  150634. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  150635. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  150636. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  150637. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  150638. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  150639. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  150640. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  150641. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  150642. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  150643. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  150644. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  150645. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  150646. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  150647. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  150648. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  150649. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  150650. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  150651. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  150652. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  150653. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  150654. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  150655. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  150656. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  150657. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  150658. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  150659. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  150660. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  150661. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  150662. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  150663. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  150664. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  150665. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  150666. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  150667. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  150668. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  150669. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  150670. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  150671. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  150672. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  150673. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  150674. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  150675. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  150676. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  150677. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  150678. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  150679. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  150680. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  150681. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  150682. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  150683. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  150684. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  150685. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  150686. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  150687. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  150688. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  150689. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  150690. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  150691. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  150692. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  150693. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  150694. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  150695. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  150696. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  150697. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  150698. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  150699. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  150700. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  150701. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  150702. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  150703. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  150704. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  150705. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  150706. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  150707. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  150708. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  150709. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  150710. };
  150711. static float vwin2048[1024] = {
  150712. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  150713. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  150714. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  150715. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  150716. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  150717. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  150718. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  150719. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  150720. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  150721. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  150722. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  150723. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  150724. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  150725. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  150726. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  150727. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  150728. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  150729. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  150730. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  150731. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  150732. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  150733. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  150734. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  150735. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  150736. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  150737. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  150738. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  150739. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  150740. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  150741. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  150742. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  150743. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  150744. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  150745. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  150746. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  150747. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  150748. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  150749. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  150750. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  150751. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  150752. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  150753. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  150754. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  150755. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  150756. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  150757. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  150758. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  150759. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  150760. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  150761. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  150762. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  150763. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  150764. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  150765. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  150766. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  150767. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  150768. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  150769. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  150770. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  150771. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  150772. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  150773. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  150774. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  150775. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  150776. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  150777. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  150778. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  150779. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  150780. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  150781. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  150782. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  150783. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  150784. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  150785. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  150786. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  150787. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  150788. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  150789. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  150790. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  150791. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  150792. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  150793. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  150794. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  150795. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  150796. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  150797. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  150798. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  150799. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  150800. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  150801. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  150802. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  150803. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  150804. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  150805. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  150806. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  150807. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  150808. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  150809. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  150810. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  150811. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  150812. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  150813. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  150814. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  150815. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  150816. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  150817. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  150818. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  150819. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  150820. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  150821. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  150822. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  150823. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  150824. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  150825. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  150826. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  150827. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  150828. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  150829. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  150830. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  150831. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  150832. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  150833. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  150834. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  150835. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  150836. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  150837. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  150838. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  150839. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  150840. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  150841. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  150842. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  150843. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  150844. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  150845. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  150846. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  150847. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  150848. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  150849. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  150850. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  150851. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  150852. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  150853. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  150854. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  150855. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  150856. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  150857. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  150858. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  150859. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  150860. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  150861. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  150862. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  150863. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  150864. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  150865. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  150866. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  150867. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  150868. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  150869. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  150870. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  150871. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  150872. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  150873. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  150874. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  150875. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  150876. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  150877. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  150878. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  150879. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  150880. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  150881. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  150882. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  150883. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  150884. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  150885. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  150886. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  150887. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  150888. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  150889. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  150890. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  150891. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  150892. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  150893. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  150894. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  150895. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  150896. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  150897. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  150898. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  150899. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  150900. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  150901. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  150902. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  150903. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  150904. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  150905. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  150906. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  150907. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  150908. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  150909. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  150910. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  150911. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  150912. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  150913. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  150914. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  150915. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  150916. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  150917. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  150918. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  150919. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  150920. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  150921. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  150922. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  150923. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  150924. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  150925. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  150926. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  150927. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  150928. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  150929. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  150930. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  150931. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  150932. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  150933. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  150934. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  150935. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  150936. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  150937. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  150938. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  150939. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  150940. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  150941. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  150942. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  150943. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  150944. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  150945. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  150946. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  150947. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  150948. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  150949. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  150950. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  150951. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  150952. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  150953. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  150954. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  150955. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  150956. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  150957. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  150958. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  150959. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  150960. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  150961. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  150962. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  150963. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  150964. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  150965. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  150966. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  150967. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  150968. };
  150969. static float vwin4096[2048] = {
  150970. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  150971. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  150972. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  150973. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  150974. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  150975. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  150976. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  150977. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  150978. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  150979. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  150980. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  150981. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  150982. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  150983. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  150984. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  150985. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  150986. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  150987. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  150988. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  150989. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  150990. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  150991. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  150992. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  150993. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  150994. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  150995. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  150996. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  150997. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  150998. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  150999. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  151000. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  151001. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  151002. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  151003. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  151004. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  151005. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  151006. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  151007. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  151008. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  151009. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  151010. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  151011. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  151012. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  151013. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  151014. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  151015. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  151016. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  151017. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  151018. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  151019. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  151020. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  151021. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  151022. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  151023. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  151024. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  151025. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  151026. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  151027. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  151028. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  151029. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  151030. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  151031. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  151032. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  151033. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  151034. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  151035. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  151036. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  151037. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  151038. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  151039. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  151040. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  151041. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  151042. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  151043. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  151044. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  151045. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  151046. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  151047. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  151048. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  151049. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  151050. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  151051. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  151052. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  151053. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  151054. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  151055. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  151056. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  151057. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  151058. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  151059. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  151060. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  151061. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  151062. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  151063. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  151064. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  151065. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  151066. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  151067. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  151068. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  151069. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  151070. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  151071. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  151072. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  151073. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  151074. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  151075. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  151076. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  151077. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  151078. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  151079. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  151080. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  151081. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  151082. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  151083. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  151084. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  151085. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  151086. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  151087. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  151088. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  151089. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  151090. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  151091. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  151092. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  151093. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  151094. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  151095. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  151096. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  151097. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  151098. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  151099. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  151100. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  151101. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  151102. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  151103. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  151104. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  151105. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  151106. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  151107. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  151108. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  151109. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  151110. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  151111. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  151112. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  151113. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  151114. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  151115. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  151116. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  151117. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  151118. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  151119. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  151120. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  151121. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  151122. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  151123. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  151124. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  151125. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  151126. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  151127. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  151128. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  151129. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  151130. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  151131. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  151132. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  151133. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  151134. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  151135. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  151136. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  151137. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  151138. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  151139. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  151140. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  151141. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  151142. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  151143. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  151144. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  151145. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  151146. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  151147. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  151148. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  151149. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  151150. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  151151. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  151152. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  151153. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  151154. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  151155. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  151156. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  151157. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  151158. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  151159. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  151160. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  151161. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  151162. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  151163. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  151164. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  151165. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  151166. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  151167. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  151168. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  151169. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  151170. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  151171. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  151172. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  151173. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  151174. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  151175. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  151176. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  151177. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  151178. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  151179. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  151180. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  151181. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  151182. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  151183. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  151184. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  151185. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  151186. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  151187. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  151188. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  151189. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  151190. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  151191. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  151192. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  151193. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  151194. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  151195. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  151196. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  151197. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  151198. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  151199. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  151200. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  151201. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  151202. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  151203. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  151204. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  151205. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  151206. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  151207. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  151208. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  151209. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  151210. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  151211. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  151212. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  151213. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  151214. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  151215. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  151216. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  151217. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  151218. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  151219. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  151220. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  151221. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  151222. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  151223. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  151224. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  151225. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  151226. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  151227. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  151228. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  151229. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  151230. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  151231. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  151232. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  151233. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  151234. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  151235. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  151236. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  151237. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  151238. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  151239. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  151240. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  151241. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  151242. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  151243. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  151244. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  151245. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  151246. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  151247. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  151248. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  151249. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  151250. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  151251. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  151252. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  151253. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  151254. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  151255. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  151256. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  151257. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  151258. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  151259. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  151260. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  151261. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  151262. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  151263. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  151264. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  151265. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  151266. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  151267. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  151268. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  151269. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  151270. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  151271. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  151272. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  151273. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  151274. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  151275. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  151276. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  151277. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  151278. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  151279. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  151280. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  151281. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  151282. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  151283. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  151284. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  151285. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  151286. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  151287. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  151288. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  151289. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  151290. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  151291. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  151292. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  151293. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  151294. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  151295. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  151296. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  151297. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  151298. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  151299. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  151300. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  151301. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  151302. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  151303. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  151304. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  151305. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  151306. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  151307. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  151308. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  151309. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  151310. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  151311. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  151312. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  151313. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  151314. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  151315. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  151316. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  151317. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  151318. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  151319. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  151320. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  151321. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  151322. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  151323. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  151324. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  151325. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  151326. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  151327. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  151328. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  151329. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  151330. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  151331. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  151332. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  151333. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  151334. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  151335. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  151336. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  151337. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  151338. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  151339. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  151340. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  151341. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  151342. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  151343. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  151344. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  151345. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  151346. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  151347. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  151348. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  151349. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  151350. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  151351. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  151352. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  151353. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  151354. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  151355. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  151356. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  151357. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  151358. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  151359. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  151360. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  151361. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  151362. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  151363. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  151364. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  151365. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  151366. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  151367. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  151368. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  151369. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  151370. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  151371. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  151372. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  151373. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  151374. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  151375. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  151376. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  151377. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  151378. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  151379. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  151380. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  151381. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  151382. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  151383. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  151384. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  151385. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  151386. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  151387. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  151388. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  151389. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  151390. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  151391. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  151392. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  151393. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  151394. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  151395. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  151396. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  151397. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  151398. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  151399. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  151400. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  151401. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  151402. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  151403. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  151404. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  151405. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  151406. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  151407. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  151408. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  151409. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  151410. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  151411. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  151412. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  151413. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  151414. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  151415. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  151416. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  151417. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  151418. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  151419. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  151420. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  151421. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  151422. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  151423. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  151424. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  151425. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  151426. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  151427. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  151428. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  151429. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  151430. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  151431. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  151432. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  151433. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  151434. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  151435. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  151436. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  151437. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  151438. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  151439. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  151440. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  151441. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  151442. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  151443. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  151444. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  151445. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  151446. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  151447. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  151448. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  151449. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  151450. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  151451. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  151452. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  151453. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  151454. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  151455. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  151456. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  151457. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  151458. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  151459. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  151460. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  151461. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  151462. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  151463. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  151464. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  151465. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  151466. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  151467. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  151468. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  151469. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  151470. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  151471. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  151472. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  151473. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  151474. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  151475. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  151476. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  151477. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  151478. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  151479. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  151480. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  151481. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  151482. };
  151483. static float vwin8192[4096] = {
  151484. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  151485. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  151486. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  151487. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  151488. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  151489. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  151490. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  151491. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  151492. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  151493. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  151494. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  151495. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  151496. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  151497. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  151498. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  151499. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  151500. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  151501. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  151502. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  151503. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  151504. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  151505. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  151506. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  151507. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  151508. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  151509. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  151510. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  151511. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  151512. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  151513. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  151514. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  151515. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  151516. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  151517. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  151518. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  151519. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  151520. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  151521. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  151522. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  151523. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  151524. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  151525. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  151526. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  151527. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  151528. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  151529. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  151530. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  151531. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  151532. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  151533. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  151534. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  151535. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  151536. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  151537. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  151538. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  151539. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  151540. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  151541. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  151542. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  151543. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  151544. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  151545. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  151546. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  151547. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  151548. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  151549. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  151550. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  151551. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  151552. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  151553. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  151554. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  151555. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  151556. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  151557. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  151558. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  151559. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  151560. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  151561. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  151562. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  151563. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  151564. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  151565. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  151566. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  151567. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  151568. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  151569. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  151570. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  151571. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  151572. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  151573. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  151574. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  151575. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  151576. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  151577. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  151578. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  151579. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  151580. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  151581. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  151582. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  151583. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  151584. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  151585. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  151586. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  151587. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  151588. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  151589. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  151590. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  151591. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  151592. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  151593. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  151594. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  151595. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  151596. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  151597. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  151598. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  151599. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  151600. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  151601. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  151602. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  151603. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  151604. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  151605. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  151606. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  151607. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  151608. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  151609. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  151610. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  151611. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  151612. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  151613. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  151614. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  151615. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  151616. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  151617. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  151618. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  151619. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  151620. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  151621. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  151622. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  151623. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  151624. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  151625. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  151626. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  151627. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  151628. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  151629. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  151630. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  151631. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  151632. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  151633. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  151634. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  151635. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  151636. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  151637. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  151638. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  151639. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  151640. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  151641. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  151642. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  151643. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  151644. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  151645. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  151646. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  151647. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  151648. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  151649. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  151650. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  151651. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  151652. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  151653. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  151654. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  151655. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  151656. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  151657. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  151658. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  151659. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  151660. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  151661. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  151662. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  151663. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  151664. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  151665. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  151666. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  151667. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  151668. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  151669. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  151670. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  151671. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  151672. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  151673. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  151674. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  151675. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  151676. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  151677. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  151678. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  151679. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  151680. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  151681. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  151682. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  151683. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  151684. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  151685. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  151686. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  151687. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  151688. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  151689. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  151690. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  151691. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  151692. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  151693. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  151694. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  151695. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  151696. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  151697. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  151698. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  151699. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  151700. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  151701. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  151702. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  151703. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  151704. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  151705. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  151706. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  151707. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  151708. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  151709. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  151710. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  151711. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  151712. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  151713. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  151714. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  151715. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  151716. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  151717. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  151718. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  151719. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  151720. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  151721. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  151722. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  151723. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  151724. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  151725. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  151726. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  151727. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  151728. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  151729. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  151730. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  151731. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  151732. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  151733. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  151734. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  151735. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  151736. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  151737. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  151738. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  151739. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  151740. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  151741. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  151742. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  151743. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  151744. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  151745. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  151746. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  151747. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  151748. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  151749. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  151750. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  151751. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  151752. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  151753. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  151754. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  151755. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  151756. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  151757. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  151758. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  151759. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  151760. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  151761. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  151762. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  151763. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  151764. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  151765. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  151766. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  151767. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  151768. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  151769. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  151770. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  151771. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  151772. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  151773. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  151774. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  151775. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  151776. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  151777. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  151778. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  151779. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  151780. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  151781. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  151782. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  151783. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  151784. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  151785. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  151786. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  151787. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  151788. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  151789. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  151790. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  151791. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  151792. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  151793. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  151794. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  151795. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  151796. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  151797. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  151798. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  151799. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  151800. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  151801. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  151802. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  151803. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  151804. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  151805. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  151806. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  151807. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  151808. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  151809. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  151810. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  151811. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  151812. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  151813. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  151814. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  151815. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  151816. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  151817. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  151818. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  151819. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  151820. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  151821. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  151822. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  151823. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  151824. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  151825. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  151826. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  151827. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  151828. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  151829. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  151830. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  151831. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  151832. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  151833. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  151834. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  151835. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  151836. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  151837. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  151838. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  151839. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  151840. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  151841. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  151842. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  151843. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  151844. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  151845. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  151846. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  151847. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  151848. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  151849. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  151850. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  151851. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  151852. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  151853. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  151854. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  151855. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  151856. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  151857. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  151858. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  151859. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  151860. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  151861. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  151862. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  151863. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  151864. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  151865. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  151866. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  151867. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  151868. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  151869. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  151870. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  151871. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  151872. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  151873. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  151874. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  151875. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  151876. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  151877. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  151878. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  151879. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  151880. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  151881. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  151882. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  151883. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  151884. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  151885. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  151886. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  151887. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  151888. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  151889. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  151890. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  151891. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  151892. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  151893. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  151894. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  151895. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  151896. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  151897. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  151898. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  151899. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  151900. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  151901. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  151902. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  151903. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  151904. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  151905. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  151906. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  151907. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  151908. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  151909. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  151910. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  151911. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  151912. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  151913. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  151914. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  151915. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  151916. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  151917. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  151918. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  151919. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  151920. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  151921. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  151922. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  151923. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  151924. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  151925. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  151926. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  151927. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  151928. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  151929. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  151930. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  151931. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  151932. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  151933. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  151934. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  151935. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  151936. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  151937. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  151938. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  151939. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  151940. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  151941. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  151942. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  151943. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  151944. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  151945. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  151946. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  151947. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  151948. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  151949. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  151950. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  151951. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  151952. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  151953. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  151954. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  151955. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  151956. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  151957. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  151958. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  151959. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  151960. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  151961. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  151962. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  151963. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  151964. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  151965. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  151966. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  151967. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  151968. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  151969. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  151970. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  151971. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  151972. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  151973. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  151974. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  151975. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  151976. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  151977. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  151978. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  151979. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  151980. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  151981. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  151982. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  151983. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  151984. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  151985. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  151986. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  151987. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  151988. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  151989. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  151990. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  151991. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  151992. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  151993. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  151994. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  151995. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  151996. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  151997. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  151998. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  151999. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  152000. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  152001. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  152002. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  152003. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  152004. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  152005. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  152006. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  152007. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  152008. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  152009. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  152010. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  152011. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  152012. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  152013. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  152014. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  152015. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  152016. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  152017. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  152018. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  152019. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  152020. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  152021. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  152022. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  152023. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  152024. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  152025. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  152026. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  152027. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  152028. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  152029. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  152030. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  152031. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  152032. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  152033. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  152034. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  152035. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  152036. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  152037. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  152038. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  152039. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  152040. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  152041. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  152042. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  152043. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  152044. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  152045. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  152046. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  152047. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  152048. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  152049. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  152050. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  152051. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  152052. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  152053. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  152054. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  152055. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  152056. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  152057. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  152058. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  152059. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  152060. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  152061. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  152062. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  152063. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  152064. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  152065. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  152066. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  152067. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  152068. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  152069. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  152070. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  152071. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  152072. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  152073. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  152074. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  152075. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  152076. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  152077. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  152078. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  152079. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  152080. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  152081. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  152082. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  152083. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  152084. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  152085. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  152086. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  152087. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  152088. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  152089. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  152090. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  152091. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  152092. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  152093. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  152094. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  152095. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  152096. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  152097. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  152098. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  152099. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  152100. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  152101. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  152102. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  152103. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  152104. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  152105. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  152106. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  152107. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  152108. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  152109. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  152110. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  152111. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  152112. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  152113. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  152114. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  152115. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  152116. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  152117. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  152118. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  152119. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  152120. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  152121. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  152122. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  152123. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  152124. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  152125. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  152126. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  152127. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  152128. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  152129. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  152130. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  152131. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  152132. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  152133. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  152134. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  152135. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  152136. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  152137. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  152138. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  152139. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  152140. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  152141. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  152142. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  152143. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  152144. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  152145. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  152146. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  152147. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  152148. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  152149. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  152150. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  152151. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  152152. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  152153. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  152154. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  152155. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  152156. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  152157. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  152158. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  152159. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  152160. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  152161. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  152162. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  152163. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  152164. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  152165. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  152166. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  152167. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  152168. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  152169. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  152170. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  152171. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  152172. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  152173. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  152174. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  152175. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  152176. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  152177. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  152178. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  152179. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  152180. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  152181. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  152182. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  152183. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  152184. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  152185. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  152186. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  152187. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  152188. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  152189. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  152190. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  152191. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  152192. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  152193. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  152194. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  152195. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  152196. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  152197. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  152198. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  152199. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  152200. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  152201. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  152202. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  152203. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  152204. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  152205. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  152206. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  152207. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  152208. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  152209. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  152210. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  152211. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  152212. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  152213. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  152214. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  152215. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  152216. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  152217. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  152218. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  152219. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  152220. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  152221. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  152222. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  152223. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  152224. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  152225. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  152226. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  152227. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  152228. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  152229. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  152230. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  152231. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  152232. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  152233. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  152234. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  152235. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  152236. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  152237. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  152238. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  152239. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  152240. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  152241. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  152242. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  152243. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  152244. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  152245. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  152246. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  152247. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  152248. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  152249. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  152250. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  152251. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  152252. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  152253. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  152254. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  152255. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  152256. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  152257. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  152258. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  152259. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  152260. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  152261. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  152262. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  152263. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  152264. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  152265. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  152266. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  152267. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  152268. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  152269. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  152270. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  152271. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  152272. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  152273. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  152274. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  152275. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  152276. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  152277. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  152278. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  152279. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  152280. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  152281. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  152282. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  152283. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  152284. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  152285. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  152286. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  152287. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  152288. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  152289. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  152290. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  152291. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  152292. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  152293. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  152294. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  152295. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  152296. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  152297. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  152298. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  152299. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  152300. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  152301. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  152302. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  152303. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  152304. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  152305. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  152306. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  152307. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  152308. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  152309. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  152310. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  152311. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  152312. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  152313. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  152314. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  152315. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  152316. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  152317. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  152318. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  152319. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  152320. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  152321. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  152322. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  152323. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  152324. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  152325. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  152326. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  152327. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  152328. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  152329. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  152330. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  152331. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  152332. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  152333. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  152334. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  152335. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  152336. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  152337. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  152338. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  152339. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  152340. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  152341. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  152342. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  152343. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  152344. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  152345. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  152346. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  152347. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  152348. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  152349. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  152350. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  152351. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  152352. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  152353. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  152354. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  152355. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  152356. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  152357. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  152358. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  152359. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  152360. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  152361. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  152362. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  152363. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  152364. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  152365. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  152366. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  152367. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  152368. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  152369. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  152370. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  152371. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  152372. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  152373. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  152374. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  152375. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  152376. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  152377. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  152378. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  152379. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  152380. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  152381. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  152382. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  152383. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  152384. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  152385. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  152386. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  152387. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  152388. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  152389. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  152390. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  152391. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  152392. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  152393. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  152394. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  152395. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  152396. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  152397. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  152398. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  152399. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  152400. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  152401. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  152402. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  152403. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  152404. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  152405. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  152406. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  152407. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  152408. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  152409. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  152410. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  152411. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  152412. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  152413. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  152414. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  152415. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  152416. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  152417. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  152418. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  152419. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  152420. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  152421. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  152422. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  152423. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  152424. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  152425. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  152426. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  152427. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  152428. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  152429. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  152430. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  152431. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  152432. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  152433. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  152434. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  152435. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  152436. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  152437. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  152438. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  152439. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  152440. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  152441. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  152442. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  152443. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  152444. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  152445. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  152446. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  152447. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  152448. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  152449. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  152450. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  152451. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  152452. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  152453. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  152454. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  152455. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  152456. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  152457. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  152458. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  152459. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  152460. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  152461. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  152462. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  152463. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  152464. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  152465. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  152466. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  152467. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  152468. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  152469. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  152470. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  152471. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  152472. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  152473. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  152474. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  152475. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  152476. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  152477. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  152478. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  152479. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  152480. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  152481. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  152482. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  152483. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  152484. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  152485. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  152486. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  152487. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  152488. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  152489. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  152490. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  152491. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  152492. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  152493. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  152494. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  152495. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  152496. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  152497. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  152498. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  152499. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  152500. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  152501. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  152502. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  152503. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  152504. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  152505. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  152506. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152507. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152508. };
  152509. static float *vwin[8] = {
  152510. vwin64,
  152511. vwin128,
  152512. vwin256,
  152513. vwin512,
  152514. vwin1024,
  152515. vwin2048,
  152516. vwin4096,
  152517. vwin8192,
  152518. };
  152519. float *_vorbis_window_get(int n){
  152520. return vwin[n];
  152521. }
  152522. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  152523. int lW,int W,int nW){
  152524. lW=(W?lW:0);
  152525. nW=(W?nW:0);
  152526. {
  152527. float *windowLW=vwin[winno[lW]];
  152528. float *windowNW=vwin[winno[nW]];
  152529. long n=blocksizes[W];
  152530. long ln=blocksizes[lW];
  152531. long rn=blocksizes[nW];
  152532. long leftbegin=n/4-ln/4;
  152533. long leftend=leftbegin+ln/2;
  152534. long rightbegin=n/2+n/4-rn/4;
  152535. long rightend=rightbegin+rn/2;
  152536. int i,p;
  152537. for(i=0;i<leftbegin;i++)
  152538. d[i]=0.f;
  152539. for(p=0;i<leftend;i++,p++)
  152540. d[i]*=windowLW[p];
  152541. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  152542. d[i]*=windowNW[p];
  152543. for(;i<n;i++)
  152544. d[i]=0.f;
  152545. }
  152546. }
  152547. #endif
  152548. /********* End of inlined file: window.c *********/
  152549. }
  152550. BEGIN_JUCE_NAMESPACE
  152551. using namespace OggVorbisNamespace;
  152552. #define oggFormatName TRANS("Ogg-Vorbis file")
  152553. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  152554. class OggReader : public AudioFormatReader
  152555. {
  152556. OggVorbis_File ovFile;
  152557. ov_callbacks callbacks;
  152558. AudioSampleBuffer reservoir;
  152559. int reservoirStart, samplesInReservoir;
  152560. public:
  152561. OggReader (InputStream* const inp)
  152562. : AudioFormatReader (inp, oggFormatName),
  152563. reservoir (2, 2048),
  152564. reservoirStart (0),
  152565. samplesInReservoir (0)
  152566. {
  152567. sampleRate = 0;
  152568. usesFloatingPointData = true;
  152569. callbacks.read_func = &oggReadCallback;
  152570. callbacks.seek_func = &oggSeekCallback;
  152571. callbacks.close_func = &oggCloseCallback;
  152572. callbacks.tell_func = &oggTellCallback;
  152573. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  152574. if (err == 0)
  152575. {
  152576. vorbis_info* info = ov_info (&ovFile, -1);
  152577. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  152578. numChannels = info->channels;
  152579. bitsPerSample = 16;
  152580. sampleRate = info->rate;
  152581. reservoir.setSize (numChannels,
  152582. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  152583. }
  152584. }
  152585. ~OggReader()
  152586. {
  152587. ov_clear (&ovFile);
  152588. }
  152589. bool read (int** destSamples,
  152590. int64 startSampleInFile,
  152591. int numSamples)
  152592. {
  152593. if (startSampleInFile < reservoirStart
  152594. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  152595. {
  152596. // buffer miss, so refill the reservoir
  152597. int bitStream = 0;
  152598. reservoirStart = (int) jmax ((int64) 0, startSampleInFile - 32);
  152599. samplesInReservoir = jmax (numSamples + 32, reservoir.getNumSamples());
  152600. reservoir.setSize (numChannels, samplesInReservoir, false, false, true);
  152601. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  152602. ov_pcm_seek (&ovFile, reservoirStart);
  152603. int offset = 0;
  152604. int numToRead = samplesInReservoir;
  152605. while (numToRead > 0)
  152606. {
  152607. float** dataIn = 0;
  152608. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  152609. if (samps == 0)
  152610. break;
  152611. jassert (samps <= numToRead);
  152612. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  152613. {
  152614. memcpy (reservoir.getSampleData (i, offset),
  152615. dataIn[i],
  152616. sizeof (float) * samps);
  152617. }
  152618. numToRead -= samps;
  152619. offset += samps;
  152620. }
  152621. if (numToRead > 0)
  152622. reservoir.clear (offset, numToRead);
  152623. }
  152624. if (numSamples > 0)
  152625. {
  152626. for (unsigned int i = 0; i < numChannels; ++i)
  152627. {
  152628. if (destSamples[i] == 0)
  152629. break;
  152630. memcpy (destSamples[i],
  152631. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  152632. (int) (startSampleInFile - reservoirStart)),
  152633. sizeof (float) * numSamples);
  152634. }
  152635. }
  152636. return true;
  152637. }
  152638. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  152639. {
  152640. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  152641. }
  152642. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  152643. {
  152644. InputStream* const in = (InputStream*) datasource;
  152645. if (whence == SEEK_CUR)
  152646. offset += in->getPosition();
  152647. else if (whence == SEEK_END)
  152648. offset += in->getTotalLength();
  152649. in->setPosition (offset);
  152650. return 0;
  152651. }
  152652. static int oggCloseCallback (void*)
  152653. {
  152654. return 0;
  152655. }
  152656. static long oggTellCallback (void* datasource)
  152657. {
  152658. return (long) ((InputStream*) datasource)->getPosition();
  152659. }
  152660. juce_UseDebuggingNewOperator
  152661. };
  152662. class OggWriter : public AudioFormatWriter
  152663. {
  152664. ogg_stream_state os;
  152665. ogg_page og;
  152666. ogg_packet op;
  152667. vorbis_info vi;
  152668. vorbis_comment vc;
  152669. vorbis_dsp_state vd;
  152670. vorbis_block vb;
  152671. public:
  152672. bool ok;
  152673. OggWriter (OutputStream* const out,
  152674. const double sampleRate,
  152675. const int numChannels,
  152676. const int bitsPerSample,
  152677. const int qualityIndex)
  152678. : AudioFormatWriter (out, oggFormatName,
  152679. sampleRate,
  152680. numChannels,
  152681. bitsPerSample)
  152682. {
  152683. ok = false;
  152684. vorbis_info_init (&vi);
  152685. if (vorbis_encode_init_vbr (&vi,
  152686. numChannels,
  152687. (int) sampleRate,
  152688. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  152689. {
  152690. vorbis_comment_init (&vc);
  152691. if (JUCEApplication::getInstance() != 0)
  152692. vorbis_comment_add_tag (&vc, "ENCODER",
  152693. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  152694. vorbis_analysis_init (&vd, &vi);
  152695. vorbis_block_init (&vd, &vb);
  152696. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  152697. ogg_packet header;
  152698. ogg_packet header_comm;
  152699. ogg_packet header_code;
  152700. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  152701. ogg_stream_packetin (&os, &header);
  152702. ogg_stream_packetin (&os, &header_comm);
  152703. ogg_stream_packetin (&os, &header_code);
  152704. for (;;)
  152705. {
  152706. if (ogg_stream_flush (&os, &og) == 0)
  152707. break;
  152708. output->write (og.header, og.header_len);
  152709. output->write (og.body, og.body_len);
  152710. }
  152711. ok = true;
  152712. }
  152713. }
  152714. ~OggWriter()
  152715. {
  152716. if (ok)
  152717. {
  152718. ogg_stream_clear (&os);
  152719. vorbis_block_clear (&vb);
  152720. vorbis_dsp_clear (&vd);
  152721. vorbis_comment_clear (&vc);
  152722. vorbis_info_clear (&vi);
  152723. output->flush();
  152724. }
  152725. else
  152726. {
  152727. vorbis_info_clear (&vi);
  152728. output = 0; // to stop the base class deleting this, as it needs to be returned
  152729. // to the caller of createWriter()
  152730. }
  152731. }
  152732. bool write (const int** samplesToWrite, int numSamples)
  152733. {
  152734. if (! ok)
  152735. return false;
  152736. if (numSamples > 0)
  152737. {
  152738. const double gain = 1.0 / 0x80000000u;
  152739. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  152740. for (int i = numChannels; --i >= 0;)
  152741. {
  152742. float* const dst = vorbisBuffer[i];
  152743. const int* const src = samplesToWrite [i];
  152744. if (src != 0 && dst != 0)
  152745. {
  152746. for (int j = 0; j < numSamples; ++j)
  152747. dst[j] = (float) (src[j] * gain);
  152748. }
  152749. }
  152750. }
  152751. vorbis_analysis_wrote (&vd, numSamples);
  152752. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  152753. {
  152754. vorbis_analysis (&vb, 0);
  152755. vorbis_bitrate_addblock (&vb);
  152756. while (vorbis_bitrate_flushpacket (&vd, &op))
  152757. {
  152758. ogg_stream_packetin (&os, &op);
  152759. for (;;)
  152760. {
  152761. if (ogg_stream_pageout (&os, &og) == 0)
  152762. break;
  152763. output->write (og.header, og.header_len);
  152764. output->write (og.body, og.body_len);
  152765. if (ogg_page_eos (&og))
  152766. break;
  152767. }
  152768. }
  152769. }
  152770. return true;
  152771. }
  152772. juce_UseDebuggingNewOperator
  152773. };
  152774. OggVorbisAudioFormat::OggVorbisAudioFormat()
  152775. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  152776. {
  152777. }
  152778. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  152779. {
  152780. }
  152781. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  152782. {
  152783. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  152784. return Array <int> (rates);
  152785. }
  152786. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  152787. {
  152788. Array <int> depths;
  152789. depths.add (32);
  152790. return depths;
  152791. }
  152792. bool OggVorbisAudioFormat::canDoStereo()
  152793. {
  152794. return true;
  152795. }
  152796. bool OggVorbisAudioFormat::canDoMono()
  152797. {
  152798. return true;
  152799. }
  152800. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  152801. const bool deleteStreamIfOpeningFails)
  152802. {
  152803. OggReader* r = new OggReader (in);
  152804. if (r->sampleRate == 0)
  152805. {
  152806. if (! deleteStreamIfOpeningFails)
  152807. r->input = 0;
  152808. deleteAndZero (r);
  152809. }
  152810. return r;
  152811. }
  152812. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  152813. double sampleRate,
  152814. unsigned int numChannels,
  152815. int bitsPerSample,
  152816. const StringPairArray& /*metadataValues*/,
  152817. int qualityOptionIndex)
  152818. {
  152819. OggWriter* w = new OggWriter (out,
  152820. sampleRate,
  152821. numChannels,
  152822. bitsPerSample,
  152823. qualityOptionIndex);
  152824. if (! w->ok)
  152825. deleteAndZero (w);
  152826. return w;
  152827. }
  152828. bool OggVorbisAudioFormat::isCompressed()
  152829. {
  152830. return true;
  152831. }
  152832. const StringArray OggVorbisAudioFormat::getQualityOptions()
  152833. {
  152834. StringArray s;
  152835. s.add ("Low Quality");
  152836. s.add ("Medium Quality");
  152837. s.add ("High Quality");
  152838. return s;
  152839. }
  152840. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  152841. {
  152842. FileInputStream* const in = source.createInputStream();
  152843. if (in != 0)
  152844. {
  152845. AudioFormatReader* const r = createReaderFor (in, true);
  152846. if (r != 0)
  152847. {
  152848. const int64 numSamps = r->lengthInSamples;
  152849. delete r;
  152850. const int64 fileNumSamps = source.getSize() / 4;
  152851. const double ratio = numSamps / (double) fileNumSamps;
  152852. if (ratio > 12.0)
  152853. return 0;
  152854. else if (ratio > 6.0)
  152855. return 1;
  152856. else
  152857. return 2;
  152858. }
  152859. }
  152860. return 1;
  152861. }
  152862. END_JUCE_NAMESPACE
  152863. #endif
  152864. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  152865. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  152866. #if JUCE_MSVC
  152867. #pragma warning (push)
  152868. #endif
  152869. namespace jpeglibNamespace
  152870. {
  152871. extern "C"
  152872. {
  152873. #define JPEG_INTERNALS
  152874. #undef FAR
  152875. /********* Start of inlined file: jpeglib.h *********/
  152876. #ifndef JPEGLIB_H
  152877. #define JPEGLIB_H
  152878. /*
  152879. * First we include the configuration files that record how this
  152880. * installation of the JPEG library is set up. jconfig.h can be
  152881. * generated automatically for many systems. jmorecfg.h contains
  152882. * manual configuration options that most people need not worry about.
  152883. */
  152884. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  152885. /********* Start of inlined file: jconfig.h *********/
  152886. /* see jconfig.doc for explanations */
  152887. // disable all the warnings under MSVC
  152888. #ifdef _MSC_VER
  152889. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  152890. #endif
  152891. #ifdef __BORLANDC__
  152892. #pragma warn -8057
  152893. #pragma warn -8019
  152894. #pragma warn -8004
  152895. #pragma warn -8008
  152896. #endif
  152897. #define HAVE_PROTOTYPES
  152898. #define HAVE_UNSIGNED_CHAR
  152899. #define HAVE_UNSIGNED_SHORT
  152900. /* #define void char */
  152901. /* #define const */
  152902. #undef CHAR_IS_UNSIGNED
  152903. #define HAVE_STDDEF_H
  152904. #define HAVE_STDLIB_H
  152905. #undef NEED_BSD_STRINGS
  152906. #undef NEED_SYS_TYPES_H
  152907. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  152908. #undef NEED_SHORT_EXTERNAL_NAMES
  152909. #undef INCOMPLETE_TYPES_BROKEN
  152910. /* Define "boolean" as unsigned char, not int, per Windows custom */
  152911. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  152912. typedef unsigned char boolean;
  152913. #endif
  152914. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  152915. #ifdef JPEG_INTERNALS
  152916. #undef RIGHT_SHIFT_IS_UNSIGNED
  152917. #endif /* JPEG_INTERNALS */
  152918. #ifdef JPEG_CJPEG_DJPEG
  152919. #define BMP_SUPPORTED /* BMP image file format */
  152920. #define GIF_SUPPORTED /* GIF image file format */
  152921. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  152922. #undef RLE_SUPPORTED /* Utah RLE image file format */
  152923. #define TARGA_SUPPORTED /* Targa image file format */
  152924. #define TWO_FILE_COMMANDLINE /* optional */
  152925. #define USE_SETMODE /* Microsoft has setmode() */
  152926. #undef NEED_SIGNAL_CATCHER
  152927. #undef DONT_USE_B_MODE
  152928. #undef PROGRESS_REPORT /* optional */
  152929. #endif /* JPEG_CJPEG_DJPEG */
  152930. /********* End of inlined file: jconfig.h *********/
  152931. /* widely used configuration options */
  152932. #endif
  152933. /********* Start of inlined file: jmorecfg.h *********/
  152934. /*
  152935. * Define BITS_IN_JSAMPLE as either
  152936. * 8 for 8-bit sample values (the usual setting)
  152937. * 12 for 12-bit sample values
  152938. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  152939. * JPEG standard, and the IJG code does not support anything else!
  152940. * We do not support run-time selection of data precision, sorry.
  152941. */
  152942. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  152943. /*
  152944. * Maximum number of components (color channels) allowed in JPEG image.
  152945. * To meet the letter of the JPEG spec, set this to 255. However, darn
  152946. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  152947. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  152948. * really short on memory. (Each allowed component costs a hundred or so
  152949. * bytes of storage, whether actually used in an image or not.)
  152950. */
  152951. #define MAX_COMPONENTS 10 /* maximum number of image components */
  152952. /*
  152953. * Basic data types.
  152954. * You may need to change these if you have a machine with unusual data
  152955. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  152956. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  152957. * but it had better be at least 16.
  152958. */
  152959. /* Representation of a single sample (pixel element value).
  152960. * We frequently allocate large arrays of these, so it's important to keep
  152961. * them small. But if you have memory to burn and access to char or short
  152962. * arrays is very slow on your hardware, you might want to change these.
  152963. */
  152964. #if BITS_IN_JSAMPLE == 8
  152965. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  152966. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  152967. */
  152968. #ifdef HAVE_UNSIGNED_CHAR
  152969. typedef unsigned char JSAMPLE;
  152970. #define GETJSAMPLE(value) ((int) (value))
  152971. #else /* not HAVE_UNSIGNED_CHAR */
  152972. typedef char JSAMPLE;
  152973. #ifdef CHAR_IS_UNSIGNED
  152974. #define GETJSAMPLE(value) ((int) (value))
  152975. #else
  152976. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  152977. #endif /* CHAR_IS_UNSIGNED */
  152978. #endif /* HAVE_UNSIGNED_CHAR */
  152979. #define MAXJSAMPLE 255
  152980. #define CENTERJSAMPLE 128
  152981. #endif /* BITS_IN_JSAMPLE == 8 */
  152982. #if BITS_IN_JSAMPLE == 12
  152983. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  152984. * On nearly all machines "short" will do nicely.
  152985. */
  152986. typedef short JSAMPLE;
  152987. #define GETJSAMPLE(value) ((int) (value))
  152988. #define MAXJSAMPLE 4095
  152989. #define CENTERJSAMPLE 2048
  152990. #endif /* BITS_IN_JSAMPLE == 12 */
  152991. /* Representation of a DCT frequency coefficient.
  152992. * This should be a signed value of at least 16 bits; "short" is usually OK.
  152993. * Again, we allocate large arrays of these, but you can change to int
  152994. * if you have memory to burn and "short" is really slow.
  152995. */
  152996. typedef short JCOEF;
  152997. /* Compressed datastreams are represented as arrays of JOCTET.
  152998. * These must be EXACTLY 8 bits wide, at least once they are written to
  152999. * external storage. Note that when using the stdio data source/destination
  153000. * managers, this is also the data type passed to fread/fwrite.
  153001. */
  153002. #ifdef HAVE_UNSIGNED_CHAR
  153003. typedef unsigned char JOCTET;
  153004. #define GETJOCTET(value) (value)
  153005. #else /* not HAVE_UNSIGNED_CHAR */
  153006. typedef char JOCTET;
  153007. #ifdef CHAR_IS_UNSIGNED
  153008. #define GETJOCTET(value) (value)
  153009. #else
  153010. #define GETJOCTET(value) ((value) & 0xFF)
  153011. #endif /* CHAR_IS_UNSIGNED */
  153012. #endif /* HAVE_UNSIGNED_CHAR */
  153013. /* These typedefs are used for various table entries and so forth.
  153014. * They must be at least as wide as specified; but making them too big
  153015. * won't cost a huge amount of memory, so we don't provide special
  153016. * extraction code like we did for JSAMPLE. (In other words, these
  153017. * typedefs live at a different point on the speed/space tradeoff curve.)
  153018. */
  153019. /* UINT8 must hold at least the values 0..255. */
  153020. #ifdef HAVE_UNSIGNED_CHAR
  153021. typedef unsigned char UINT8;
  153022. #else /* not HAVE_UNSIGNED_CHAR */
  153023. #ifdef CHAR_IS_UNSIGNED
  153024. typedef char UINT8;
  153025. #else /* not CHAR_IS_UNSIGNED */
  153026. typedef short UINT8;
  153027. #endif /* CHAR_IS_UNSIGNED */
  153028. #endif /* HAVE_UNSIGNED_CHAR */
  153029. /* UINT16 must hold at least the values 0..65535. */
  153030. #ifdef HAVE_UNSIGNED_SHORT
  153031. typedef unsigned short UINT16;
  153032. #else /* not HAVE_UNSIGNED_SHORT */
  153033. typedef unsigned int UINT16;
  153034. #endif /* HAVE_UNSIGNED_SHORT */
  153035. /* INT16 must hold at least the values -32768..32767. */
  153036. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  153037. typedef short INT16;
  153038. #endif
  153039. /* INT32 must hold at least signed 32-bit values. */
  153040. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  153041. typedef long INT32;
  153042. #endif
  153043. /* Datatype used for image dimensions. The JPEG standard only supports
  153044. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  153045. * "unsigned int" is sufficient on all machines. However, if you need to
  153046. * handle larger images and you don't mind deviating from the spec, you
  153047. * can change this datatype.
  153048. */
  153049. typedef unsigned int JDIMENSION;
  153050. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  153051. /* These macros are used in all function definitions and extern declarations.
  153052. * You could modify them if you need to change function linkage conventions;
  153053. * in particular, you'll need to do that to make the library a Windows DLL.
  153054. * Another application is to make all functions global for use with debuggers
  153055. * or code profilers that require it.
  153056. */
  153057. /* a function called through method pointers: */
  153058. #define METHODDEF(type) static type
  153059. /* a function used only in its module: */
  153060. #define LOCAL(type) static type
  153061. /* a function referenced thru EXTERNs: */
  153062. #define GLOBAL(type) type
  153063. /* a reference to a GLOBAL function: */
  153064. #define EXTERN(type) extern type
  153065. /* This macro is used to declare a "method", that is, a function pointer.
  153066. * We want to supply prototype parameters if the compiler can cope.
  153067. * Note that the arglist parameter must be parenthesized!
  153068. * Again, you can customize this if you need special linkage keywords.
  153069. */
  153070. #ifdef HAVE_PROTOTYPES
  153071. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  153072. #else
  153073. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  153074. #endif
  153075. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  153076. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  153077. * by just saying "FAR *" where such a pointer is needed. In a few places
  153078. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  153079. */
  153080. #ifdef NEED_FAR_POINTERS
  153081. #define FAR far
  153082. #else
  153083. #define FAR
  153084. #endif
  153085. /*
  153086. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  153087. * in standard header files. Or you may have conflicts with application-
  153088. * specific header files that you want to include together with these files.
  153089. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  153090. */
  153091. #ifndef HAVE_BOOLEAN
  153092. typedef int boolean;
  153093. #endif
  153094. #ifndef FALSE /* in case these macros already exist */
  153095. #define FALSE 0 /* values of boolean */
  153096. #endif
  153097. #ifndef TRUE
  153098. #define TRUE 1
  153099. #endif
  153100. /*
  153101. * The remaining options affect code selection within the JPEG library,
  153102. * but they don't need to be visible to most applications using the library.
  153103. * To minimize application namespace pollution, the symbols won't be
  153104. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  153105. */
  153106. #ifdef JPEG_INTERNALS
  153107. #define JPEG_INTERNAL_OPTIONS
  153108. #endif
  153109. #ifdef JPEG_INTERNAL_OPTIONS
  153110. /*
  153111. * These defines indicate whether to include various optional functions.
  153112. * Undefining some of these symbols will produce a smaller but less capable
  153113. * library. Note that you can leave certain source files out of the
  153114. * compilation/linking process if you've #undef'd the corresponding symbols.
  153115. * (You may HAVE to do that if your compiler doesn't like null source files.)
  153116. */
  153117. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  153118. /* Capability options common to encoder and decoder: */
  153119. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  153120. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  153121. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  153122. /* Encoder capability options: */
  153123. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153124. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153125. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153126. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  153127. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  153128. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  153129. * precision, so jchuff.c normally uses entropy optimization to compute
  153130. * usable tables for higher precision. If you don't want to do optimization,
  153131. * you'll have to supply different default Huffman tables.
  153132. * The exact same statements apply for progressive JPEG: the default tables
  153133. * don't work for progressive mode. (This may get fixed, however.)
  153134. */
  153135. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  153136. /* Decoder capability options: */
  153137. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153138. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153139. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153140. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  153141. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  153142. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  153143. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  153144. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  153145. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  153146. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  153147. /* more capability options later, no doubt */
  153148. /*
  153149. * Ordering of RGB data in scanlines passed to or from the application.
  153150. * If your application wants to deal with data in the order B,G,R, just
  153151. * change these macros. You can also deal with formats such as R,G,B,X
  153152. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  153153. * the offsets will also change the order in which colormap data is organized.
  153154. * RESTRICTIONS:
  153155. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  153156. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  153157. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  153158. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  153159. * is not 3 (they don't understand about dummy color components!). So you
  153160. * can't use color quantization if you change that value.
  153161. */
  153162. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  153163. #define RGB_GREEN 1 /* Offset of Green */
  153164. #define RGB_BLUE 2 /* Offset of Blue */
  153165. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  153166. /* Definitions for speed-related optimizations. */
  153167. /* If your compiler supports inline functions, define INLINE
  153168. * as the inline keyword; otherwise define it as empty.
  153169. */
  153170. #ifndef INLINE
  153171. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  153172. #define INLINE __inline__
  153173. #endif
  153174. #ifndef INLINE
  153175. #define INLINE /* default is to define it as empty */
  153176. #endif
  153177. #endif
  153178. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  153179. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  153180. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  153181. */
  153182. #ifndef MULTIPLIER
  153183. #define MULTIPLIER int /* type for fastest integer multiply */
  153184. #endif
  153185. /* FAST_FLOAT should be either float or double, whichever is done faster
  153186. * by your compiler. (Note that this type is only used in the floating point
  153187. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  153188. * Typically, float is faster in ANSI C compilers, while double is faster in
  153189. * pre-ANSI compilers (because they insist on converting to double anyway).
  153190. * The code below therefore chooses float if we have ANSI-style prototypes.
  153191. */
  153192. #ifndef FAST_FLOAT
  153193. #ifdef HAVE_PROTOTYPES
  153194. #define FAST_FLOAT float
  153195. #else
  153196. #define FAST_FLOAT double
  153197. #endif
  153198. #endif
  153199. #endif /* JPEG_INTERNAL_OPTIONS */
  153200. /********* End of inlined file: jmorecfg.h *********/
  153201. /* seldom changed options */
  153202. /* Version ID for the JPEG library.
  153203. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  153204. */
  153205. #define JPEG_LIB_VERSION 62 /* Version 6b */
  153206. /* Various constants determining the sizes of things.
  153207. * All of these are specified by the JPEG standard, so don't change them
  153208. * if you want to be compatible.
  153209. */
  153210. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  153211. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  153212. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  153213. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  153214. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  153215. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  153216. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  153217. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  153218. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  153219. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  153220. * to handle it. We even let you do this from the jconfig.h file. However,
  153221. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  153222. * sometimes emits noncompliant files doesn't mean you should too.
  153223. */
  153224. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  153225. #ifndef D_MAX_BLOCKS_IN_MCU
  153226. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  153227. #endif
  153228. /* Data structures for images (arrays of samples and of DCT coefficients).
  153229. * On 80x86 machines, the image arrays are too big for near pointers,
  153230. * but the pointer arrays can fit in near memory.
  153231. */
  153232. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  153233. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  153234. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  153235. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  153236. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  153237. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  153238. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  153239. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  153240. /* Types for JPEG compression parameters and working tables. */
  153241. /* DCT coefficient quantization tables. */
  153242. typedef struct {
  153243. /* This array gives the coefficient quantizers in natural array order
  153244. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  153245. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  153246. */
  153247. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  153248. /* This field is used only during compression. It's initialized FALSE when
  153249. * the table is created, and set TRUE when it's been output to the file.
  153250. * You could suppress output of a table by setting this to TRUE.
  153251. * (See jpeg_suppress_tables for an example.)
  153252. */
  153253. boolean sent_table; /* TRUE when table has been output */
  153254. } JQUANT_TBL;
  153255. /* Huffman coding tables. */
  153256. typedef struct {
  153257. /* These two fields directly represent the contents of a JPEG DHT marker */
  153258. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  153259. /* length k bits; bits[0] is unused */
  153260. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  153261. /* This field is used only during compression. It's initialized FALSE when
  153262. * the table is created, and set TRUE when it's been output to the file.
  153263. * You could suppress output of a table by setting this to TRUE.
  153264. * (See jpeg_suppress_tables for an example.)
  153265. */
  153266. boolean sent_table; /* TRUE when table has been output */
  153267. } JHUFF_TBL;
  153268. /* Basic info about one component (color channel). */
  153269. typedef struct {
  153270. /* These values are fixed over the whole image. */
  153271. /* For compression, they must be supplied by parameter setup; */
  153272. /* for decompression, they are read from the SOF marker. */
  153273. int component_id; /* identifier for this component (0..255) */
  153274. int component_index; /* its index in SOF or cinfo->comp_info[] */
  153275. int h_samp_factor; /* horizontal sampling factor (1..4) */
  153276. int v_samp_factor; /* vertical sampling factor (1..4) */
  153277. int quant_tbl_no; /* quantization table selector (0..3) */
  153278. /* These values may vary between scans. */
  153279. /* For compression, they must be supplied by parameter setup; */
  153280. /* for decompression, they are read from the SOS marker. */
  153281. /* The decompressor output side may not use these variables. */
  153282. int dc_tbl_no; /* DC entropy table selector (0..3) */
  153283. int ac_tbl_no; /* AC entropy table selector (0..3) */
  153284. /* Remaining fields should be treated as private by applications. */
  153285. /* These values are computed during compression or decompression startup: */
  153286. /* Component's size in DCT blocks.
  153287. * Any dummy blocks added to complete an MCU are not counted; therefore
  153288. * these values do not depend on whether a scan is interleaved or not.
  153289. */
  153290. JDIMENSION width_in_blocks;
  153291. JDIMENSION height_in_blocks;
  153292. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  153293. * For decompression this is the size of the output from one DCT block,
  153294. * reflecting any scaling we choose to apply during the IDCT step.
  153295. * Values of 1,2,4,8 are likely to be supported. Note that different
  153296. * components may receive different IDCT scalings.
  153297. */
  153298. int DCT_scaled_size;
  153299. /* The downsampled dimensions are the component's actual, unpadded number
  153300. * of samples at the main buffer (preprocessing/compression interface), thus
  153301. * downsampled_width = ceil(image_width * Hi/Hmax)
  153302. * and similarly for height. For decompression, IDCT scaling is included, so
  153303. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  153304. */
  153305. JDIMENSION downsampled_width; /* actual width in samples */
  153306. JDIMENSION downsampled_height; /* actual height in samples */
  153307. /* This flag is used only for decompression. In cases where some of the
  153308. * components will be ignored (eg grayscale output from YCbCr image),
  153309. * we can skip most computations for the unused components.
  153310. */
  153311. boolean component_needed; /* do we need the value of this component? */
  153312. /* These values are computed before starting a scan of the component. */
  153313. /* The decompressor output side may not use these variables. */
  153314. int MCU_width; /* number of blocks per MCU, horizontally */
  153315. int MCU_height; /* number of blocks per MCU, vertically */
  153316. int MCU_blocks; /* MCU_width * MCU_height */
  153317. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  153318. int last_col_width; /* # of non-dummy blocks across in last MCU */
  153319. int last_row_height; /* # of non-dummy blocks down in last MCU */
  153320. /* Saved quantization table for component; NULL if none yet saved.
  153321. * See jdinput.c comments about the need for this information.
  153322. * This field is currently used only for decompression.
  153323. */
  153324. JQUANT_TBL * quant_table;
  153325. /* Private per-component storage for DCT or IDCT subsystem. */
  153326. void * dct_table;
  153327. } jpeg_component_info;
  153328. /* The script for encoding a multiple-scan file is an array of these: */
  153329. typedef struct {
  153330. int comps_in_scan; /* number of components encoded in this scan */
  153331. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  153332. int Ss, Se; /* progressive JPEG spectral selection parms */
  153333. int Ah, Al; /* progressive JPEG successive approx. parms */
  153334. } jpeg_scan_info;
  153335. /* The decompressor can save APPn and COM markers in a list of these: */
  153336. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  153337. struct jpeg_marker_struct {
  153338. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  153339. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  153340. unsigned int original_length; /* # bytes of data in the file */
  153341. unsigned int data_length; /* # bytes of data saved at data[] */
  153342. JOCTET FAR * data; /* the data contained in the marker */
  153343. /* the marker length word is not counted in data_length or original_length */
  153344. };
  153345. /* Known color spaces. */
  153346. typedef enum {
  153347. JCS_UNKNOWN, /* error/unspecified */
  153348. JCS_GRAYSCALE, /* monochrome */
  153349. JCS_RGB, /* red/green/blue */
  153350. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  153351. JCS_CMYK, /* C/M/Y/K */
  153352. JCS_YCCK /* Y/Cb/Cr/K */
  153353. } J_COLOR_SPACE;
  153354. /* DCT/IDCT algorithm options. */
  153355. typedef enum {
  153356. JDCT_ISLOW, /* slow but accurate integer algorithm */
  153357. JDCT_IFAST, /* faster, less accurate integer method */
  153358. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  153359. } J_DCT_METHOD;
  153360. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  153361. #define JDCT_DEFAULT JDCT_ISLOW
  153362. #endif
  153363. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  153364. #define JDCT_FASTEST JDCT_IFAST
  153365. #endif
  153366. /* Dithering options for decompression. */
  153367. typedef enum {
  153368. JDITHER_NONE, /* no dithering */
  153369. JDITHER_ORDERED, /* simple ordered dither */
  153370. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  153371. } J_DITHER_MODE;
  153372. /* Common fields between JPEG compression and decompression master structs. */
  153373. #define jpeg_common_fields \
  153374. struct jpeg_error_mgr * err; /* Error handler module */\
  153375. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  153376. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  153377. void * client_data; /* Available for use by application */\
  153378. boolean is_decompressor; /* So common code can tell which is which */\
  153379. int global_state /* For checking call sequence validity */
  153380. /* Routines that are to be used by both halves of the library are declared
  153381. * to receive a pointer to this structure. There are no actual instances of
  153382. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  153383. */
  153384. struct jpeg_common_struct {
  153385. jpeg_common_fields; /* Fields common to both master struct types */
  153386. /* Additional fields follow in an actual jpeg_compress_struct or
  153387. * jpeg_decompress_struct. All three structs must agree on these
  153388. * initial fields! (This would be a lot cleaner in C++.)
  153389. */
  153390. };
  153391. typedef struct jpeg_common_struct * j_common_ptr;
  153392. typedef struct jpeg_compress_struct * j_compress_ptr;
  153393. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  153394. /* Master record for a compression instance */
  153395. struct jpeg_compress_struct {
  153396. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  153397. /* Destination for compressed data */
  153398. struct jpeg_destination_mgr * dest;
  153399. /* Description of source image --- these fields must be filled in by
  153400. * outer application before starting compression. in_color_space must
  153401. * be correct before you can even call jpeg_set_defaults().
  153402. */
  153403. JDIMENSION image_width; /* input image width */
  153404. JDIMENSION image_height; /* input image height */
  153405. int input_components; /* # of color components in input image */
  153406. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  153407. double input_gamma; /* image gamma of input image */
  153408. /* Compression parameters --- these fields must be set before calling
  153409. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  153410. * initialize everything to reasonable defaults, then changing anything
  153411. * the application specifically wants to change. That way you won't get
  153412. * burnt when new parameters are added. Also note that there are several
  153413. * helper routines to simplify changing parameters.
  153414. */
  153415. int data_precision; /* bits of precision in image data */
  153416. int num_components; /* # of color components in JPEG image */
  153417. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  153418. jpeg_component_info * comp_info;
  153419. /* comp_info[i] describes component that appears i'th in SOF */
  153420. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  153421. /* ptrs to coefficient quantization tables, or NULL if not defined */
  153422. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153423. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153424. /* ptrs to Huffman coding tables, or NULL if not defined */
  153425. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  153426. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  153427. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  153428. int num_scans; /* # of entries in scan_info array */
  153429. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  153430. /* The default value of scan_info is NULL, which causes a single-scan
  153431. * sequential JPEG file to be emitted. To create a multi-scan file,
  153432. * set num_scans and scan_info to point to an array of scan definitions.
  153433. */
  153434. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  153435. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  153436. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  153437. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  153438. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  153439. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  153440. /* The restart interval can be specified in absolute MCUs by setting
  153441. * restart_interval, or in MCU rows by setting restart_in_rows
  153442. * (in which case the correct restart_interval will be figured
  153443. * for each scan).
  153444. */
  153445. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  153446. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  153447. /* Parameters controlling emission of special markers. */
  153448. boolean write_JFIF_header; /* should a JFIF marker be written? */
  153449. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  153450. UINT8 JFIF_minor_version;
  153451. /* These three values are not used by the JPEG code, merely copied */
  153452. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  153453. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  153454. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  153455. UINT8 density_unit; /* JFIF code for pixel size units */
  153456. UINT16 X_density; /* Horizontal pixel density */
  153457. UINT16 Y_density; /* Vertical pixel density */
  153458. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  153459. /* State variable: index of next scanline to be written to
  153460. * jpeg_write_scanlines(). Application may use this to control its
  153461. * processing loop, e.g., "while (next_scanline < image_height)".
  153462. */
  153463. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  153464. /* Remaining fields are known throughout compressor, but generally
  153465. * should not be touched by a surrounding application.
  153466. */
  153467. /*
  153468. * These fields are computed during compression startup
  153469. */
  153470. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  153471. int max_h_samp_factor; /* largest h_samp_factor */
  153472. int max_v_samp_factor; /* largest v_samp_factor */
  153473. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  153474. /* The coefficient controller receives data in units of MCU rows as defined
  153475. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  153476. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  153477. * "iMCU" (interleaved MCU) row.
  153478. */
  153479. /*
  153480. * These fields are valid during any one scan.
  153481. * They describe the components and MCUs actually appearing in the scan.
  153482. */
  153483. int comps_in_scan; /* # of JPEG components in this scan */
  153484. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  153485. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  153486. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  153487. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  153488. int blocks_in_MCU; /* # of DCT blocks per MCU */
  153489. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  153490. /* MCU_membership[i] is index in cur_comp_info of component owning */
  153491. /* i'th block in an MCU */
  153492. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  153493. /*
  153494. * Links to compression subobjects (methods and private variables of modules)
  153495. */
  153496. struct jpeg_comp_master * master;
  153497. struct jpeg_c_main_controller * main;
  153498. struct jpeg_c_prep_controller * prep;
  153499. struct jpeg_c_coef_controller * coef;
  153500. struct jpeg_marker_writer * marker;
  153501. struct jpeg_color_converter * cconvert;
  153502. struct jpeg_downsampler * downsample;
  153503. struct jpeg_forward_dct * fdct;
  153504. struct jpeg_entropy_encoder * entropy;
  153505. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  153506. int script_space_size;
  153507. };
  153508. /* Master record for a decompression instance */
  153509. struct jpeg_decompress_struct {
  153510. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  153511. /* Source of compressed data */
  153512. struct jpeg_source_mgr * src;
  153513. /* Basic description of image --- filled in by jpeg_read_header(). */
  153514. /* Application may inspect these values to decide how to process image. */
  153515. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  153516. JDIMENSION image_height; /* nominal image height */
  153517. int num_components; /* # of color components in JPEG image */
  153518. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  153519. /* Decompression processing parameters --- these fields must be set before
  153520. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  153521. * them to default values.
  153522. */
  153523. J_COLOR_SPACE out_color_space; /* colorspace for output */
  153524. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  153525. double output_gamma; /* image gamma wanted in output */
  153526. boolean buffered_image; /* TRUE=multiple output passes */
  153527. boolean raw_data_out; /* TRUE=downsampled data wanted */
  153528. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  153529. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  153530. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  153531. boolean quantize_colors; /* TRUE=colormapped output wanted */
  153532. /* the following are ignored if not quantize_colors: */
  153533. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  153534. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  153535. int desired_number_of_colors; /* max # colors to use in created colormap */
  153536. /* these are significant only in buffered-image mode: */
  153537. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  153538. boolean enable_external_quant;/* enable future use of external colormap */
  153539. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  153540. /* Description of actual output image that will be returned to application.
  153541. * These fields are computed by jpeg_start_decompress().
  153542. * You can also use jpeg_calc_output_dimensions() to determine these values
  153543. * in advance of calling jpeg_start_decompress().
  153544. */
  153545. JDIMENSION output_width; /* scaled image width */
  153546. JDIMENSION output_height; /* scaled image height */
  153547. int out_color_components; /* # of color components in out_color_space */
  153548. int output_components; /* # of color components returned */
  153549. /* output_components is 1 (a colormap index) when quantizing colors;
  153550. * otherwise it equals out_color_components.
  153551. */
  153552. int rec_outbuf_height; /* min recommended height of scanline buffer */
  153553. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  153554. * high, space and time will be wasted due to unnecessary data copying.
  153555. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  153556. */
  153557. /* When quantizing colors, the output colormap is described by these fields.
  153558. * The application can supply a colormap by setting colormap non-NULL before
  153559. * calling jpeg_start_decompress; otherwise a colormap is created during
  153560. * jpeg_start_decompress or jpeg_start_output.
  153561. * The map has out_color_components rows and actual_number_of_colors columns.
  153562. */
  153563. int actual_number_of_colors; /* number of entries in use */
  153564. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  153565. /* State variables: these variables indicate the progress of decompression.
  153566. * The application may examine these but must not modify them.
  153567. */
  153568. /* Row index of next scanline to be read from jpeg_read_scanlines().
  153569. * Application may use this to control its processing loop, e.g.,
  153570. * "while (output_scanline < output_height)".
  153571. */
  153572. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  153573. /* Current input scan number and number of iMCU rows completed in scan.
  153574. * These indicate the progress of the decompressor input side.
  153575. */
  153576. int input_scan_number; /* Number of SOS markers seen so far */
  153577. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  153578. /* The "output scan number" is the notional scan being displayed by the
  153579. * output side. The decompressor will not allow output scan/row number
  153580. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  153581. */
  153582. int output_scan_number; /* Nominal scan number being displayed */
  153583. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  153584. /* Current progression status. coef_bits[c][i] indicates the precision
  153585. * with which component c's DCT coefficient i (in zigzag order) is known.
  153586. * It is -1 when no data has yet been received, otherwise it is the point
  153587. * transform (shift) value for the most recent scan of the coefficient
  153588. * (thus, 0 at completion of the progression).
  153589. * This pointer is NULL when reading a non-progressive file.
  153590. */
  153591. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  153592. /* Internal JPEG parameters --- the application usually need not look at
  153593. * these fields. Note that the decompressor output side may not use
  153594. * any parameters that can change between scans.
  153595. */
  153596. /* Quantization and Huffman tables are carried forward across input
  153597. * datastreams when processing abbreviated JPEG datastreams.
  153598. */
  153599. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  153600. /* ptrs to coefficient quantization tables, or NULL if not defined */
  153601. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153602. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153603. /* ptrs to Huffman coding tables, or NULL if not defined */
  153604. /* These parameters are never carried across datastreams, since they
  153605. * are given in SOF/SOS markers or defined to be reset by SOI.
  153606. */
  153607. int data_precision; /* bits of precision in image data */
  153608. jpeg_component_info * comp_info;
  153609. /* comp_info[i] describes component that appears i'th in SOF */
  153610. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  153611. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  153612. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  153613. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  153614. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  153615. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  153616. /* These fields record data obtained from optional markers recognized by
  153617. * the JPEG library.
  153618. */
  153619. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  153620. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  153621. UINT8 JFIF_major_version; /* JFIF version number */
  153622. UINT8 JFIF_minor_version;
  153623. UINT8 density_unit; /* JFIF code for pixel size units */
  153624. UINT16 X_density; /* Horizontal pixel density */
  153625. UINT16 Y_density; /* Vertical pixel density */
  153626. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  153627. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  153628. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  153629. /* Aside from the specific data retained from APPn markers known to the
  153630. * library, the uninterpreted contents of any or all APPn and COM markers
  153631. * can be saved in a list for examination by the application.
  153632. */
  153633. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  153634. /* Remaining fields are known throughout decompressor, but generally
  153635. * should not be touched by a surrounding application.
  153636. */
  153637. /*
  153638. * These fields are computed during decompression startup
  153639. */
  153640. int max_h_samp_factor; /* largest h_samp_factor */
  153641. int max_v_samp_factor; /* largest v_samp_factor */
  153642. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  153643. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  153644. /* The coefficient controller's input and output progress is measured in
  153645. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  153646. * in fully interleaved JPEG scans, but are used whether the scan is
  153647. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  153648. * rows of each component. Therefore, the IDCT output contains
  153649. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  153650. */
  153651. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  153652. /*
  153653. * These fields are valid during any one scan.
  153654. * They describe the components and MCUs actually appearing in the scan.
  153655. * Note that the decompressor output side must not use these fields.
  153656. */
  153657. int comps_in_scan; /* # of JPEG components in this scan */
  153658. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  153659. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  153660. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  153661. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  153662. int blocks_in_MCU; /* # of DCT blocks per MCU */
  153663. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  153664. /* MCU_membership[i] is index in cur_comp_info of component owning */
  153665. /* i'th block in an MCU */
  153666. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  153667. /* This field is shared between entropy decoder and marker parser.
  153668. * It is either zero or the code of a JPEG marker that has been
  153669. * read from the data source, but has not yet been processed.
  153670. */
  153671. int unread_marker;
  153672. /*
  153673. * Links to decompression subobjects (methods, private variables of modules)
  153674. */
  153675. struct jpeg_decomp_master * master;
  153676. struct jpeg_d_main_controller * main;
  153677. struct jpeg_d_coef_controller * coef;
  153678. struct jpeg_d_post_controller * post;
  153679. struct jpeg_input_controller * inputctl;
  153680. struct jpeg_marker_reader * marker;
  153681. struct jpeg_entropy_decoder * entropy;
  153682. struct jpeg_inverse_dct * idct;
  153683. struct jpeg_upsampler * upsample;
  153684. struct jpeg_color_deconverter * cconvert;
  153685. struct jpeg_color_quantizer * cquantize;
  153686. };
  153687. /* "Object" declarations for JPEG modules that may be supplied or called
  153688. * directly by the surrounding application.
  153689. * As with all objects in the JPEG library, these structs only define the
  153690. * publicly visible methods and state variables of a module. Additional
  153691. * private fields may exist after the public ones.
  153692. */
  153693. /* Error handler object */
  153694. struct jpeg_error_mgr {
  153695. /* Error exit handler: does not return to caller */
  153696. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  153697. /* Conditionally emit a trace or warning message */
  153698. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  153699. /* Routine that actually outputs a trace or error message */
  153700. JMETHOD(void, output_message, (j_common_ptr cinfo));
  153701. /* Format a message string for the most recent JPEG error or message */
  153702. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  153703. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  153704. /* Reset error state variables at start of a new image */
  153705. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  153706. /* The message ID code and any parameters are saved here.
  153707. * A message can have one string parameter or up to 8 int parameters.
  153708. */
  153709. int msg_code;
  153710. #define JMSG_STR_PARM_MAX 80
  153711. union {
  153712. int i[8];
  153713. char s[JMSG_STR_PARM_MAX];
  153714. } msg_parm;
  153715. /* Standard state variables for error facility */
  153716. int trace_level; /* max msg_level that will be displayed */
  153717. /* For recoverable corrupt-data errors, we emit a warning message,
  153718. * but keep going unless emit_message chooses to abort. emit_message
  153719. * should count warnings in num_warnings. The surrounding application
  153720. * can check for bad data by seeing if num_warnings is nonzero at the
  153721. * end of processing.
  153722. */
  153723. long num_warnings; /* number of corrupt-data warnings */
  153724. /* These fields point to the table(s) of error message strings.
  153725. * An application can change the table pointer to switch to a different
  153726. * message list (typically, to change the language in which errors are
  153727. * reported). Some applications may wish to add additional error codes
  153728. * that will be handled by the JPEG library error mechanism; the second
  153729. * table pointer is used for this purpose.
  153730. *
  153731. * First table includes all errors generated by JPEG library itself.
  153732. * Error code 0 is reserved for a "no such error string" message.
  153733. */
  153734. const char * const * jpeg_message_table; /* Library errors */
  153735. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  153736. /* Second table can be added by application (see cjpeg/djpeg for example).
  153737. * It contains strings numbered first_addon_message..last_addon_message.
  153738. */
  153739. const char * const * addon_message_table; /* Non-library errors */
  153740. int first_addon_message; /* code for first string in addon table */
  153741. int last_addon_message; /* code for last string in addon table */
  153742. };
  153743. /* Progress monitor object */
  153744. struct jpeg_progress_mgr {
  153745. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  153746. long pass_counter; /* work units completed in this pass */
  153747. long pass_limit; /* total number of work units in this pass */
  153748. int completed_passes; /* passes completed so far */
  153749. int total_passes; /* total number of passes expected */
  153750. };
  153751. /* Data destination object for compression */
  153752. struct jpeg_destination_mgr {
  153753. JOCTET * next_output_byte; /* => next byte to write in buffer */
  153754. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  153755. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  153756. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  153757. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  153758. };
  153759. /* Data source object for decompression */
  153760. struct jpeg_source_mgr {
  153761. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  153762. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  153763. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  153764. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  153765. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  153766. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  153767. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  153768. };
  153769. /* Memory manager object.
  153770. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  153771. * and "really big" objects (virtual arrays with backing store if needed).
  153772. * The memory manager does not allow individual objects to be freed; rather,
  153773. * each created object is assigned to a pool, and whole pools can be freed
  153774. * at once. This is faster and more convenient than remembering exactly what
  153775. * to free, especially where malloc()/free() are not too speedy.
  153776. * NB: alloc routines never return NULL. They exit to error_exit if not
  153777. * successful.
  153778. */
  153779. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  153780. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  153781. #define JPOOL_NUMPOOLS 2
  153782. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  153783. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  153784. struct jpeg_memory_mgr {
  153785. /* Method pointers */
  153786. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  153787. size_t sizeofobject));
  153788. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  153789. size_t sizeofobject));
  153790. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  153791. JDIMENSION samplesperrow,
  153792. JDIMENSION numrows));
  153793. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  153794. JDIMENSION blocksperrow,
  153795. JDIMENSION numrows));
  153796. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  153797. int pool_id,
  153798. boolean pre_zero,
  153799. JDIMENSION samplesperrow,
  153800. JDIMENSION numrows,
  153801. JDIMENSION maxaccess));
  153802. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  153803. int pool_id,
  153804. boolean pre_zero,
  153805. JDIMENSION blocksperrow,
  153806. JDIMENSION numrows,
  153807. JDIMENSION maxaccess));
  153808. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  153809. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  153810. jvirt_sarray_ptr ptr,
  153811. JDIMENSION start_row,
  153812. JDIMENSION num_rows,
  153813. boolean writable));
  153814. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  153815. jvirt_barray_ptr ptr,
  153816. JDIMENSION start_row,
  153817. JDIMENSION num_rows,
  153818. boolean writable));
  153819. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  153820. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  153821. /* Limit on memory allocation for this JPEG object. (Note that this is
  153822. * merely advisory, not a guaranteed maximum; it only affects the space
  153823. * used for virtual-array buffers.) May be changed by outer application
  153824. * after creating the JPEG object.
  153825. */
  153826. long max_memory_to_use;
  153827. /* Maximum allocation request accepted by alloc_large. */
  153828. long max_alloc_chunk;
  153829. };
  153830. /* Routine signature for application-supplied marker processing methods.
  153831. * Need not pass marker code since it is stored in cinfo->unread_marker.
  153832. */
  153833. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  153834. /* Declarations for routines called by application.
  153835. * The JPP macro hides prototype parameters from compilers that can't cope.
  153836. * Note JPP requires double parentheses.
  153837. */
  153838. #ifdef HAVE_PROTOTYPES
  153839. #define JPP(arglist) arglist
  153840. #else
  153841. #define JPP(arglist) ()
  153842. #endif
  153843. /* Short forms of external names for systems with brain-damaged linkers.
  153844. * We shorten external names to be unique in the first six letters, which
  153845. * is good enough for all known systems.
  153846. * (If your compiler itself needs names to be unique in less than 15
  153847. * characters, you are out of luck. Get a better compiler.)
  153848. */
  153849. #ifdef NEED_SHORT_EXTERNAL_NAMES
  153850. #define jpeg_std_error jStdError
  153851. #define jpeg_CreateCompress jCreaCompress
  153852. #define jpeg_CreateDecompress jCreaDecompress
  153853. #define jpeg_destroy_compress jDestCompress
  153854. #define jpeg_destroy_decompress jDestDecompress
  153855. #define jpeg_stdio_dest jStdDest
  153856. #define jpeg_stdio_src jStdSrc
  153857. #define jpeg_set_defaults jSetDefaults
  153858. #define jpeg_set_colorspace jSetColorspace
  153859. #define jpeg_default_colorspace jDefColorspace
  153860. #define jpeg_set_quality jSetQuality
  153861. #define jpeg_set_linear_quality jSetLQuality
  153862. #define jpeg_add_quant_table jAddQuantTable
  153863. #define jpeg_quality_scaling jQualityScaling
  153864. #define jpeg_simple_progression jSimProgress
  153865. #define jpeg_suppress_tables jSuppressTables
  153866. #define jpeg_alloc_quant_table jAlcQTable
  153867. #define jpeg_alloc_huff_table jAlcHTable
  153868. #define jpeg_start_compress jStrtCompress
  153869. #define jpeg_write_scanlines jWrtScanlines
  153870. #define jpeg_finish_compress jFinCompress
  153871. #define jpeg_write_raw_data jWrtRawData
  153872. #define jpeg_write_marker jWrtMarker
  153873. #define jpeg_write_m_header jWrtMHeader
  153874. #define jpeg_write_m_byte jWrtMByte
  153875. #define jpeg_write_tables jWrtTables
  153876. #define jpeg_read_header jReadHeader
  153877. #define jpeg_start_decompress jStrtDecompress
  153878. #define jpeg_read_scanlines jReadScanlines
  153879. #define jpeg_finish_decompress jFinDecompress
  153880. #define jpeg_read_raw_data jReadRawData
  153881. #define jpeg_has_multiple_scans jHasMultScn
  153882. #define jpeg_start_output jStrtOutput
  153883. #define jpeg_finish_output jFinOutput
  153884. #define jpeg_input_complete jInComplete
  153885. #define jpeg_new_colormap jNewCMap
  153886. #define jpeg_consume_input jConsumeInput
  153887. #define jpeg_calc_output_dimensions jCalcDimensions
  153888. #define jpeg_save_markers jSaveMarkers
  153889. #define jpeg_set_marker_processor jSetMarker
  153890. #define jpeg_read_coefficients jReadCoefs
  153891. #define jpeg_write_coefficients jWrtCoefs
  153892. #define jpeg_copy_critical_parameters jCopyCrit
  153893. #define jpeg_abort_compress jAbrtCompress
  153894. #define jpeg_abort_decompress jAbrtDecompress
  153895. #define jpeg_abort jAbort
  153896. #define jpeg_destroy jDestroy
  153897. #define jpeg_resync_to_restart jResyncRestart
  153898. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  153899. /* Default error-management setup */
  153900. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  153901. JPP((struct jpeg_error_mgr * err));
  153902. /* Initialization of JPEG compression objects.
  153903. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  153904. * names that applications should call. These expand to calls on
  153905. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  153906. * passed for version mismatch checking.
  153907. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  153908. */
  153909. #define jpeg_create_compress(cinfo) \
  153910. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  153911. (size_t) sizeof(struct jpeg_compress_struct))
  153912. #define jpeg_create_decompress(cinfo) \
  153913. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  153914. (size_t) sizeof(struct jpeg_decompress_struct))
  153915. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  153916. int version, size_t structsize));
  153917. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  153918. int version, size_t structsize));
  153919. /* Destruction of JPEG compression objects */
  153920. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  153921. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  153922. /* Standard data source and destination managers: stdio streams. */
  153923. /* Caller is responsible for opening the file before and closing after. */
  153924. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  153925. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  153926. /* Default parameter setup for compression */
  153927. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  153928. /* Compression parameter setup aids */
  153929. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  153930. J_COLOR_SPACE colorspace));
  153931. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  153932. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  153933. boolean force_baseline));
  153934. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  153935. int scale_factor,
  153936. boolean force_baseline));
  153937. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  153938. const unsigned int *basic_table,
  153939. int scale_factor,
  153940. boolean force_baseline));
  153941. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  153942. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  153943. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  153944. boolean suppress));
  153945. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  153946. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  153947. /* Main entry points for compression */
  153948. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  153949. boolean write_all_tables));
  153950. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  153951. JSAMPARRAY scanlines,
  153952. JDIMENSION num_lines));
  153953. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  153954. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  153955. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  153956. JSAMPIMAGE data,
  153957. JDIMENSION num_lines));
  153958. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  153959. EXTERN(void) jpeg_write_marker
  153960. JPP((j_compress_ptr cinfo, int marker,
  153961. const JOCTET * dataptr, unsigned int datalen));
  153962. /* Same, but piecemeal. */
  153963. EXTERN(void) jpeg_write_m_header
  153964. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  153965. EXTERN(void) jpeg_write_m_byte
  153966. JPP((j_compress_ptr cinfo, int val));
  153967. /* Alternate compression function: just write an abbreviated table file */
  153968. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  153969. /* Decompression startup: read start of JPEG datastream to see what's there */
  153970. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  153971. boolean require_image));
  153972. /* Return value is one of: */
  153973. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  153974. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  153975. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  153976. /* If you pass require_image = TRUE (normal case), you need not check for
  153977. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  153978. * JPEG_SUSPENDED is only possible if you use a data source module that can
  153979. * give a suspension return (the stdio source module doesn't).
  153980. */
  153981. /* Main entry points for decompression */
  153982. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  153983. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  153984. JSAMPARRAY scanlines,
  153985. JDIMENSION max_lines));
  153986. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  153987. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  153988. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  153989. JSAMPIMAGE data,
  153990. JDIMENSION max_lines));
  153991. /* Additional entry points for buffered-image mode. */
  153992. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  153993. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  153994. int scan_number));
  153995. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  153996. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  153997. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  153998. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  153999. /* Return value is one of: */
  154000. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  154001. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  154002. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  154003. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  154004. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  154005. /* Precalculate output dimensions for current decompression parameters. */
  154006. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  154007. /* Control saving of COM and APPn markers into marker_list. */
  154008. EXTERN(void) jpeg_save_markers
  154009. JPP((j_decompress_ptr cinfo, int marker_code,
  154010. unsigned int length_limit));
  154011. /* Install a special processing method for COM or APPn markers. */
  154012. EXTERN(void) jpeg_set_marker_processor
  154013. JPP((j_decompress_ptr cinfo, int marker_code,
  154014. jpeg_marker_parser_method routine));
  154015. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  154016. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  154017. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  154018. jvirt_barray_ptr * coef_arrays));
  154019. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  154020. j_compress_ptr dstinfo));
  154021. /* If you choose to abort compression or decompression before completing
  154022. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  154023. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  154024. * if you're done with the JPEG object, but if you want to clean it up and
  154025. * reuse it, call this:
  154026. */
  154027. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  154028. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  154029. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  154030. * flavor of JPEG object. These may be more convenient in some places.
  154031. */
  154032. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  154033. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  154034. /* Default restart-marker-resync procedure for use by data source modules */
  154035. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  154036. int desired));
  154037. /* These marker codes are exported since applications and data source modules
  154038. * are likely to want to use them.
  154039. */
  154040. #define JPEG_RST0 0xD0 /* RST0 marker code */
  154041. #define JPEG_EOI 0xD9 /* EOI marker code */
  154042. #define JPEG_APP0 0xE0 /* APP0 marker code */
  154043. #define JPEG_COM 0xFE /* COM marker code */
  154044. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  154045. * for structure definitions that are never filled in, keep it quiet by
  154046. * supplying dummy definitions for the various substructures.
  154047. */
  154048. #ifdef INCOMPLETE_TYPES_BROKEN
  154049. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  154050. struct jvirt_sarray_control { long dummy; };
  154051. struct jvirt_barray_control { long dummy; };
  154052. struct jpeg_comp_master { long dummy; };
  154053. struct jpeg_c_main_controller { long dummy; };
  154054. struct jpeg_c_prep_controller { long dummy; };
  154055. struct jpeg_c_coef_controller { long dummy; };
  154056. struct jpeg_marker_writer { long dummy; };
  154057. struct jpeg_color_converter { long dummy; };
  154058. struct jpeg_downsampler { long dummy; };
  154059. struct jpeg_forward_dct { long dummy; };
  154060. struct jpeg_entropy_encoder { long dummy; };
  154061. struct jpeg_decomp_master { long dummy; };
  154062. struct jpeg_d_main_controller { long dummy; };
  154063. struct jpeg_d_coef_controller { long dummy; };
  154064. struct jpeg_d_post_controller { long dummy; };
  154065. struct jpeg_input_controller { long dummy; };
  154066. struct jpeg_marker_reader { long dummy; };
  154067. struct jpeg_entropy_decoder { long dummy; };
  154068. struct jpeg_inverse_dct { long dummy; };
  154069. struct jpeg_upsampler { long dummy; };
  154070. struct jpeg_color_deconverter { long dummy; };
  154071. struct jpeg_color_quantizer { long dummy; };
  154072. #endif /* JPEG_INTERNALS */
  154073. #endif /* INCOMPLETE_TYPES_BROKEN */
  154074. /*
  154075. * The JPEG library modules define JPEG_INTERNALS before including this file.
  154076. * The internal structure declarations are read only when that is true.
  154077. * Applications using the library should not include jpegint.h, but may wish
  154078. * to include jerror.h.
  154079. */
  154080. #ifdef JPEG_INTERNALS
  154081. /********* Start of inlined file: jpegint.h *********/
  154082. /* Declarations for both compression & decompression */
  154083. typedef enum { /* Operating modes for buffer controllers */
  154084. JBUF_PASS_THRU, /* Plain stripwise operation */
  154085. /* Remaining modes require a full-image buffer to have been created */
  154086. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  154087. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  154088. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  154089. } J_BUF_MODE;
  154090. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  154091. #define CSTATE_START 100 /* after create_compress */
  154092. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  154093. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  154094. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  154095. #define DSTATE_START 200 /* after create_decompress */
  154096. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  154097. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  154098. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  154099. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  154100. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  154101. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  154102. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  154103. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  154104. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  154105. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  154106. /* Declarations for compression modules */
  154107. /* Master control module */
  154108. struct jpeg_comp_master {
  154109. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  154110. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  154111. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154112. /* State variables made visible to other modules */
  154113. boolean call_pass_startup; /* True if pass_startup must be called */
  154114. boolean is_last_pass; /* True during last pass */
  154115. };
  154116. /* Main buffer control (downsampled-data buffer) */
  154117. struct jpeg_c_main_controller {
  154118. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154119. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  154120. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  154121. JDIMENSION in_rows_avail));
  154122. };
  154123. /* Compression preprocessing (downsampling input buffer control) */
  154124. struct jpeg_c_prep_controller {
  154125. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154126. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  154127. JSAMPARRAY input_buf,
  154128. JDIMENSION *in_row_ctr,
  154129. JDIMENSION in_rows_avail,
  154130. JSAMPIMAGE output_buf,
  154131. JDIMENSION *out_row_group_ctr,
  154132. JDIMENSION out_row_groups_avail));
  154133. };
  154134. /* Coefficient buffer control */
  154135. struct jpeg_c_coef_controller {
  154136. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154137. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  154138. JSAMPIMAGE input_buf));
  154139. };
  154140. /* Colorspace conversion */
  154141. struct jpeg_color_converter {
  154142. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154143. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  154144. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  154145. JDIMENSION output_row, int num_rows));
  154146. };
  154147. /* Downsampling */
  154148. struct jpeg_downsampler {
  154149. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154150. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  154151. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  154152. JSAMPIMAGE output_buf,
  154153. JDIMENSION out_row_group_index));
  154154. boolean need_context_rows; /* TRUE if need rows above & below */
  154155. };
  154156. /* Forward DCT (also controls coefficient quantization) */
  154157. struct jpeg_forward_dct {
  154158. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154159. /* perhaps this should be an array??? */
  154160. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  154161. jpeg_component_info * compptr,
  154162. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  154163. JDIMENSION start_row, JDIMENSION start_col,
  154164. JDIMENSION num_blocks));
  154165. };
  154166. /* Entropy encoding */
  154167. struct jpeg_entropy_encoder {
  154168. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  154169. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  154170. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154171. };
  154172. /* Marker writing */
  154173. struct jpeg_marker_writer {
  154174. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  154175. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  154176. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  154177. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  154178. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  154179. /* These routines are exported to allow insertion of extra markers */
  154180. /* Probably only COM and APPn markers should be written this way */
  154181. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  154182. unsigned int datalen));
  154183. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  154184. };
  154185. /* Declarations for decompression modules */
  154186. /* Master control module */
  154187. struct jpeg_decomp_master {
  154188. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  154189. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  154190. /* State variables made visible to other modules */
  154191. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  154192. };
  154193. /* Input control module */
  154194. struct jpeg_input_controller {
  154195. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  154196. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  154197. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154198. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  154199. /* State variables made visible to other modules */
  154200. boolean has_multiple_scans; /* True if file has multiple scans */
  154201. boolean eoi_reached; /* True when EOI has been consumed */
  154202. };
  154203. /* Main buffer control (downsampled-data buffer) */
  154204. struct jpeg_d_main_controller {
  154205. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154206. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  154207. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  154208. JDIMENSION out_rows_avail));
  154209. };
  154210. /* Coefficient buffer control */
  154211. struct jpeg_d_coef_controller {
  154212. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154213. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  154214. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  154215. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  154216. JSAMPIMAGE output_buf));
  154217. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  154218. jvirt_barray_ptr *coef_arrays;
  154219. };
  154220. /* Decompression postprocessing (color quantization buffer control) */
  154221. struct jpeg_d_post_controller {
  154222. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154223. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  154224. JSAMPIMAGE input_buf,
  154225. JDIMENSION *in_row_group_ctr,
  154226. JDIMENSION in_row_groups_avail,
  154227. JSAMPARRAY output_buf,
  154228. JDIMENSION *out_row_ctr,
  154229. JDIMENSION out_rows_avail));
  154230. };
  154231. /* Marker reading & parsing */
  154232. struct jpeg_marker_reader {
  154233. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  154234. /* Read markers until SOS or EOI.
  154235. * Returns same codes as are defined for jpeg_consume_input:
  154236. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  154237. */
  154238. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  154239. /* Read a restart marker --- exported for use by entropy decoder only */
  154240. jpeg_marker_parser_method read_restart_marker;
  154241. /* State of marker reader --- nominally internal, but applications
  154242. * supplying COM or APPn handlers might like to know the state.
  154243. */
  154244. boolean saw_SOI; /* found SOI? */
  154245. boolean saw_SOF; /* found SOF? */
  154246. int next_restart_num; /* next restart number expected (0-7) */
  154247. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  154248. };
  154249. /* Entropy decoding */
  154250. struct jpeg_entropy_decoder {
  154251. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154252. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  154253. JBLOCKROW *MCU_data));
  154254. /* This is here to share code between baseline and progressive decoders; */
  154255. /* other modules probably should not use it */
  154256. boolean insufficient_data; /* set TRUE after emitting warning */
  154257. };
  154258. /* Inverse DCT (also performs dequantization) */
  154259. typedef JMETHOD(void, inverse_DCT_method_ptr,
  154260. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  154261. JCOEFPTR coef_block,
  154262. JSAMPARRAY output_buf, JDIMENSION output_col));
  154263. struct jpeg_inverse_dct {
  154264. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154265. /* It is useful to allow each component to have a separate IDCT method. */
  154266. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  154267. };
  154268. /* Upsampling (note that upsampler must also call color converter) */
  154269. struct jpeg_upsampler {
  154270. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154271. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  154272. JSAMPIMAGE input_buf,
  154273. JDIMENSION *in_row_group_ctr,
  154274. JDIMENSION in_row_groups_avail,
  154275. JSAMPARRAY output_buf,
  154276. JDIMENSION *out_row_ctr,
  154277. JDIMENSION out_rows_avail));
  154278. boolean need_context_rows; /* TRUE if need rows above & below */
  154279. };
  154280. /* Colorspace conversion */
  154281. struct jpeg_color_deconverter {
  154282. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154283. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  154284. JSAMPIMAGE input_buf, JDIMENSION input_row,
  154285. JSAMPARRAY output_buf, int num_rows));
  154286. };
  154287. /* Color quantization or color precision reduction */
  154288. struct jpeg_color_quantizer {
  154289. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  154290. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  154291. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  154292. int num_rows));
  154293. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  154294. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  154295. };
  154296. /* Miscellaneous useful macros */
  154297. #undef MAX
  154298. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  154299. #undef MIN
  154300. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  154301. /* We assume that right shift corresponds to signed division by 2 with
  154302. * rounding towards minus infinity. This is correct for typical "arithmetic
  154303. * shift" instructions that shift in copies of the sign bit. But some
  154304. * C compilers implement >> with an unsigned shift. For these machines you
  154305. * must define RIGHT_SHIFT_IS_UNSIGNED.
  154306. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  154307. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  154308. * included in the variables of any routine using RIGHT_SHIFT.
  154309. */
  154310. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  154311. #define SHIFT_TEMPS INT32 shift_temp;
  154312. #define RIGHT_SHIFT(x,shft) \
  154313. ((shift_temp = (x)) < 0 ? \
  154314. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  154315. (shift_temp >> (shft)))
  154316. #else
  154317. #define SHIFT_TEMPS
  154318. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  154319. #endif
  154320. /* Short forms of external names for systems with brain-damaged linkers. */
  154321. #ifdef NEED_SHORT_EXTERNAL_NAMES
  154322. #define jinit_compress_master jICompress
  154323. #define jinit_c_master_control jICMaster
  154324. #define jinit_c_main_controller jICMainC
  154325. #define jinit_c_prep_controller jICPrepC
  154326. #define jinit_c_coef_controller jICCoefC
  154327. #define jinit_color_converter jICColor
  154328. #define jinit_downsampler jIDownsampler
  154329. #define jinit_forward_dct jIFDCT
  154330. #define jinit_huff_encoder jIHEncoder
  154331. #define jinit_phuff_encoder jIPHEncoder
  154332. #define jinit_marker_writer jIMWriter
  154333. #define jinit_master_decompress jIDMaster
  154334. #define jinit_d_main_controller jIDMainC
  154335. #define jinit_d_coef_controller jIDCoefC
  154336. #define jinit_d_post_controller jIDPostC
  154337. #define jinit_input_controller jIInCtlr
  154338. #define jinit_marker_reader jIMReader
  154339. #define jinit_huff_decoder jIHDecoder
  154340. #define jinit_phuff_decoder jIPHDecoder
  154341. #define jinit_inverse_dct jIIDCT
  154342. #define jinit_upsampler jIUpsampler
  154343. #define jinit_color_deconverter jIDColor
  154344. #define jinit_1pass_quantizer jI1Quant
  154345. #define jinit_2pass_quantizer jI2Quant
  154346. #define jinit_merged_upsampler jIMUpsampler
  154347. #define jinit_memory_mgr jIMemMgr
  154348. #define jdiv_round_up jDivRound
  154349. #define jround_up jRound
  154350. #define jcopy_sample_rows jCopySamples
  154351. #define jcopy_block_row jCopyBlocks
  154352. #define jzero_far jZeroFar
  154353. #define jpeg_zigzag_order jZIGTable
  154354. #define jpeg_natural_order jZAGTable
  154355. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  154356. /* Compression module initialization routines */
  154357. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  154358. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  154359. boolean transcode_only));
  154360. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  154361. boolean need_full_buffer));
  154362. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  154363. boolean need_full_buffer));
  154364. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  154365. boolean need_full_buffer));
  154366. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  154367. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  154368. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  154369. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  154370. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  154371. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  154372. /* Decompression module initialization routines */
  154373. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  154374. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  154375. boolean need_full_buffer));
  154376. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  154377. boolean need_full_buffer));
  154378. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  154379. boolean need_full_buffer));
  154380. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  154381. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  154382. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  154383. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  154384. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  154385. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  154386. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  154387. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  154388. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  154389. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  154390. /* Memory manager initialization */
  154391. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  154392. /* Utility routines in jutils.c */
  154393. EXTERN(long) jdiv_round_up JPP((long a, long b));
  154394. EXTERN(long) jround_up JPP((long a, long b));
  154395. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  154396. JSAMPARRAY output_array, int dest_row,
  154397. int num_rows, JDIMENSION num_cols));
  154398. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  154399. JDIMENSION num_blocks));
  154400. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  154401. /* Constant tables in jutils.c */
  154402. #if 0 /* This table is not actually needed in v6a */
  154403. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  154404. #endif
  154405. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  154406. /* Suppress undefined-structure complaints if necessary. */
  154407. #ifdef INCOMPLETE_TYPES_BROKEN
  154408. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  154409. struct jvirt_sarray_control { long dummy; };
  154410. struct jvirt_barray_control { long dummy; };
  154411. #endif
  154412. #endif /* INCOMPLETE_TYPES_BROKEN */
  154413. /********* End of inlined file: jpegint.h *********/
  154414. /* fetch private declarations */
  154415. /********* Start of inlined file: jerror.h *********/
  154416. /*
  154417. * To define the enum list of message codes, include this file without
  154418. * defining macro JMESSAGE. To create a message string table, include it
  154419. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  154420. */
  154421. #ifndef JMESSAGE
  154422. #ifndef JERROR_H
  154423. /* First time through, define the enum list */
  154424. #define JMAKE_ENUM_LIST
  154425. #else
  154426. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  154427. #define JMESSAGE(code,string)
  154428. #endif /* JERROR_H */
  154429. #endif /* JMESSAGE */
  154430. #ifdef JMAKE_ENUM_LIST
  154431. typedef enum {
  154432. #define JMESSAGE(code,string) code ,
  154433. #endif /* JMAKE_ENUM_LIST */
  154434. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  154435. /* For maintenance convenience, list is alphabetical by message code name */
  154436. JMESSAGE(JERR_ARITH_NOTIMPL,
  154437. "Sorry, there are legal restrictions on arithmetic coding")
  154438. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  154439. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  154440. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  154441. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  154442. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  154443. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  154444. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  154445. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  154446. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  154447. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  154448. JMESSAGE(JERR_BAD_LIB_VERSION,
  154449. "Wrong JPEG library version: library is %d, caller expects %d")
  154450. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  154451. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  154452. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  154453. JMESSAGE(JERR_BAD_PROGRESSION,
  154454. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  154455. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  154456. "Invalid progressive parameters at scan script entry %d")
  154457. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  154458. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  154459. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  154460. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  154461. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  154462. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  154463. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  154464. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  154465. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  154466. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  154467. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  154468. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  154469. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  154470. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  154471. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  154472. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  154473. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  154474. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  154475. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  154476. JMESSAGE(JERR_FILE_READ, "Input file read error")
  154477. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  154478. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  154479. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  154480. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  154481. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  154482. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  154483. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  154484. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  154485. "Cannot transcode due to multiple use of quantization table %d")
  154486. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  154487. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  154488. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  154489. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  154490. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  154491. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  154492. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  154493. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  154494. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  154495. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  154496. JMESSAGE(JERR_QUANT_COMPONENTS,
  154497. "Cannot quantize more than %d color components")
  154498. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  154499. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  154500. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  154501. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  154502. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  154503. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  154504. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  154505. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  154506. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  154507. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  154508. JMESSAGE(JERR_TFILE_WRITE,
  154509. "Write failed on temporary file --- out of disk space?")
  154510. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  154511. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  154512. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  154513. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  154514. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  154515. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  154516. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  154517. JMESSAGE(JMSG_VERSION, JVERSION)
  154518. JMESSAGE(JTRC_16BIT_TABLES,
  154519. "Caution: quantization tables are too coarse for baseline JPEG")
  154520. JMESSAGE(JTRC_ADOBE,
  154521. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  154522. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  154523. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  154524. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  154525. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  154526. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  154527. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  154528. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  154529. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  154530. JMESSAGE(JTRC_EOI, "End Of Image")
  154531. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  154532. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  154533. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  154534. "Warning: thumbnail image size does not match data length %u")
  154535. JMESSAGE(JTRC_JFIF_EXTENSION,
  154536. "JFIF extension marker: type 0x%02x, length %u")
  154537. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  154538. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  154539. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  154540. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  154541. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  154542. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  154543. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  154544. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  154545. JMESSAGE(JTRC_RST, "RST%d")
  154546. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  154547. "Smoothing not supported with nonstandard sampling ratios")
  154548. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  154549. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  154550. JMESSAGE(JTRC_SOI, "Start of Image")
  154551. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  154552. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  154553. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  154554. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  154555. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  154556. JMESSAGE(JTRC_THUMB_JPEG,
  154557. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  154558. JMESSAGE(JTRC_THUMB_PALETTE,
  154559. "JFIF extension marker: palette thumbnail image, length %u")
  154560. JMESSAGE(JTRC_THUMB_RGB,
  154561. "JFIF extension marker: RGB thumbnail image, length %u")
  154562. JMESSAGE(JTRC_UNKNOWN_IDS,
  154563. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  154564. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  154565. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  154566. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  154567. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  154568. "Inconsistent progression sequence for component %d coefficient %d")
  154569. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  154570. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  154571. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  154572. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  154573. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  154574. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  154575. JMESSAGE(JWRN_MUST_RESYNC,
  154576. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  154577. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  154578. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  154579. #ifdef JMAKE_ENUM_LIST
  154580. JMSG_LASTMSGCODE
  154581. } J_MESSAGE_CODE;
  154582. #undef JMAKE_ENUM_LIST
  154583. #endif /* JMAKE_ENUM_LIST */
  154584. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  154585. #undef JMESSAGE
  154586. #ifndef JERROR_H
  154587. #define JERROR_H
  154588. /* Macros to simplify using the error and trace message stuff */
  154589. /* The first parameter is either type of cinfo pointer */
  154590. /* Fatal errors (print message and exit) */
  154591. #define ERREXIT(cinfo,code) \
  154592. ((cinfo)->err->msg_code = (code), \
  154593. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154594. #define ERREXIT1(cinfo,code,p1) \
  154595. ((cinfo)->err->msg_code = (code), \
  154596. (cinfo)->err->msg_parm.i[0] = (p1), \
  154597. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154598. #define ERREXIT2(cinfo,code,p1,p2) \
  154599. ((cinfo)->err->msg_code = (code), \
  154600. (cinfo)->err->msg_parm.i[0] = (p1), \
  154601. (cinfo)->err->msg_parm.i[1] = (p2), \
  154602. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154603. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  154604. ((cinfo)->err->msg_code = (code), \
  154605. (cinfo)->err->msg_parm.i[0] = (p1), \
  154606. (cinfo)->err->msg_parm.i[1] = (p2), \
  154607. (cinfo)->err->msg_parm.i[2] = (p3), \
  154608. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154609. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  154610. ((cinfo)->err->msg_code = (code), \
  154611. (cinfo)->err->msg_parm.i[0] = (p1), \
  154612. (cinfo)->err->msg_parm.i[1] = (p2), \
  154613. (cinfo)->err->msg_parm.i[2] = (p3), \
  154614. (cinfo)->err->msg_parm.i[3] = (p4), \
  154615. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154616. #define ERREXITS(cinfo,code,str) \
  154617. ((cinfo)->err->msg_code = (code), \
  154618. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  154619. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154620. #define MAKESTMT(stuff) do { stuff } while (0)
  154621. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  154622. #define WARNMS(cinfo,code) \
  154623. ((cinfo)->err->msg_code = (code), \
  154624. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154625. #define WARNMS1(cinfo,code,p1) \
  154626. ((cinfo)->err->msg_code = (code), \
  154627. (cinfo)->err->msg_parm.i[0] = (p1), \
  154628. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154629. #define WARNMS2(cinfo,code,p1,p2) \
  154630. ((cinfo)->err->msg_code = (code), \
  154631. (cinfo)->err->msg_parm.i[0] = (p1), \
  154632. (cinfo)->err->msg_parm.i[1] = (p2), \
  154633. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154634. /* Informational/debugging messages */
  154635. #define TRACEMS(cinfo,lvl,code) \
  154636. ((cinfo)->err->msg_code = (code), \
  154637. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154638. #define TRACEMS1(cinfo,lvl,code,p1) \
  154639. ((cinfo)->err->msg_code = (code), \
  154640. (cinfo)->err->msg_parm.i[0] = (p1), \
  154641. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154642. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  154643. ((cinfo)->err->msg_code = (code), \
  154644. (cinfo)->err->msg_parm.i[0] = (p1), \
  154645. (cinfo)->err->msg_parm.i[1] = (p2), \
  154646. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154647. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  154648. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154649. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  154650. (cinfo)->err->msg_code = (code); \
  154651. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154652. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  154653. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154654. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154655. (cinfo)->err->msg_code = (code); \
  154656. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154657. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  154658. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154659. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154660. _mp[4] = (p5); \
  154661. (cinfo)->err->msg_code = (code); \
  154662. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154663. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  154664. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154665. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154666. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  154667. (cinfo)->err->msg_code = (code); \
  154668. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154669. #define TRACEMSS(cinfo,lvl,code,str) \
  154670. ((cinfo)->err->msg_code = (code), \
  154671. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  154672. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154673. #endif /* JERROR_H */
  154674. /********* End of inlined file: jerror.h *********/
  154675. /* fetch error codes too */
  154676. #endif
  154677. #endif /* JPEGLIB_H */
  154678. /********* End of inlined file: jpeglib.h *********/
  154679. /********* Start of inlined file: jcapimin.c *********/
  154680. #define JPEG_INTERNALS
  154681. /********* Start of inlined file: jinclude.h *********/
  154682. /* Include auto-config file to find out which system include files we need. */
  154683. #ifndef __jinclude_h__
  154684. #define __jinclude_h__
  154685. /********* Start of inlined file: jconfig.h *********/
  154686. /* see jconfig.doc for explanations */
  154687. // disable all the warnings under MSVC
  154688. #ifdef _MSC_VER
  154689. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  154690. #endif
  154691. #ifdef __BORLANDC__
  154692. #pragma warn -8057
  154693. #pragma warn -8019
  154694. #pragma warn -8004
  154695. #pragma warn -8008
  154696. #endif
  154697. #define HAVE_PROTOTYPES
  154698. #define HAVE_UNSIGNED_CHAR
  154699. #define HAVE_UNSIGNED_SHORT
  154700. /* #define void char */
  154701. /* #define const */
  154702. #undef CHAR_IS_UNSIGNED
  154703. #define HAVE_STDDEF_H
  154704. #define HAVE_STDLIB_H
  154705. #undef NEED_BSD_STRINGS
  154706. #undef NEED_SYS_TYPES_H
  154707. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  154708. #undef NEED_SHORT_EXTERNAL_NAMES
  154709. #undef INCOMPLETE_TYPES_BROKEN
  154710. /* Define "boolean" as unsigned char, not int, per Windows custom */
  154711. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  154712. typedef unsigned char boolean;
  154713. #endif
  154714. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  154715. #ifdef JPEG_INTERNALS
  154716. #undef RIGHT_SHIFT_IS_UNSIGNED
  154717. #endif /* JPEG_INTERNALS */
  154718. #ifdef JPEG_CJPEG_DJPEG
  154719. #define BMP_SUPPORTED /* BMP image file format */
  154720. #define GIF_SUPPORTED /* GIF image file format */
  154721. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  154722. #undef RLE_SUPPORTED /* Utah RLE image file format */
  154723. #define TARGA_SUPPORTED /* Targa image file format */
  154724. #define TWO_FILE_COMMANDLINE /* optional */
  154725. #define USE_SETMODE /* Microsoft has setmode() */
  154726. #undef NEED_SIGNAL_CATCHER
  154727. #undef DONT_USE_B_MODE
  154728. #undef PROGRESS_REPORT /* optional */
  154729. #endif /* JPEG_CJPEG_DJPEG */
  154730. /********* End of inlined file: jconfig.h *********/
  154731. /* auto configuration options */
  154732. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  154733. /*
  154734. * We need the NULL macro and size_t typedef.
  154735. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  154736. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  154737. * pull in <sys/types.h> as well.
  154738. * Note that the core JPEG library does not require <stdio.h>;
  154739. * only the default error handler and data source/destination modules do.
  154740. * But we must pull it in because of the references to FILE in jpeglib.h.
  154741. * You can remove those references if you want to compile without <stdio.h>.
  154742. */
  154743. #ifdef HAVE_STDDEF_H
  154744. #include <stddef.h>
  154745. #endif
  154746. #ifdef HAVE_STDLIB_H
  154747. #include <stdlib.h>
  154748. #endif
  154749. #ifdef NEED_SYS_TYPES_H
  154750. #include <sys/types.h>
  154751. #endif
  154752. #include <stdio.h>
  154753. /*
  154754. * We need memory copying and zeroing functions, plus strncpy().
  154755. * ANSI and System V implementations declare these in <string.h>.
  154756. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  154757. * Some systems may declare memset and memcpy in <memory.h>.
  154758. *
  154759. * NOTE: we assume the size parameters to these functions are of type size_t.
  154760. * Change the casts in these macros if not!
  154761. */
  154762. #ifdef NEED_BSD_STRINGS
  154763. #include <strings.h>
  154764. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  154765. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  154766. #else /* not BSD, assume ANSI/SysV string lib */
  154767. #include <string.h>
  154768. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  154769. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  154770. #endif
  154771. /*
  154772. * In ANSI C, and indeed any rational implementation, size_t is also the
  154773. * type returned by sizeof(). However, it seems there are some irrational
  154774. * implementations out there, in which sizeof() returns an int even though
  154775. * size_t is defined as long or unsigned long. To ensure consistent results
  154776. * we always use this SIZEOF() macro in place of using sizeof() directly.
  154777. */
  154778. #define SIZEOF(object) ((size_t) sizeof(object))
  154779. /*
  154780. * The modules that use fread() and fwrite() always invoke them through
  154781. * these macros. On some systems you may need to twiddle the argument casts.
  154782. * CAUTION: argument order is different from underlying functions!
  154783. */
  154784. #define JFREAD(file,buf,sizeofbuf) \
  154785. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  154786. #define JFWRITE(file,buf,sizeofbuf) \
  154787. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  154788. typedef enum { /* JPEG marker codes */
  154789. M_SOF0 = 0xc0,
  154790. M_SOF1 = 0xc1,
  154791. M_SOF2 = 0xc2,
  154792. M_SOF3 = 0xc3,
  154793. M_SOF5 = 0xc5,
  154794. M_SOF6 = 0xc6,
  154795. M_SOF7 = 0xc7,
  154796. M_JPG = 0xc8,
  154797. M_SOF9 = 0xc9,
  154798. M_SOF10 = 0xca,
  154799. M_SOF11 = 0xcb,
  154800. M_SOF13 = 0xcd,
  154801. M_SOF14 = 0xce,
  154802. M_SOF15 = 0xcf,
  154803. M_DHT = 0xc4,
  154804. M_DAC = 0xcc,
  154805. M_RST0 = 0xd0,
  154806. M_RST1 = 0xd1,
  154807. M_RST2 = 0xd2,
  154808. M_RST3 = 0xd3,
  154809. M_RST4 = 0xd4,
  154810. M_RST5 = 0xd5,
  154811. M_RST6 = 0xd6,
  154812. M_RST7 = 0xd7,
  154813. M_SOI = 0xd8,
  154814. M_EOI = 0xd9,
  154815. M_SOS = 0xda,
  154816. M_DQT = 0xdb,
  154817. M_DNL = 0xdc,
  154818. M_DRI = 0xdd,
  154819. M_DHP = 0xde,
  154820. M_EXP = 0xdf,
  154821. M_APP0 = 0xe0,
  154822. M_APP1 = 0xe1,
  154823. M_APP2 = 0xe2,
  154824. M_APP3 = 0xe3,
  154825. M_APP4 = 0xe4,
  154826. M_APP5 = 0xe5,
  154827. M_APP6 = 0xe6,
  154828. M_APP7 = 0xe7,
  154829. M_APP8 = 0xe8,
  154830. M_APP9 = 0xe9,
  154831. M_APP10 = 0xea,
  154832. M_APP11 = 0xeb,
  154833. M_APP12 = 0xec,
  154834. M_APP13 = 0xed,
  154835. M_APP14 = 0xee,
  154836. M_APP15 = 0xef,
  154837. M_JPG0 = 0xf0,
  154838. M_JPG13 = 0xfd,
  154839. M_COM = 0xfe,
  154840. M_TEM = 0x01,
  154841. M_ERROR = 0x100
  154842. } JPEG_MARKER;
  154843. /*
  154844. * Figure F.12: extend sign bit.
  154845. * On some machines, a shift and add will be faster than a table lookup.
  154846. */
  154847. #ifdef AVOID_TABLES
  154848. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  154849. #else
  154850. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  154851. static const int extend_test[16] = /* entry n is 2**(n-1) */
  154852. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  154853. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  154854. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  154855. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  154856. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  154857. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  154858. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  154859. #endif /* AVOID_TABLES */
  154860. #endif
  154861. /********* End of inlined file: jinclude.h *********/
  154862. /*
  154863. * Initialization of a JPEG compression object.
  154864. * The error manager must already be set up (in case memory manager fails).
  154865. */
  154866. GLOBAL(void)
  154867. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  154868. {
  154869. int i;
  154870. /* Guard against version mismatches between library and caller. */
  154871. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  154872. if (version != JPEG_LIB_VERSION)
  154873. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  154874. if (structsize != SIZEOF(struct jpeg_compress_struct))
  154875. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  154876. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  154877. /* For debugging purposes, we zero the whole master structure.
  154878. * But the application has already set the err pointer, and may have set
  154879. * client_data, so we have to save and restore those fields.
  154880. * Note: if application hasn't set client_data, tools like Purify may
  154881. * complain here.
  154882. */
  154883. {
  154884. struct jpeg_error_mgr * err = cinfo->err;
  154885. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  154886. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  154887. cinfo->err = err;
  154888. cinfo->client_data = client_data;
  154889. }
  154890. cinfo->is_decompressor = FALSE;
  154891. /* Initialize a memory manager instance for this object */
  154892. jinit_memory_mgr((j_common_ptr) cinfo);
  154893. /* Zero out pointers to permanent structures. */
  154894. cinfo->progress = NULL;
  154895. cinfo->dest = NULL;
  154896. cinfo->comp_info = NULL;
  154897. for (i = 0; i < NUM_QUANT_TBLS; i++)
  154898. cinfo->quant_tbl_ptrs[i] = NULL;
  154899. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  154900. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  154901. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  154902. }
  154903. cinfo->script_space = NULL;
  154904. cinfo->input_gamma = 1.0; /* in case application forgets */
  154905. /* OK, I'm ready */
  154906. cinfo->global_state = CSTATE_START;
  154907. }
  154908. /*
  154909. * Destruction of a JPEG compression object
  154910. */
  154911. GLOBAL(void)
  154912. jpeg_destroy_compress (j_compress_ptr cinfo)
  154913. {
  154914. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  154915. }
  154916. /*
  154917. * Abort processing of a JPEG compression operation,
  154918. * but don't destroy the object itself.
  154919. */
  154920. GLOBAL(void)
  154921. jpeg_abort_compress (j_compress_ptr cinfo)
  154922. {
  154923. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  154924. }
  154925. /*
  154926. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  154927. * Marks all currently defined tables as already written (if suppress)
  154928. * or not written (if !suppress). This will control whether they get emitted
  154929. * by a subsequent jpeg_start_compress call.
  154930. *
  154931. * This routine is exported for use by applications that want to produce
  154932. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  154933. * since it is called by jpeg_start_compress, we put it here --- otherwise
  154934. * jcparam.o would be linked whether the application used it or not.
  154935. */
  154936. GLOBAL(void)
  154937. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  154938. {
  154939. int i;
  154940. JQUANT_TBL * qtbl;
  154941. JHUFF_TBL * htbl;
  154942. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  154943. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  154944. qtbl->sent_table = suppress;
  154945. }
  154946. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  154947. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  154948. htbl->sent_table = suppress;
  154949. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  154950. htbl->sent_table = suppress;
  154951. }
  154952. }
  154953. /*
  154954. * Finish JPEG compression.
  154955. *
  154956. * If a multipass operating mode was selected, this may do a great deal of
  154957. * work including most of the actual output.
  154958. */
  154959. GLOBAL(void)
  154960. jpeg_finish_compress (j_compress_ptr cinfo)
  154961. {
  154962. JDIMENSION iMCU_row;
  154963. if (cinfo->global_state == CSTATE_SCANNING ||
  154964. cinfo->global_state == CSTATE_RAW_OK) {
  154965. /* Terminate first pass */
  154966. if (cinfo->next_scanline < cinfo->image_height)
  154967. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  154968. (*cinfo->master->finish_pass) (cinfo);
  154969. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  154970. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  154971. /* Perform any remaining passes */
  154972. while (! cinfo->master->is_last_pass) {
  154973. (*cinfo->master->prepare_for_pass) (cinfo);
  154974. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  154975. if (cinfo->progress != NULL) {
  154976. cinfo->progress->pass_counter = (long) iMCU_row;
  154977. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  154978. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  154979. }
  154980. /* We bypass the main controller and invoke coef controller directly;
  154981. * all work is being done from the coefficient buffer.
  154982. */
  154983. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  154984. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  154985. }
  154986. (*cinfo->master->finish_pass) (cinfo);
  154987. }
  154988. /* Write EOI, do final cleanup */
  154989. (*cinfo->marker->write_file_trailer) (cinfo);
  154990. (*cinfo->dest->term_destination) (cinfo);
  154991. /* We can use jpeg_abort to release memory and reset global_state */
  154992. jpeg_abort((j_common_ptr) cinfo);
  154993. }
  154994. /*
  154995. * Write a special marker.
  154996. * This is only recommended for writing COM or APPn markers.
  154997. * Must be called after jpeg_start_compress() and before
  154998. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  154999. */
  155000. GLOBAL(void)
  155001. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  155002. const JOCTET *dataptr, unsigned int datalen)
  155003. {
  155004. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  155005. if (cinfo->next_scanline != 0 ||
  155006. (cinfo->global_state != CSTATE_SCANNING &&
  155007. cinfo->global_state != CSTATE_RAW_OK &&
  155008. cinfo->global_state != CSTATE_WRCOEFS))
  155009. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155010. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155011. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  155012. while (datalen--) {
  155013. (*write_marker_byte) (cinfo, *dataptr);
  155014. dataptr++;
  155015. }
  155016. }
  155017. /* Same, but piecemeal. */
  155018. GLOBAL(void)
  155019. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  155020. {
  155021. if (cinfo->next_scanline != 0 ||
  155022. (cinfo->global_state != CSTATE_SCANNING &&
  155023. cinfo->global_state != CSTATE_RAW_OK &&
  155024. cinfo->global_state != CSTATE_WRCOEFS))
  155025. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155026. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155027. }
  155028. GLOBAL(void)
  155029. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  155030. {
  155031. (*cinfo->marker->write_marker_byte) (cinfo, val);
  155032. }
  155033. /*
  155034. * Alternate compression function: just write an abbreviated table file.
  155035. * Before calling this, all parameters and a data destination must be set up.
  155036. *
  155037. * To produce a pair of files containing abbreviated tables and abbreviated
  155038. * image data, one would proceed as follows:
  155039. *
  155040. * initialize JPEG object
  155041. * set JPEG parameters
  155042. * set destination to table file
  155043. * jpeg_write_tables(cinfo);
  155044. * set destination to image file
  155045. * jpeg_start_compress(cinfo, FALSE);
  155046. * write data...
  155047. * jpeg_finish_compress(cinfo);
  155048. *
  155049. * jpeg_write_tables has the side effect of marking all tables written
  155050. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  155051. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  155052. */
  155053. GLOBAL(void)
  155054. jpeg_write_tables (j_compress_ptr cinfo)
  155055. {
  155056. if (cinfo->global_state != CSTATE_START)
  155057. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155058. /* (Re)initialize error mgr and destination modules */
  155059. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155060. (*cinfo->dest->init_destination) (cinfo);
  155061. /* Initialize the marker writer ... bit of a crock to do it here. */
  155062. jinit_marker_writer(cinfo);
  155063. /* Write them tables! */
  155064. (*cinfo->marker->write_tables_only) (cinfo);
  155065. /* And clean up. */
  155066. (*cinfo->dest->term_destination) (cinfo);
  155067. /*
  155068. * In library releases up through v6a, we called jpeg_abort() here to free
  155069. * any working memory allocated by the destination manager and marker
  155070. * writer. Some applications had a problem with that: they allocated space
  155071. * of their own from the library memory manager, and didn't want it to go
  155072. * away during write_tables. So now we do nothing. This will cause a
  155073. * memory leak if an app calls write_tables repeatedly without doing a full
  155074. * compression cycle or otherwise resetting the JPEG object. However, that
  155075. * seems less bad than unexpectedly freeing memory in the normal case.
  155076. * An app that prefers the old behavior can call jpeg_abort for itself after
  155077. * each call to jpeg_write_tables().
  155078. */
  155079. }
  155080. /********* End of inlined file: jcapimin.c *********/
  155081. /********* Start of inlined file: jcapistd.c *********/
  155082. #define JPEG_INTERNALS
  155083. /*
  155084. * Compression initialization.
  155085. * Before calling this, all parameters and a data destination must be set up.
  155086. *
  155087. * We require a write_all_tables parameter as a failsafe check when writing
  155088. * multiple datastreams from the same compression object. Since prior runs
  155089. * will have left all the tables marked sent_table=TRUE, a subsequent run
  155090. * would emit an abbreviated stream (no tables) by default. This may be what
  155091. * is wanted, but for safety's sake it should not be the default behavior:
  155092. * programmers should have to make a deliberate choice to emit abbreviated
  155093. * images. Therefore the documentation and examples should encourage people
  155094. * to pass write_all_tables=TRUE; then it will take active thought to do the
  155095. * wrong thing.
  155096. */
  155097. GLOBAL(void)
  155098. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  155099. {
  155100. if (cinfo->global_state != CSTATE_START)
  155101. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155102. if (write_all_tables)
  155103. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  155104. /* (Re)initialize error mgr and destination modules */
  155105. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155106. (*cinfo->dest->init_destination) (cinfo);
  155107. /* Perform master selection of active modules */
  155108. jinit_compress_master(cinfo);
  155109. /* Set up for the first pass */
  155110. (*cinfo->master->prepare_for_pass) (cinfo);
  155111. /* Ready for application to drive first pass through jpeg_write_scanlines
  155112. * or jpeg_write_raw_data.
  155113. */
  155114. cinfo->next_scanline = 0;
  155115. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  155116. }
  155117. /*
  155118. * Write some scanlines of data to the JPEG compressor.
  155119. *
  155120. * The return value will be the number of lines actually written.
  155121. * This should be less than the supplied num_lines only in case that
  155122. * the data destination module has requested suspension of the compressor,
  155123. * or if more than image_height scanlines are passed in.
  155124. *
  155125. * Note: we warn about excess calls to jpeg_write_scanlines() since
  155126. * this likely signals an application programmer error. However,
  155127. * excess scanlines passed in the last valid call are *silently* ignored,
  155128. * so that the application need not adjust num_lines for end-of-image
  155129. * when using a multiple-scanline buffer.
  155130. */
  155131. GLOBAL(JDIMENSION)
  155132. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  155133. JDIMENSION num_lines)
  155134. {
  155135. JDIMENSION row_ctr, rows_left;
  155136. if (cinfo->global_state != CSTATE_SCANNING)
  155137. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155138. if (cinfo->next_scanline >= cinfo->image_height)
  155139. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155140. /* Call progress monitor hook if present */
  155141. if (cinfo->progress != NULL) {
  155142. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155143. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155144. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155145. }
  155146. /* Give master control module another chance if this is first call to
  155147. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  155148. * delayed so that application can write COM, etc, markers between
  155149. * jpeg_start_compress and jpeg_write_scanlines.
  155150. */
  155151. if (cinfo->master->call_pass_startup)
  155152. (*cinfo->master->pass_startup) (cinfo);
  155153. /* Ignore any extra scanlines at bottom of image. */
  155154. rows_left = cinfo->image_height - cinfo->next_scanline;
  155155. if (num_lines > rows_left)
  155156. num_lines = rows_left;
  155157. row_ctr = 0;
  155158. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  155159. cinfo->next_scanline += row_ctr;
  155160. return row_ctr;
  155161. }
  155162. /*
  155163. * Alternate entry point to write raw data.
  155164. * Processes exactly one iMCU row per call, unless suspended.
  155165. */
  155166. GLOBAL(JDIMENSION)
  155167. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  155168. JDIMENSION num_lines)
  155169. {
  155170. JDIMENSION lines_per_iMCU_row;
  155171. if (cinfo->global_state != CSTATE_RAW_OK)
  155172. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155173. if (cinfo->next_scanline >= cinfo->image_height) {
  155174. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155175. return 0;
  155176. }
  155177. /* Call progress monitor hook if present */
  155178. if (cinfo->progress != NULL) {
  155179. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155180. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155181. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155182. }
  155183. /* Give master control module another chance if this is first call to
  155184. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  155185. * delayed so that application can write COM, etc, markers between
  155186. * jpeg_start_compress and jpeg_write_raw_data.
  155187. */
  155188. if (cinfo->master->call_pass_startup)
  155189. (*cinfo->master->pass_startup) (cinfo);
  155190. /* Verify that at least one iMCU row has been passed. */
  155191. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  155192. if (num_lines < lines_per_iMCU_row)
  155193. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  155194. /* Directly compress the row. */
  155195. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  155196. /* If compressor did not consume the whole row, suspend processing. */
  155197. return 0;
  155198. }
  155199. /* OK, we processed one iMCU row. */
  155200. cinfo->next_scanline += lines_per_iMCU_row;
  155201. return lines_per_iMCU_row;
  155202. }
  155203. /********* End of inlined file: jcapistd.c *********/
  155204. /********* Start of inlined file: jccoefct.c *********/
  155205. #define JPEG_INTERNALS
  155206. /* We use a full-image coefficient buffer when doing Huffman optimization,
  155207. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  155208. * step is run during the first pass, and subsequent passes need only read
  155209. * the buffered coefficients.
  155210. */
  155211. #ifdef ENTROPY_OPT_SUPPORTED
  155212. #define FULL_COEF_BUFFER_SUPPORTED
  155213. #else
  155214. #ifdef C_MULTISCAN_FILES_SUPPORTED
  155215. #define FULL_COEF_BUFFER_SUPPORTED
  155216. #endif
  155217. #endif
  155218. /* Private buffer controller object */
  155219. typedef struct {
  155220. struct jpeg_c_coef_controller pub; /* public fields */
  155221. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  155222. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  155223. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  155224. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  155225. /* For single-pass compression, it's sufficient to buffer just one MCU
  155226. * (although this may prove a bit slow in practice). We allocate a
  155227. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  155228. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  155229. * it's not really very big; this is to keep the module interfaces unchanged
  155230. * when a large coefficient buffer is necessary.)
  155231. * In multi-pass modes, this array points to the current MCU's blocks
  155232. * within the virtual arrays.
  155233. */
  155234. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  155235. /* In multi-pass modes, we need a virtual block array for each component. */
  155236. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  155237. } my_coef_controller;
  155238. typedef my_coef_controller * my_coef_ptr;
  155239. /* Forward declarations */
  155240. METHODDEF(boolean) compress_data
  155241. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155242. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155243. METHODDEF(boolean) compress_first_pass
  155244. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155245. METHODDEF(boolean) compress_output
  155246. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155247. #endif
  155248. LOCAL(void)
  155249. start_iMCU_row (j_compress_ptr cinfo)
  155250. /* Reset within-iMCU-row counters for a new row */
  155251. {
  155252. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155253. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  155254. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  155255. * But at the bottom of the image, process only what's left.
  155256. */
  155257. if (cinfo->comps_in_scan > 1) {
  155258. coef->MCU_rows_per_iMCU_row = 1;
  155259. } else {
  155260. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  155261. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  155262. else
  155263. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  155264. }
  155265. coef->mcu_ctr = 0;
  155266. coef->MCU_vert_offset = 0;
  155267. }
  155268. /*
  155269. * Initialize for a processing pass.
  155270. */
  155271. METHODDEF(void)
  155272. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  155273. {
  155274. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155275. coef->iMCU_row_num = 0;
  155276. start_iMCU_row(cinfo);
  155277. switch (pass_mode) {
  155278. case JBUF_PASS_THRU:
  155279. if (coef->whole_image[0] != NULL)
  155280. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155281. coef->pub.compress_data = compress_data;
  155282. break;
  155283. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155284. case JBUF_SAVE_AND_PASS:
  155285. if (coef->whole_image[0] == NULL)
  155286. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155287. coef->pub.compress_data = compress_first_pass;
  155288. break;
  155289. case JBUF_CRANK_DEST:
  155290. if (coef->whole_image[0] == NULL)
  155291. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155292. coef->pub.compress_data = compress_output;
  155293. break;
  155294. #endif
  155295. default:
  155296. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155297. break;
  155298. }
  155299. }
  155300. /*
  155301. * Process some data in the single-pass case.
  155302. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155303. * per call, ie, v_samp_factor block rows for each component in the image.
  155304. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  155305. *
  155306. * NB: input_buf contains a plane for each component in image,
  155307. * which we index according to the component's SOF position.
  155308. */
  155309. METHODDEF(boolean)
  155310. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155311. {
  155312. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155313. JDIMENSION MCU_col_num; /* index of current MCU within row */
  155314. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  155315. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  155316. int blkn, bi, ci, yindex, yoffset, blockcnt;
  155317. JDIMENSION ypos, xpos;
  155318. jpeg_component_info *compptr;
  155319. /* Loop to write as much as one whole iMCU row */
  155320. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  155321. yoffset++) {
  155322. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  155323. MCU_col_num++) {
  155324. /* Determine where data comes from in input_buf and do the DCT thing.
  155325. * Each call on forward_DCT processes a horizontal row of DCT blocks
  155326. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  155327. * sequentially. Dummy blocks at the right or bottom edge are filled in
  155328. * specially. The data in them does not matter for image reconstruction,
  155329. * so we fill them with values that will encode to the smallest amount of
  155330. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  155331. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  155332. */
  155333. blkn = 0;
  155334. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155335. compptr = cinfo->cur_comp_info[ci];
  155336. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  155337. : compptr->last_col_width;
  155338. xpos = MCU_col_num * compptr->MCU_sample_width;
  155339. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  155340. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  155341. if (coef->iMCU_row_num < last_iMCU_row ||
  155342. yoffset+yindex < compptr->last_row_height) {
  155343. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  155344. input_buf[compptr->component_index],
  155345. coef->MCU_buffer[blkn],
  155346. ypos, xpos, (JDIMENSION) blockcnt);
  155347. if (blockcnt < compptr->MCU_width) {
  155348. /* Create some dummy blocks at the right edge of the image. */
  155349. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  155350. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  155351. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  155352. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  155353. }
  155354. }
  155355. } else {
  155356. /* Create a row of dummy blocks at the bottom of the image. */
  155357. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  155358. compptr->MCU_width * SIZEOF(JBLOCK));
  155359. for (bi = 0; bi < compptr->MCU_width; bi++) {
  155360. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  155361. }
  155362. }
  155363. blkn += compptr->MCU_width;
  155364. ypos += DCTSIZE;
  155365. }
  155366. }
  155367. /* Try to write the MCU. In event of a suspension failure, we will
  155368. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  155369. */
  155370. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  155371. /* Suspension forced; update state counters and exit */
  155372. coef->MCU_vert_offset = yoffset;
  155373. coef->mcu_ctr = MCU_col_num;
  155374. return FALSE;
  155375. }
  155376. }
  155377. /* Completed an MCU row, but perhaps not an iMCU row */
  155378. coef->mcu_ctr = 0;
  155379. }
  155380. /* Completed the iMCU row, advance counters for next one */
  155381. coef->iMCU_row_num++;
  155382. start_iMCU_row(cinfo);
  155383. return TRUE;
  155384. }
  155385. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155386. /*
  155387. * Process some data in the first pass of a multi-pass case.
  155388. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155389. * per call, ie, v_samp_factor block rows for each component in the image.
  155390. * This amount of data is read from the source buffer, DCT'd and quantized,
  155391. * and saved into the virtual arrays. We also generate suitable dummy blocks
  155392. * as needed at the right and lower edges. (The dummy blocks are constructed
  155393. * in the virtual arrays, which have been padded appropriately.) This makes
  155394. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  155395. *
  155396. * We must also emit the data to the entropy encoder. This is conveniently
  155397. * done by calling compress_output() after we've loaded the current strip
  155398. * of the virtual arrays.
  155399. *
  155400. * NB: input_buf contains a plane for each component in image. All
  155401. * components are DCT'd and loaded into the virtual arrays in this pass.
  155402. * However, it may be that only a subset of the components are emitted to
  155403. * the entropy encoder during this first pass; be careful about looking
  155404. * at the scan-dependent variables (MCU dimensions, etc).
  155405. */
  155406. METHODDEF(boolean)
  155407. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155408. {
  155409. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155410. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  155411. JDIMENSION blocks_across, MCUs_across, MCUindex;
  155412. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  155413. JCOEF lastDC;
  155414. jpeg_component_info *compptr;
  155415. JBLOCKARRAY buffer;
  155416. JBLOCKROW thisblockrow, lastblockrow;
  155417. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  155418. ci++, compptr++) {
  155419. /* Align the virtual buffer for this component. */
  155420. buffer = (*cinfo->mem->access_virt_barray)
  155421. ((j_common_ptr) cinfo, coef->whole_image[ci],
  155422. coef->iMCU_row_num * compptr->v_samp_factor,
  155423. (JDIMENSION) compptr->v_samp_factor, TRUE);
  155424. /* Count non-dummy DCT block rows in this iMCU row. */
  155425. if (coef->iMCU_row_num < last_iMCU_row)
  155426. block_rows = compptr->v_samp_factor;
  155427. else {
  155428. /* NB: can't use last_row_height here, since may not be set! */
  155429. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  155430. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  155431. }
  155432. blocks_across = compptr->width_in_blocks;
  155433. h_samp_factor = compptr->h_samp_factor;
  155434. /* Count number of dummy blocks to be added at the right margin. */
  155435. ndummy = (int) (blocks_across % h_samp_factor);
  155436. if (ndummy > 0)
  155437. ndummy = h_samp_factor - ndummy;
  155438. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  155439. * on forward_DCT processes a complete horizontal row of DCT blocks.
  155440. */
  155441. for (block_row = 0; block_row < block_rows; block_row++) {
  155442. thisblockrow = buffer[block_row];
  155443. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  155444. input_buf[ci], thisblockrow,
  155445. (JDIMENSION) (block_row * DCTSIZE),
  155446. (JDIMENSION) 0, blocks_across);
  155447. if (ndummy > 0) {
  155448. /* Create dummy blocks at the right edge of the image. */
  155449. thisblockrow += blocks_across; /* => first dummy block */
  155450. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  155451. lastDC = thisblockrow[-1][0];
  155452. for (bi = 0; bi < ndummy; bi++) {
  155453. thisblockrow[bi][0] = lastDC;
  155454. }
  155455. }
  155456. }
  155457. /* If at end of image, create dummy block rows as needed.
  155458. * The tricky part here is that within each MCU, we want the DC values
  155459. * of the dummy blocks to match the last real block's DC value.
  155460. * This squeezes a few more bytes out of the resulting file...
  155461. */
  155462. if (coef->iMCU_row_num == last_iMCU_row) {
  155463. blocks_across += ndummy; /* include lower right corner */
  155464. MCUs_across = blocks_across / h_samp_factor;
  155465. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  155466. block_row++) {
  155467. thisblockrow = buffer[block_row];
  155468. lastblockrow = buffer[block_row-1];
  155469. jzero_far((void FAR *) thisblockrow,
  155470. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  155471. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  155472. lastDC = lastblockrow[h_samp_factor-1][0];
  155473. for (bi = 0; bi < h_samp_factor; bi++) {
  155474. thisblockrow[bi][0] = lastDC;
  155475. }
  155476. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  155477. lastblockrow += h_samp_factor;
  155478. }
  155479. }
  155480. }
  155481. }
  155482. /* NB: compress_output will increment iMCU_row_num if successful.
  155483. * A suspension return will result in redoing all the work above next time.
  155484. */
  155485. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  155486. return compress_output(cinfo, input_buf);
  155487. }
  155488. /*
  155489. * Process some data in subsequent passes of a multi-pass case.
  155490. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155491. * per call, ie, v_samp_factor block rows for each component in the scan.
  155492. * The data is obtained from the virtual arrays and fed to the entropy coder.
  155493. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  155494. *
  155495. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  155496. */
  155497. METHODDEF(boolean)
  155498. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155499. {
  155500. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155501. JDIMENSION MCU_col_num; /* index of current MCU within row */
  155502. int blkn, ci, xindex, yindex, yoffset;
  155503. JDIMENSION start_col;
  155504. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  155505. JBLOCKROW buffer_ptr;
  155506. jpeg_component_info *compptr;
  155507. /* Align the virtual buffers for the components used in this scan.
  155508. * NB: during first pass, this is safe only because the buffers will
  155509. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  155510. */
  155511. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155512. compptr = cinfo->cur_comp_info[ci];
  155513. buffer[ci] = (*cinfo->mem->access_virt_barray)
  155514. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  155515. coef->iMCU_row_num * compptr->v_samp_factor,
  155516. (JDIMENSION) compptr->v_samp_factor, FALSE);
  155517. }
  155518. /* Loop to process one whole iMCU row */
  155519. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  155520. yoffset++) {
  155521. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  155522. MCU_col_num++) {
  155523. /* Construct list of pointers to DCT blocks belonging to this MCU */
  155524. blkn = 0; /* index of current DCT block within MCU */
  155525. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155526. compptr = cinfo->cur_comp_info[ci];
  155527. start_col = MCU_col_num * compptr->MCU_width;
  155528. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  155529. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  155530. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  155531. coef->MCU_buffer[blkn++] = buffer_ptr++;
  155532. }
  155533. }
  155534. }
  155535. /* Try to write the MCU. */
  155536. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  155537. /* Suspension forced; update state counters and exit */
  155538. coef->MCU_vert_offset = yoffset;
  155539. coef->mcu_ctr = MCU_col_num;
  155540. return FALSE;
  155541. }
  155542. }
  155543. /* Completed an MCU row, but perhaps not an iMCU row */
  155544. coef->mcu_ctr = 0;
  155545. }
  155546. /* Completed the iMCU row, advance counters for next one */
  155547. coef->iMCU_row_num++;
  155548. start_iMCU_row(cinfo);
  155549. return TRUE;
  155550. }
  155551. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  155552. /*
  155553. * Initialize coefficient buffer controller.
  155554. */
  155555. GLOBAL(void)
  155556. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  155557. {
  155558. my_coef_ptr coef;
  155559. coef = (my_coef_ptr)
  155560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155561. SIZEOF(my_coef_controller));
  155562. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  155563. coef->pub.start_pass = start_pass_coef;
  155564. /* Create the coefficient buffer. */
  155565. if (need_full_buffer) {
  155566. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155567. /* Allocate a full-image virtual array for each component, */
  155568. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  155569. int ci;
  155570. jpeg_component_info *compptr;
  155571. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  155572. ci++, compptr++) {
  155573. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  155574. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  155575. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  155576. (long) compptr->h_samp_factor),
  155577. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  155578. (long) compptr->v_samp_factor),
  155579. (JDIMENSION) compptr->v_samp_factor);
  155580. }
  155581. #else
  155582. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155583. #endif
  155584. } else {
  155585. /* We only need a single-MCU buffer. */
  155586. JBLOCKROW buffer;
  155587. int i;
  155588. buffer = (JBLOCKROW)
  155589. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155590. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  155591. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  155592. coef->MCU_buffer[i] = buffer + i;
  155593. }
  155594. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  155595. }
  155596. }
  155597. /********* End of inlined file: jccoefct.c *********/
  155598. /********* Start of inlined file: jccolor.c *********/
  155599. #define JPEG_INTERNALS
  155600. /* Private subobject */
  155601. typedef struct {
  155602. struct jpeg_color_converter pub; /* public fields */
  155603. /* Private state for RGB->YCC conversion */
  155604. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  155605. } my_color_converter;
  155606. typedef my_color_converter * my_cconvert_ptr;
  155607. /**************** RGB -> YCbCr conversion: most common case **************/
  155608. /*
  155609. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  155610. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  155611. * The conversion equations to be implemented are therefore
  155612. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  155613. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  155614. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  155615. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  155616. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  155617. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  155618. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  155619. * were not represented exactly. Now we sacrifice exact representation of
  155620. * maximum red and maximum blue in order to get exact grayscales.
  155621. *
  155622. * To avoid floating-point arithmetic, we represent the fractional constants
  155623. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  155624. * the products by 2^16, with appropriate rounding, to get the correct answer.
  155625. *
  155626. * For even more speed, we avoid doing any multiplications in the inner loop
  155627. * by precalculating the constants times R,G,B for all possible values.
  155628. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  155629. * for 12-bit samples it is still acceptable. It's not very reasonable for
  155630. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  155631. * colorspace anyway.
  155632. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  155633. * in the tables to save adding them separately in the inner loop.
  155634. */
  155635. #define SCALEBITS 16 /* speediest right-shift on some machines */
  155636. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  155637. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  155638. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  155639. /* We allocate one big table and divide it up into eight parts, instead of
  155640. * doing eight alloc_small requests. This lets us use a single table base
  155641. * address, which can be held in a register in the inner loops on many
  155642. * machines (more than can hold all eight addresses, anyway).
  155643. */
  155644. #define R_Y_OFF 0 /* offset to R => Y section */
  155645. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  155646. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  155647. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  155648. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  155649. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  155650. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  155651. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  155652. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  155653. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  155654. /*
  155655. * Initialize for RGB->YCC colorspace conversion.
  155656. */
  155657. METHODDEF(void)
  155658. rgb_ycc_start (j_compress_ptr cinfo)
  155659. {
  155660. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155661. INT32 * rgb_ycc_tab;
  155662. INT32 i;
  155663. /* Allocate and fill in the conversion tables. */
  155664. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  155665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155666. (TABLE_SIZE * SIZEOF(INT32)));
  155667. for (i = 0; i <= MAXJSAMPLE; i++) {
  155668. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  155669. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  155670. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  155671. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  155672. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  155673. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  155674. * This ensures that the maximum output will round to MAXJSAMPLE
  155675. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  155676. */
  155677. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  155678. /* B=>Cb and R=>Cr tables are the same
  155679. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  155680. */
  155681. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  155682. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  155683. }
  155684. }
  155685. /*
  155686. * Convert some rows of samples to the JPEG colorspace.
  155687. *
  155688. * Note that we change from the application's interleaved-pixel format
  155689. * to our internal noninterleaved, one-plane-per-component format.
  155690. * The input buffer is therefore three times as wide as the output buffer.
  155691. *
  155692. * A starting row offset is provided only for the output buffer. The caller
  155693. * can easily adjust the passed input_buf value to accommodate any row
  155694. * offset required on that side.
  155695. */
  155696. METHODDEF(void)
  155697. rgb_ycc_convert (j_compress_ptr cinfo,
  155698. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155699. JDIMENSION output_row, int num_rows)
  155700. {
  155701. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155702. register int r, g, b;
  155703. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155704. register JSAMPROW inptr;
  155705. register JSAMPROW outptr0, outptr1, outptr2;
  155706. register JDIMENSION col;
  155707. JDIMENSION num_cols = cinfo->image_width;
  155708. while (--num_rows >= 0) {
  155709. inptr = *input_buf++;
  155710. outptr0 = output_buf[0][output_row];
  155711. outptr1 = output_buf[1][output_row];
  155712. outptr2 = output_buf[2][output_row];
  155713. output_row++;
  155714. for (col = 0; col < num_cols; col++) {
  155715. r = GETJSAMPLE(inptr[RGB_RED]);
  155716. g = GETJSAMPLE(inptr[RGB_GREEN]);
  155717. b = GETJSAMPLE(inptr[RGB_BLUE]);
  155718. inptr += RGB_PIXELSIZE;
  155719. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  155720. * must be too; we do not need an explicit range-limiting operation.
  155721. * Hence the value being shifted is never negative, and we don't
  155722. * need the general RIGHT_SHIFT macro.
  155723. */
  155724. /* Y */
  155725. outptr0[col] = (JSAMPLE)
  155726. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155727. >> SCALEBITS);
  155728. /* Cb */
  155729. outptr1[col] = (JSAMPLE)
  155730. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  155731. >> SCALEBITS);
  155732. /* Cr */
  155733. outptr2[col] = (JSAMPLE)
  155734. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  155735. >> SCALEBITS);
  155736. }
  155737. }
  155738. }
  155739. /**************** Cases other than RGB -> YCbCr **************/
  155740. /*
  155741. * Convert some rows of samples to the JPEG colorspace.
  155742. * This version handles RGB->grayscale conversion, which is the same
  155743. * as the RGB->Y portion of RGB->YCbCr.
  155744. * We assume rgb_ycc_start has been called (we only use the Y tables).
  155745. */
  155746. METHODDEF(void)
  155747. rgb_gray_convert (j_compress_ptr cinfo,
  155748. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155749. JDIMENSION output_row, int num_rows)
  155750. {
  155751. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155752. register int r, g, b;
  155753. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155754. register JSAMPROW inptr;
  155755. register JSAMPROW outptr;
  155756. register JDIMENSION col;
  155757. JDIMENSION num_cols = cinfo->image_width;
  155758. while (--num_rows >= 0) {
  155759. inptr = *input_buf++;
  155760. outptr = output_buf[0][output_row];
  155761. output_row++;
  155762. for (col = 0; col < num_cols; col++) {
  155763. r = GETJSAMPLE(inptr[RGB_RED]);
  155764. g = GETJSAMPLE(inptr[RGB_GREEN]);
  155765. b = GETJSAMPLE(inptr[RGB_BLUE]);
  155766. inptr += RGB_PIXELSIZE;
  155767. /* Y */
  155768. outptr[col] = (JSAMPLE)
  155769. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155770. >> SCALEBITS);
  155771. }
  155772. }
  155773. }
  155774. /*
  155775. * Convert some rows of samples to the JPEG colorspace.
  155776. * This version handles Adobe-style CMYK->YCCK conversion,
  155777. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  155778. * conversion as above, while passing K (black) unchanged.
  155779. * We assume rgb_ycc_start has been called.
  155780. */
  155781. METHODDEF(void)
  155782. cmyk_ycck_convert (j_compress_ptr cinfo,
  155783. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155784. JDIMENSION output_row, int num_rows)
  155785. {
  155786. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155787. register int r, g, b;
  155788. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155789. register JSAMPROW inptr;
  155790. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  155791. register JDIMENSION col;
  155792. JDIMENSION num_cols = cinfo->image_width;
  155793. while (--num_rows >= 0) {
  155794. inptr = *input_buf++;
  155795. outptr0 = output_buf[0][output_row];
  155796. outptr1 = output_buf[1][output_row];
  155797. outptr2 = output_buf[2][output_row];
  155798. outptr3 = output_buf[3][output_row];
  155799. output_row++;
  155800. for (col = 0; col < num_cols; col++) {
  155801. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  155802. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  155803. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  155804. /* K passes through as-is */
  155805. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  155806. inptr += 4;
  155807. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  155808. * must be too; we do not need an explicit range-limiting operation.
  155809. * Hence the value being shifted is never negative, and we don't
  155810. * need the general RIGHT_SHIFT macro.
  155811. */
  155812. /* Y */
  155813. outptr0[col] = (JSAMPLE)
  155814. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155815. >> SCALEBITS);
  155816. /* Cb */
  155817. outptr1[col] = (JSAMPLE)
  155818. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  155819. >> SCALEBITS);
  155820. /* Cr */
  155821. outptr2[col] = (JSAMPLE)
  155822. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  155823. >> SCALEBITS);
  155824. }
  155825. }
  155826. }
  155827. /*
  155828. * Convert some rows of samples to the JPEG colorspace.
  155829. * This version handles grayscale output with no conversion.
  155830. * The source can be either plain grayscale or YCbCr (since Y == gray).
  155831. */
  155832. METHODDEF(void)
  155833. grayscale_convert (j_compress_ptr cinfo,
  155834. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155835. JDIMENSION output_row, int num_rows)
  155836. {
  155837. register JSAMPROW inptr;
  155838. register JSAMPROW outptr;
  155839. register JDIMENSION col;
  155840. JDIMENSION num_cols = cinfo->image_width;
  155841. int instride = cinfo->input_components;
  155842. while (--num_rows >= 0) {
  155843. inptr = *input_buf++;
  155844. outptr = output_buf[0][output_row];
  155845. output_row++;
  155846. for (col = 0; col < num_cols; col++) {
  155847. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  155848. inptr += instride;
  155849. }
  155850. }
  155851. }
  155852. /*
  155853. * Convert some rows of samples to the JPEG colorspace.
  155854. * This version handles multi-component colorspaces without conversion.
  155855. * We assume input_components == num_components.
  155856. */
  155857. METHODDEF(void)
  155858. null_convert (j_compress_ptr cinfo,
  155859. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155860. JDIMENSION output_row, int num_rows)
  155861. {
  155862. register JSAMPROW inptr;
  155863. register JSAMPROW outptr;
  155864. register JDIMENSION col;
  155865. register int ci;
  155866. int nc = cinfo->num_components;
  155867. JDIMENSION num_cols = cinfo->image_width;
  155868. while (--num_rows >= 0) {
  155869. /* It seems fastest to make a separate pass for each component. */
  155870. for (ci = 0; ci < nc; ci++) {
  155871. inptr = *input_buf;
  155872. outptr = output_buf[ci][output_row];
  155873. for (col = 0; col < num_cols; col++) {
  155874. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  155875. inptr += nc;
  155876. }
  155877. }
  155878. input_buf++;
  155879. output_row++;
  155880. }
  155881. }
  155882. /*
  155883. * Empty method for start_pass.
  155884. */
  155885. METHODDEF(void)
  155886. null_method (j_compress_ptr cinfo)
  155887. {
  155888. /* no work needed */
  155889. }
  155890. /*
  155891. * Module initialization routine for input colorspace conversion.
  155892. */
  155893. GLOBAL(void)
  155894. jinit_color_converter (j_compress_ptr cinfo)
  155895. {
  155896. my_cconvert_ptr cconvert;
  155897. cconvert = (my_cconvert_ptr)
  155898. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155899. SIZEOF(my_color_converter));
  155900. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  155901. /* set start_pass to null method until we find out differently */
  155902. cconvert->pub.start_pass = null_method;
  155903. /* Make sure input_components agrees with in_color_space */
  155904. switch (cinfo->in_color_space) {
  155905. case JCS_GRAYSCALE:
  155906. if (cinfo->input_components != 1)
  155907. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155908. break;
  155909. case JCS_RGB:
  155910. #if RGB_PIXELSIZE != 3
  155911. if (cinfo->input_components != RGB_PIXELSIZE)
  155912. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155913. break;
  155914. #endif /* else share code with YCbCr */
  155915. case JCS_YCbCr:
  155916. if (cinfo->input_components != 3)
  155917. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155918. break;
  155919. case JCS_CMYK:
  155920. case JCS_YCCK:
  155921. if (cinfo->input_components != 4)
  155922. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155923. break;
  155924. default: /* JCS_UNKNOWN can be anything */
  155925. if (cinfo->input_components < 1)
  155926. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155927. break;
  155928. }
  155929. /* Check num_components, set conversion method based on requested space */
  155930. switch (cinfo->jpeg_color_space) {
  155931. case JCS_GRAYSCALE:
  155932. if (cinfo->num_components != 1)
  155933. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155934. if (cinfo->in_color_space == JCS_GRAYSCALE)
  155935. cconvert->pub.color_convert = grayscale_convert;
  155936. else if (cinfo->in_color_space == JCS_RGB) {
  155937. cconvert->pub.start_pass = rgb_ycc_start;
  155938. cconvert->pub.color_convert = rgb_gray_convert;
  155939. } else if (cinfo->in_color_space == JCS_YCbCr)
  155940. cconvert->pub.color_convert = grayscale_convert;
  155941. else
  155942. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155943. break;
  155944. case JCS_RGB:
  155945. if (cinfo->num_components != 3)
  155946. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155947. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  155948. cconvert->pub.color_convert = null_convert;
  155949. else
  155950. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155951. break;
  155952. case JCS_YCbCr:
  155953. if (cinfo->num_components != 3)
  155954. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155955. if (cinfo->in_color_space == JCS_RGB) {
  155956. cconvert->pub.start_pass = rgb_ycc_start;
  155957. cconvert->pub.color_convert = rgb_ycc_convert;
  155958. } else if (cinfo->in_color_space == JCS_YCbCr)
  155959. cconvert->pub.color_convert = null_convert;
  155960. else
  155961. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155962. break;
  155963. case JCS_CMYK:
  155964. if (cinfo->num_components != 4)
  155965. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155966. if (cinfo->in_color_space == JCS_CMYK)
  155967. cconvert->pub.color_convert = null_convert;
  155968. else
  155969. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155970. break;
  155971. case JCS_YCCK:
  155972. if (cinfo->num_components != 4)
  155973. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155974. if (cinfo->in_color_space == JCS_CMYK) {
  155975. cconvert->pub.start_pass = rgb_ycc_start;
  155976. cconvert->pub.color_convert = cmyk_ycck_convert;
  155977. } else if (cinfo->in_color_space == JCS_YCCK)
  155978. cconvert->pub.color_convert = null_convert;
  155979. else
  155980. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155981. break;
  155982. default: /* allow null conversion of JCS_UNKNOWN */
  155983. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  155984. cinfo->num_components != cinfo->input_components)
  155985. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155986. cconvert->pub.color_convert = null_convert;
  155987. break;
  155988. }
  155989. }
  155990. /********* End of inlined file: jccolor.c *********/
  155991. #undef FIX
  155992. /********* Start of inlined file: jcdctmgr.c *********/
  155993. #define JPEG_INTERNALS
  155994. /********* Start of inlined file: jdct.h *********/
  155995. /*
  155996. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  155997. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  155998. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  155999. * implementations use an array of type FAST_FLOAT, instead.)
  156000. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  156001. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  156002. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  156003. * convention improves accuracy in integer implementations and saves some
  156004. * work in floating-point ones.
  156005. * Quantization of the output coefficients is done by jcdctmgr.c.
  156006. */
  156007. #ifndef __jdct_h__
  156008. #define __jdct_h__
  156009. #if BITS_IN_JSAMPLE == 8
  156010. typedef int DCTELEM; /* 16 or 32 bits is fine */
  156011. #else
  156012. typedef INT32 DCTELEM; /* must have 32 bits */
  156013. #endif
  156014. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  156015. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  156016. /*
  156017. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  156018. * to an output sample array. The routine must dequantize the input data as
  156019. * well as perform the IDCT; for dequantization, it uses the multiplier table
  156020. * pointed to by compptr->dct_table. The output data is to be placed into the
  156021. * sample array starting at a specified column. (Any row offset needed will
  156022. * be applied to the array pointer before it is passed to the IDCT code.)
  156023. * Note that the number of samples emitted by the IDCT routine is
  156024. * DCT_scaled_size * DCT_scaled_size.
  156025. */
  156026. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  156027. /*
  156028. * Each IDCT routine has its own ideas about the best dct_table element type.
  156029. */
  156030. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  156031. #if BITS_IN_JSAMPLE == 8
  156032. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  156033. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  156034. #else
  156035. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  156036. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  156037. #endif
  156038. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  156039. /*
  156040. * Each IDCT routine is responsible for range-limiting its results and
  156041. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  156042. * be quite far out of range if the input data is corrupt, so a bulletproof
  156043. * range-limiting step is required. We use a mask-and-table-lookup method
  156044. * to do the combined operations quickly. See the comments with
  156045. * prepare_range_limit_table (in jdmaster.c) for more info.
  156046. */
  156047. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  156048. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  156049. /* Short forms of external names for systems with brain-damaged linkers. */
  156050. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156051. #define jpeg_fdct_islow jFDislow
  156052. #define jpeg_fdct_ifast jFDifast
  156053. #define jpeg_fdct_float jFDfloat
  156054. #define jpeg_idct_islow jRDislow
  156055. #define jpeg_idct_ifast jRDifast
  156056. #define jpeg_idct_float jRDfloat
  156057. #define jpeg_idct_4x4 jRD4x4
  156058. #define jpeg_idct_2x2 jRD2x2
  156059. #define jpeg_idct_1x1 jRD1x1
  156060. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156061. /* Extern declarations for the forward and inverse DCT routines. */
  156062. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  156063. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  156064. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  156065. EXTERN(void) jpeg_idct_islow
  156066. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156067. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156068. EXTERN(void) jpeg_idct_ifast
  156069. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156070. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156071. EXTERN(void) jpeg_idct_float
  156072. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156073. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156074. EXTERN(void) jpeg_idct_4x4
  156075. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156076. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156077. EXTERN(void) jpeg_idct_2x2
  156078. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156079. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156080. EXTERN(void) jpeg_idct_1x1
  156081. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156082. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156083. /*
  156084. * Macros for handling fixed-point arithmetic; these are used by many
  156085. * but not all of the DCT/IDCT modules.
  156086. *
  156087. * All values are expected to be of type INT32.
  156088. * Fractional constants are scaled left by CONST_BITS bits.
  156089. * CONST_BITS is defined within each module using these macros,
  156090. * and may differ from one module to the next.
  156091. */
  156092. #define ONE ((INT32) 1)
  156093. #define CONST_SCALE (ONE << CONST_BITS)
  156094. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  156095. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  156096. * thus causing a lot of useless floating-point operations at run time.
  156097. */
  156098. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  156099. /* Descale and correctly round an INT32 value that's scaled by N bits.
  156100. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  156101. * the fudge factor is correct for either sign of X.
  156102. */
  156103. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  156104. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  156105. * This macro is used only when the two inputs will actually be no more than
  156106. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  156107. * full 32x32 multiply. This provides a useful speedup on many machines.
  156108. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  156109. * in C, but some C compilers will do the right thing if you provide the
  156110. * correct combination of casts.
  156111. */
  156112. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156113. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  156114. #endif
  156115. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  156116. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  156117. #endif
  156118. #ifndef MULTIPLY16C16 /* default definition */
  156119. #define MULTIPLY16C16(var,const) ((var) * (const))
  156120. #endif
  156121. /* Same except both inputs are variables. */
  156122. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156123. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  156124. #endif
  156125. #ifndef MULTIPLY16V16 /* default definition */
  156126. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  156127. #endif
  156128. #endif
  156129. /********* End of inlined file: jdct.h *********/
  156130. /* Private declarations for DCT subsystem */
  156131. /* Private subobject for this module */
  156132. typedef struct {
  156133. struct jpeg_forward_dct pub; /* public fields */
  156134. /* Pointer to the DCT routine actually in use */
  156135. forward_DCT_method_ptr do_dct;
  156136. /* The actual post-DCT divisors --- not identical to the quant table
  156137. * entries, because of scaling (especially for an unnormalized DCT).
  156138. * Each table is given in normal array order.
  156139. */
  156140. DCTELEM * divisors[NUM_QUANT_TBLS];
  156141. #ifdef DCT_FLOAT_SUPPORTED
  156142. /* Same as above for the floating-point case. */
  156143. float_DCT_method_ptr do_float_dct;
  156144. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  156145. #endif
  156146. } my_fdct_controller;
  156147. typedef my_fdct_controller * my_fdct_ptr;
  156148. /*
  156149. * Initialize for a processing pass.
  156150. * Verify that all referenced Q-tables are present, and set up
  156151. * the divisor table for each one.
  156152. * In the current implementation, DCT of all components is done during
  156153. * the first pass, even if only some components will be output in the
  156154. * first scan. Hence all components should be examined here.
  156155. */
  156156. METHODDEF(void)
  156157. start_pass_fdctmgr (j_compress_ptr cinfo)
  156158. {
  156159. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156160. int ci, qtblno, i;
  156161. jpeg_component_info *compptr;
  156162. JQUANT_TBL * qtbl;
  156163. DCTELEM * dtbl;
  156164. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156165. ci++, compptr++) {
  156166. qtblno = compptr->quant_tbl_no;
  156167. /* Make sure specified quantization table is present */
  156168. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  156169. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  156170. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  156171. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  156172. /* Compute divisors for this quant table */
  156173. /* We may do this more than once for same table, but it's not a big deal */
  156174. switch (cinfo->dct_method) {
  156175. #ifdef DCT_ISLOW_SUPPORTED
  156176. case JDCT_ISLOW:
  156177. /* For LL&M IDCT method, divisors are equal to raw quantization
  156178. * coefficients multiplied by 8 (to counteract scaling).
  156179. */
  156180. if (fdct->divisors[qtblno] == NULL) {
  156181. fdct->divisors[qtblno] = (DCTELEM *)
  156182. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156183. DCTSIZE2 * SIZEOF(DCTELEM));
  156184. }
  156185. dtbl = fdct->divisors[qtblno];
  156186. for (i = 0; i < DCTSIZE2; i++) {
  156187. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  156188. }
  156189. break;
  156190. #endif
  156191. #ifdef DCT_IFAST_SUPPORTED
  156192. case JDCT_IFAST:
  156193. {
  156194. /* For AA&N IDCT method, divisors are equal to quantization
  156195. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156196. * scalefactor[0] = 1
  156197. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156198. * We apply a further scale factor of 8.
  156199. */
  156200. #define CONST_BITS 14
  156201. static const INT16 aanscales[DCTSIZE2] = {
  156202. /* precomputed values scaled up by 14 bits */
  156203. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156204. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  156205. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  156206. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  156207. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156208. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  156209. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  156210. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  156211. };
  156212. SHIFT_TEMPS
  156213. if (fdct->divisors[qtblno] == NULL) {
  156214. fdct->divisors[qtblno] = (DCTELEM *)
  156215. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156216. DCTSIZE2 * SIZEOF(DCTELEM));
  156217. }
  156218. dtbl = fdct->divisors[qtblno];
  156219. for (i = 0; i < DCTSIZE2; i++) {
  156220. dtbl[i] = (DCTELEM)
  156221. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  156222. (INT32) aanscales[i]),
  156223. CONST_BITS-3);
  156224. }
  156225. }
  156226. break;
  156227. #endif
  156228. #ifdef DCT_FLOAT_SUPPORTED
  156229. case JDCT_FLOAT:
  156230. {
  156231. /* For float AA&N IDCT method, divisors are equal to quantization
  156232. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156233. * scalefactor[0] = 1
  156234. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156235. * We apply a further scale factor of 8.
  156236. * What's actually stored is 1/divisor so that the inner loop can
  156237. * use a multiplication rather than a division.
  156238. */
  156239. FAST_FLOAT * fdtbl;
  156240. int row, col;
  156241. static const double aanscalefactor[DCTSIZE] = {
  156242. 1.0, 1.387039845, 1.306562965, 1.175875602,
  156243. 1.0, 0.785694958, 0.541196100, 0.275899379
  156244. };
  156245. if (fdct->float_divisors[qtblno] == NULL) {
  156246. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  156247. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156248. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  156249. }
  156250. fdtbl = fdct->float_divisors[qtblno];
  156251. i = 0;
  156252. for (row = 0; row < DCTSIZE; row++) {
  156253. for (col = 0; col < DCTSIZE; col++) {
  156254. fdtbl[i] = (FAST_FLOAT)
  156255. (1.0 / (((double) qtbl->quantval[i] *
  156256. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  156257. i++;
  156258. }
  156259. }
  156260. }
  156261. break;
  156262. #endif
  156263. default:
  156264. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156265. break;
  156266. }
  156267. }
  156268. }
  156269. /*
  156270. * Perform forward DCT on one or more blocks of a component.
  156271. *
  156272. * The input samples are taken from the sample_data[] array starting at
  156273. * position start_row/start_col, and moving to the right for any additional
  156274. * blocks. The quantized coefficients are returned in coef_blocks[].
  156275. */
  156276. METHODDEF(void)
  156277. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  156278. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156279. JDIMENSION start_row, JDIMENSION start_col,
  156280. JDIMENSION num_blocks)
  156281. /* This version is used for integer DCT implementations. */
  156282. {
  156283. /* This routine is heavily used, so it's worth coding it tightly. */
  156284. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156285. forward_DCT_method_ptr do_dct = fdct->do_dct;
  156286. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  156287. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  156288. JDIMENSION bi;
  156289. sample_data += start_row; /* fold in the vertical offset once */
  156290. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  156291. /* Load data into workspace, applying unsigned->signed conversion */
  156292. { register DCTELEM *workspaceptr;
  156293. register JSAMPROW elemptr;
  156294. register int elemr;
  156295. workspaceptr = workspace;
  156296. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  156297. elemptr = sample_data[elemr] + start_col;
  156298. #if DCTSIZE == 8 /* unroll the inner loop */
  156299. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156300. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156301. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156302. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156303. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156304. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156305. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156306. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156307. #else
  156308. { register int elemc;
  156309. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  156310. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156311. }
  156312. }
  156313. #endif
  156314. }
  156315. }
  156316. /* Perform the DCT */
  156317. (*do_dct) (workspace);
  156318. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  156319. { register DCTELEM temp, qval;
  156320. register int i;
  156321. register JCOEFPTR output_ptr = coef_blocks[bi];
  156322. for (i = 0; i < DCTSIZE2; i++) {
  156323. qval = divisors[i];
  156324. temp = workspace[i];
  156325. /* Divide the coefficient value by qval, ensuring proper rounding.
  156326. * Since C does not specify the direction of rounding for negative
  156327. * quotients, we have to force the dividend positive for portability.
  156328. *
  156329. * In most files, at least half of the output values will be zero
  156330. * (at default quantization settings, more like three-quarters...)
  156331. * so we should ensure that this case is fast. On many machines,
  156332. * a comparison is enough cheaper than a divide to make a special test
  156333. * a win. Since both inputs will be nonnegative, we need only test
  156334. * for a < b to discover whether a/b is 0.
  156335. * If your machine's division is fast enough, define FAST_DIVIDE.
  156336. */
  156337. #ifdef FAST_DIVIDE
  156338. #define DIVIDE_BY(a,b) a /= b
  156339. #else
  156340. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  156341. #endif
  156342. if (temp < 0) {
  156343. temp = -temp;
  156344. temp += qval>>1; /* for rounding */
  156345. DIVIDE_BY(temp, qval);
  156346. temp = -temp;
  156347. } else {
  156348. temp += qval>>1; /* for rounding */
  156349. DIVIDE_BY(temp, qval);
  156350. }
  156351. output_ptr[i] = (JCOEF) temp;
  156352. }
  156353. }
  156354. }
  156355. }
  156356. #ifdef DCT_FLOAT_SUPPORTED
  156357. METHODDEF(void)
  156358. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  156359. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156360. JDIMENSION start_row, JDIMENSION start_col,
  156361. JDIMENSION num_blocks)
  156362. /* This version is used for floating-point DCT implementations. */
  156363. {
  156364. /* This routine is heavily used, so it's worth coding it tightly. */
  156365. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156366. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  156367. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  156368. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  156369. JDIMENSION bi;
  156370. sample_data += start_row; /* fold in the vertical offset once */
  156371. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  156372. /* Load data into workspace, applying unsigned->signed conversion */
  156373. { register FAST_FLOAT *workspaceptr;
  156374. register JSAMPROW elemptr;
  156375. register int elemr;
  156376. workspaceptr = workspace;
  156377. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  156378. elemptr = sample_data[elemr] + start_col;
  156379. #if DCTSIZE == 8 /* unroll the inner loop */
  156380. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156381. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156382. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156383. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156384. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156385. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156386. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156387. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156388. #else
  156389. { register int elemc;
  156390. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  156391. *workspaceptr++ = (FAST_FLOAT)
  156392. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156393. }
  156394. }
  156395. #endif
  156396. }
  156397. }
  156398. /* Perform the DCT */
  156399. (*do_dct) (workspace);
  156400. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  156401. { register FAST_FLOAT temp;
  156402. register int i;
  156403. register JCOEFPTR output_ptr = coef_blocks[bi];
  156404. for (i = 0; i < DCTSIZE2; i++) {
  156405. /* Apply the quantization and scaling factor */
  156406. temp = workspace[i] * divisors[i];
  156407. /* Round to nearest integer.
  156408. * Since C does not specify the direction of rounding for negative
  156409. * quotients, we have to force the dividend positive for portability.
  156410. * The maximum coefficient size is +-16K (for 12-bit data), so this
  156411. * code should work for either 16-bit or 32-bit ints.
  156412. */
  156413. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  156414. }
  156415. }
  156416. }
  156417. }
  156418. #endif /* DCT_FLOAT_SUPPORTED */
  156419. /*
  156420. * Initialize FDCT manager.
  156421. */
  156422. GLOBAL(void)
  156423. jinit_forward_dct (j_compress_ptr cinfo)
  156424. {
  156425. my_fdct_ptr fdct;
  156426. int i;
  156427. fdct = (my_fdct_ptr)
  156428. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156429. SIZEOF(my_fdct_controller));
  156430. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  156431. fdct->pub.start_pass = start_pass_fdctmgr;
  156432. switch (cinfo->dct_method) {
  156433. #ifdef DCT_ISLOW_SUPPORTED
  156434. case JDCT_ISLOW:
  156435. fdct->pub.forward_DCT = forward_DCT;
  156436. fdct->do_dct = jpeg_fdct_islow;
  156437. break;
  156438. #endif
  156439. #ifdef DCT_IFAST_SUPPORTED
  156440. case JDCT_IFAST:
  156441. fdct->pub.forward_DCT = forward_DCT;
  156442. fdct->do_dct = jpeg_fdct_ifast;
  156443. break;
  156444. #endif
  156445. #ifdef DCT_FLOAT_SUPPORTED
  156446. case JDCT_FLOAT:
  156447. fdct->pub.forward_DCT = forward_DCT_float;
  156448. fdct->do_float_dct = jpeg_fdct_float;
  156449. break;
  156450. #endif
  156451. default:
  156452. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156453. break;
  156454. }
  156455. /* Mark divisor tables unallocated */
  156456. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  156457. fdct->divisors[i] = NULL;
  156458. #ifdef DCT_FLOAT_SUPPORTED
  156459. fdct->float_divisors[i] = NULL;
  156460. #endif
  156461. }
  156462. }
  156463. /********* End of inlined file: jcdctmgr.c *********/
  156464. #undef CONST_BITS
  156465. /********* Start of inlined file: jchuff.c *********/
  156466. #define JPEG_INTERNALS
  156467. /********* Start of inlined file: jchuff.h *********/
  156468. /* The legal range of a DCT coefficient is
  156469. * -1024 .. +1023 for 8-bit data;
  156470. * -16384 .. +16383 for 12-bit data.
  156471. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  156472. */
  156473. #ifndef _jchuff_h_
  156474. #define _jchuff_h_
  156475. #if BITS_IN_JSAMPLE == 8
  156476. #define MAX_COEF_BITS 10
  156477. #else
  156478. #define MAX_COEF_BITS 14
  156479. #endif
  156480. /* Derived data constructed for each Huffman table */
  156481. typedef struct {
  156482. unsigned int ehufco[256]; /* code for each symbol */
  156483. char ehufsi[256]; /* length of code for each symbol */
  156484. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  156485. } c_derived_tbl;
  156486. /* Short forms of external names for systems with brain-damaged linkers. */
  156487. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156488. #define jpeg_make_c_derived_tbl jMkCDerived
  156489. #define jpeg_gen_optimal_table jGenOptTbl
  156490. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156491. /* Expand a Huffman table definition into the derived format */
  156492. EXTERN(void) jpeg_make_c_derived_tbl
  156493. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  156494. c_derived_tbl ** pdtbl));
  156495. /* Generate an optimal table definition given the specified counts */
  156496. EXTERN(void) jpeg_gen_optimal_table
  156497. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  156498. #endif
  156499. /********* End of inlined file: jchuff.h *********/
  156500. /* Declarations shared with jcphuff.c */
  156501. /* Expanded entropy encoder object for Huffman encoding.
  156502. *
  156503. * The savable_state subrecord contains fields that change within an MCU,
  156504. * but must not be updated permanently until we complete the MCU.
  156505. */
  156506. typedef struct {
  156507. INT32 put_buffer; /* current bit-accumulation buffer */
  156508. int put_bits; /* # of bits now in it */
  156509. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  156510. } savable_state;
  156511. /* This macro is to work around compilers with missing or broken
  156512. * structure assignment. You'll need to fix this code if you have
  156513. * such a compiler and you change MAX_COMPS_IN_SCAN.
  156514. */
  156515. #ifndef NO_STRUCT_ASSIGN
  156516. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  156517. #else
  156518. #if MAX_COMPS_IN_SCAN == 4
  156519. #define ASSIGN_STATE(dest,src) \
  156520. ((dest).put_buffer = (src).put_buffer, \
  156521. (dest).put_bits = (src).put_bits, \
  156522. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  156523. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  156524. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  156525. (dest).last_dc_val[3] = (src).last_dc_val[3])
  156526. #endif
  156527. #endif
  156528. typedef struct {
  156529. struct jpeg_entropy_encoder pub; /* public fields */
  156530. savable_state saved; /* Bit buffer & DC state at start of MCU */
  156531. /* These fields are NOT loaded into local working state. */
  156532. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  156533. int next_restart_num; /* next restart number to write (0-7) */
  156534. /* Pointers to derived tables (these workspaces have image lifespan) */
  156535. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  156536. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  156537. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  156538. long * dc_count_ptrs[NUM_HUFF_TBLS];
  156539. long * ac_count_ptrs[NUM_HUFF_TBLS];
  156540. #endif
  156541. } huff_entropy_encoder;
  156542. typedef huff_entropy_encoder * huff_entropy_ptr;
  156543. /* Working state while writing an MCU.
  156544. * This struct contains all the fields that are needed by subroutines.
  156545. */
  156546. typedef struct {
  156547. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156548. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156549. savable_state cur; /* Current bit buffer & DC state */
  156550. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  156551. } working_state;
  156552. /* Forward declarations */
  156553. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  156554. JBLOCKROW *MCU_data));
  156555. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  156556. #ifdef ENTROPY_OPT_SUPPORTED
  156557. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  156558. JBLOCKROW *MCU_data));
  156559. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  156560. #endif
  156561. /*
  156562. * Initialize for a Huffman-compressed scan.
  156563. * If gather_statistics is TRUE, we do not output anything during the scan,
  156564. * just count the Huffman symbols used and generate Huffman code tables.
  156565. */
  156566. METHODDEF(void)
  156567. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  156568. {
  156569. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156570. int ci, dctbl, actbl;
  156571. jpeg_component_info * compptr;
  156572. if (gather_statistics) {
  156573. #ifdef ENTROPY_OPT_SUPPORTED
  156574. entropy->pub.encode_mcu = encode_mcu_gather;
  156575. entropy->pub.finish_pass = finish_pass_gather;
  156576. #else
  156577. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156578. #endif
  156579. } else {
  156580. entropy->pub.encode_mcu = encode_mcu_huff;
  156581. entropy->pub.finish_pass = finish_pass_huff;
  156582. }
  156583. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156584. compptr = cinfo->cur_comp_info[ci];
  156585. dctbl = compptr->dc_tbl_no;
  156586. actbl = compptr->ac_tbl_no;
  156587. if (gather_statistics) {
  156588. #ifdef ENTROPY_OPT_SUPPORTED
  156589. /* Check for invalid table indexes */
  156590. /* (make_c_derived_tbl does this in the other path) */
  156591. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  156592. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  156593. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  156594. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  156595. /* Allocate and zero the statistics tables */
  156596. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  156597. if (entropy->dc_count_ptrs[dctbl] == NULL)
  156598. entropy->dc_count_ptrs[dctbl] = (long *)
  156599. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156600. 257 * SIZEOF(long));
  156601. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  156602. if (entropy->ac_count_ptrs[actbl] == NULL)
  156603. entropy->ac_count_ptrs[actbl] = (long *)
  156604. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156605. 257 * SIZEOF(long));
  156606. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  156607. #endif
  156608. } else {
  156609. /* Compute derived values for Huffman tables */
  156610. /* We may do this more than once for a table, but it's not expensive */
  156611. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  156612. & entropy->dc_derived_tbls[dctbl]);
  156613. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  156614. & entropy->ac_derived_tbls[actbl]);
  156615. }
  156616. /* Initialize DC predictions to 0 */
  156617. entropy->saved.last_dc_val[ci] = 0;
  156618. }
  156619. /* Initialize bit buffer to empty */
  156620. entropy->saved.put_buffer = 0;
  156621. entropy->saved.put_bits = 0;
  156622. /* Initialize restart stuff */
  156623. entropy->restarts_to_go = cinfo->restart_interval;
  156624. entropy->next_restart_num = 0;
  156625. }
  156626. /*
  156627. * Compute the derived values for a Huffman table.
  156628. * This routine also performs some validation checks on the table.
  156629. *
  156630. * Note this is also used by jcphuff.c.
  156631. */
  156632. GLOBAL(void)
  156633. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  156634. c_derived_tbl ** pdtbl)
  156635. {
  156636. JHUFF_TBL *htbl;
  156637. c_derived_tbl *dtbl;
  156638. int p, i, l, lastp, si, maxsymbol;
  156639. char huffsize[257];
  156640. unsigned int huffcode[257];
  156641. unsigned int code;
  156642. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  156643. * paralleling the order of the symbols themselves in htbl->huffval[].
  156644. */
  156645. /* Find the input Huffman table */
  156646. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  156647. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  156648. htbl =
  156649. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  156650. if (htbl == NULL)
  156651. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  156652. /* Allocate a workspace if we haven't already done so. */
  156653. if (*pdtbl == NULL)
  156654. *pdtbl = (c_derived_tbl *)
  156655. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156656. SIZEOF(c_derived_tbl));
  156657. dtbl = *pdtbl;
  156658. /* Figure C.1: make table of Huffman code length for each symbol */
  156659. p = 0;
  156660. for (l = 1; l <= 16; l++) {
  156661. i = (int) htbl->bits[l];
  156662. if (i < 0 || p + i > 256) /* protect against table overrun */
  156663. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156664. while (i--)
  156665. huffsize[p++] = (char) l;
  156666. }
  156667. huffsize[p] = 0;
  156668. lastp = p;
  156669. /* Figure C.2: generate the codes themselves */
  156670. /* We also validate that the counts represent a legal Huffman code tree. */
  156671. code = 0;
  156672. si = huffsize[0];
  156673. p = 0;
  156674. while (huffsize[p]) {
  156675. while (((int) huffsize[p]) == si) {
  156676. huffcode[p++] = code;
  156677. code++;
  156678. }
  156679. /* code is now 1 more than the last code used for codelength si; but
  156680. * it must still fit in si bits, since no code is allowed to be all ones.
  156681. */
  156682. if (((INT32) code) >= (((INT32) 1) << si))
  156683. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156684. code <<= 1;
  156685. si++;
  156686. }
  156687. /* Figure C.3: generate encoding tables */
  156688. /* These are code and size indexed by symbol value */
  156689. /* Set all codeless symbols to have code length 0;
  156690. * this lets us detect duplicate VAL entries here, and later
  156691. * allows emit_bits to detect any attempt to emit such symbols.
  156692. */
  156693. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  156694. /* This is also a convenient place to check for out-of-range
  156695. * and duplicated VAL entries. We allow 0..255 for AC symbols
  156696. * but only 0..15 for DC. (We could constrain them further
  156697. * based on data depth and mode, but this seems enough.)
  156698. */
  156699. maxsymbol = isDC ? 15 : 255;
  156700. for (p = 0; p < lastp; p++) {
  156701. i = htbl->huffval[p];
  156702. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  156703. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156704. dtbl->ehufco[i] = huffcode[p];
  156705. dtbl->ehufsi[i] = huffsize[p];
  156706. }
  156707. }
  156708. /* Outputting bytes to the file */
  156709. /* Emit a byte, taking 'action' if must suspend. */
  156710. #define emit_byte(state,val,action) \
  156711. { *(state)->next_output_byte++ = (JOCTET) (val); \
  156712. if (--(state)->free_in_buffer == 0) \
  156713. if (! dump_buffer(state)) \
  156714. { action; } }
  156715. LOCAL(boolean)
  156716. dump_buffer (working_state * state)
  156717. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  156718. {
  156719. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  156720. if (! (*dest->empty_output_buffer) (state->cinfo))
  156721. return FALSE;
  156722. /* After a successful buffer dump, must reset buffer pointers */
  156723. state->next_output_byte = dest->next_output_byte;
  156724. state->free_in_buffer = dest->free_in_buffer;
  156725. return TRUE;
  156726. }
  156727. /* Outputting bits to the file */
  156728. /* Only the right 24 bits of put_buffer are used; the valid bits are
  156729. * left-justified in this part. At most 16 bits can be passed to emit_bits
  156730. * in one call, and we never retain more than 7 bits in put_buffer
  156731. * between calls, so 24 bits are sufficient.
  156732. */
  156733. INLINE
  156734. LOCAL(boolean)
  156735. emit_bits (working_state * state, unsigned int code, int size)
  156736. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  156737. {
  156738. /* This routine is heavily used, so it's worth coding tightly. */
  156739. register INT32 put_buffer = (INT32) code;
  156740. register int put_bits = state->cur.put_bits;
  156741. /* if size is 0, caller used an invalid Huffman table entry */
  156742. if (size == 0)
  156743. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  156744. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  156745. put_bits += size; /* new number of bits in buffer */
  156746. put_buffer <<= 24 - put_bits; /* align incoming bits */
  156747. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  156748. while (put_bits >= 8) {
  156749. int c = (int) ((put_buffer >> 16) & 0xFF);
  156750. emit_byte(state, c, return FALSE);
  156751. if (c == 0xFF) { /* need to stuff a zero byte? */
  156752. emit_byte(state, 0, return FALSE);
  156753. }
  156754. put_buffer <<= 8;
  156755. put_bits -= 8;
  156756. }
  156757. state->cur.put_buffer = put_buffer; /* update state variables */
  156758. state->cur.put_bits = put_bits;
  156759. return TRUE;
  156760. }
  156761. LOCAL(boolean)
  156762. flush_bits (working_state * state)
  156763. {
  156764. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  156765. return FALSE;
  156766. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  156767. state->cur.put_bits = 0;
  156768. return TRUE;
  156769. }
  156770. /* Encode a single block's worth of coefficients */
  156771. LOCAL(boolean)
  156772. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  156773. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  156774. {
  156775. register int temp, temp2;
  156776. register int nbits;
  156777. register int k, r, i;
  156778. /* Encode the DC coefficient difference per section F.1.2.1 */
  156779. temp = temp2 = block[0] - last_dc_val;
  156780. if (temp < 0) {
  156781. temp = -temp; /* temp is abs value of input */
  156782. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  156783. /* This code assumes we are on a two's complement machine */
  156784. temp2--;
  156785. }
  156786. /* Find the number of bits needed for the magnitude of the coefficient */
  156787. nbits = 0;
  156788. while (temp) {
  156789. nbits++;
  156790. temp >>= 1;
  156791. }
  156792. /* Check for out-of-range coefficient values.
  156793. * Since we're encoding a difference, the range limit is twice as much.
  156794. */
  156795. if (nbits > MAX_COEF_BITS+1)
  156796. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  156797. /* Emit the Huffman-coded symbol for the number of bits */
  156798. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  156799. return FALSE;
  156800. /* Emit that number of bits of the value, if positive, */
  156801. /* or the complement of its magnitude, if negative. */
  156802. if (nbits) /* emit_bits rejects calls with size 0 */
  156803. if (! emit_bits(state, (unsigned int) temp2, nbits))
  156804. return FALSE;
  156805. /* Encode the AC coefficients per section F.1.2.2 */
  156806. r = 0; /* r = run length of zeros */
  156807. for (k = 1; k < DCTSIZE2; k++) {
  156808. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  156809. r++;
  156810. } else {
  156811. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  156812. while (r > 15) {
  156813. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  156814. return FALSE;
  156815. r -= 16;
  156816. }
  156817. temp2 = temp;
  156818. if (temp < 0) {
  156819. temp = -temp; /* temp is abs value of input */
  156820. /* This code assumes we are on a two's complement machine */
  156821. temp2--;
  156822. }
  156823. /* Find the number of bits needed for the magnitude of the coefficient */
  156824. nbits = 1; /* there must be at least one 1 bit */
  156825. while ((temp >>= 1))
  156826. nbits++;
  156827. /* Check for out-of-range coefficient values */
  156828. if (nbits > MAX_COEF_BITS)
  156829. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  156830. /* Emit Huffman symbol for run length / number of bits */
  156831. i = (r << 4) + nbits;
  156832. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  156833. return FALSE;
  156834. /* Emit that number of bits of the value, if positive, */
  156835. /* or the complement of its magnitude, if negative. */
  156836. if (! emit_bits(state, (unsigned int) temp2, nbits))
  156837. return FALSE;
  156838. r = 0;
  156839. }
  156840. }
  156841. /* If the last coef(s) were zero, emit an end-of-block code */
  156842. if (r > 0)
  156843. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  156844. return FALSE;
  156845. return TRUE;
  156846. }
  156847. /*
  156848. * Emit a restart marker & resynchronize predictions.
  156849. */
  156850. LOCAL(boolean)
  156851. emit_restart (working_state * state, int restart_num)
  156852. {
  156853. int ci;
  156854. if (! flush_bits(state))
  156855. return FALSE;
  156856. emit_byte(state, 0xFF, return FALSE);
  156857. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  156858. /* Re-initialize DC predictions to 0 */
  156859. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  156860. state->cur.last_dc_val[ci] = 0;
  156861. /* The restart counter is not updated until we successfully write the MCU. */
  156862. return TRUE;
  156863. }
  156864. /*
  156865. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  156866. */
  156867. METHODDEF(boolean)
  156868. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  156869. {
  156870. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156871. working_state state;
  156872. int blkn, ci;
  156873. jpeg_component_info * compptr;
  156874. /* Load up working state */
  156875. state.next_output_byte = cinfo->dest->next_output_byte;
  156876. state.free_in_buffer = cinfo->dest->free_in_buffer;
  156877. ASSIGN_STATE(state.cur, entropy->saved);
  156878. state.cinfo = cinfo;
  156879. /* Emit restart marker if needed */
  156880. if (cinfo->restart_interval) {
  156881. if (entropy->restarts_to_go == 0)
  156882. if (! emit_restart(&state, entropy->next_restart_num))
  156883. return FALSE;
  156884. }
  156885. /* Encode the MCU data blocks */
  156886. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  156887. ci = cinfo->MCU_membership[blkn];
  156888. compptr = cinfo->cur_comp_info[ci];
  156889. if (! encode_one_block(&state,
  156890. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  156891. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  156892. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  156893. return FALSE;
  156894. /* Update last_dc_val */
  156895. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  156896. }
  156897. /* Completed MCU, so update state */
  156898. cinfo->dest->next_output_byte = state.next_output_byte;
  156899. cinfo->dest->free_in_buffer = state.free_in_buffer;
  156900. ASSIGN_STATE(entropy->saved, state.cur);
  156901. /* Update restart-interval state too */
  156902. if (cinfo->restart_interval) {
  156903. if (entropy->restarts_to_go == 0) {
  156904. entropy->restarts_to_go = cinfo->restart_interval;
  156905. entropy->next_restart_num++;
  156906. entropy->next_restart_num &= 7;
  156907. }
  156908. entropy->restarts_to_go--;
  156909. }
  156910. return TRUE;
  156911. }
  156912. /*
  156913. * Finish up at the end of a Huffman-compressed scan.
  156914. */
  156915. METHODDEF(void)
  156916. finish_pass_huff (j_compress_ptr cinfo)
  156917. {
  156918. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156919. working_state state;
  156920. /* Load up working state ... flush_bits needs it */
  156921. state.next_output_byte = cinfo->dest->next_output_byte;
  156922. state.free_in_buffer = cinfo->dest->free_in_buffer;
  156923. ASSIGN_STATE(state.cur, entropy->saved);
  156924. state.cinfo = cinfo;
  156925. /* Flush out the last data */
  156926. if (! flush_bits(&state))
  156927. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  156928. /* Update state */
  156929. cinfo->dest->next_output_byte = state.next_output_byte;
  156930. cinfo->dest->free_in_buffer = state.free_in_buffer;
  156931. ASSIGN_STATE(entropy->saved, state.cur);
  156932. }
  156933. /*
  156934. * Huffman coding optimization.
  156935. *
  156936. * We first scan the supplied data and count the number of uses of each symbol
  156937. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  156938. * Then we build a Huffman coding tree for the observed counts.
  156939. * Symbols which are not needed at all for the particular image are not
  156940. * assigned any code, which saves space in the DHT marker as well as in
  156941. * the compressed data.
  156942. */
  156943. #ifdef ENTROPY_OPT_SUPPORTED
  156944. /* Process a single block's worth of coefficients */
  156945. LOCAL(void)
  156946. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  156947. long dc_counts[], long ac_counts[])
  156948. {
  156949. register int temp;
  156950. register int nbits;
  156951. register int k, r;
  156952. /* Encode the DC coefficient difference per section F.1.2.1 */
  156953. temp = block[0] - last_dc_val;
  156954. if (temp < 0)
  156955. temp = -temp;
  156956. /* Find the number of bits needed for the magnitude of the coefficient */
  156957. nbits = 0;
  156958. while (temp) {
  156959. nbits++;
  156960. temp >>= 1;
  156961. }
  156962. /* Check for out-of-range coefficient values.
  156963. * Since we're encoding a difference, the range limit is twice as much.
  156964. */
  156965. if (nbits > MAX_COEF_BITS+1)
  156966. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  156967. /* Count the Huffman symbol for the number of bits */
  156968. dc_counts[nbits]++;
  156969. /* Encode the AC coefficients per section F.1.2.2 */
  156970. r = 0; /* r = run length of zeros */
  156971. for (k = 1; k < DCTSIZE2; k++) {
  156972. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  156973. r++;
  156974. } else {
  156975. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  156976. while (r > 15) {
  156977. ac_counts[0xF0]++;
  156978. r -= 16;
  156979. }
  156980. /* Find the number of bits needed for the magnitude of the coefficient */
  156981. if (temp < 0)
  156982. temp = -temp;
  156983. /* Find the number of bits needed for the magnitude of the coefficient */
  156984. nbits = 1; /* there must be at least one 1 bit */
  156985. while ((temp >>= 1))
  156986. nbits++;
  156987. /* Check for out-of-range coefficient values */
  156988. if (nbits > MAX_COEF_BITS)
  156989. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  156990. /* Count Huffman symbol for run length / number of bits */
  156991. ac_counts[(r << 4) + nbits]++;
  156992. r = 0;
  156993. }
  156994. }
  156995. /* If the last coef(s) were zero, emit an end-of-block code */
  156996. if (r > 0)
  156997. ac_counts[0]++;
  156998. }
  156999. /*
  157000. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  157001. * No data is actually output, so no suspension return is possible.
  157002. */
  157003. METHODDEF(boolean)
  157004. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157005. {
  157006. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157007. int blkn, ci;
  157008. jpeg_component_info * compptr;
  157009. /* Take care of restart intervals if needed */
  157010. if (cinfo->restart_interval) {
  157011. if (entropy->restarts_to_go == 0) {
  157012. /* Re-initialize DC predictions to 0 */
  157013. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  157014. entropy->saved.last_dc_val[ci] = 0;
  157015. /* Update restart state */
  157016. entropy->restarts_to_go = cinfo->restart_interval;
  157017. }
  157018. entropy->restarts_to_go--;
  157019. }
  157020. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157021. ci = cinfo->MCU_membership[blkn];
  157022. compptr = cinfo->cur_comp_info[ci];
  157023. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  157024. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  157025. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  157026. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  157027. }
  157028. return TRUE;
  157029. }
  157030. /*
  157031. * Generate the best Huffman code table for the given counts, fill htbl.
  157032. * Note this is also used by jcphuff.c.
  157033. *
  157034. * The JPEG standard requires that no symbol be assigned a codeword of all
  157035. * one bits (so that padding bits added at the end of a compressed segment
  157036. * can't look like a valid code). Because of the canonical ordering of
  157037. * codewords, this just means that there must be an unused slot in the
  157038. * longest codeword length category. Section K.2 of the JPEG spec suggests
  157039. * reserving such a slot by pretending that symbol 256 is a valid symbol
  157040. * with count 1. In theory that's not optimal; giving it count zero but
  157041. * including it in the symbol set anyway should give a better Huffman code.
  157042. * But the theoretically better code actually seems to come out worse in
  157043. * practice, because it produces more all-ones bytes (which incur stuffed
  157044. * zero bytes in the final file). In any case the difference is tiny.
  157045. *
  157046. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  157047. * If some symbols have a very small but nonzero probability, the Huffman tree
  157048. * must be adjusted to meet the code length restriction. We currently use
  157049. * the adjustment method suggested in JPEG section K.2. This method is *not*
  157050. * optimal; it may not choose the best possible limited-length code. But
  157051. * typically only very-low-frequency symbols will be given less-than-optimal
  157052. * lengths, so the code is almost optimal. Experimental comparisons against
  157053. * an optimal limited-length-code algorithm indicate that the difference is
  157054. * microscopic --- usually less than a hundredth of a percent of total size.
  157055. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  157056. */
  157057. GLOBAL(void)
  157058. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  157059. {
  157060. #define MAX_CLEN 32 /* assumed maximum initial code length */
  157061. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  157062. int codesize[257]; /* codesize[k] = code length of symbol k */
  157063. int others[257]; /* next symbol in current branch of tree */
  157064. int c1, c2;
  157065. int p, i, j;
  157066. long v;
  157067. /* This algorithm is explained in section K.2 of the JPEG standard */
  157068. MEMZERO(bits, SIZEOF(bits));
  157069. MEMZERO(codesize, SIZEOF(codesize));
  157070. for (i = 0; i < 257; i++)
  157071. others[i] = -1; /* init links to empty */
  157072. freq[256] = 1; /* make sure 256 has a nonzero count */
  157073. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  157074. * that no real symbol is given code-value of all ones, because 256
  157075. * will be placed last in the largest codeword category.
  157076. */
  157077. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  157078. for (;;) {
  157079. /* Find the smallest nonzero frequency, set c1 = its symbol */
  157080. /* In case of ties, take the larger symbol number */
  157081. c1 = -1;
  157082. v = 1000000000L;
  157083. for (i = 0; i <= 256; i++) {
  157084. if (freq[i] && freq[i] <= v) {
  157085. v = freq[i];
  157086. c1 = i;
  157087. }
  157088. }
  157089. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  157090. /* In case of ties, take the larger symbol number */
  157091. c2 = -1;
  157092. v = 1000000000L;
  157093. for (i = 0; i <= 256; i++) {
  157094. if (freq[i] && freq[i] <= v && i != c1) {
  157095. v = freq[i];
  157096. c2 = i;
  157097. }
  157098. }
  157099. /* Done if we've merged everything into one frequency */
  157100. if (c2 < 0)
  157101. break;
  157102. /* Else merge the two counts/trees */
  157103. freq[c1] += freq[c2];
  157104. freq[c2] = 0;
  157105. /* Increment the codesize of everything in c1's tree branch */
  157106. codesize[c1]++;
  157107. while (others[c1] >= 0) {
  157108. c1 = others[c1];
  157109. codesize[c1]++;
  157110. }
  157111. others[c1] = c2; /* chain c2 onto c1's tree branch */
  157112. /* Increment the codesize of everything in c2's tree branch */
  157113. codesize[c2]++;
  157114. while (others[c2] >= 0) {
  157115. c2 = others[c2];
  157116. codesize[c2]++;
  157117. }
  157118. }
  157119. /* Now count the number of symbols of each code length */
  157120. for (i = 0; i <= 256; i++) {
  157121. if (codesize[i]) {
  157122. /* The JPEG standard seems to think that this can't happen, */
  157123. /* but I'm paranoid... */
  157124. if (codesize[i] > MAX_CLEN)
  157125. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  157126. bits[codesize[i]]++;
  157127. }
  157128. }
  157129. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  157130. * Huffman procedure assigned any such lengths, we must adjust the coding.
  157131. * Here is what the JPEG spec says about how this next bit works:
  157132. * Since symbols are paired for the longest Huffman code, the symbols are
  157133. * removed from this length category two at a time. The prefix for the pair
  157134. * (which is one bit shorter) is allocated to one of the pair; then,
  157135. * skipping the BITS entry for that prefix length, a code word from the next
  157136. * shortest nonzero BITS entry is converted into a prefix for two code words
  157137. * one bit longer.
  157138. */
  157139. for (i = MAX_CLEN; i > 16; i--) {
  157140. while (bits[i] > 0) {
  157141. j = i - 2; /* find length of new prefix to be used */
  157142. while (bits[j] == 0)
  157143. j--;
  157144. bits[i] -= 2; /* remove two symbols */
  157145. bits[i-1]++; /* one goes in this length */
  157146. bits[j+1] += 2; /* two new symbols in this length */
  157147. bits[j]--; /* symbol of this length is now a prefix */
  157148. }
  157149. }
  157150. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  157151. while (bits[i] == 0) /* find largest codelength still in use */
  157152. i--;
  157153. bits[i]--;
  157154. /* Return final symbol counts (only for lengths 0..16) */
  157155. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  157156. /* Return a list of the symbols sorted by code length */
  157157. /* It's not real clear to me why we don't need to consider the codelength
  157158. * changes made above, but the JPEG spec seems to think this works.
  157159. */
  157160. p = 0;
  157161. for (i = 1; i <= MAX_CLEN; i++) {
  157162. for (j = 0; j <= 255; j++) {
  157163. if (codesize[j] == i) {
  157164. htbl->huffval[p] = (UINT8) j;
  157165. p++;
  157166. }
  157167. }
  157168. }
  157169. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  157170. htbl->sent_table = FALSE;
  157171. }
  157172. /*
  157173. * Finish up a statistics-gathering pass and create the new Huffman tables.
  157174. */
  157175. METHODDEF(void)
  157176. finish_pass_gather (j_compress_ptr cinfo)
  157177. {
  157178. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157179. int ci, dctbl, actbl;
  157180. jpeg_component_info * compptr;
  157181. JHUFF_TBL **htblptr;
  157182. boolean did_dc[NUM_HUFF_TBLS];
  157183. boolean did_ac[NUM_HUFF_TBLS];
  157184. /* It's important not to apply jpeg_gen_optimal_table more than once
  157185. * per table, because it clobbers the input frequency counts!
  157186. */
  157187. MEMZERO(did_dc, SIZEOF(did_dc));
  157188. MEMZERO(did_ac, SIZEOF(did_ac));
  157189. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157190. compptr = cinfo->cur_comp_info[ci];
  157191. dctbl = compptr->dc_tbl_no;
  157192. actbl = compptr->ac_tbl_no;
  157193. if (! did_dc[dctbl]) {
  157194. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  157195. if (*htblptr == NULL)
  157196. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157197. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  157198. did_dc[dctbl] = TRUE;
  157199. }
  157200. if (! did_ac[actbl]) {
  157201. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  157202. if (*htblptr == NULL)
  157203. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157204. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  157205. did_ac[actbl] = TRUE;
  157206. }
  157207. }
  157208. }
  157209. #endif /* ENTROPY_OPT_SUPPORTED */
  157210. /*
  157211. * Module initialization routine for Huffman entropy encoding.
  157212. */
  157213. GLOBAL(void)
  157214. jinit_huff_encoder (j_compress_ptr cinfo)
  157215. {
  157216. huff_entropy_ptr entropy;
  157217. int i;
  157218. entropy = (huff_entropy_ptr)
  157219. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157220. SIZEOF(huff_entropy_encoder));
  157221. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  157222. entropy->pub.start_pass = start_pass_huff;
  157223. /* Mark tables unallocated */
  157224. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157225. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  157226. #ifdef ENTROPY_OPT_SUPPORTED
  157227. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  157228. #endif
  157229. }
  157230. }
  157231. /********* End of inlined file: jchuff.c *********/
  157232. #undef emit_byte
  157233. /********* Start of inlined file: jcinit.c *********/
  157234. #define JPEG_INTERNALS
  157235. /*
  157236. * Master selection of compression modules.
  157237. * This is done once at the start of processing an image. We determine
  157238. * which modules will be used and give them appropriate initialization calls.
  157239. */
  157240. GLOBAL(void)
  157241. jinit_compress_master (j_compress_ptr cinfo)
  157242. {
  157243. /* Initialize master control (includes parameter checking/processing) */
  157244. jinit_c_master_control(cinfo, FALSE /* full compression */);
  157245. /* Preprocessing */
  157246. if (! cinfo->raw_data_in) {
  157247. jinit_color_converter(cinfo);
  157248. jinit_downsampler(cinfo);
  157249. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  157250. }
  157251. /* Forward DCT */
  157252. jinit_forward_dct(cinfo);
  157253. /* Entropy encoding: either Huffman or arithmetic coding. */
  157254. if (cinfo->arith_code) {
  157255. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  157256. } else {
  157257. if (cinfo->progressive_mode) {
  157258. #ifdef C_PROGRESSIVE_SUPPORTED
  157259. jinit_phuff_encoder(cinfo);
  157260. #else
  157261. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157262. #endif
  157263. } else
  157264. jinit_huff_encoder(cinfo);
  157265. }
  157266. /* Need a full-image coefficient buffer in any multi-pass mode. */
  157267. jinit_c_coef_controller(cinfo,
  157268. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  157269. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  157270. jinit_marker_writer(cinfo);
  157271. /* We can now tell the memory manager to allocate virtual arrays. */
  157272. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  157273. /* Write the datastream header (SOI) immediately.
  157274. * Frame and scan headers are postponed till later.
  157275. * This lets application insert special markers after the SOI.
  157276. */
  157277. (*cinfo->marker->write_file_header) (cinfo);
  157278. }
  157279. /********* End of inlined file: jcinit.c *********/
  157280. /********* Start of inlined file: jcmainct.c *********/
  157281. #define JPEG_INTERNALS
  157282. /* Note: currently, there is no operating mode in which a full-image buffer
  157283. * is needed at this step. If there were, that mode could not be used with
  157284. * "raw data" input, since this module is bypassed in that case. However,
  157285. * we've left the code here for possible use in special applications.
  157286. */
  157287. #undef FULL_MAIN_BUFFER_SUPPORTED
  157288. /* Private buffer controller object */
  157289. typedef struct {
  157290. struct jpeg_c_main_controller pub; /* public fields */
  157291. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  157292. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  157293. boolean suspended; /* remember if we suspended output */
  157294. J_BUF_MODE pass_mode; /* current operating mode */
  157295. /* If using just a strip buffer, this points to the entire set of buffers
  157296. * (we allocate one for each component). In the full-image case, this
  157297. * points to the currently accessible strips of the virtual arrays.
  157298. */
  157299. JSAMPARRAY buffer[MAX_COMPONENTS];
  157300. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157301. /* If using full-image storage, this array holds pointers to virtual-array
  157302. * control blocks for each component. Unused if not full-image storage.
  157303. */
  157304. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  157305. #endif
  157306. } my_main_controller;
  157307. typedef my_main_controller * my_main_ptr;
  157308. /* Forward declarations */
  157309. METHODDEF(void) process_data_simple_main
  157310. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  157311. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  157312. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157313. METHODDEF(void) process_data_buffer_main
  157314. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  157315. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  157316. #endif
  157317. /*
  157318. * Initialize for a processing pass.
  157319. */
  157320. METHODDEF(void)
  157321. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157322. {
  157323. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  157324. /* Do nothing in raw-data mode. */
  157325. if (cinfo->raw_data_in)
  157326. return;
  157327. main_->cur_iMCU_row = 0; /* initialize counters */
  157328. main_->rowgroup_ctr = 0;
  157329. main_->suspended = FALSE;
  157330. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  157331. switch (pass_mode) {
  157332. case JBUF_PASS_THRU:
  157333. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157334. if (main_->whole_image[0] != NULL)
  157335. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157336. #endif
  157337. main_->pub.process_data = process_data_simple_main;
  157338. break;
  157339. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157340. case JBUF_SAVE_SOURCE:
  157341. case JBUF_CRANK_DEST:
  157342. case JBUF_SAVE_AND_PASS:
  157343. if (main_->whole_image[0] == NULL)
  157344. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157345. main_->pub.process_data = process_data_buffer_main;
  157346. break;
  157347. #endif
  157348. default:
  157349. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157350. break;
  157351. }
  157352. }
  157353. /*
  157354. * Process some data.
  157355. * This routine handles the simple pass-through mode,
  157356. * where we have only a strip buffer.
  157357. */
  157358. METHODDEF(void)
  157359. process_data_simple_main (j_compress_ptr cinfo,
  157360. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157361. JDIMENSION in_rows_avail)
  157362. {
  157363. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  157364. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  157365. /* Read input data if we haven't filled the main buffer yet */
  157366. if (main_->rowgroup_ctr < DCTSIZE)
  157367. (*cinfo->prep->pre_process_data) (cinfo,
  157368. input_buf, in_row_ctr, in_rows_avail,
  157369. main_->buffer, &main_->rowgroup_ctr,
  157370. (JDIMENSION) DCTSIZE);
  157371. /* If we don't have a full iMCU row buffered, return to application for
  157372. * more data. Note that preprocessor will always pad to fill the iMCU row
  157373. * at the bottom of the image.
  157374. */
  157375. if (main_->rowgroup_ctr != DCTSIZE)
  157376. return;
  157377. /* Send the completed row to the compressor */
  157378. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  157379. /* If compressor did not consume the whole row, then we must need to
  157380. * suspend processing and return to the application. In this situation
  157381. * we pretend we didn't yet consume the last input row; otherwise, if
  157382. * it happened to be the last row of the image, the application would
  157383. * think we were done.
  157384. */
  157385. if (! main_->suspended) {
  157386. (*in_row_ctr)--;
  157387. main_->suspended = TRUE;
  157388. }
  157389. return;
  157390. }
  157391. /* We did finish the row. Undo our little suspension hack if a previous
  157392. * call suspended; then mark the main buffer empty.
  157393. */
  157394. if (main_->suspended) {
  157395. (*in_row_ctr)++;
  157396. main_->suspended = FALSE;
  157397. }
  157398. main_->rowgroup_ctr = 0;
  157399. main_->cur_iMCU_row++;
  157400. }
  157401. }
  157402. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157403. /*
  157404. * Process some data.
  157405. * This routine handles all of the modes that use a full-size buffer.
  157406. */
  157407. METHODDEF(void)
  157408. process_data_buffer_main (j_compress_ptr cinfo,
  157409. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157410. JDIMENSION in_rows_avail)
  157411. {
  157412. my_main_ptr main = (my_main_ptr) cinfo->main;
  157413. int ci;
  157414. jpeg_component_info *compptr;
  157415. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  157416. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  157417. /* Realign the virtual buffers if at the start of an iMCU row. */
  157418. if (main->rowgroup_ctr == 0) {
  157419. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157420. ci++, compptr++) {
  157421. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  157422. ((j_common_ptr) cinfo, main->whole_image[ci],
  157423. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  157424. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  157425. }
  157426. /* In a read pass, pretend we just read some source data. */
  157427. if (! writing) {
  157428. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  157429. main->rowgroup_ctr = DCTSIZE;
  157430. }
  157431. }
  157432. /* If a write pass, read input data until the current iMCU row is full. */
  157433. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  157434. if (writing) {
  157435. (*cinfo->prep->pre_process_data) (cinfo,
  157436. input_buf, in_row_ctr, in_rows_avail,
  157437. main->buffer, &main->rowgroup_ctr,
  157438. (JDIMENSION) DCTSIZE);
  157439. /* Return to application if we need more data to fill the iMCU row. */
  157440. if (main->rowgroup_ctr < DCTSIZE)
  157441. return;
  157442. }
  157443. /* Emit data, unless this is a sink-only pass. */
  157444. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  157445. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  157446. /* If compressor did not consume the whole row, then we must need to
  157447. * suspend processing and return to the application. In this situation
  157448. * we pretend we didn't yet consume the last input row; otherwise, if
  157449. * it happened to be the last row of the image, the application would
  157450. * think we were done.
  157451. */
  157452. if (! main->suspended) {
  157453. (*in_row_ctr)--;
  157454. main->suspended = TRUE;
  157455. }
  157456. return;
  157457. }
  157458. /* We did finish the row. Undo our little suspension hack if a previous
  157459. * call suspended; then mark the main buffer empty.
  157460. */
  157461. if (main->suspended) {
  157462. (*in_row_ctr)++;
  157463. main->suspended = FALSE;
  157464. }
  157465. }
  157466. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  157467. main->rowgroup_ctr = 0;
  157468. main->cur_iMCU_row++;
  157469. }
  157470. }
  157471. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  157472. /*
  157473. * Initialize main buffer controller.
  157474. */
  157475. GLOBAL(void)
  157476. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157477. {
  157478. my_main_ptr main_;
  157479. int ci;
  157480. jpeg_component_info *compptr;
  157481. main_ = (my_main_ptr)
  157482. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157483. SIZEOF(my_main_controller));
  157484. cinfo->main = (struct jpeg_c_main_controller *) main_;
  157485. main_->pub.start_pass = start_pass_main;
  157486. /* We don't need to create a buffer in raw-data mode. */
  157487. if (cinfo->raw_data_in)
  157488. return;
  157489. /* Create the buffer. It holds downsampled data, so each component
  157490. * may be of a different size.
  157491. */
  157492. if (need_full_buffer) {
  157493. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157494. /* Allocate a full-image virtual array for each component */
  157495. /* Note we pad the bottom to a multiple of the iMCU height */
  157496. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157497. ci++, compptr++) {
  157498. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  157499. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157500. compptr->width_in_blocks * DCTSIZE,
  157501. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157502. (long) compptr->v_samp_factor) * DCTSIZE,
  157503. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  157504. }
  157505. #else
  157506. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157507. #endif
  157508. } else {
  157509. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157510. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  157511. #endif
  157512. /* Allocate a strip buffer for each component */
  157513. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157514. ci++, compptr++) {
  157515. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  157516. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157517. compptr->width_in_blocks * DCTSIZE,
  157518. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  157519. }
  157520. }
  157521. }
  157522. /********* End of inlined file: jcmainct.c *********/
  157523. /********* Start of inlined file: jcmarker.c *********/
  157524. #define JPEG_INTERNALS
  157525. /* Private state */
  157526. typedef struct {
  157527. struct jpeg_marker_writer pub; /* public fields */
  157528. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  157529. } my_marker_writer;
  157530. typedef my_marker_writer * my_marker_ptr;
  157531. /*
  157532. * Basic output routines.
  157533. *
  157534. * Note that we do not support suspension while writing a marker.
  157535. * Therefore, an application using suspension must ensure that there is
  157536. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  157537. * calling jpeg_start_compress, and enough space to write the trailing EOI
  157538. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  157539. * modes are not supported at all with suspension, so those two are the only
  157540. * points where markers will be written.
  157541. */
  157542. LOCAL(void)
  157543. emit_byte (j_compress_ptr cinfo, int val)
  157544. /* Emit a byte */
  157545. {
  157546. struct jpeg_destination_mgr * dest = cinfo->dest;
  157547. *(dest->next_output_byte)++ = (JOCTET) val;
  157548. if (--dest->free_in_buffer == 0) {
  157549. if (! (*dest->empty_output_buffer) (cinfo))
  157550. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157551. }
  157552. }
  157553. LOCAL(void)
  157554. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  157555. /* Emit a marker code */
  157556. {
  157557. emit_byte(cinfo, 0xFF);
  157558. emit_byte(cinfo, (int) mark);
  157559. }
  157560. LOCAL(void)
  157561. emit_2bytes (j_compress_ptr cinfo, int value)
  157562. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  157563. {
  157564. emit_byte(cinfo, (value >> 8) & 0xFF);
  157565. emit_byte(cinfo, value & 0xFF);
  157566. }
  157567. /*
  157568. * Routines to write specific marker types.
  157569. */
  157570. LOCAL(int)
  157571. emit_dqt (j_compress_ptr cinfo, int index)
  157572. /* Emit a DQT marker */
  157573. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  157574. {
  157575. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  157576. int prec;
  157577. int i;
  157578. if (qtbl == NULL)
  157579. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  157580. prec = 0;
  157581. for (i = 0; i < DCTSIZE2; i++) {
  157582. if (qtbl->quantval[i] > 255)
  157583. prec = 1;
  157584. }
  157585. if (! qtbl->sent_table) {
  157586. emit_marker(cinfo, M_DQT);
  157587. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  157588. emit_byte(cinfo, index + (prec<<4));
  157589. for (i = 0; i < DCTSIZE2; i++) {
  157590. /* The table entries must be emitted in zigzag order. */
  157591. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  157592. if (prec)
  157593. emit_byte(cinfo, (int) (qval >> 8));
  157594. emit_byte(cinfo, (int) (qval & 0xFF));
  157595. }
  157596. qtbl->sent_table = TRUE;
  157597. }
  157598. return prec;
  157599. }
  157600. LOCAL(void)
  157601. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  157602. /* Emit a DHT marker */
  157603. {
  157604. JHUFF_TBL * htbl;
  157605. int length, i;
  157606. if (is_ac) {
  157607. htbl = cinfo->ac_huff_tbl_ptrs[index];
  157608. index += 0x10; /* output index has AC bit set */
  157609. } else {
  157610. htbl = cinfo->dc_huff_tbl_ptrs[index];
  157611. }
  157612. if (htbl == NULL)
  157613. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  157614. if (! htbl->sent_table) {
  157615. emit_marker(cinfo, M_DHT);
  157616. length = 0;
  157617. for (i = 1; i <= 16; i++)
  157618. length += htbl->bits[i];
  157619. emit_2bytes(cinfo, length + 2 + 1 + 16);
  157620. emit_byte(cinfo, index);
  157621. for (i = 1; i <= 16; i++)
  157622. emit_byte(cinfo, htbl->bits[i]);
  157623. for (i = 0; i < length; i++)
  157624. emit_byte(cinfo, htbl->huffval[i]);
  157625. htbl->sent_table = TRUE;
  157626. }
  157627. }
  157628. LOCAL(void)
  157629. emit_dac (j_compress_ptr cinfo)
  157630. /* Emit a DAC marker */
  157631. /* Since the useful info is so small, we want to emit all the tables in */
  157632. /* one DAC marker. Therefore this routine does its own scan of the table. */
  157633. {
  157634. #ifdef C_ARITH_CODING_SUPPORTED
  157635. char dc_in_use[NUM_ARITH_TBLS];
  157636. char ac_in_use[NUM_ARITH_TBLS];
  157637. int length, i;
  157638. jpeg_component_info *compptr;
  157639. for (i = 0; i < NUM_ARITH_TBLS; i++)
  157640. dc_in_use[i] = ac_in_use[i] = 0;
  157641. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157642. compptr = cinfo->cur_comp_info[i];
  157643. dc_in_use[compptr->dc_tbl_no] = 1;
  157644. ac_in_use[compptr->ac_tbl_no] = 1;
  157645. }
  157646. length = 0;
  157647. for (i = 0; i < NUM_ARITH_TBLS; i++)
  157648. length += dc_in_use[i] + ac_in_use[i];
  157649. emit_marker(cinfo, M_DAC);
  157650. emit_2bytes(cinfo, length*2 + 2);
  157651. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  157652. if (dc_in_use[i]) {
  157653. emit_byte(cinfo, i);
  157654. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  157655. }
  157656. if (ac_in_use[i]) {
  157657. emit_byte(cinfo, i + 0x10);
  157658. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  157659. }
  157660. }
  157661. #endif /* C_ARITH_CODING_SUPPORTED */
  157662. }
  157663. LOCAL(void)
  157664. emit_dri (j_compress_ptr cinfo)
  157665. /* Emit a DRI marker */
  157666. {
  157667. emit_marker(cinfo, M_DRI);
  157668. emit_2bytes(cinfo, 4); /* fixed length */
  157669. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  157670. }
  157671. LOCAL(void)
  157672. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  157673. /* Emit a SOF marker */
  157674. {
  157675. int ci;
  157676. jpeg_component_info *compptr;
  157677. emit_marker(cinfo, code);
  157678. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  157679. /* Make sure image isn't bigger than SOF field can handle */
  157680. if ((long) cinfo->image_height > 65535L ||
  157681. (long) cinfo->image_width > 65535L)
  157682. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  157683. emit_byte(cinfo, cinfo->data_precision);
  157684. emit_2bytes(cinfo, (int) cinfo->image_height);
  157685. emit_2bytes(cinfo, (int) cinfo->image_width);
  157686. emit_byte(cinfo, cinfo->num_components);
  157687. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157688. ci++, compptr++) {
  157689. emit_byte(cinfo, compptr->component_id);
  157690. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  157691. emit_byte(cinfo, compptr->quant_tbl_no);
  157692. }
  157693. }
  157694. LOCAL(void)
  157695. emit_sos (j_compress_ptr cinfo)
  157696. /* Emit a SOS marker */
  157697. {
  157698. int i, td, ta;
  157699. jpeg_component_info *compptr;
  157700. emit_marker(cinfo, M_SOS);
  157701. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  157702. emit_byte(cinfo, cinfo->comps_in_scan);
  157703. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157704. compptr = cinfo->cur_comp_info[i];
  157705. emit_byte(cinfo, compptr->component_id);
  157706. td = compptr->dc_tbl_no;
  157707. ta = compptr->ac_tbl_no;
  157708. if (cinfo->progressive_mode) {
  157709. /* Progressive mode: only DC or only AC tables are used in one scan;
  157710. * furthermore, Huffman coding of DC refinement uses no table at all.
  157711. * We emit 0 for unused field(s); this is recommended by the P&M text
  157712. * but does not seem to be specified in the standard.
  157713. */
  157714. if (cinfo->Ss == 0) {
  157715. ta = 0; /* DC scan */
  157716. if (cinfo->Ah != 0 && !cinfo->arith_code)
  157717. td = 0; /* no DC table either */
  157718. } else {
  157719. td = 0; /* AC scan */
  157720. }
  157721. }
  157722. emit_byte(cinfo, (td << 4) + ta);
  157723. }
  157724. emit_byte(cinfo, cinfo->Ss);
  157725. emit_byte(cinfo, cinfo->Se);
  157726. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  157727. }
  157728. LOCAL(void)
  157729. emit_jfif_app0 (j_compress_ptr cinfo)
  157730. /* Emit a JFIF-compliant APP0 marker */
  157731. {
  157732. /*
  157733. * Length of APP0 block (2 bytes)
  157734. * Block ID (4 bytes - ASCII "JFIF")
  157735. * Zero byte (1 byte to terminate the ID string)
  157736. * Version Major, Minor (2 bytes - major first)
  157737. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  157738. * Xdpu (2 bytes - dots per unit horizontal)
  157739. * Ydpu (2 bytes - dots per unit vertical)
  157740. * Thumbnail X size (1 byte)
  157741. * Thumbnail Y size (1 byte)
  157742. */
  157743. emit_marker(cinfo, M_APP0);
  157744. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  157745. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  157746. emit_byte(cinfo, 0x46);
  157747. emit_byte(cinfo, 0x49);
  157748. emit_byte(cinfo, 0x46);
  157749. emit_byte(cinfo, 0);
  157750. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  157751. emit_byte(cinfo, cinfo->JFIF_minor_version);
  157752. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  157753. emit_2bytes(cinfo, (int) cinfo->X_density);
  157754. emit_2bytes(cinfo, (int) cinfo->Y_density);
  157755. emit_byte(cinfo, 0); /* No thumbnail image */
  157756. emit_byte(cinfo, 0);
  157757. }
  157758. LOCAL(void)
  157759. emit_adobe_app14 (j_compress_ptr cinfo)
  157760. /* Emit an Adobe APP14 marker */
  157761. {
  157762. /*
  157763. * Length of APP14 block (2 bytes)
  157764. * Block ID (5 bytes - ASCII "Adobe")
  157765. * Version Number (2 bytes - currently 100)
  157766. * Flags0 (2 bytes - currently 0)
  157767. * Flags1 (2 bytes - currently 0)
  157768. * Color transform (1 byte)
  157769. *
  157770. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  157771. * now in circulation seem to use Version = 100, so that's what we write.
  157772. *
  157773. * We write the color transform byte as 1 if the JPEG color space is
  157774. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  157775. * whether the encoder performed a transformation, which is pretty useless.
  157776. */
  157777. emit_marker(cinfo, M_APP14);
  157778. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  157779. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  157780. emit_byte(cinfo, 0x64);
  157781. emit_byte(cinfo, 0x6F);
  157782. emit_byte(cinfo, 0x62);
  157783. emit_byte(cinfo, 0x65);
  157784. emit_2bytes(cinfo, 100); /* Version */
  157785. emit_2bytes(cinfo, 0); /* Flags0 */
  157786. emit_2bytes(cinfo, 0); /* Flags1 */
  157787. switch (cinfo->jpeg_color_space) {
  157788. case JCS_YCbCr:
  157789. emit_byte(cinfo, 1); /* Color transform = 1 */
  157790. break;
  157791. case JCS_YCCK:
  157792. emit_byte(cinfo, 2); /* Color transform = 2 */
  157793. break;
  157794. default:
  157795. emit_byte(cinfo, 0); /* Color transform = 0 */
  157796. break;
  157797. }
  157798. }
  157799. /*
  157800. * These routines allow writing an arbitrary marker with parameters.
  157801. * The only intended use is to emit COM or APPn markers after calling
  157802. * write_file_header and before calling write_frame_header.
  157803. * Other uses are not guaranteed to produce desirable results.
  157804. * Counting the parameter bytes properly is the caller's responsibility.
  157805. */
  157806. METHODDEF(void)
  157807. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157808. /* Emit an arbitrary marker header */
  157809. {
  157810. if (datalen > (unsigned int) 65533) /* safety check */
  157811. ERREXIT(cinfo, JERR_BAD_LENGTH);
  157812. emit_marker(cinfo, (JPEG_MARKER) marker);
  157813. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  157814. }
  157815. METHODDEF(void)
  157816. write_marker_byte (j_compress_ptr cinfo, int val)
  157817. /* Emit one byte of marker parameters following write_marker_header */
  157818. {
  157819. emit_byte(cinfo, val);
  157820. }
  157821. /*
  157822. * Write datastream header.
  157823. * This consists of an SOI and optional APPn markers.
  157824. * We recommend use of the JFIF marker, but not the Adobe marker,
  157825. * when using YCbCr or grayscale data. The JFIF marker should NOT
  157826. * be used for any other JPEG colorspace. The Adobe marker is helpful
  157827. * to distinguish RGB, CMYK, and YCCK colorspaces.
  157828. * Note that an application can write additional header markers after
  157829. * jpeg_start_compress returns.
  157830. */
  157831. METHODDEF(void)
  157832. write_file_header (j_compress_ptr cinfo)
  157833. {
  157834. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  157835. emit_marker(cinfo, M_SOI); /* first the SOI */
  157836. /* SOI is defined to reset restart interval to 0 */
  157837. marker->last_restart_interval = 0;
  157838. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  157839. emit_jfif_app0(cinfo);
  157840. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  157841. emit_adobe_app14(cinfo);
  157842. }
  157843. /*
  157844. * Write frame header.
  157845. * This consists of DQT and SOFn markers.
  157846. * Note that we do not emit the SOF until we have emitted the DQT(s).
  157847. * This avoids compatibility problems with incorrect implementations that
  157848. * try to error-check the quant table numbers as soon as they see the SOF.
  157849. */
  157850. METHODDEF(void)
  157851. write_frame_header (j_compress_ptr cinfo)
  157852. {
  157853. int ci, prec;
  157854. boolean is_baseline;
  157855. jpeg_component_info *compptr;
  157856. /* Emit DQT for each quantization table.
  157857. * Note that emit_dqt() suppresses any duplicate tables.
  157858. */
  157859. prec = 0;
  157860. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157861. ci++, compptr++) {
  157862. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  157863. }
  157864. /* now prec is nonzero iff there are any 16-bit quant tables. */
  157865. /* Check for a non-baseline specification.
  157866. * Note we assume that Huffman table numbers won't be changed later.
  157867. */
  157868. if (cinfo->arith_code || cinfo->progressive_mode ||
  157869. cinfo->data_precision != 8) {
  157870. is_baseline = FALSE;
  157871. } else {
  157872. is_baseline = TRUE;
  157873. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157874. ci++, compptr++) {
  157875. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  157876. is_baseline = FALSE;
  157877. }
  157878. if (prec && is_baseline) {
  157879. is_baseline = FALSE;
  157880. /* If it's baseline except for quantizer size, warn the user */
  157881. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  157882. }
  157883. }
  157884. /* Emit the proper SOF marker */
  157885. if (cinfo->arith_code) {
  157886. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  157887. } else {
  157888. if (cinfo->progressive_mode)
  157889. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  157890. else if (is_baseline)
  157891. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  157892. else
  157893. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  157894. }
  157895. }
  157896. /*
  157897. * Write scan header.
  157898. * This consists of DHT or DAC markers, optional DRI, and SOS.
  157899. * Compressed data will be written following the SOS.
  157900. */
  157901. METHODDEF(void)
  157902. write_scan_header (j_compress_ptr cinfo)
  157903. {
  157904. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  157905. int i;
  157906. jpeg_component_info *compptr;
  157907. if (cinfo->arith_code) {
  157908. /* Emit arith conditioning info. We may have some duplication
  157909. * if the file has multiple scans, but it's so small it's hardly
  157910. * worth worrying about.
  157911. */
  157912. emit_dac(cinfo);
  157913. } else {
  157914. /* Emit Huffman tables.
  157915. * Note that emit_dht() suppresses any duplicate tables.
  157916. */
  157917. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157918. compptr = cinfo->cur_comp_info[i];
  157919. if (cinfo->progressive_mode) {
  157920. /* Progressive mode: only DC or only AC tables are used in one scan */
  157921. if (cinfo->Ss == 0) {
  157922. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  157923. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  157924. } else {
  157925. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  157926. }
  157927. } else {
  157928. /* Sequential mode: need both DC and AC tables */
  157929. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  157930. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  157931. }
  157932. }
  157933. }
  157934. /* Emit DRI if required --- note that DRI value could change for each scan.
  157935. * We avoid wasting space with unnecessary DRIs, however.
  157936. */
  157937. if (cinfo->restart_interval != marker->last_restart_interval) {
  157938. emit_dri(cinfo);
  157939. marker->last_restart_interval = cinfo->restart_interval;
  157940. }
  157941. emit_sos(cinfo);
  157942. }
  157943. /*
  157944. * Write datastream trailer.
  157945. */
  157946. METHODDEF(void)
  157947. write_file_trailer (j_compress_ptr cinfo)
  157948. {
  157949. emit_marker(cinfo, M_EOI);
  157950. }
  157951. /*
  157952. * Write an abbreviated table-specification datastream.
  157953. * This consists of SOI, DQT and DHT tables, and EOI.
  157954. * Any table that is defined and not marked sent_table = TRUE will be
  157955. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  157956. */
  157957. METHODDEF(void)
  157958. write_tables_only (j_compress_ptr cinfo)
  157959. {
  157960. int i;
  157961. emit_marker(cinfo, M_SOI);
  157962. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157963. if (cinfo->quant_tbl_ptrs[i] != NULL)
  157964. (void) emit_dqt(cinfo, i);
  157965. }
  157966. if (! cinfo->arith_code) {
  157967. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157968. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  157969. emit_dht(cinfo, i, FALSE);
  157970. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  157971. emit_dht(cinfo, i, TRUE);
  157972. }
  157973. }
  157974. emit_marker(cinfo, M_EOI);
  157975. }
  157976. /*
  157977. * Initialize the marker writer module.
  157978. */
  157979. GLOBAL(void)
  157980. jinit_marker_writer (j_compress_ptr cinfo)
  157981. {
  157982. my_marker_ptr marker;
  157983. /* Create the subobject */
  157984. marker = (my_marker_ptr)
  157985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157986. SIZEOF(my_marker_writer));
  157987. cinfo->marker = (struct jpeg_marker_writer *) marker;
  157988. /* Initialize method pointers */
  157989. marker->pub.write_file_header = write_file_header;
  157990. marker->pub.write_frame_header = write_frame_header;
  157991. marker->pub.write_scan_header = write_scan_header;
  157992. marker->pub.write_file_trailer = write_file_trailer;
  157993. marker->pub.write_tables_only = write_tables_only;
  157994. marker->pub.write_marker_header = write_marker_header;
  157995. marker->pub.write_marker_byte = write_marker_byte;
  157996. /* Initialize private state */
  157997. marker->last_restart_interval = 0;
  157998. }
  157999. /********* End of inlined file: jcmarker.c *********/
  158000. /********* Start of inlined file: jcmaster.c *********/
  158001. #define JPEG_INTERNALS
  158002. /* Private state */
  158003. typedef enum {
  158004. main_pass, /* input data, also do first output step */
  158005. huff_opt_pass, /* Huffman code optimization pass */
  158006. output_pass /* data output pass */
  158007. } c_pass_type;
  158008. typedef struct {
  158009. struct jpeg_comp_master pub; /* public fields */
  158010. c_pass_type pass_type; /* the type of the current pass */
  158011. int pass_number; /* # of passes completed */
  158012. int total_passes; /* total # of passes needed */
  158013. int scan_number; /* current index in scan_info[] */
  158014. } my_comp_master;
  158015. typedef my_comp_master * my_master_ptr;
  158016. /*
  158017. * Support routines that do various essential calculations.
  158018. */
  158019. LOCAL(void)
  158020. initial_setup (j_compress_ptr cinfo)
  158021. /* Do computations that are needed before master selection phase */
  158022. {
  158023. int ci;
  158024. jpeg_component_info *compptr;
  158025. long samplesperrow;
  158026. JDIMENSION jd_samplesperrow;
  158027. /* Sanity check on image dimensions */
  158028. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  158029. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  158030. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  158031. /* Make sure image isn't bigger than I can handle */
  158032. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  158033. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  158034. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  158035. /* Width of an input scanline must be representable as JDIMENSION. */
  158036. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  158037. jd_samplesperrow = (JDIMENSION) samplesperrow;
  158038. if ((long) jd_samplesperrow != samplesperrow)
  158039. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  158040. /* For now, precision must match compiled-in value... */
  158041. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  158042. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  158043. /* Check that number of components won't exceed internal array sizes */
  158044. if (cinfo->num_components > MAX_COMPONENTS)
  158045. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158046. MAX_COMPONENTS);
  158047. /* Compute maximum sampling factors; check factor validity */
  158048. cinfo->max_h_samp_factor = 1;
  158049. cinfo->max_v_samp_factor = 1;
  158050. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158051. ci++, compptr++) {
  158052. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  158053. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  158054. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  158055. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  158056. compptr->h_samp_factor);
  158057. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  158058. compptr->v_samp_factor);
  158059. }
  158060. /* Compute dimensions of components */
  158061. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158062. ci++, compptr++) {
  158063. /* Fill in the correct component_index value; don't rely on application */
  158064. compptr->component_index = ci;
  158065. /* For compression, we never do DCT scaling. */
  158066. compptr->DCT_scaled_size = DCTSIZE;
  158067. /* Size in DCT blocks */
  158068. compptr->width_in_blocks = (JDIMENSION)
  158069. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158070. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  158071. compptr->height_in_blocks = (JDIMENSION)
  158072. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158073. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  158074. /* Size in samples */
  158075. compptr->downsampled_width = (JDIMENSION)
  158076. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158077. (long) cinfo->max_h_samp_factor);
  158078. compptr->downsampled_height = (JDIMENSION)
  158079. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158080. (long) cinfo->max_v_samp_factor);
  158081. /* Mark component needed (this flag isn't actually used for compression) */
  158082. compptr->component_needed = TRUE;
  158083. }
  158084. /* Compute number of fully interleaved MCU rows (number of times that
  158085. * main controller will call coefficient controller).
  158086. */
  158087. cinfo->total_iMCU_rows = (JDIMENSION)
  158088. jdiv_round_up((long) cinfo->image_height,
  158089. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158090. }
  158091. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158092. LOCAL(void)
  158093. validate_script (j_compress_ptr cinfo)
  158094. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  158095. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  158096. */
  158097. {
  158098. const jpeg_scan_info * scanptr;
  158099. int scanno, ncomps, ci, coefi, thisi;
  158100. int Ss, Se, Ah, Al;
  158101. boolean component_sent[MAX_COMPONENTS];
  158102. #ifdef C_PROGRESSIVE_SUPPORTED
  158103. int * last_bitpos_ptr;
  158104. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  158105. /* -1 until that coefficient has been seen; then last Al for it */
  158106. #endif
  158107. if (cinfo->num_scans <= 0)
  158108. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  158109. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  158110. * for progressive JPEG, no scan can have this.
  158111. */
  158112. scanptr = cinfo->scan_info;
  158113. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  158114. #ifdef C_PROGRESSIVE_SUPPORTED
  158115. cinfo->progressive_mode = TRUE;
  158116. last_bitpos_ptr = & last_bitpos[0][0];
  158117. for (ci = 0; ci < cinfo->num_components; ci++)
  158118. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  158119. *last_bitpos_ptr++ = -1;
  158120. #else
  158121. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158122. #endif
  158123. } else {
  158124. cinfo->progressive_mode = FALSE;
  158125. for (ci = 0; ci < cinfo->num_components; ci++)
  158126. component_sent[ci] = FALSE;
  158127. }
  158128. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  158129. /* Validate component indexes */
  158130. ncomps = scanptr->comps_in_scan;
  158131. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  158132. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  158133. for (ci = 0; ci < ncomps; ci++) {
  158134. thisi = scanptr->component_index[ci];
  158135. if (thisi < 0 || thisi >= cinfo->num_components)
  158136. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158137. /* Components must appear in SOF order within each scan */
  158138. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  158139. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158140. }
  158141. /* Validate progression parameters */
  158142. Ss = scanptr->Ss;
  158143. Se = scanptr->Se;
  158144. Ah = scanptr->Ah;
  158145. Al = scanptr->Al;
  158146. if (cinfo->progressive_mode) {
  158147. #ifdef C_PROGRESSIVE_SUPPORTED
  158148. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  158149. * seems wrong: the upper bound ought to depend on data precision.
  158150. * Perhaps they really meant 0..N+1 for N-bit precision.
  158151. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  158152. * out-of-range reconstructed DC values during the first DC scan,
  158153. * which might cause problems for some decoders.
  158154. */
  158155. #if BITS_IN_JSAMPLE == 8
  158156. #define MAX_AH_AL 10
  158157. #else
  158158. #define MAX_AH_AL 13
  158159. #endif
  158160. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  158161. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  158162. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158163. if (Ss == 0) {
  158164. if (Se != 0) /* DC and AC together not OK */
  158165. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158166. } else {
  158167. if (ncomps != 1) /* AC scans must be for only one component */
  158168. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158169. }
  158170. for (ci = 0; ci < ncomps; ci++) {
  158171. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  158172. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  158173. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158174. for (coefi = Ss; coefi <= Se; coefi++) {
  158175. if (last_bitpos_ptr[coefi] < 0) {
  158176. /* first scan of this coefficient */
  158177. if (Ah != 0)
  158178. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158179. } else {
  158180. /* not first scan */
  158181. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  158182. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158183. }
  158184. last_bitpos_ptr[coefi] = Al;
  158185. }
  158186. }
  158187. #endif
  158188. } else {
  158189. /* For sequential JPEG, all progression parameters must be these: */
  158190. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  158191. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158192. /* Make sure components are not sent twice */
  158193. for (ci = 0; ci < ncomps; ci++) {
  158194. thisi = scanptr->component_index[ci];
  158195. if (component_sent[thisi])
  158196. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158197. component_sent[thisi] = TRUE;
  158198. }
  158199. }
  158200. }
  158201. /* Now verify that everything got sent. */
  158202. if (cinfo->progressive_mode) {
  158203. #ifdef C_PROGRESSIVE_SUPPORTED
  158204. /* For progressive mode, we only check that at least some DC data
  158205. * got sent for each component; the spec does not require that all bits
  158206. * of all coefficients be transmitted. Would it be wiser to enforce
  158207. * transmission of all coefficient bits??
  158208. */
  158209. for (ci = 0; ci < cinfo->num_components; ci++) {
  158210. if (last_bitpos[ci][0] < 0)
  158211. ERREXIT(cinfo, JERR_MISSING_DATA);
  158212. }
  158213. #endif
  158214. } else {
  158215. for (ci = 0; ci < cinfo->num_components; ci++) {
  158216. if (! component_sent[ci])
  158217. ERREXIT(cinfo, JERR_MISSING_DATA);
  158218. }
  158219. }
  158220. }
  158221. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  158222. LOCAL(void)
  158223. select_scan_parameters (j_compress_ptr cinfo)
  158224. /* Set up the scan parameters for the current scan */
  158225. {
  158226. int ci;
  158227. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158228. if (cinfo->scan_info != NULL) {
  158229. /* Prepare for current scan --- the script is already validated */
  158230. my_master_ptr master = (my_master_ptr) cinfo->master;
  158231. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  158232. cinfo->comps_in_scan = scanptr->comps_in_scan;
  158233. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  158234. cinfo->cur_comp_info[ci] =
  158235. &cinfo->comp_info[scanptr->component_index[ci]];
  158236. }
  158237. cinfo->Ss = scanptr->Ss;
  158238. cinfo->Se = scanptr->Se;
  158239. cinfo->Ah = scanptr->Ah;
  158240. cinfo->Al = scanptr->Al;
  158241. }
  158242. else
  158243. #endif
  158244. {
  158245. /* Prepare for single sequential-JPEG scan containing all components */
  158246. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  158247. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158248. MAX_COMPS_IN_SCAN);
  158249. cinfo->comps_in_scan = cinfo->num_components;
  158250. for (ci = 0; ci < cinfo->num_components; ci++) {
  158251. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  158252. }
  158253. cinfo->Ss = 0;
  158254. cinfo->Se = DCTSIZE2-1;
  158255. cinfo->Ah = 0;
  158256. cinfo->Al = 0;
  158257. }
  158258. }
  158259. LOCAL(void)
  158260. per_scan_setup (j_compress_ptr cinfo)
  158261. /* Do computations that are needed before processing a JPEG scan */
  158262. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  158263. {
  158264. int ci, mcublks, tmp;
  158265. jpeg_component_info *compptr;
  158266. if (cinfo->comps_in_scan == 1) {
  158267. /* Noninterleaved (single-component) scan */
  158268. compptr = cinfo->cur_comp_info[0];
  158269. /* Overall image size in MCUs */
  158270. cinfo->MCUs_per_row = compptr->width_in_blocks;
  158271. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  158272. /* For noninterleaved scan, always one block per MCU */
  158273. compptr->MCU_width = 1;
  158274. compptr->MCU_height = 1;
  158275. compptr->MCU_blocks = 1;
  158276. compptr->MCU_sample_width = DCTSIZE;
  158277. compptr->last_col_width = 1;
  158278. /* For noninterleaved scans, it is convenient to define last_row_height
  158279. * as the number of block rows present in the last iMCU row.
  158280. */
  158281. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  158282. if (tmp == 0) tmp = compptr->v_samp_factor;
  158283. compptr->last_row_height = tmp;
  158284. /* Prepare array describing MCU composition */
  158285. cinfo->blocks_in_MCU = 1;
  158286. cinfo->MCU_membership[0] = 0;
  158287. } else {
  158288. /* Interleaved (multi-component) scan */
  158289. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  158290. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  158291. MAX_COMPS_IN_SCAN);
  158292. /* Overall image size in MCUs */
  158293. cinfo->MCUs_per_row = (JDIMENSION)
  158294. jdiv_round_up((long) cinfo->image_width,
  158295. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  158296. cinfo->MCU_rows_in_scan = (JDIMENSION)
  158297. jdiv_round_up((long) cinfo->image_height,
  158298. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158299. cinfo->blocks_in_MCU = 0;
  158300. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158301. compptr = cinfo->cur_comp_info[ci];
  158302. /* Sampling factors give # of blocks of component in each MCU */
  158303. compptr->MCU_width = compptr->h_samp_factor;
  158304. compptr->MCU_height = compptr->v_samp_factor;
  158305. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  158306. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  158307. /* Figure number of non-dummy blocks in last MCU column & row */
  158308. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  158309. if (tmp == 0) tmp = compptr->MCU_width;
  158310. compptr->last_col_width = tmp;
  158311. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  158312. if (tmp == 0) tmp = compptr->MCU_height;
  158313. compptr->last_row_height = tmp;
  158314. /* Prepare array describing MCU composition */
  158315. mcublks = compptr->MCU_blocks;
  158316. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  158317. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  158318. while (mcublks-- > 0) {
  158319. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  158320. }
  158321. }
  158322. }
  158323. /* Convert restart specified in rows to actual MCU count. */
  158324. /* Note that count must fit in 16 bits, so we provide limiting. */
  158325. if (cinfo->restart_in_rows > 0) {
  158326. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  158327. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  158328. }
  158329. }
  158330. /*
  158331. * Per-pass setup.
  158332. * This is called at the beginning of each pass. We determine which modules
  158333. * will be active during this pass and give them appropriate start_pass calls.
  158334. * We also set is_last_pass to indicate whether any more passes will be
  158335. * required.
  158336. */
  158337. METHODDEF(void)
  158338. prepare_for_pass (j_compress_ptr cinfo)
  158339. {
  158340. my_master_ptr master = (my_master_ptr) cinfo->master;
  158341. switch (master->pass_type) {
  158342. case main_pass:
  158343. /* Initial pass: will collect input data, and do either Huffman
  158344. * optimization or data output for the first scan.
  158345. */
  158346. select_scan_parameters(cinfo);
  158347. per_scan_setup(cinfo);
  158348. if (! cinfo->raw_data_in) {
  158349. (*cinfo->cconvert->start_pass) (cinfo);
  158350. (*cinfo->downsample->start_pass) (cinfo);
  158351. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  158352. }
  158353. (*cinfo->fdct->start_pass) (cinfo);
  158354. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  158355. (*cinfo->coef->start_pass) (cinfo,
  158356. (master->total_passes > 1 ?
  158357. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  158358. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  158359. if (cinfo->optimize_coding) {
  158360. /* No immediate data output; postpone writing frame/scan headers */
  158361. master->pub.call_pass_startup = FALSE;
  158362. } else {
  158363. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  158364. master->pub.call_pass_startup = TRUE;
  158365. }
  158366. break;
  158367. #ifdef ENTROPY_OPT_SUPPORTED
  158368. case huff_opt_pass:
  158369. /* Do Huffman optimization for a scan after the first one. */
  158370. select_scan_parameters(cinfo);
  158371. per_scan_setup(cinfo);
  158372. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  158373. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  158374. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  158375. master->pub.call_pass_startup = FALSE;
  158376. break;
  158377. }
  158378. /* Special case: Huffman DC refinement scans need no Huffman table
  158379. * and therefore we can skip the optimization pass for them.
  158380. */
  158381. master->pass_type = output_pass;
  158382. master->pass_number++;
  158383. /*FALLTHROUGH*/
  158384. #endif
  158385. case output_pass:
  158386. /* Do a data-output pass. */
  158387. /* We need not repeat per-scan setup if prior optimization pass did it. */
  158388. if (! cinfo->optimize_coding) {
  158389. select_scan_parameters(cinfo);
  158390. per_scan_setup(cinfo);
  158391. }
  158392. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  158393. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  158394. /* We emit frame/scan headers now */
  158395. if (master->scan_number == 0)
  158396. (*cinfo->marker->write_frame_header) (cinfo);
  158397. (*cinfo->marker->write_scan_header) (cinfo);
  158398. master->pub.call_pass_startup = FALSE;
  158399. break;
  158400. default:
  158401. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158402. }
  158403. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  158404. /* Set up progress monitor's pass info if present */
  158405. if (cinfo->progress != NULL) {
  158406. cinfo->progress->completed_passes = master->pass_number;
  158407. cinfo->progress->total_passes = master->total_passes;
  158408. }
  158409. }
  158410. /*
  158411. * Special start-of-pass hook.
  158412. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  158413. * In single-pass processing, we need this hook because we don't want to
  158414. * write frame/scan headers during jpeg_start_compress; we want to let the
  158415. * application write COM markers etc. between jpeg_start_compress and the
  158416. * jpeg_write_scanlines loop.
  158417. * In multi-pass processing, this routine is not used.
  158418. */
  158419. METHODDEF(void)
  158420. pass_startup (j_compress_ptr cinfo)
  158421. {
  158422. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  158423. (*cinfo->marker->write_frame_header) (cinfo);
  158424. (*cinfo->marker->write_scan_header) (cinfo);
  158425. }
  158426. /*
  158427. * Finish up at end of pass.
  158428. */
  158429. METHODDEF(void)
  158430. finish_pass_master (j_compress_ptr cinfo)
  158431. {
  158432. my_master_ptr master = (my_master_ptr) cinfo->master;
  158433. /* The entropy coder always needs an end-of-pass call,
  158434. * either to analyze statistics or to flush its output buffer.
  158435. */
  158436. (*cinfo->entropy->finish_pass) (cinfo);
  158437. /* Update state for next pass */
  158438. switch (master->pass_type) {
  158439. case main_pass:
  158440. /* next pass is either output of scan 0 (after optimization)
  158441. * or output of scan 1 (if no optimization).
  158442. */
  158443. master->pass_type = output_pass;
  158444. if (! cinfo->optimize_coding)
  158445. master->scan_number++;
  158446. break;
  158447. case huff_opt_pass:
  158448. /* next pass is always output of current scan */
  158449. master->pass_type = output_pass;
  158450. break;
  158451. case output_pass:
  158452. /* next pass is either optimization or output of next scan */
  158453. if (cinfo->optimize_coding)
  158454. master->pass_type = huff_opt_pass;
  158455. master->scan_number++;
  158456. break;
  158457. }
  158458. master->pass_number++;
  158459. }
  158460. /*
  158461. * Initialize master compression control.
  158462. */
  158463. GLOBAL(void)
  158464. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  158465. {
  158466. my_master_ptr master;
  158467. master = (my_master_ptr)
  158468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158469. SIZEOF(my_comp_master));
  158470. cinfo->master = (struct jpeg_comp_master *) master;
  158471. master->pub.prepare_for_pass = prepare_for_pass;
  158472. master->pub.pass_startup = pass_startup;
  158473. master->pub.finish_pass = finish_pass_master;
  158474. master->pub.is_last_pass = FALSE;
  158475. /* Validate parameters, determine derived values */
  158476. initial_setup(cinfo);
  158477. if (cinfo->scan_info != NULL) {
  158478. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158479. validate_script(cinfo);
  158480. #else
  158481. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158482. #endif
  158483. } else {
  158484. cinfo->progressive_mode = FALSE;
  158485. cinfo->num_scans = 1;
  158486. }
  158487. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  158488. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  158489. /* Initialize my private state */
  158490. if (transcode_only) {
  158491. /* no main pass in transcoding */
  158492. if (cinfo->optimize_coding)
  158493. master->pass_type = huff_opt_pass;
  158494. else
  158495. master->pass_type = output_pass;
  158496. } else {
  158497. /* for normal compression, first pass is always this type: */
  158498. master->pass_type = main_pass;
  158499. }
  158500. master->scan_number = 0;
  158501. master->pass_number = 0;
  158502. if (cinfo->optimize_coding)
  158503. master->total_passes = cinfo->num_scans * 2;
  158504. else
  158505. master->total_passes = cinfo->num_scans;
  158506. }
  158507. /********* End of inlined file: jcmaster.c *********/
  158508. /********* Start of inlined file: jcomapi.c *********/
  158509. #define JPEG_INTERNALS
  158510. /*
  158511. * Abort processing of a JPEG compression or decompression operation,
  158512. * but don't destroy the object itself.
  158513. *
  158514. * For this, we merely clean up all the nonpermanent memory pools.
  158515. * Note that temp files (virtual arrays) are not allowed to belong to
  158516. * the permanent pool, so we will be able to close all temp files here.
  158517. * Closing a data source or destination, if necessary, is the application's
  158518. * responsibility.
  158519. */
  158520. GLOBAL(void)
  158521. jpeg_abort (j_common_ptr cinfo)
  158522. {
  158523. int pool;
  158524. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  158525. if (cinfo->mem == NULL)
  158526. return;
  158527. /* Releasing pools in reverse order might help avoid fragmentation
  158528. * with some (brain-damaged) malloc libraries.
  158529. */
  158530. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  158531. (*cinfo->mem->free_pool) (cinfo, pool);
  158532. }
  158533. /* Reset overall state for possible reuse of object */
  158534. if (cinfo->is_decompressor) {
  158535. cinfo->global_state = DSTATE_START;
  158536. /* Try to keep application from accessing now-deleted marker list.
  158537. * A bit kludgy to do it here, but this is the most central place.
  158538. */
  158539. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  158540. } else {
  158541. cinfo->global_state = CSTATE_START;
  158542. }
  158543. }
  158544. /*
  158545. * Destruction of a JPEG object.
  158546. *
  158547. * Everything gets deallocated except the master jpeg_compress_struct itself
  158548. * and the error manager struct. Both of these are supplied by the application
  158549. * and must be freed, if necessary, by the application. (Often they are on
  158550. * the stack and so don't need to be freed anyway.)
  158551. * Closing a data source or destination, if necessary, is the application's
  158552. * responsibility.
  158553. */
  158554. GLOBAL(void)
  158555. jpeg_destroy (j_common_ptr cinfo)
  158556. {
  158557. /* We need only tell the memory manager to release everything. */
  158558. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  158559. if (cinfo->mem != NULL)
  158560. (*cinfo->mem->self_destruct) (cinfo);
  158561. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  158562. cinfo->global_state = 0; /* mark it destroyed */
  158563. }
  158564. /*
  158565. * Convenience routines for allocating quantization and Huffman tables.
  158566. * (Would jutils.c be a more reasonable place to put these?)
  158567. */
  158568. GLOBAL(JQUANT_TBL *)
  158569. jpeg_alloc_quant_table (j_common_ptr cinfo)
  158570. {
  158571. JQUANT_TBL *tbl;
  158572. tbl = (JQUANT_TBL *)
  158573. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  158574. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  158575. return tbl;
  158576. }
  158577. GLOBAL(JHUFF_TBL *)
  158578. jpeg_alloc_huff_table (j_common_ptr cinfo)
  158579. {
  158580. JHUFF_TBL *tbl;
  158581. tbl = (JHUFF_TBL *)
  158582. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  158583. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  158584. return tbl;
  158585. }
  158586. /********* End of inlined file: jcomapi.c *********/
  158587. /********* Start of inlined file: jcparam.c *********/
  158588. #define JPEG_INTERNALS
  158589. /*
  158590. * Quantization table setup routines
  158591. */
  158592. GLOBAL(void)
  158593. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  158594. const unsigned int *basic_table,
  158595. int scale_factor, boolean force_baseline)
  158596. /* Define a quantization table equal to the basic_table times
  158597. * a scale factor (given as a percentage).
  158598. * If force_baseline is TRUE, the computed quantization table entries
  158599. * are limited to 1..255 for JPEG baseline compatibility.
  158600. */
  158601. {
  158602. JQUANT_TBL ** qtblptr;
  158603. int i;
  158604. long temp;
  158605. /* Safety check to ensure start_compress not called yet. */
  158606. if (cinfo->global_state != CSTATE_START)
  158607. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158608. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  158609. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  158610. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  158611. if (*qtblptr == NULL)
  158612. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  158613. for (i = 0; i < DCTSIZE2; i++) {
  158614. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  158615. /* limit the values to the valid range */
  158616. if (temp <= 0L) temp = 1L;
  158617. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  158618. if (force_baseline && temp > 255L)
  158619. temp = 255L; /* limit to baseline range if requested */
  158620. (*qtblptr)->quantval[i] = (UINT16) temp;
  158621. }
  158622. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  158623. (*qtblptr)->sent_table = FALSE;
  158624. }
  158625. GLOBAL(void)
  158626. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  158627. boolean force_baseline)
  158628. /* Set or change the 'quality' (quantization) setting, using default tables
  158629. * and a straight percentage-scaling quality scale. In most cases it's better
  158630. * to use jpeg_set_quality (below); this entry point is provided for
  158631. * applications that insist on a linear percentage scaling.
  158632. */
  158633. {
  158634. /* These are the sample quantization tables given in JPEG spec section K.1.
  158635. * The spec says that the values given produce "good" quality, and
  158636. * when divided by 2, "very good" quality.
  158637. */
  158638. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  158639. 16, 11, 10, 16, 24, 40, 51, 61,
  158640. 12, 12, 14, 19, 26, 58, 60, 55,
  158641. 14, 13, 16, 24, 40, 57, 69, 56,
  158642. 14, 17, 22, 29, 51, 87, 80, 62,
  158643. 18, 22, 37, 56, 68, 109, 103, 77,
  158644. 24, 35, 55, 64, 81, 104, 113, 92,
  158645. 49, 64, 78, 87, 103, 121, 120, 101,
  158646. 72, 92, 95, 98, 112, 100, 103, 99
  158647. };
  158648. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  158649. 17, 18, 24, 47, 99, 99, 99, 99,
  158650. 18, 21, 26, 66, 99, 99, 99, 99,
  158651. 24, 26, 56, 99, 99, 99, 99, 99,
  158652. 47, 66, 99, 99, 99, 99, 99, 99,
  158653. 99, 99, 99, 99, 99, 99, 99, 99,
  158654. 99, 99, 99, 99, 99, 99, 99, 99,
  158655. 99, 99, 99, 99, 99, 99, 99, 99,
  158656. 99, 99, 99, 99, 99, 99, 99, 99
  158657. };
  158658. /* Set up two quantization tables using the specified scaling */
  158659. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  158660. scale_factor, force_baseline);
  158661. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  158662. scale_factor, force_baseline);
  158663. }
  158664. GLOBAL(int)
  158665. jpeg_quality_scaling (int quality)
  158666. /* Convert a user-specified quality rating to a percentage scaling factor
  158667. * for an underlying quantization table, using our recommended scaling curve.
  158668. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  158669. */
  158670. {
  158671. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  158672. if (quality <= 0) quality = 1;
  158673. if (quality > 100) quality = 100;
  158674. /* The basic table is used as-is (scaling 100) for a quality of 50.
  158675. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  158676. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  158677. * to make all the table entries 1 (hence, minimum quantization loss).
  158678. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  158679. */
  158680. if (quality < 50)
  158681. quality = 5000 / quality;
  158682. else
  158683. quality = 200 - quality*2;
  158684. return quality;
  158685. }
  158686. GLOBAL(void)
  158687. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  158688. /* Set or change the 'quality' (quantization) setting, using default tables.
  158689. * This is the standard quality-adjusting entry point for typical user
  158690. * interfaces; only those who want detailed control over quantization tables
  158691. * would use the preceding three routines directly.
  158692. */
  158693. {
  158694. /* Convert user 0-100 rating to percentage scaling */
  158695. quality = jpeg_quality_scaling(quality);
  158696. /* Set up standard quality tables */
  158697. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  158698. }
  158699. /*
  158700. * Huffman table setup routines
  158701. */
  158702. LOCAL(void)
  158703. add_huff_table (j_compress_ptr cinfo,
  158704. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  158705. /* Define a Huffman table */
  158706. {
  158707. int nsymbols, len;
  158708. if (*htblptr == NULL)
  158709. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158710. /* Copy the number-of-symbols-of-each-code-length counts */
  158711. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  158712. /* Validate the counts. We do this here mainly so we can copy the right
  158713. * number of symbols from the val[] array, without risking marching off
  158714. * the end of memory. jchuff.c will do a more thorough test later.
  158715. */
  158716. nsymbols = 0;
  158717. for (len = 1; len <= 16; len++)
  158718. nsymbols += bits[len];
  158719. if (nsymbols < 1 || nsymbols > 256)
  158720. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158721. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  158722. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  158723. (*htblptr)->sent_table = FALSE;
  158724. }
  158725. LOCAL(void)
  158726. std_huff_tables (j_compress_ptr cinfo)
  158727. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  158728. /* IMPORTANT: these are only valid for 8-bit data precision! */
  158729. {
  158730. static const UINT8 bits_dc_luminance[17] =
  158731. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  158732. static const UINT8 val_dc_luminance[] =
  158733. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  158734. static const UINT8 bits_dc_chrominance[17] =
  158735. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  158736. static const UINT8 val_dc_chrominance[] =
  158737. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  158738. static const UINT8 bits_ac_luminance[17] =
  158739. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  158740. static const UINT8 val_ac_luminance[] =
  158741. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  158742. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  158743. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  158744. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  158745. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  158746. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  158747. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  158748. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  158749. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  158750. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  158751. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  158752. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  158753. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  158754. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  158755. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  158756. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  158757. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  158758. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  158759. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  158760. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  158761. 0xf9, 0xfa };
  158762. static const UINT8 bits_ac_chrominance[17] =
  158763. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  158764. static const UINT8 val_ac_chrominance[] =
  158765. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  158766. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  158767. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  158768. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  158769. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  158770. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  158771. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  158772. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  158773. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  158774. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  158775. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  158776. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  158777. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  158778. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  158779. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  158780. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  158781. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  158782. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  158783. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  158784. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  158785. 0xf9, 0xfa };
  158786. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  158787. bits_dc_luminance, val_dc_luminance);
  158788. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  158789. bits_ac_luminance, val_ac_luminance);
  158790. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  158791. bits_dc_chrominance, val_dc_chrominance);
  158792. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  158793. bits_ac_chrominance, val_ac_chrominance);
  158794. }
  158795. /*
  158796. * Default parameter setup for compression.
  158797. *
  158798. * Applications that don't choose to use this routine must do their
  158799. * own setup of all these parameters. Alternately, you can call this
  158800. * to establish defaults and then alter parameters selectively. This
  158801. * is the recommended approach since, if we add any new parameters,
  158802. * your code will still work (they'll be set to reasonable defaults).
  158803. */
  158804. GLOBAL(void)
  158805. jpeg_set_defaults (j_compress_ptr cinfo)
  158806. {
  158807. int i;
  158808. /* Safety check to ensure start_compress not called yet. */
  158809. if (cinfo->global_state != CSTATE_START)
  158810. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158811. /* Allocate comp_info array large enough for maximum component count.
  158812. * Array is made permanent in case application wants to compress
  158813. * multiple images at same param settings.
  158814. */
  158815. if (cinfo->comp_info == NULL)
  158816. cinfo->comp_info = (jpeg_component_info *)
  158817. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  158818. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  158819. /* Initialize everything not dependent on the color space */
  158820. cinfo->data_precision = BITS_IN_JSAMPLE;
  158821. /* Set up two quantization tables using default quality of 75 */
  158822. jpeg_set_quality(cinfo, 75, TRUE);
  158823. /* Set up two Huffman tables */
  158824. std_huff_tables(cinfo);
  158825. /* Initialize default arithmetic coding conditioning */
  158826. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  158827. cinfo->arith_dc_L[i] = 0;
  158828. cinfo->arith_dc_U[i] = 1;
  158829. cinfo->arith_ac_K[i] = 5;
  158830. }
  158831. /* Default is no multiple-scan output */
  158832. cinfo->scan_info = NULL;
  158833. cinfo->num_scans = 0;
  158834. /* Expect normal source image, not raw downsampled data */
  158835. cinfo->raw_data_in = FALSE;
  158836. /* Use Huffman coding, not arithmetic coding, by default */
  158837. cinfo->arith_code = FALSE;
  158838. /* By default, don't do extra passes to optimize entropy coding */
  158839. cinfo->optimize_coding = FALSE;
  158840. /* The standard Huffman tables are only valid for 8-bit data precision.
  158841. * If the precision is higher, force optimization on so that usable
  158842. * tables will be computed. This test can be removed if default tables
  158843. * are supplied that are valid for the desired precision.
  158844. */
  158845. if (cinfo->data_precision > 8)
  158846. cinfo->optimize_coding = TRUE;
  158847. /* By default, use the simpler non-cosited sampling alignment */
  158848. cinfo->CCIR601_sampling = FALSE;
  158849. /* No input smoothing */
  158850. cinfo->smoothing_factor = 0;
  158851. /* DCT algorithm preference */
  158852. cinfo->dct_method = JDCT_DEFAULT;
  158853. /* No restart markers */
  158854. cinfo->restart_interval = 0;
  158855. cinfo->restart_in_rows = 0;
  158856. /* Fill in default JFIF marker parameters. Note that whether the marker
  158857. * will actually be written is determined by jpeg_set_colorspace.
  158858. *
  158859. * By default, the library emits JFIF version code 1.01.
  158860. * An application that wants to emit JFIF 1.02 extension markers should set
  158861. * JFIF_minor_version to 2. We could probably get away with just defaulting
  158862. * to 1.02, but there may still be some decoders in use that will complain
  158863. * about that; saying 1.01 should minimize compatibility problems.
  158864. */
  158865. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  158866. cinfo->JFIF_minor_version = 1;
  158867. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  158868. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  158869. cinfo->Y_density = 1;
  158870. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  158871. jpeg_default_colorspace(cinfo);
  158872. }
  158873. /*
  158874. * Select an appropriate JPEG colorspace for in_color_space.
  158875. */
  158876. GLOBAL(void)
  158877. jpeg_default_colorspace (j_compress_ptr cinfo)
  158878. {
  158879. switch (cinfo->in_color_space) {
  158880. case JCS_GRAYSCALE:
  158881. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  158882. break;
  158883. case JCS_RGB:
  158884. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  158885. break;
  158886. case JCS_YCbCr:
  158887. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  158888. break;
  158889. case JCS_CMYK:
  158890. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  158891. break;
  158892. case JCS_YCCK:
  158893. jpeg_set_colorspace(cinfo, JCS_YCCK);
  158894. break;
  158895. case JCS_UNKNOWN:
  158896. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  158897. break;
  158898. default:
  158899. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158900. }
  158901. }
  158902. /*
  158903. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  158904. */
  158905. GLOBAL(void)
  158906. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  158907. {
  158908. jpeg_component_info * compptr;
  158909. int ci;
  158910. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  158911. (compptr = &cinfo->comp_info[index], \
  158912. compptr->component_id = (id), \
  158913. compptr->h_samp_factor = (hsamp), \
  158914. compptr->v_samp_factor = (vsamp), \
  158915. compptr->quant_tbl_no = (quant), \
  158916. compptr->dc_tbl_no = (dctbl), \
  158917. compptr->ac_tbl_no = (actbl) )
  158918. /* Safety check to ensure start_compress not called yet. */
  158919. if (cinfo->global_state != CSTATE_START)
  158920. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158921. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  158922. * tables 1 for chrominance components.
  158923. */
  158924. cinfo->jpeg_color_space = colorspace;
  158925. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  158926. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  158927. switch (colorspace) {
  158928. case JCS_GRAYSCALE:
  158929. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  158930. cinfo->num_components = 1;
  158931. /* JFIF specifies component ID 1 */
  158932. SET_COMP(0, 1, 1,1, 0, 0,0);
  158933. break;
  158934. case JCS_RGB:
  158935. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  158936. cinfo->num_components = 3;
  158937. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  158938. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  158939. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  158940. break;
  158941. case JCS_YCbCr:
  158942. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  158943. cinfo->num_components = 3;
  158944. /* JFIF specifies component IDs 1,2,3 */
  158945. /* We default to 2x2 subsamples of chrominance */
  158946. SET_COMP(0, 1, 2,2, 0, 0,0);
  158947. SET_COMP(1, 2, 1,1, 1, 1,1);
  158948. SET_COMP(2, 3, 1,1, 1, 1,1);
  158949. break;
  158950. case JCS_CMYK:
  158951. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  158952. cinfo->num_components = 4;
  158953. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  158954. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  158955. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  158956. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  158957. break;
  158958. case JCS_YCCK:
  158959. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  158960. cinfo->num_components = 4;
  158961. SET_COMP(0, 1, 2,2, 0, 0,0);
  158962. SET_COMP(1, 2, 1,1, 1, 1,1);
  158963. SET_COMP(2, 3, 1,1, 1, 1,1);
  158964. SET_COMP(3, 4, 2,2, 0, 0,0);
  158965. break;
  158966. case JCS_UNKNOWN:
  158967. cinfo->num_components = cinfo->input_components;
  158968. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  158969. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158970. MAX_COMPONENTS);
  158971. for (ci = 0; ci < cinfo->num_components; ci++) {
  158972. SET_COMP(ci, ci, 1,1, 0, 0,0);
  158973. }
  158974. break;
  158975. default:
  158976. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158977. }
  158978. }
  158979. #ifdef C_PROGRESSIVE_SUPPORTED
  158980. LOCAL(jpeg_scan_info *)
  158981. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  158982. int Ss, int Se, int Ah, int Al)
  158983. /* Support routine: generate one scan for specified component */
  158984. {
  158985. scanptr->comps_in_scan = 1;
  158986. scanptr->component_index[0] = ci;
  158987. scanptr->Ss = Ss;
  158988. scanptr->Se = Se;
  158989. scanptr->Ah = Ah;
  158990. scanptr->Al = Al;
  158991. scanptr++;
  158992. return scanptr;
  158993. }
  158994. LOCAL(jpeg_scan_info *)
  158995. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  158996. int Ss, int Se, int Ah, int Al)
  158997. /* Support routine: generate one scan for each component */
  158998. {
  158999. int ci;
  159000. for (ci = 0; ci < ncomps; ci++) {
  159001. scanptr->comps_in_scan = 1;
  159002. scanptr->component_index[0] = ci;
  159003. scanptr->Ss = Ss;
  159004. scanptr->Se = Se;
  159005. scanptr->Ah = Ah;
  159006. scanptr->Al = Al;
  159007. scanptr++;
  159008. }
  159009. return scanptr;
  159010. }
  159011. LOCAL(jpeg_scan_info *)
  159012. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  159013. /* Support routine: generate interleaved DC scan if possible, else N scans */
  159014. {
  159015. int ci;
  159016. if (ncomps <= MAX_COMPS_IN_SCAN) {
  159017. /* Single interleaved DC scan */
  159018. scanptr->comps_in_scan = ncomps;
  159019. for (ci = 0; ci < ncomps; ci++)
  159020. scanptr->component_index[ci] = ci;
  159021. scanptr->Ss = scanptr->Se = 0;
  159022. scanptr->Ah = Ah;
  159023. scanptr->Al = Al;
  159024. scanptr++;
  159025. } else {
  159026. /* Noninterleaved DC scan for each component */
  159027. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  159028. }
  159029. return scanptr;
  159030. }
  159031. /*
  159032. * Create a recommended progressive-JPEG script.
  159033. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  159034. */
  159035. GLOBAL(void)
  159036. jpeg_simple_progression (j_compress_ptr cinfo)
  159037. {
  159038. int ncomps = cinfo->num_components;
  159039. int nscans;
  159040. jpeg_scan_info * scanptr;
  159041. /* Safety check to ensure start_compress not called yet. */
  159042. if (cinfo->global_state != CSTATE_START)
  159043. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159044. /* Figure space needed for script. Calculation must match code below! */
  159045. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159046. /* Custom script for YCbCr color images. */
  159047. nscans = 10;
  159048. } else {
  159049. /* All-purpose script for other color spaces. */
  159050. if (ncomps > MAX_COMPS_IN_SCAN)
  159051. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  159052. else
  159053. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  159054. }
  159055. /* Allocate space for script.
  159056. * We need to put it in the permanent pool in case the application performs
  159057. * multiple compressions without changing the settings. To avoid a memory
  159058. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  159059. * object, we try to re-use previously allocated space, and we allocate
  159060. * enough space to handle YCbCr even if initially asked for grayscale.
  159061. */
  159062. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  159063. cinfo->script_space_size = MAX(nscans, 10);
  159064. cinfo->script_space = (jpeg_scan_info *)
  159065. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159066. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  159067. }
  159068. scanptr = cinfo->script_space;
  159069. cinfo->scan_info = scanptr;
  159070. cinfo->num_scans = nscans;
  159071. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159072. /* Custom script for YCbCr color images. */
  159073. /* Initial DC scan */
  159074. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159075. /* Initial AC scan: get some luma data out in a hurry */
  159076. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  159077. /* Chroma data is too small to be worth expending many scans on */
  159078. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  159079. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  159080. /* Complete spectral selection for luma AC */
  159081. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  159082. /* Refine next bit of luma AC */
  159083. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  159084. /* Finish DC successive approximation */
  159085. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159086. /* Finish AC successive approximation */
  159087. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  159088. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  159089. /* Luma bottom bit comes last since it's usually largest scan */
  159090. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  159091. } else {
  159092. /* All-purpose script for other color spaces. */
  159093. /* Successive approximation first pass */
  159094. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159095. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  159096. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  159097. /* Successive approximation second pass */
  159098. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  159099. /* Successive approximation final pass */
  159100. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159101. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  159102. }
  159103. }
  159104. #endif /* C_PROGRESSIVE_SUPPORTED */
  159105. /********* End of inlined file: jcparam.c *********/
  159106. /********* Start of inlined file: jcphuff.c *********/
  159107. #define JPEG_INTERNALS
  159108. #ifdef C_PROGRESSIVE_SUPPORTED
  159109. /* Expanded entropy encoder object for progressive Huffman encoding. */
  159110. typedef struct {
  159111. struct jpeg_entropy_encoder pub; /* public fields */
  159112. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  159113. boolean gather_statistics;
  159114. /* Bit-level coding status.
  159115. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  159116. */
  159117. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159118. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159119. INT32 put_buffer; /* current bit-accumulation buffer */
  159120. int put_bits; /* # of bits now in it */
  159121. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  159122. /* Coding status for DC components */
  159123. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159124. /* Coding status for AC components */
  159125. int ac_tbl_no; /* the table number of the single component */
  159126. unsigned int EOBRUN; /* run length of EOBs */
  159127. unsigned int BE; /* # of buffered correction bits before MCU */
  159128. char * bit_buffer; /* buffer for correction bits (1 per char) */
  159129. /* packing correction bits tightly would save some space but cost time... */
  159130. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159131. int next_restart_num; /* next restart number to write (0-7) */
  159132. /* Pointers to derived tables (these workspaces have image lifespan).
  159133. * Since any one scan codes only DC or only AC, we only need one set
  159134. * of tables, not one for DC and one for AC.
  159135. */
  159136. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  159137. /* Statistics tables for optimization; again, one set is enough */
  159138. long * count_ptrs[NUM_HUFF_TBLS];
  159139. } phuff_entropy_encoder;
  159140. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  159141. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  159142. * buffer can hold. Larger sizes may slightly improve compression, but
  159143. * 1000 is already well into the realm of overkill.
  159144. * The minimum safe size is 64 bits.
  159145. */
  159146. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  159147. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  159148. * We assume that int right shift is unsigned if INT32 right shift is,
  159149. * which should be safe.
  159150. */
  159151. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159152. #define ISHIFT_TEMPS int ishift_temp;
  159153. #define IRIGHT_SHIFT(x,shft) \
  159154. ((ishift_temp = (x)) < 0 ? \
  159155. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  159156. (ishift_temp >> (shft)))
  159157. #else
  159158. #define ISHIFT_TEMPS
  159159. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  159160. #endif
  159161. /* Forward declarations */
  159162. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  159163. JBLOCKROW *MCU_data));
  159164. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  159165. JBLOCKROW *MCU_data));
  159166. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  159167. JBLOCKROW *MCU_data));
  159168. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  159169. JBLOCKROW *MCU_data));
  159170. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  159171. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  159172. /*
  159173. * Initialize for a Huffman-compressed scan using progressive JPEG.
  159174. */
  159175. METHODDEF(void)
  159176. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  159177. {
  159178. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159179. boolean is_DC_band;
  159180. int ci, tbl;
  159181. jpeg_component_info * compptr;
  159182. entropy->cinfo = cinfo;
  159183. entropy->gather_statistics = gather_statistics;
  159184. is_DC_band = (cinfo->Ss == 0);
  159185. /* We assume jcmaster.c already validated the scan parameters. */
  159186. /* Select execution routines */
  159187. if (cinfo->Ah == 0) {
  159188. if (is_DC_band)
  159189. entropy->pub.encode_mcu = encode_mcu_DC_first;
  159190. else
  159191. entropy->pub.encode_mcu = encode_mcu_AC_first;
  159192. } else {
  159193. if (is_DC_band)
  159194. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  159195. else {
  159196. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  159197. /* AC refinement needs a correction bit buffer */
  159198. if (entropy->bit_buffer == NULL)
  159199. entropy->bit_buffer = (char *)
  159200. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159201. MAX_CORR_BITS * SIZEOF(char));
  159202. }
  159203. }
  159204. if (gather_statistics)
  159205. entropy->pub.finish_pass = finish_pass_gather_phuff;
  159206. else
  159207. entropy->pub.finish_pass = finish_pass_phuff;
  159208. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  159209. * for AC coefficients.
  159210. */
  159211. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159212. compptr = cinfo->cur_comp_info[ci];
  159213. /* Initialize DC predictions to 0 */
  159214. entropy->last_dc_val[ci] = 0;
  159215. /* Get table index */
  159216. if (is_DC_band) {
  159217. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159218. continue;
  159219. tbl = compptr->dc_tbl_no;
  159220. } else {
  159221. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  159222. }
  159223. if (gather_statistics) {
  159224. /* Check for invalid table index */
  159225. /* (make_c_derived_tbl does this in the other path) */
  159226. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  159227. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  159228. /* Allocate and zero the statistics tables */
  159229. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159230. if (entropy->count_ptrs[tbl] == NULL)
  159231. entropy->count_ptrs[tbl] = (long *)
  159232. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159233. 257 * SIZEOF(long));
  159234. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  159235. } else {
  159236. /* Compute derived values for Huffman table */
  159237. /* We may do this more than once for a table, but it's not expensive */
  159238. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  159239. & entropy->derived_tbls[tbl]);
  159240. }
  159241. }
  159242. /* Initialize AC stuff */
  159243. entropy->EOBRUN = 0;
  159244. entropy->BE = 0;
  159245. /* Initialize bit buffer to empty */
  159246. entropy->put_buffer = 0;
  159247. entropy->put_bits = 0;
  159248. /* Initialize restart stuff */
  159249. entropy->restarts_to_go = cinfo->restart_interval;
  159250. entropy->next_restart_num = 0;
  159251. }
  159252. /* Outputting bytes to the file.
  159253. * NB: these must be called only when actually outputting,
  159254. * that is, entropy->gather_statistics == FALSE.
  159255. */
  159256. /* Emit a byte */
  159257. #define emit_byte(entropy,val) \
  159258. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  159259. if (--(entropy)->free_in_buffer == 0) \
  159260. dump_buffer_p(entropy); }
  159261. LOCAL(void)
  159262. dump_buffer_p (phuff_entropy_ptr entropy)
  159263. /* Empty the output buffer; we do not support suspension in this module. */
  159264. {
  159265. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  159266. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  159267. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  159268. /* After a successful buffer dump, must reset buffer pointers */
  159269. entropy->next_output_byte = dest->next_output_byte;
  159270. entropy->free_in_buffer = dest->free_in_buffer;
  159271. }
  159272. /* Outputting bits to the file */
  159273. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159274. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159275. * in one call, and we never retain more than 7 bits in put_buffer
  159276. * between calls, so 24 bits are sufficient.
  159277. */
  159278. INLINE
  159279. LOCAL(void)
  159280. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  159281. /* Emit some bits, unless we are in gather mode */
  159282. {
  159283. /* This routine is heavily used, so it's worth coding tightly. */
  159284. register INT32 put_buffer = (INT32) code;
  159285. register int put_bits = entropy->put_bits;
  159286. /* if size is 0, caller used an invalid Huffman table entry */
  159287. if (size == 0)
  159288. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  159289. if (entropy->gather_statistics)
  159290. return; /* do nothing if we're only getting stats */
  159291. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159292. put_bits += size; /* new number of bits in buffer */
  159293. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159294. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  159295. while (put_bits >= 8) {
  159296. int c = (int) ((put_buffer >> 16) & 0xFF);
  159297. emit_byte(entropy, c);
  159298. if (c == 0xFF) { /* need to stuff a zero byte? */
  159299. emit_byte(entropy, 0);
  159300. }
  159301. put_buffer <<= 8;
  159302. put_bits -= 8;
  159303. }
  159304. entropy->put_buffer = put_buffer; /* update variables */
  159305. entropy->put_bits = put_bits;
  159306. }
  159307. LOCAL(void)
  159308. flush_bits_p (phuff_entropy_ptr entropy)
  159309. {
  159310. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  159311. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  159312. entropy->put_bits = 0;
  159313. }
  159314. /*
  159315. * Emit (or just count) a Huffman symbol.
  159316. */
  159317. INLINE
  159318. LOCAL(void)
  159319. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  159320. {
  159321. if (entropy->gather_statistics)
  159322. entropy->count_ptrs[tbl_no][symbol]++;
  159323. else {
  159324. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  159325. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  159326. }
  159327. }
  159328. /*
  159329. * Emit bits from a correction bit buffer.
  159330. */
  159331. LOCAL(void)
  159332. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  159333. unsigned int nbits)
  159334. {
  159335. if (entropy->gather_statistics)
  159336. return; /* no real work */
  159337. while (nbits > 0) {
  159338. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  159339. bufstart++;
  159340. nbits--;
  159341. }
  159342. }
  159343. /*
  159344. * Emit any pending EOBRUN symbol.
  159345. */
  159346. LOCAL(void)
  159347. emit_eobrun (phuff_entropy_ptr entropy)
  159348. {
  159349. register int temp, nbits;
  159350. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  159351. temp = entropy->EOBRUN;
  159352. nbits = 0;
  159353. while ((temp >>= 1))
  159354. nbits++;
  159355. /* safety check: shouldn't happen given limited correction-bit buffer */
  159356. if (nbits > 14)
  159357. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  159358. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  159359. if (nbits)
  159360. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  159361. entropy->EOBRUN = 0;
  159362. /* Emit any buffered correction bits */
  159363. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  159364. entropy->BE = 0;
  159365. }
  159366. }
  159367. /*
  159368. * Emit a restart marker & resynchronize predictions.
  159369. */
  159370. LOCAL(void)
  159371. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  159372. {
  159373. int ci;
  159374. emit_eobrun(entropy);
  159375. if (! entropy->gather_statistics) {
  159376. flush_bits_p(entropy);
  159377. emit_byte(entropy, 0xFF);
  159378. emit_byte(entropy, JPEG_RST0 + restart_num);
  159379. }
  159380. if (entropy->cinfo->Ss == 0) {
  159381. /* Re-initialize DC predictions to 0 */
  159382. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  159383. entropy->last_dc_val[ci] = 0;
  159384. } else {
  159385. /* Re-initialize all AC-related fields to 0 */
  159386. entropy->EOBRUN = 0;
  159387. entropy->BE = 0;
  159388. }
  159389. }
  159390. /*
  159391. * MCU encoding for DC initial scan (either spectral selection,
  159392. * or first pass of successive approximation).
  159393. */
  159394. METHODDEF(boolean)
  159395. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159396. {
  159397. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159398. register int temp, temp2;
  159399. register int nbits;
  159400. int blkn, ci;
  159401. int Al = cinfo->Al;
  159402. JBLOCKROW block;
  159403. jpeg_component_info * compptr;
  159404. ISHIFT_TEMPS
  159405. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159406. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159407. /* Emit restart marker if needed */
  159408. if (cinfo->restart_interval)
  159409. if (entropy->restarts_to_go == 0)
  159410. emit_restart_p(entropy, entropy->next_restart_num);
  159411. /* Encode the MCU data blocks */
  159412. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159413. block = MCU_data[blkn];
  159414. ci = cinfo->MCU_membership[blkn];
  159415. compptr = cinfo->cur_comp_info[ci];
  159416. /* Compute the DC value after the required point transform by Al.
  159417. * This is simply an arithmetic right shift.
  159418. */
  159419. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  159420. /* DC differences are figured on the point-transformed values. */
  159421. temp = temp2 - entropy->last_dc_val[ci];
  159422. entropy->last_dc_val[ci] = temp2;
  159423. /* Encode the DC coefficient difference per section G.1.2.1 */
  159424. temp2 = temp;
  159425. if (temp < 0) {
  159426. temp = -temp; /* temp is abs value of input */
  159427. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159428. /* This code assumes we are on a two's complement machine */
  159429. temp2--;
  159430. }
  159431. /* Find the number of bits needed for the magnitude of the coefficient */
  159432. nbits = 0;
  159433. while (temp) {
  159434. nbits++;
  159435. temp >>= 1;
  159436. }
  159437. /* Check for out-of-range coefficient values.
  159438. * Since we're encoding a difference, the range limit is twice as much.
  159439. */
  159440. if (nbits > MAX_COEF_BITS+1)
  159441. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159442. /* Count/emit the Huffman-coded symbol for the number of bits */
  159443. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  159444. /* Emit that number of bits of the value, if positive, */
  159445. /* or the complement of its magnitude, if negative. */
  159446. if (nbits) /* emit_bits rejects calls with size 0 */
  159447. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  159448. }
  159449. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159450. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159451. /* Update restart-interval state too */
  159452. if (cinfo->restart_interval) {
  159453. if (entropy->restarts_to_go == 0) {
  159454. entropy->restarts_to_go = cinfo->restart_interval;
  159455. entropy->next_restart_num++;
  159456. entropy->next_restart_num &= 7;
  159457. }
  159458. entropy->restarts_to_go--;
  159459. }
  159460. return TRUE;
  159461. }
  159462. /*
  159463. * MCU encoding for AC initial scan (either spectral selection,
  159464. * or first pass of successive approximation).
  159465. */
  159466. METHODDEF(boolean)
  159467. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159468. {
  159469. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159470. register int temp, temp2;
  159471. register int nbits;
  159472. register int r, k;
  159473. int Se = cinfo->Se;
  159474. int Al = cinfo->Al;
  159475. JBLOCKROW block;
  159476. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159477. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159478. /* Emit restart marker if needed */
  159479. if (cinfo->restart_interval)
  159480. if (entropy->restarts_to_go == 0)
  159481. emit_restart_p(entropy, entropy->next_restart_num);
  159482. /* Encode the MCU data block */
  159483. block = MCU_data[0];
  159484. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  159485. r = 0; /* r = run length of zeros */
  159486. for (k = cinfo->Ss; k <= Se; k++) {
  159487. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  159488. r++;
  159489. continue;
  159490. }
  159491. /* We must apply the point transform by Al. For AC coefficients this
  159492. * is an integer division with rounding towards 0. To do this portably
  159493. * in C, we shift after obtaining the absolute value; so the code is
  159494. * interwoven with finding the abs value (temp) and output bits (temp2).
  159495. */
  159496. if (temp < 0) {
  159497. temp = -temp; /* temp is abs value of input */
  159498. temp >>= Al; /* apply the point transform */
  159499. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  159500. temp2 = ~temp;
  159501. } else {
  159502. temp >>= Al; /* apply the point transform */
  159503. temp2 = temp;
  159504. }
  159505. /* Watch out for case that nonzero coef is zero after point transform */
  159506. if (temp == 0) {
  159507. r++;
  159508. continue;
  159509. }
  159510. /* Emit any pending EOBRUN */
  159511. if (entropy->EOBRUN > 0)
  159512. emit_eobrun(entropy);
  159513. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159514. while (r > 15) {
  159515. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  159516. r -= 16;
  159517. }
  159518. /* Find the number of bits needed for the magnitude of the coefficient */
  159519. nbits = 1; /* there must be at least one 1 bit */
  159520. while ((temp >>= 1))
  159521. nbits++;
  159522. /* Check for out-of-range coefficient values */
  159523. if (nbits > MAX_COEF_BITS)
  159524. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159525. /* Count/emit Huffman symbol for run length / number of bits */
  159526. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  159527. /* Emit that number of bits of the value, if positive, */
  159528. /* or the complement of its magnitude, if negative. */
  159529. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  159530. r = 0; /* reset zero run length */
  159531. }
  159532. if (r > 0) { /* If there are trailing zeroes, */
  159533. entropy->EOBRUN++; /* count an EOB */
  159534. if (entropy->EOBRUN == 0x7FFF)
  159535. emit_eobrun(entropy); /* force it out to avoid overflow */
  159536. }
  159537. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159538. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159539. /* Update restart-interval state too */
  159540. if (cinfo->restart_interval) {
  159541. if (entropy->restarts_to_go == 0) {
  159542. entropy->restarts_to_go = cinfo->restart_interval;
  159543. entropy->next_restart_num++;
  159544. entropy->next_restart_num &= 7;
  159545. }
  159546. entropy->restarts_to_go--;
  159547. }
  159548. return TRUE;
  159549. }
  159550. /*
  159551. * MCU encoding for DC successive approximation refinement scan.
  159552. * Note: we assume such scans can be multi-component, although the spec
  159553. * is not very clear on the point.
  159554. */
  159555. METHODDEF(boolean)
  159556. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159557. {
  159558. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159559. register int temp;
  159560. int blkn;
  159561. int Al = cinfo->Al;
  159562. JBLOCKROW block;
  159563. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159564. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159565. /* Emit restart marker if needed */
  159566. if (cinfo->restart_interval)
  159567. if (entropy->restarts_to_go == 0)
  159568. emit_restart_p(entropy, entropy->next_restart_num);
  159569. /* Encode the MCU data blocks */
  159570. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159571. block = MCU_data[blkn];
  159572. /* We simply emit the Al'th bit of the DC coefficient value. */
  159573. temp = (*block)[0];
  159574. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  159575. }
  159576. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159577. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159578. /* Update restart-interval state too */
  159579. if (cinfo->restart_interval) {
  159580. if (entropy->restarts_to_go == 0) {
  159581. entropy->restarts_to_go = cinfo->restart_interval;
  159582. entropy->next_restart_num++;
  159583. entropy->next_restart_num &= 7;
  159584. }
  159585. entropy->restarts_to_go--;
  159586. }
  159587. return TRUE;
  159588. }
  159589. /*
  159590. * MCU encoding for AC successive approximation refinement scan.
  159591. */
  159592. METHODDEF(boolean)
  159593. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159594. {
  159595. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159596. register int temp;
  159597. register int r, k;
  159598. int EOB;
  159599. char *BR_buffer;
  159600. unsigned int BR;
  159601. int Se = cinfo->Se;
  159602. int Al = cinfo->Al;
  159603. JBLOCKROW block;
  159604. int absvalues[DCTSIZE2];
  159605. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159606. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159607. /* Emit restart marker if needed */
  159608. if (cinfo->restart_interval)
  159609. if (entropy->restarts_to_go == 0)
  159610. emit_restart_p(entropy, entropy->next_restart_num);
  159611. /* Encode the MCU data block */
  159612. block = MCU_data[0];
  159613. /* It is convenient to make a pre-pass to determine the transformed
  159614. * coefficients' absolute values and the EOB position.
  159615. */
  159616. EOB = 0;
  159617. for (k = cinfo->Ss; k <= Se; k++) {
  159618. temp = (*block)[jpeg_natural_order[k]];
  159619. /* We must apply the point transform by Al. For AC coefficients this
  159620. * is an integer division with rounding towards 0. To do this portably
  159621. * in C, we shift after obtaining the absolute value.
  159622. */
  159623. if (temp < 0)
  159624. temp = -temp; /* temp is abs value of input */
  159625. temp >>= Al; /* apply the point transform */
  159626. absvalues[k] = temp; /* save abs value for main pass */
  159627. if (temp == 1)
  159628. EOB = k; /* EOB = index of last newly-nonzero coef */
  159629. }
  159630. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  159631. r = 0; /* r = run length of zeros */
  159632. BR = 0; /* BR = count of buffered bits added now */
  159633. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  159634. for (k = cinfo->Ss; k <= Se; k++) {
  159635. if ((temp = absvalues[k]) == 0) {
  159636. r++;
  159637. continue;
  159638. }
  159639. /* Emit any required ZRLs, but not if they can be folded into EOB */
  159640. while (r > 15 && k <= EOB) {
  159641. /* emit any pending EOBRUN and the BE correction bits */
  159642. emit_eobrun(entropy);
  159643. /* Emit ZRL */
  159644. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  159645. r -= 16;
  159646. /* Emit buffered correction bits that must be associated with ZRL */
  159647. emit_buffered_bits(entropy, BR_buffer, BR);
  159648. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  159649. BR = 0;
  159650. }
  159651. /* If the coef was previously nonzero, it only needs a correction bit.
  159652. * NOTE: a straight translation of the spec's figure G.7 would suggest
  159653. * that we also need to test r > 15. But if r > 15, we can only get here
  159654. * if k > EOB, which implies that this coefficient is not 1.
  159655. */
  159656. if (temp > 1) {
  159657. /* The correction bit is the next bit of the absolute value. */
  159658. BR_buffer[BR++] = (char) (temp & 1);
  159659. continue;
  159660. }
  159661. /* Emit any pending EOBRUN and the BE correction bits */
  159662. emit_eobrun(entropy);
  159663. /* Count/emit Huffman symbol for run length / number of bits */
  159664. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  159665. /* Emit output bit for newly-nonzero coef */
  159666. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  159667. emit_bits_p(entropy, (unsigned int) temp, 1);
  159668. /* Emit buffered correction bits that must be associated with this code */
  159669. emit_buffered_bits(entropy, BR_buffer, BR);
  159670. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  159671. BR = 0;
  159672. r = 0; /* reset zero run length */
  159673. }
  159674. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  159675. entropy->EOBRUN++; /* count an EOB */
  159676. entropy->BE += BR; /* concat my correction bits to older ones */
  159677. /* We force out the EOB if we risk either:
  159678. * 1. overflow of the EOB counter;
  159679. * 2. overflow of the correction bit buffer during the next MCU.
  159680. */
  159681. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  159682. emit_eobrun(entropy);
  159683. }
  159684. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159685. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159686. /* Update restart-interval state too */
  159687. if (cinfo->restart_interval) {
  159688. if (entropy->restarts_to_go == 0) {
  159689. entropy->restarts_to_go = cinfo->restart_interval;
  159690. entropy->next_restart_num++;
  159691. entropy->next_restart_num &= 7;
  159692. }
  159693. entropy->restarts_to_go--;
  159694. }
  159695. return TRUE;
  159696. }
  159697. /*
  159698. * Finish up at the end of a Huffman-compressed progressive scan.
  159699. */
  159700. METHODDEF(void)
  159701. finish_pass_phuff (j_compress_ptr cinfo)
  159702. {
  159703. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159704. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159705. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159706. /* Flush out any buffered data */
  159707. emit_eobrun(entropy);
  159708. flush_bits_p(entropy);
  159709. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159710. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159711. }
  159712. /*
  159713. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159714. */
  159715. METHODDEF(void)
  159716. finish_pass_gather_phuff (j_compress_ptr cinfo)
  159717. {
  159718. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159719. boolean is_DC_band;
  159720. int ci, tbl;
  159721. jpeg_component_info * compptr;
  159722. JHUFF_TBL **htblptr;
  159723. boolean did[NUM_HUFF_TBLS];
  159724. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  159725. emit_eobrun(entropy);
  159726. is_DC_band = (cinfo->Ss == 0);
  159727. /* It's important not to apply jpeg_gen_optimal_table more than once
  159728. * per table, because it clobbers the input frequency counts!
  159729. */
  159730. MEMZERO(did, SIZEOF(did));
  159731. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159732. compptr = cinfo->cur_comp_info[ci];
  159733. if (is_DC_band) {
  159734. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159735. continue;
  159736. tbl = compptr->dc_tbl_no;
  159737. } else {
  159738. tbl = compptr->ac_tbl_no;
  159739. }
  159740. if (! did[tbl]) {
  159741. if (is_DC_band)
  159742. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  159743. else
  159744. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  159745. if (*htblptr == NULL)
  159746. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159747. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  159748. did[tbl] = TRUE;
  159749. }
  159750. }
  159751. }
  159752. /*
  159753. * Module initialization routine for progressive Huffman entropy encoding.
  159754. */
  159755. GLOBAL(void)
  159756. jinit_phuff_encoder (j_compress_ptr cinfo)
  159757. {
  159758. phuff_entropy_ptr entropy;
  159759. int i;
  159760. entropy = (phuff_entropy_ptr)
  159761. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159762. SIZEOF(phuff_entropy_encoder));
  159763. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159764. entropy->pub.start_pass = start_pass_phuff;
  159765. /* Mark tables unallocated */
  159766. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159767. entropy->derived_tbls[i] = NULL;
  159768. entropy->count_ptrs[i] = NULL;
  159769. }
  159770. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  159771. }
  159772. #endif /* C_PROGRESSIVE_SUPPORTED */
  159773. /********* End of inlined file: jcphuff.c *********/
  159774. /********* Start of inlined file: jcprepct.c *********/
  159775. #define JPEG_INTERNALS
  159776. /* At present, jcsample.c can request context rows only for smoothing.
  159777. * In the future, we might also need context rows for CCIR601 sampling
  159778. * or other more-complex downsampling procedures. The code to support
  159779. * context rows should be compiled only if needed.
  159780. */
  159781. #ifdef INPUT_SMOOTHING_SUPPORTED
  159782. #define CONTEXT_ROWS_SUPPORTED
  159783. #endif
  159784. /*
  159785. * For the simple (no-context-row) case, we just need to buffer one
  159786. * row group's worth of pixels for the downsampling step. At the bottom of
  159787. * the image, we pad to a full row group by replicating the last pixel row.
  159788. * The downsampler's last output row is then replicated if needed to pad
  159789. * out to a full iMCU row.
  159790. *
  159791. * When providing context rows, we must buffer three row groups' worth of
  159792. * pixels. Three row groups are physically allocated, but the row pointer
  159793. * arrays are made five row groups high, with the extra pointers above and
  159794. * below "wrapping around" to point to the last and first real row groups.
  159795. * This allows the downsampler to access the proper context rows.
  159796. * At the top and bottom of the image, we create dummy context rows by
  159797. * copying the first or last real pixel row. This copying could be avoided
  159798. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  159799. * trouble on the compression side.
  159800. */
  159801. /* Private buffer controller object */
  159802. typedef struct {
  159803. struct jpeg_c_prep_controller pub; /* public fields */
  159804. /* Downsampling input buffer. This buffer holds color-converted data
  159805. * until we have enough to do a downsample step.
  159806. */
  159807. JSAMPARRAY color_buf[MAX_COMPONENTS];
  159808. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  159809. int next_buf_row; /* index of next row to store in color_buf */
  159810. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  159811. int this_row_group; /* starting row index of group to process */
  159812. int next_buf_stop; /* downsample when we reach this index */
  159813. #endif
  159814. } my_prep_controller;
  159815. typedef my_prep_controller * my_prep_ptr;
  159816. /*
  159817. * Initialize for a processing pass.
  159818. */
  159819. METHODDEF(void)
  159820. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159821. {
  159822. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159823. if (pass_mode != JBUF_PASS_THRU)
  159824. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159825. /* Initialize total-height counter for detecting bottom of image */
  159826. prep->rows_to_go = cinfo->image_height;
  159827. /* Mark the conversion buffer empty */
  159828. prep->next_buf_row = 0;
  159829. #ifdef CONTEXT_ROWS_SUPPORTED
  159830. /* Preset additional state variables for context mode.
  159831. * These aren't used in non-context mode, so we needn't test which mode.
  159832. */
  159833. prep->this_row_group = 0;
  159834. /* Set next_buf_stop to stop after two row groups have been read in. */
  159835. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  159836. #endif
  159837. }
  159838. /*
  159839. * Expand an image vertically from height input_rows to height output_rows,
  159840. * by duplicating the bottom row.
  159841. */
  159842. LOCAL(void)
  159843. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  159844. int input_rows, int output_rows)
  159845. {
  159846. register int row;
  159847. for (row = input_rows; row < output_rows; row++) {
  159848. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  159849. 1, num_cols);
  159850. }
  159851. }
  159852. /*
  159853. * Process some data in the simple no-context case.
  159854. *
  159855. * Preprocessor output data is counted in "row groups". A row group
  159856. * is defined to be v_samp_factor sample rows of each component.
  159857. * Downsampling will produce this much data from each max_v_samp_factor
  159858. * input rows.
  159859. */
  159860. METHODDEF(void)
  159861. pre_process_data (j_compress_ptr cinfo,
  159862. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159863. JDIMENSION in_rows_avail,
  159864. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  159865. JDIMENSION out_row_groups_avail)
  159866. {
  159867. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159868. int numrows, ci;
  159869. JDIMENSION inrows;
  159870. jpeg_component_info * compptr;
  159871. while (*in_row_ctr < in_rows_avail &&
  159872. *out_row_group_ctr < out_row_groups_avail) {
  159873. /* Do color conversion to fill the conversion buffer. */
  159874. inrows = in_rows_avail - *in_row_ctr;
  159875. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  159876. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  159877. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  159878. prep->color_buf,
  159879. (JDIMENSION) prep->next_buf_row,
  159880. numrows);
  159881. *in_row_ctr += numrows;
  159882. prep->next_buf_row += numrows;
  159883. prep->rows_to_go -= numrows;
  159884. /* If at bottom of image, pad to fill the conversion buffer. */
  159885. if (prep->rows_to_go == 0 &&
  159886. prep->next_buf_row < cinfo->max_v_samp_factor) {
  159887. for (ci = 0; ci < cinfo->num_components; ci++) {
  159888. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  159889. prep->next_buf_row, cinfo->max_v_samp_factor);
  159890. }
  159891. prep->next_buf_row = cinfo->max_v_samp_factor;
  159892. }
  159893. /* If we've filled the conversion buffer, empty it. */
  159894. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  159895. (*cinfo->downsample->downsample) (cinfo,
  159896. prep->color_buf, (JDIMENSION) 0,
  159897. output_buf, *out_row_group_ctr);
  159898. prep->next_buf_row = 0;
  159899. (*out_row_group_ctr)++;
  159900. }
  159901. /* If at bottom of image, pad the output to a full iMCU height.
  159902. * Note we assume the caller is providing a one-iMCU-height output buffer!
  159903. */
  159904. if (prep->rows_to_go == 0 &&
  159905. *out_row_group_ctr < out_row_groups_avail) {
  159906. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159907. ci++, compptr++) {
  159908. expand_bottom_edge(output_buf[ci],
  159909. compptr->width_in_blocks * DCTSIZE,
  159910. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  159911. (int) (out_row_groups_avail * compptr->v_samp_factor));
  159912. }
  159913. *out_row_group_ctr = out_row_groups_avail;
  159914. break; /* can exit outer loop without test */
  159915. }
  159916. }
  159917. }
  159918. #ifdef CONTEXT_ROWS_SUPPORTED
  159919. /*
  159920. * Process some data in the context case.
  159921. */
  159922. METHODDEF(void)
  159923. pre_process_context (j_compress_ptr cinfo,
  159924. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159925. JDIMENSION in_rows_avail,
  159926. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  159927. JDIMENSION out_row_groups_avail)
  159928. {
  159929. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159930. int numrows, ci;
  159931. int buf_height = cinfo->max_v_samp_factor * 3;
  159932. JDIMENSION inrows;
  159933. while (*out_row_group_ctr < out_row_groups_avail) {
  159934. if (*in_row_ctr < in_rows_avail) {
  159935. /* Do color conversion to fill the conversion buffer. */
  159936. inrows = in_rows_avail - *in_row_ctr;
  159937. numrows = prep->next_buf_stop - prep->next_buf_row;
  159938. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  159939. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  159940. prep->color_buf,
  159941. (JDIMENSION) prep->next_buf_row,
  159942. numrows);
  159943. /* Pad at top of image, if first time through */
  159944. if (prep->rows_to_go == cinfo->image_height) {
  159945. for (ci = 0; ci < cinfo->num_components; ci++) {
  159946. int row;
  159947. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  159948. jcopy_sample_rows(prep->color_buf[ci], 0,
  159949. prep->color_buf[ci], -row,
  159950. 1, cinfo->image_width);
  159951. }
  159952. }
  159953. }
  159954. *in_row_ctr += numrows;
  159955. prep->next_buf_row += numrows;
  159956. prep->rows_to_go -= numrows;
  159957. } else {
  159958. /* Return for more data, unless we are at the bottom of the image. */
  159959. if (prep->rows_to_go != 0)
  159960. break;
  159961. /* When at bottom of image, pad to fill the conversion buffer. */
  159962. if (prep->next_buf_row < prep->next_buf_stop) {
  159963. for (ci = 0; ci < cinfo->num_components; ci++) {
  159964. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  159965. prep->next_buf_row, prep->next_buf_stop);
  159966. }
  159967. prep->next_buf_row = prep->next_buf_stop;
  159968. }
  159969. }
  159970. /* If we've gotten enough data, downsample a row group. */
  159971. if (prep->next_buf_row == prep->next_buf_stop) {
  159972. (*cinfo->downsample->downsample) (cinfo,
  159973. prep->color_buf,
  159974. (JDIMENSION) prep->this_row_group,
  159975. output_buf, *out_row_group_ctr);
  159976. (*out_row_group_ctr)++;
  159977. /* Advance pointers with wraparound as necessary. */
  159978. prep->this_row_group += cinfo->max_v_samp_factor;
  159979. if (prep->this_row_group >= buf_height)
  159980. prep->this_row_group = 0;
  159981. if (prep->next_buf_row >= buf_height)
  159982. prep->next_buf_row = 0;
  159983. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  159984. }
  159985. }
  159986. }
  159987. /*
  159988. * Create the wrapped-around downsampling input buffer needed for context mode.
  159989. */
  159990. LOCAL(void)
  159991. create_context_buffer (j_compress_ptr cinfo)
  159992. {
  159993. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159994. int rgroup_height = cinfo->max_v_samp_factor;
  159995. int ci, i;
  159996. jpeg_component_info * compptr;
  159997. JSAMPARRAY true_buffer, fake_buffer;
  159998. /* Grab enough space for fake row pointers for all the components;
  159999. * we need five row groups' worth of pointers for each component.
  160000. */
  160001. fake_buffer = (JSAMPARRAY)
  160002. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160003. (cinfo->num_components * 5 * rgroup_height) *
  160004. SIZEOF(JSAMPROW));
  160005. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160006. ci++, compptr++) {
  160007. /* Allocate the actual buffer space (3 row groups) for this component.
  160008. * We make the buffer wide enough to allow the downsampler to edge-expand
  160009. * horizontally within the buffer, if it so chooses.
  160010. */
  160011. true_buffer = (*cinfo->mem->alloc_sarray)
  160012. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160013. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160014. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160015. (JDIMENSION) (3 * rgroup_height));
  160016. /* Copy true buffer row pointers into the middle of the fake row array */
  160017. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  160018. 3 * rgroup_height * SIZEOF(JSAMPROW));
  160019. /* Fill in the above and below wraparound pointers */
  160020. for (i = 0; i < rgroup_height; i++) {
  160021. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  160022. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  160023. }
  160024. prep->color_buf[ci] = fake_buffer + rgroup_height;
  160025. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  160026. }
  160027. }
  160028. #endif /* CONTEXT_ROWS_SUPPORTED */
  160029. /*
  160030. * Initialize preprocessing controller.
  160031. */
  160032. GLOBAL(void)
  160033. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160034. {
  160035. my_prep_ptr prep;
  160036. int ci;
  160037. jpeg_component_info * compptr;
  160038. if (need_full_buffer) /* safety check */
  160039. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160040. prep = (my_prep_ptr)
  160041. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160042. SIZEOF(my_prep_controller));
  160043. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  160044. prep->pub.start_pass = start_pass_prep;
  160045. /* Allocate the color conversion buffer.
  160046. * We make the buffer wide enough to allow the downsampler to edge-expand
  160047. * horizontally within the buffer, if it so chooses.
  160048. */
  160049. if (cinfo->downsample->need_context_rows) {
  160050. /* Set up to provide context rows */
  160051. #ifdef CONTEXT_ROWS_SUPPORTED
  160052. prep->pub.pre_process_data = pre_process_context;
  160053. create_context_buffer(cinfo);
  160054. #else
  160055. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160056. #endif
  160057. } else {
  160058. /* No context, just make it tall enough for one row group */
  160059. prep->pub.pre_process_data = pre_process_data;
  160060. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160061. ci++, compptr++) {
  160062. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  160063. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160064. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160065. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160066. (JDIMENSION) cinfo->max_v_samp_factor);
  160067. }
  160068. }
  160069. }
  160070. /********* End of inlined file: jcprepct.c *********/
  160071. /********* Start of inlined file: jcsample.c *********/
  160072. #define JPEG_INTERNALS
  160073. /* Pointer to routine to downsample a single component */
  160074. typedef JMETHOD(void, downsample1_ptr,
  160075. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160076. JSAMPARRAY input_data, JSAMPARRAY output_data));
  160077. /* Private subobject */
  160078. typedef struct {
  160079. struct jpeg_downsampler pub; /* public fields */
  160080. /* Downsampling method pointers, one per component */
  160081. downsample1_ptr methods[MAX_COMPONENTS];
  160082. } my_downsampler;
  160083. typedef my_downsampler * my_downsample_ptr;
  160084. /*
  160085. * Initialize for a downsampling pass.
  160086. */
  160087. METHODDEF(void)
  160088. start_pass_downsample (j_compress_ptr cinfo)
  160089. {
  160090. /* no work for now */
  160091. }
  160092. /*
  160093. * Expand a component horizontally from width input_cols to width output_cols,
  160094. * by duplicating the rightmost samples.
  160095. */
  160096. LOCAL(void)
  160097. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  160098. JDIMENSION input_cols, JDIMENSION output_cols)
  160099. {
  160100. register JSAMPROW ptr;
  160101. register JSAMPLE pixval;
  160102. register int count;
  160103. int row;
  160104. int numcols = (int) (output_cols - input_cols);
  160105. if (numcols > 0) {
  160106. for (row = 0; row < num_rows; row++) {
  160107. ptr = image_data[row] + input_cols;
  160108. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  160109. for (count = numcols; count > 0; count--)
  160110. *ptr++ = pixval;
  160111. }
  160112. }
  160113. }
  160114. /*
  160115. * Do downsampling for a whole row group (all components).
  160116. *
  160117. * In this version we simply downsample each component independently.
  160118. */
  160119. METHODDEF(void)
  160120. sep_downsample (j_compress_ptr cinfo,
  160121. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160122. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  160123. {
  160124. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  160125. int ci;
  160126. jpeg_component_info * compptr;
  160127. JSAMPARRAY in_ptr, out_ptr;
  160128. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160129. ci++, compptr++) {
  160130. in_ptr = input_buf[ci] + in_row_index;
  160131. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  160132. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  160133. }
  160134. }
  160135. /*
  160136. * Downsample pixel values of a single component.
  160137. * One row group is processed per call.
  160138. * This version handles arbitrary integral sampling ratios, without smoothing.
  160139. * Note that this version is not actually used for customary sampling ratios.
  160140. */
  160141. METHODDEF(void)
  160142. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160143. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160144. {
  160145. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  160146. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  160147. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160148. JSAMPROW inptr, outptr;
  160149. INT32 outvalue;
  160150. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  160151. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  160152. numpix = h_expand * v_expand;
  160153. numpix2 = numpix/2;
  160154. /* Expand input data enough to let all the output samples be generated
  160155. * by the standard loop. Special-casing padded output would be more
  160156. * efficient.
  160157. */
  160158. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160159. cinfo->image_width, output_cols * h_expand);
  160160. inrow = 0;
  160161. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160162. outptr = output_data[outrow];
  160163. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  160164. outcol++, outcol_h += h_expand) {
  160165. outvalue = 0;
  160166. for (v = 0; v < v_expand; v++) {
  160167. inptr = input_data[inrow+v] + outcol_h;
  160168. for (h = 0; h < h_expand; h++) {
  160169. outvalue += (INT32) GETJSAMPLE(*inptr++);
  160170. }
  160171. }
  160172. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  160173. }
  160174. inrow += v_expand;
  160175. }
  160176. }
  160177. /*
  160178. * Downsample pixel values of a single component.
  160179. * This version handles the special case of a full-size component,
  160180. * without smoothing.
  160181. */
  160182. METHODDEF(void)
  160183. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160184. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160185. {
  160186. /* Copy the data */
  160187. jcopy_sample_rows(input_data, 0, output_data, 0,
  160188. cinfo->max_v_samp_factor, cinfo->image_width);
  160189. /* Edge-expand */
  160190. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  160191. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  160192. }
  160193. /*
  160194. * Downsample pixel values of a single component.
  160195. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  160196. * without smoothing.
  160197. *
  160198. * A note about the "bias" calculations: when rounding fractional values to
  160199. * integer, we do not want to always round 0.5 up to the next integer.
  160200. * If we did that, we'd introduce a noticeable bias towards larger values.
  160201. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  160202. * alternate pixel locations (a simple ordered dither pattern).
  160203. */
  160204. METHODDEF(void)
  160205. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160206. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160207. {
  160208. int outrow;
  160209. JDIMENSION outcol;
  160210. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160211. register JSAMPROW inptr, outptr;
  160212. register int bias;
  160213. /* Expand input data enough to let all the output samples be generated
  160214. * by the standard loop. Special-casing padded output would be more
  160215. * efficient.
  160216. */
  160217. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160218. cinfo->image_width, output_cols * 2);
  160219. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160220. outptr = output_data[outrow];
  160221. inptr = input_data[outrow];
  160222. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  160223. for (outcol = 0; outcol < output_cols; outcol++) {
  160224. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  160225. + bias) >> 1);
  160226. bias ^= 1; /* 0=>1, 1=>0 */
  160227. inptr += 2;
  160228. }
  160229. }
  160230. }
  160231. /*
  160232. * Downsample pixel values of a single component.
  160233. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160234. * without smoothing.
  160235. */
  160236. METHODDEF(void)
  160237. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160238. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160239. {
  160240. int inrow, outrow;
  160241. JDIMENSION outcol;
  160242. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160243. register JSAMPROW inptr0, inptr1, outptr;
  160244. register int bias;
  160245. /* Expand input data enough to let all the output samples be generated
  160246. * by the standard loop. Special-casing padded output would be more
  160247. * efficient.
  160248. */
  160249. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160250. cinfo->image_width, output_cols * 2);
  160251. inrow = 0;
  160252. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160253. outptr = output_data[outrow];
  160254. inptr0 = input_data[inrow];
  160255. inptr1 = input_data[inrow+1];
  160256. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  160257. for (outcol = 0; outcol < output_cols; outcol++) {
  160258. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160259. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  160260. + bias) >> 2);
  160261. bias ^= 3; /* 1=>2, 2=>1 */
  160262. inptr0 += 2; inptr1 += 2;
  160263. }
  160264. inrow += 2;
  160265. }
  160266. }
  160267. #ifdef INPUT_SMOOTHING_SUPPORTED
  160268. /*
  160269. * Downsample pixel values of a single component.
  160270. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160271. * with smoothing. One row of context is required.
  160272. */
  160273. METHODDEF(void)
  160274. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160275. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160276. {
  160277. int inrow, outrow;
  160278. JDIMENSION colctr;
  160279. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160280. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  160281. INT32 membersum, neighsum, memberscale, neighscale;
  160282. /* Expand input data enough to let all the output samples be generated
  160283. * by the standard loop. Special-casing padded output would be more
  160284. * efficient.
  160285. */
  160286. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  160287. cinfo->image_width, output_cols * 2);
  160288. /* We don't bother to form the individual "smoothed" input pixel values;
  160289. * we can directly compute the output which is the average of the four
  160290. * smoothed values. Each of the four member pixels contributes a fraction
  160291. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  160292. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  160293. * output. The four corner-adjacent neighbor pixels contribute a fraction
  160294. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  160295. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  160296. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  160297. * factors are scaled by 2^16 = 65536.
  160298. * Also recall that SF = smoothing_factor / 1024.
  160299. */
  160300. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  160301. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  160302. inrow = 0;
  160303. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160304. outptr = output_data[outrow];
  160305. inptr0 = input_data[inrow];
  160306. inptr1 = input_data[inrow+1];
  160307. above_ptr = input_data[inrow-1];
  160308. below_ptr = input_data[inrow+2];
  160309. /* Special case for first column: pretend column -1 is same as column 0 */
  160310. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160311. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160312. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160313. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160314. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  160315. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  160316. neighsum += neighsum;
  160317. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  160318. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  160319. membersum = membersum * memberscale + neighsum * neighscale;
  160320. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160321. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  160322. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  160323. /* sum of pixels directly mapped to this output element */
  160324. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160325. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160326. /* sum of edge-neighbor pixels */
  160327. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160328. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160329. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  160330. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  160331. /* The edge-neighbors count twice as much as corner-neighbors */
  160332. neighsum += neighsum;
  160333. /* Add in the corner-neighbors */
  160334. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  160335. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  160336. /* form final output scaled up by 2^16 */
  160337. membersum = membersum * memberscale + neighsum * neighscale;
  160338. /* round, descale and output it */
  160339. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160340. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  160341. }
  160342. /* Special case for last column */
  160343. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160344. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160345. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160346. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160347. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  160348. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  160349. neighsum += neighsum;
  160350. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  160351. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  160352. membersum = membersum * memberscale + neighsum * neighscale;
  160353. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  160354. inrow += 2;
  160355. }
  160356. }
  160357. /*
  160358. * Downsample pixel values of a single component.
  160359. * This version handles the special case of a full-size component,
  160360. * with smoothing. One row of context is required.
  160361. */
  160362. METHODDEF(void)
  160363. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  160364. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160365. {
  160366. int outrow;
  160367. JDIMENSION colctr;
  160368. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160369. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  160370. INT32 membersum, neighsum, memberscale, neighscale;
  160371. int colsum, lastcolsum, nextcolsum;
  160372. /* Expand input data enough to let all the output samples be generated
  160373. * by the standard loop. Special-casing padded output would be more
  160374. * efficient.
  160375. */
  160376. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  160377. cinfo->image_width, output_cols);
  160378. /* Each of the eight neighbor pixels contributes a fraction SF to the
  160379. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  160380. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  160381. * Also recall that SF = smoothing_factor / 1024.
  160382. */
  160383. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  160384. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  160385. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160386. outptr = output_data[outrow];
  160387. inptr = input_data[outrow];
  160388. above_ptr = input_data[outrow-1];
  160389. below_ptr = input_data[outrow+1];
  160390. /* Special case for first column */
  160391. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  160392. GETJSAMPLE(*inptr);
  160393. membersum = GETJSAMPLE(*inptr++);
  160394. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  160395. GETJSAMPLE(*inptr);
  160396. neighsum = colsum + (colsum - membersum) + nextcolsum;
  160397. membersum = membersum * memberscale + neighsum * neighscale;
  160398. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160399. lastcolsum = colsum; colsum = nextcolsum;
  160400. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  160401. membersum = GETJSAMPLE(*inptr++);
  160402. above_ptr++; below_ptr++;
  160403. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  160404. GETJSAMPLE(*inptr);
  160405. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  160406. membersum = membersum * memberscale + neighsum * neighscale;
  160407. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160408. lastcolsum = colsum; colsum = nextcolsum;
  160409. }
  160410. /* Special case for last column */
  160411. membersum = GETJSAMPLE(*inptr);
  160412. neighsum = lastcolsum + (colsum - membersum) + colsum;
  160413. membersum = membersum * memberscale + neighsum * neighscale;
  160414. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  160415. }
  160416. }
  160417. #endif /* INPUT_SMOOTHING_SUPPORTED */
  160418. /*
  160419. * Module initialization routine for downsampling.
  160420. * Note that we must select a routine for each component.
  160421. */
  160422. GLOBAL(void)
  160423. jinit_downsampler (j_compress_ptr cinfo)
  160424. {
  160425. my_downsample_ptr downsample;
  160426. int ci;
  160427. jpeg_component_info * compptr;
  160428. boolean smoothok = TRUE;
  160429. downsample = (my_downsample_ptr)
  160430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160431. SIZEOF(my_downsampler));
  160432. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  160433. downsample->pub.start_pass = start_pass_downsample;
  160434. downsample->pub.downsample = sep_downsample;
  160435. downsample->pub.need_context_rows = FALSE;
  160436. if (cinfo->CCIR601_sampling)
  160437. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  160438. /* Verify we can handle the sampling factors, and set up method pointers */
  160439. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160440. ci++, compptr++) {
  160441. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  160442. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  160443. #ifdef INPUT_SMOOTHING_SUPPORTED
  160444. if (cinfo->smoothing_factor) {
  160445. downsample->methods[ci] = fullsize_smooth_downsample;
  160446. downsample->pub.need_context_rows = TRUE;
  160447. } else
  160448. #endif
  160449. downsample->methods[ci] = fullsize_downsample;
  160450. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  160451. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  160452. smoothok = FALSE;
  160453. downsample->methods[ci] = h2v1_downsample;
  160454. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  160455. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  160456. #ifdef INPUT_SMOOTHING_SUPPORTED
  160457. if (cinfo->smoothing_factor) {
  160458. downsample->methods[ci] = h2v2_smooth_downsample;
  160459. downsample->pub.need_context_rows = TRUE;
  160460. } else
  160461. #endif
  160462. downsample->methods[ci] = h2v2_downsample;
  160463. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  160464. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  160465. smoothok = FALSE;
  160466. downsample->methods[ci] = int_downsample;
  160467. } else
  160468. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  160469. }
  160470. #ifdef INPUT_SMOOTHING_SUPPORTED
  160471. if (cinfo->smoothing_factor && !smoothok)
  160472. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  160473. #endif
  160474. }
  160475. /********* End of inlined file: jcsample.c *********/
  160476. /********* Start of inlined file: jctrans.c *********/
  160477. #define JPEG_INTERNALS
  160478. /* Forward declarations */
  160479. LOCAL(void) transencode_master_selection
  160480. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  160481. LOCAL(void) transencode_coef_controller
  160482. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  160483. /*
  160484. * Compression initialization for writing raw-coefficient data.
  160485. * Before calling this, all parameters and a data destination must be set up.
  160486. * Call jpeg_finish_compress() to actually write the data.
  160487. *
  160488. * The number of passed virtual arrays must match cinfo->num_components.
  160489. * Note that the virtual arrays need not be filled or even realized at
  160490. * the time write_coefficients is called; indeed, if the virtual arrays
  160491. * were requested from this compression object's memory manager, they
  160492. * typically will be realized during this routine and filled afterwards.
  160493. */
  160494. GLOBAL(void)
  160495. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  160496. {
  160497. if (cinfo->global_state != CSTATE_START)
  160498. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160499. /* Mark all tables to be written */
  160500. jpeg_suppress_tables(cinfo, FALSE);
  160501. /* (Re)initialize error mgr and destination modules */
  160502. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160503. (*cinfo->dest->init_destination) (cinfo);
  160504. /* Perform master selection of active modules */
  160505. transencode_master_selection(cinfo, coef_arrays);
  160506. /* Wait for jpeg_finish_compress() call */
  160507. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  160508. cinfo->global_state = CSTATE_WRCOEFS;
  160509. }
  160510. /*
  160511. * Initialize the compression object with default parameters,
  160512. * then copy from the source object all parameters needed for lossless
  160513. * transcoding. Parameters that can be varied without loss (such as
  160514. * scan script and Huffman optimization) are left in their default states.
  160515. */
  160516. GLOBAL(void)
  160517. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  160518. j_compress_ptr dstinfo)
  160519. {
  160520. JQUANT_TBL ** qtblptr;
  160521. jpeg_component_info *incomp, *outcomp;
  160522. JQUANT_TBL *c_quant, *slot_quant;
  160523. int tblno, ci, coefi;
  160524. /* Safety check to ensure start_compress not called yet. */
  160525. if (dstinfo->global_state != CSTATE_START)
  160526. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  160527. /* Copy fundamental image dimensions */
  160528. dstinfo->image_width = srcinfo->image_width;
  160529. dstinfo->image_height = srcinfo->image_height;
  160530. dstinfo->input_components = srcinfo->num_components;
  160531. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  160532. /* Initialize all parameters to default values */
  160533. jpeg_set_defaults(dstinfo);
  160534. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  160535. * Fix it to get the right header markers for the image colorspace.
  160536. */
  160537. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  160538. dstinfo->data_precision = srcinfo->data_precision;
  160539. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  160540. /* Copy the source's quantization tables. */
  160541. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  160542. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  160543. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  160544. if (*qtblptr == NULL)
  160545. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  160546. MEMCOPY((*qtblptr)->quantval,
  160547. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  160548. SIZEOF((*qtblptr)->quantval));
  160549. (*qtblptr)->sent_table = FALSE;
  160550. }
  160551. }
  160552. /* Copy the source's per-component info.
  160553. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  160554. */
  160555. dstinfo->num_components = srcinfo->num_components;
  160556. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  160557. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  160558. MAX_COMPONENTS);
  160559. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  160560. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  160561. outcomp->component_id = incomp->component_id;
  160562. outcomp->h_samp_factor = incomp->h_samp_factor;
  160563. outcomp->v_samp_factor = incomp->v_samp_factor;
  160564. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  160565. /* Make sure saved quantization table for component matches the qtable
  160566. * slot. If not, the input file re-used this qtable slot.
  160567. * IJG encoder currently cannot duplicate this.
  160568. */
  160569. tblno = outcomp->quant_tbl_no;
  160570. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  160571. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  160572. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  160573. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  160574. c_quant = incomp->quant_table;
  160575. if (c_quant != NULL) {
  160576. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  160577. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  160578. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  160579. }
  160580. }
  160581. /* Note: we do not copy the source's Huffman table assignments;
  160582. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  160583. */
  160584. }
  160585. /* Also copy JFIF version and resolution information, if available.
  160586. * Strictly speaking this isn't "critical" info, but it's nearly
  160587. * always appropriate to copy it if available. In particular,
  160588. * if the application chooses to copy JFIF 1.02 extension markers from
  160589. * the source file, we need to copy the version to make sure we don't
  160590. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  160591. * We will *not*, however, copy version info from mislabeled "2.01" files.
  160592. */
  160593. if (srcinfo->saw_JFIF_marker) {
  160594. if (srcinfo->JFIF_major_version == 1) {
  160595. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  160596. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  160597. }
  160598. dstinfo->density_unit = srcinfo->density_unit;
  160599. dstinfo->X_density = srcinfo->X_density;
  160600. dstinfo->Y_density = srcinfo->Y_density;
  160601. }
  160602. }
  160603. /*
  160604. * Master selection of compression modules for transcoding.
  160605. * This substitutes for jcinit.c's initialization of the full compressor.
  160606. */
  160607. LOCAL(void)
  160608. transencode_master_selection (j_compress_ptr cinfo,
  160609. jvirt_barray_ptr * coef_arrays)
  160610. {
  160611. /* Although we don't actually use input_components for transcoding,
  160612. * jcmaster.c's initial_setup will complain if input_components is 0.
  160613. */
  160614. cinfo->input_components = 1;
  160615. /* Initialize master control (includes parameter checking/processing) */
  160616. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  160617. /* Entropy encoding: either Huffman or arithmetic coding. */
  160618. if (cinfo->arith_code) {
  160619. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  160620. } else {
  160621. if (cinfo->progressive_mode) {
  160622. #ifdef C_PROGRESSIVE_SUPPORTED
  160623. jinit_phuff_encoder(cinfo);
  160624. #else
  160625. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160626. #endif
  160627. } else
  160628. jinit_huff_encoder(cinfo);
  160629. }
  160630. /* We need a special coefficient buffer controller. */
  160631. transencode_coef_controller(cinfo, coef_arrays);
  160632. jinit_marker_writer(cinfo);
  160633. /* We can now tell the memory manager to allocate virtual arrays. */
  160634. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  160635. /* Write the datastream header (SOI, JFIF) immediately.
  160636. * Frame and scan headers are postponed till later.
  160637. * This lets application insert special markers after the SOI.
  160638. */
  160639. (*cinfo->marker->write_file_header) (cinfo);
  160640. }
  160641. /*
  160642. * The rest of this file is a special implementation of the coefficient
  160643. * buffer controller. This is similar to jccoefct.c, but it handles only
  160644. * output from presupplied virtual arrays. Furthermore, we generate any
  160645. * dummy padding blocks on-the-fly rather than expecting them to be present
  160646. * in the arrays.
  160647. */
  160648. /* Private buffer controller object */
  160649. typedef struct {
  160650. struct jpeg_c_coef_controller pub; /* public fields */
  160651. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  160652. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  160653. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  160654. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  160655. /* Virtual block array for each component. */
  160656. jvirt_barray_ptr * whole_image;
  160657. /* Workspace for constructing dummy blocks at right/bottom edges. */
  160658. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  160659. } my_coef_controller2;
  160660. typedef my_coef_controller2 * my_coef_ptr2;
  160661. LOCAL(void)
  160662. start_iMCU_row2 (j_compress_ptr cinfo)
  160663. /* Reset within-iMCU-row counters for a new row */
  160664. {
  160665. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160666. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  160667. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  160668. * But at the bottom of the image, process only what's left.
  160669. */
  160670. if (cinfo->comps_in_scan > 1) {
  160671. coef->MCU_rows_per_iMCU_row = 1;
  160672. } else {
  160673. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  160674. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  160675. else
  160676. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  160677. }
  160678. coef->mcu_ctr = 0;
  160679. coef->MCU_vert_offset = 0;
  160680. }
  160681. /*
  160682. * Initialize for a processing pass.
  160683. */
  160684. METHODDEF(void)
  160685. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160686. {
  160687. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160688. if (pass_mode != JBUF_CRANK_DEST)
  160689. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160690. coef->iMCU_row_num = 0;
  160691. start_iMCU_row2(cinfo);
  160692. }
  160693. /*
  160694. * Process some data.
  160695. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160696. * per call, ie, v_samp_factor block rows for each component in the scan.
  160697. * The data is obtained from the virtual arrays and fed to the entropy coder.
  160698. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  160699. *
  160700. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  160701. */
  160702. METHODDEF(boolean)
  160703. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  160704. {
  160705. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160706. JDIMENSION MCU_col_num; /* index of current MCU within row */
  160707. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  160708. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  160709. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  160710. JDIMENSION start_col;
  160711. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  160712. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  160713. JBLOCKROW buffer_ptr;
  160714. jpeg_component_info *compptr;
  160715. /* Align the virtual buffers for the components used in this scan. */
  160716. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160717. compptr = cinfo->cur_comp_info[ci];
  160718. buffer[ci] = (*cinfo->mem->access_virt_barray)
  160719. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  160720. coef->iMCU_row_num * compptr->v_samp_factor,
  160721. (JDIMENSION) compptr->v_samp_factor, FALSE);
  160722. }
  160723. /* Loop to process one whole iMCU row */
  160724. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  160725. yoffset++) {
  160726. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  160727. MCU_col_num++) {
  160728. /* Construct list of pointers to DCT blocks belonging to this MCU */
  160729. blkn = 0; /* index of current DCT block within MCU */
  160730. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160731. compptr = cinfo->cur_comp_info[ci];
  160732. start_col = MCU_col_num * compptr->MCU_width;
  160733. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  160734. : compptr->last_col_width;
  160735. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  160736. if (coef->iMCU_row_num < last_iMCU_row ||
  160737. yindex+yoffset < compptr->last_row_height) {
  160738. /* Fill in pointers to real blocks in this row */
  160739. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  160740. for (xindex = 0; xindex < blockcnt; xindex++)
  160741. MCU_buffer[blkn++] = buffer_ptr++;
  160742. } else {
  160743. /* At bottom of image, need a whole row of dummy blocks */
  160744. xindex = 0;
  160745. }
  160746. /* Fill in any dummy blocks needed in this row.
  160747. * Dummy blocks are filled in the same way as in jccoefct.c:
  160748. * all zeroes in the AC entries, DC entries equal to previous
  160749. * block's DC value. The init routine has already zeroed the
  160750. * AC entries, so we need only set the DC entries correctly.
  160751. */
  160752. for (; xindex < compptr->MCU_width; xindex++) {
  160753. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  160754. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  160755. blkn++;
  160756. }
  160757. }
  160758. }
  160759. /* Try to write the MCU. */
  160760. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  160761. /* Suspension forced; update state counters and exit */
  160762. coef->MCU_vert_offset = yoffset;
  160763. coef->mcu_ctr = MCU_col_num;
  160764. return FALSE;
  160765. }
  160766. }
  160767. /* Completed an MCU row, but perhaps not an iMCU row */
  160768. coef->mcu_ctr = 0;
  160769. }
  160770. /* Completed the iMCU row, advance counters for next one */
  160771. coef->iMCU_row_num++;
  160772. start_iMCU_row2(cinfo);
  160773. return TRUE;
  160774. }
  160775. /*
  160776. * Initialize coefficient buffer controller.
  160777. *
  160778. * Each passed coefficient array must be the right size for that
  160779. * coefficient: width_in_blocks wide and height_in_blocks high,
  160780. * with unitheight at least v_samp_factor.
  160781. */
  160782. LOCAL(void)
  160783. transencode_coef_controller (j_compress_ptr cinfo,
  160784. jvirt_barray_ptr * coef_arrays)
  160785. {
  160786. my_coef_ptr2 coef;
  160787. JBLOCKROW buffer;
  160788. int i;
  160789. coef = (my_coef_ptr2)
  160790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160791. SIZEOF(my_coef_controller2));
  160792. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  160793. coef->pub.start_pass = start_pass_coef2;
  160794. coef->pub.compress_data = compress_output2;
  160795. /* Save pointer to virtual arrays */
  160796. coef->whole_image = coef_arrays;
  160797. /* Allocate and pre-zero space for dummy DCT blocks. */
  160798. buffer = (JBLOCKROW)
  160799. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160800. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  160801. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  160802. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  160803. coef->dummy_buffer[i] = buffer + i;
  160804. }
  160805. }
  160806. /********* End of inlined file: jctrans.c *********/
  160807. /********* Start of inlined file: jdapistd.c *********/
  160808. #define JPEG_INTERNALS
  160809. /* Forward declarations */
  160810. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  160811. /*
  160812. * Decompression initialization.
  160813. * jpeg_read_header must be completed before calling this.
  160814. *
  160815. * If a multipass operating mode was selected, this will do all but the
  160816. * last pass, and thus may take a great deal of time.
  160817. *
  160818. * Returns FALSE if suspended. The return value need be inspected only if
  160819. * a suspending data source is used.
  160820. */
  160821. GLOBAL(boolean)
  160822. jpeg_start_decompress (j_decompress_ptr cinfo)
  160823. {
  160824. if (cinfo->global_state == DSTATE_READY) {
  160825. /* First call: initialize master control, select active modules */
  160826. jinit_master_decompress(cinfo);
  160827. if (cinfo->buffered_image) {
  160828. /* No more work here; expecting jpeg_start_output next */
  160829. cinfo->global_state = DSTATE_BUFIMAGE;
  160830. return TRUE;
  160831. }
  160832. cinfo->global_state = DSTATE_PRELOAD;
  160833. }
  160834. if (cinfo->global_state == DSTATE_PRELOAD) {
  160835. /* If file has multiple scans, absorb them all into the coef buffer */
  160836. if (cinfo->inputctl->has_multiple_scans) {
  160837. #ifdef D_MULTISCAN_FILES_SUPPORTED
  160838. for (;;) {
  160839. int retcode;
  160840. /* Call progress monitor hook if present */
  160841. if (cinfo->progress != NULL)
  160842. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160843. /* Absorb some more input */
  160844. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  160845. if (retcode == JPEG_SUSPENDED)
  160846. return FALSE;
  160847. if (retcode == JPEG_REACHED_EOI)
  160848. break;
  160849. /* Advance progress counter if appropriate */
  160850. if (cinfo->progress != NULL &&
  160851. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  160852. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  160853. /* jdmaster underestimated number of scans; ratchet up one scan */
  160854. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  160855. }
  160856. }
  160857. }
  160858. #else
  160859. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160860. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  160861. }
  160862. cinfo->output_scan_number = cinfo->input_scan_number;
  160863. } else if (cinfo->global_state != DSTATE_PRESCAN)
  160864. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160865. /* Perform any dummy output passes, and set up for the final pass */
  160866. return output_pass_setup(cinfo);
  160867. }
  160868. /*
  160869. * Set up for an output pass, and perform any dummy pass(es) needed.
  160870. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  160871. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  160872. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  160873. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  160874. */
  160875. LOCAL(boolean)
  160876. output_pass_setup (j_decompress_ptr cinfo)
  160877. {
  160878. if (cinfo->global_state != DSTATE_PRESCAN) {
  160879. /* First call: do pass setup */
  160880. (*cinfo->master->prepare_for_output_pass) (cinfo);
  160881. cinfo->output_scanline = 0;
  160882. cinfo->global_state = DSTATE_PRESCAN;
  160883. }
  160884. /* Loop over any required dummy passes */
  160885. while (cinfo->master->is_dummy_pass) {
  160886. #ifdef QUANT_2PASS_SUPPORTED
  160887. /* Crank through the dummy pass */
  160888. while (cinfo->output_scanline < cinfo->output_height) {
  160889. JDIMENSION last_scanline;
  160890. /* Call progress monitor hook if present */
  160891. if (cinfo->progress != NULL) {
  160892. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160893. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160894. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160895. }
  160896. /* Process some data */
  160897. last_scanline = cinfo->output_scanline;
  160898. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  160899. &cinfo->output_scanline, (JDIMENSION) 0);
  160900. if (cinfo->output_scanline == last_scanline)
  160901. return FALSE; /* No progress made, must suspend */
  160902. }
  160903. /* Finish up dummy pass, and set up for another one */
  160904. (*cinfo->master->finish_output_pass) (cinfo);
  160905. (*cinfo->master->prepare_for_output_pass) (cinfo);
  160906. cinfo->output_scanline = 0;
  160907. #else
  160908. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160909. #endif /* QUANT_2PASS_SUPPORTED */
  160910. }
  160911. /* Ready for application to drive output pass through
  160912. * jpeg_read_scanlines or jpeg_read_raw_data.
  160913. */
  160914. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  160915. return TRUE;
  160916. }
  160917. /*
  160918. * Read some scanlines of data from the JPEG decompressor.
  160919. *
  160920. * The return value will be the number of lines actually read.
  160921. * This may be less than the number requested in several cases,
  160922. * including bottom of image, data source suspension, and operating
  160923. * modes that emit multiple scanlines at a time.
  160924. *
  160925. * Note: we warn about excess calls to jpeg_read_scanlines() since
  160926. * this likely signals an application programmer error. However,
  160927. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  160928. */
  160929. GLOBAL(JDIMENSION)
  160930. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  160931. JDIMENSION max_lines)
  160932. {
  160933. JDIMENSION row_ctr;
  160934. if (cinfo->global_state != DSTATE_SCANNING)
  160935. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160936. if (cinfo->output_scanline >= cinfo->output_height) {
  160937. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160938. return 0;
  160939. }
  160940. /* Call progress monitor hook if present */
  160941. if (cinfo->progress != NULL) {
  160942. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160943. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160944. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160945. }
  160946. /* Process some data */
  160947. row_ctr = 0;
  160948. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  160949. cinfo->output_scanline += row_ctr;
  160950. return row_ctr;
  160951. }
  160952. /*
  160953. * Alternate entry point to read raw data.
  160954. * Processes exactly one iMCU row per call, unless suspended.
  160955. */
  160956. GLOBAL(JDIMENSION)
  160957. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  160958. JDIMENSION max_lines)
  160959. {
  160960. JDIMENSION lines_per_iMCU_row;
  160961. if (cinfo->global_state != DSTATE_RAW_OK)
  160962. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160963. if (cinfo->output_scanline >= cinfo->output_height) {
  160964. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160965. return 0;
  160966. }
  160967. /* Call progress monitor hook if present */
  160968. if (cinfo->progress != NULL) {
  160969. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160970. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160971. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160972. }
  160973. /* Verify that at least one iMCU row can be returned. */
  160974. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  160975. if (max_lines < lines_per_iMCU_row)
  160976. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  160977. /* Decompress directly into user's buffer. */
  160978. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  160979. return 0; /* suspension forced, can do nothing more */
  160980. /* OK, we processed one iMCU row. */
  160981. cinfo->output_scanline += lines_per_iMCU_row;
  160982. return lines_per_iMCU_row;
  160983. }
  160984. /* Additional entry points for buffered-image mode. */
  160985. #ifdef D_MULTISCAN_FILES_SUPPORTED
  160986. /*
  160987. * Initialize for an output pass in buffered-image mode.
  160988. */
  160989. GLOBAL(boolean)
  160990. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  160991. {
  160992. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  160993. cinfo->global_state != DSTATE_PRESCAN)
  160994. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160995. /* Limit scan number to valid range */
  160996. if (scan_number <= 0)
  160997. scan_number = 1;
  160998. if (cinfo->inputctl->eoi_reached &&
  160999. scan_number > cinfo->input_scan_number)
  161000. scan_number = cinfo->input_scan_number;
  161001. cinfo->output_scan_number = scan_number;
  161002. /* Perform any dummy output passes, and set up for the real pass */
  161003. return output_pass_setup(cinfo);
  161004. }
  161005. /*
  161006. * Finish up after an output pass in buffered-image mode.
  161007. *
  161008. * Returns FALSE if suspended. The return value need be inspected only if
  161009. * a suspending data source is used.
  161010. */
  161011. GLOBAL(boolean)
  161012. jpeg_finish_output (j_decompress_ptr cinfo)
  161013. {
  161014. if ((cinfo->global_state == DSTATE_SCANNING ||
  161015. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  161016. /* Terminate this pass. */
  161017. /* We do not require the whole pass to have been completed. */
  161018. (*cinfo->master->finish_output_pass) (cinfo);
  161019. cinfo->global_state = DSTATE_BUFPOST;
  161020. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  161021. /* BUFPOST = repeat call after a suspension, anything else is error */
  161022. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161023. }
  161024. /* Read markers looking for SOS or EOI */
  161025. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  161026. ! cinfo->inputctl->eoi_reached) {
  161027. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161028. return FALSE; /* Suspend, come back later */
  161029. }
  161030. cinfo->global_state = DSTATE_BUFIMAGE;
  161031. return TRUE;
  161032. }
  161033. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161034. /********* End of inlined file: jdapistd.c *********/
  161035. /********* Start of inlined file: jdapimin.c *********/
  161036. #define JPEG_INTERNALS
  161037. /*
  161038. * Initialization of a JPEG decompression object.
  161039. * The error manager must already be set up (in case memory manager fails).
  161040. */
  161041. GLOBAL(void)
  161042. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  161043. {
  161044. int i;
  161045. /* Guard against version mismatches between library and caller. */
  161046. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161047. if (version != JPEG_LIB_VERSION)
  161048. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161049. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  161050. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161051. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  161052. /* For debugging purposes, we zero the whole master structure.
  161053. * But the application has already set the err pointer, and may have set
  161054. * client_data, so we have to save and restore those fields.
  161055. * Note: if application hasn't set client_data, tools like Purify may
  161056. * complain here.
  161057. */
  161058. {
  161059. struct jpeg_error_mgr * err = cinfo->err;
  161060. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161061. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  161062. cinfo->err = err;
  161063. cinfo->client_data = client_data;
  161064. }
  161065. cinfo->is_decompressor = TRUE;
  161066. /* Initialize a memory manager instance for this object */
  161067. jinit_memory_mgr((j_common_ptr) cinfo);
  161068. /* Zero out pointers to permanent structures. */
  161069. cinfo->progress = NULL;
  161070. cinfo->src = NULL;
  161071. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161072. cinfo->quant_tbl_ptrs[i] = NULL;
  161073. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161074. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161075. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161076. }
  161077. /* Initialize marker processor so application can override methods
  161078. * for COM, APPn markers before calling jpeg_read_header.
  161079. */
  161080. cinfo->marker_list = NULL;
  161081. jinit_marker_reader(cinfo);
  161082. /* And initialize the overall input controller. */
  161083. jinit_input_controller(cinfo);
  161084. /* OK, I'm ready */
  161085. cinfo->global_state = DSTATE_START;
  161086. }
  161087. /*
  161088. * Destruction of a JPEG decompression object
  161089. */
  161090. GLOBAL(void)
  161091. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  161092. {
  161093. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161094. }
  161095. /*
  161096. * Abort processing of a JPEG decompression operation,
  161097. * but don't destroy the object itself.
  161098. */
  161099. GLOBAL(void)
  161100. jpeg_abort_decompress (j_decompress_ptr cinfo)
  161101. {
  161102. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161103. }
  161104. /*
  161105. * Set default decompression parameters.
  161106. */
  161107. LOCAL(void)
  161108. default_decompress_parms (j_decompress_ptr cinfo)
  161109. {
  161110. /* Guess the input colorspace, and set output colorspace accordingly. */
  161111. /* (Wish JPEG committee had provided a real way to specify this...) */
  161112. /* Note application may override our guesses. */
  161113. switch (cinfo->num_components) {
  161114. case 1:
  161115. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  161116. cinfo->out_color_space = JCS_GRAYSCALE;
  161117. break;
  161118. case 3:
  161119. if (cinfo->saw_JFIF_marker) {
  161120. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  161121. } else if (cinfo->saw_Adobe_marker) {
  161122. switch (cinfo->Adobe_transform) {
  161123. case 0:
  161124. cinfo->jpeg_color_space = JCS_RGB;
  161125. break;
  161126. case 1:
  161127. cinfo->jpeg_color_space = JCS_YCbCr;
  161128. break;
  161129. default:
  161130. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161131. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161132. break;
  161133. }
  161134. } else {
  161135. /* Saw no special markers, try to guess from the component IDs */
  161136. int cid0 = cinfo->comp_info[0].component_id;
  161137. int cid1 = cinfo->comp_info[1].component_id;
  161138. int cid2 = cinfo->comp_info[2].component_id;
  161139. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  161140. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  161141. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  161142. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  161143. else {
  161144. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  161145. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161146. }
  161147. }
  161148. /* Always guess RGB is proper output colorspace. */
  161149. cinfo->out_color_space = JCS_RGB;
  161150. break;
  161151. case 4:
  161152. if (cinfo->saw_Adobe_marker) {
  161153. switch (cinfo->Adobe_transform) {
  161154. case 0:
  161155. cinfo->jpeg_color_space = JCS_CMYK;
  161156. break;
  161157. case 2:
  161158. cinfo->jpeg_color_space = JCS_YCCK;
  161159. break;
  161160. default:
  161161. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161162. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  161163. break;
  161164. }
  161165. } else {
  161166. /* No special markers, assume straight CMYK. */
  161167. cinfo->jpeg_color_space = JCS_CMYK;
  161168. }
  161169. cinfo->out_color_space = JCS_CMYK;
  161170. break;
  161171. default:
  161172. cinfo->jpeg_color_space = JCS_UNKNOWN;
  161173. cinfo->out_color_space = JCS_UNKNOWN;
  161174. break;
  161175. }
  161176. /* Set defaults for other decompression parameters. */
  161177. cinfo->scale_num = 1; /* 1:1 scaling */
  161178. cinfo->scale_denom = 1;
  161179. cinfo->output_gamma = 1.0;
  161180. cinfo->buffered_image = FALSE;
  161181. cinfo->raw_data_out = FALSE;
  161182. cinfo->dct_method = JDCT_DEFAULT;
  161183. cinfo->do_fancy_upsampling = TRUE;
  161184. cinfo->do_block_smoothing = TRUE;
  161185. cinfo->quantize_colors = FALSE;
  161186. /* We set these in case application only sets quantize_colors. */
  161187. cinfo->dither_mode = JDITHER_FS;
  161188. #ifdef QUANT_2PASS_SUPPORTED
  161189. cinfo->two_pass_quantize = TRUE;
  161190. #else
  161191. cinfo->two_pass_quantize = FALSE;
  161192. #endif
  161193. cinfo->desired_number_of_colors = 256;
  161194. cinfo->colormap = NULL;
  161195. /* Initialize for no mode change in buffered-image mode. */
  161196. cinfo->enable_1pass_quant = FALSE;
  161197. cinfo->enable_external_quant = FALSE;
  161198. cinfo->enable_2pass_quant = FALSE;
  161199. }
  161200. /*
  161201. * Decompression startup: read start of JPEG datastream to see what's there.
  161202. * Need only initialize JPEG object and supply a data source before calling.
  161203. *
  161204. * This routine will read as far as the first SOS marker (ie, actual start of
  161205. * compressed data), and will save all tables and parameters in the JPEG
  161206. * object. It will also initialize the decompression parameters to default
  161207. * values, and finally return JPEG_HEADER_OK. On return, the application may
  161208. * adjust the decompression parameters and then call jpeg_start_decompress.
  161209. * (Or, if the application only wanted to determine the image parameters,
  161210. * the data need not be decompressed. In that case, call jpeg_abort or
  161211. * jpeg_destroy to release any temporary space.)
  161212. * If an abbreviated (tables only) datastream is presented, the routine will
  161213. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  161214. * re-use the JPEG object to read the abbreviated image datastream(s).
  161215. * It is unnecessary (but OK) to call jpeg_abort in this case.
  161216. * The JPEG_SUSPENDED return code only occurs if the data source module
  161217. * requests suspension of the decompressor. In this case the application
  161218. * should load more source data and then re-call jpeg_read_header to resume
  161219. * processing.
  161220. * If a non-suspending data source is used and require_image is TRUE, then the
  161221. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  161222. *
  161223. * This routine is now just a front end to jpeg_consume_input, with some
  161224. * extra error checking.
  161225. */
  161226. GLOBAL(int)
  161227. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  161228. {
  161229. int retcode;
  161230. if (cinfo->global_state != DSTATE_START &&
  161231. cinfo->global_state != DSTATE_INHEADER)
  161232. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161233. retcode = jpeg_consume_input(cinfo);
  161234. switch (retcode) {
  161235. case JPEG_REACHED_SOS:
  161236. retcode = JPEG_HEADER_OK;
  161237. break;
  161238. case JPEG_REACHED_EOI:
  161239. if (require_image) /* Complain if application wanted an image */
  161240. ERREXIT(cinfo, JERR_NO_IMAGE);
  161241. /* Reset to start state; it would be safer to require the application to
  161242. * call jpeg_abort, but we can't change it now for compatibility reasons.
  161243. * A side effect is to free any temporary memory (there shouldn't be any).
  161244. */
  161245. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  161246. retcode = JPEG_HEADER_TABLES_ONLY;
  161247. break;
  161248. case JPEG_SUSPENDED:
  161249. /* no work */
  161250. break;
  161251. }
  161252. return retcode;
  161253. }
  161254. /*
  161255. * Consume data in advance of what the decompressor requires.
  161256. * This can be called at any time once the decompressor object has
  161257. * been created and a data source has been set up.
  161258. *
  161259. * This routine is essentially a state machine that handles a couple
  161260. * of critical state-transition actions, namely initial setup and
  161261. * transition from header scanning to ready-for-start_decompress.
  161262. * All the actual input is done via the input controller's consume_input
  161263. * method.
  161264. */
  161265. GLOBAL(int)
  161266. jpeg_consume_input (j_decompress_ptr cinfo)
  161267. {
  161268. int retcode = JPEG_SUSPENDED;
  161269. /* NB: every possible DSTATE value should be listed in this switch */
  161270. switch (cinfo->global_state) {
  161271. case DSTATE_START:
  161272. /* Start-of-datastream actions: reset appropriate modules */
  161273. (*cinfo->inputctl->reset_input_controller) (cinfo);
  161274. /* Initialize application's data source module */
  161275. (*cinfo->src->init_source) (cinfo);
  161276. cinfo->global_state = DSTATE_INHEADER;
  161277. /*FALLTHROUGH*/
  161278. case DSTATE_INHEADER:
  161279. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161280. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  161281. /* Set up default parameters based on header data */
  161282. default_decompress_parms(cinfo);
  161283. /* Set global state: ready for start_decompress */
  161284. cinfo->global_state = DSTATE_READY;
  161285. }
  161286. break;
  161287. case DSTATE_READY:
  161288. /* Can't advance past first SOS until start_decompress is called */
  161289. retcode = JPEG_REACHED_SOS;
  161290. break;
  161291. case DSTATE_PRELOAD:
  161292. case DSTATE_PRESCAN:
  161293. case DSTATE_SCANNING:
  161294. case DSTATE_RAW_OK:
  161295. case DSTATE_BUFIMAGE:
  161296. case DSTATE_BUFPOST:
  161297. case DSTATE_STOPPING:
  161298. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161299. break;
  161300. default:
  161301. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161302. }
  161303. return retcode;
  161304. }
  161305. /*
  161306. * Have we finished reading the input file?
  161307. */
  161308. GLOBAL(boolean)
  161309. jpeg_input_complete (j_decompress_ptr cinfo)
  161310. {
  161311. /* Check for valid jpeg object */
  161312. if (cinfo->global_state < DSTATE_START ||
  161313. cinfo->global_state > DSTATE_STOPPING)
  161314. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161315. return cinfo->inputctl->eoi_reached;
  161316. }
  161317. /*
  161318. * Is there more than one scan?
  161319. */
  161320. GLOBAL(boolean)
  161321. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  161322. {
  161323. /* Only valid after jpeg_read_header completes */
  161324. if (cinfo->global_state < DSTATE_READY ||
  161325. cinfo->global_state > DSTATE_STOPPING)
  161326. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161327. return cinfo->inputctl->has_multiple_scans;
  161328. }
  161329. /*
  161330. * Finish JPEG decompression.
  161331. *
  161332. * This will normally just verify the file trailer and release temp storage.
  161333. *
  161334. * Returns FALSE if suspended. The return value need be inspected only if
  161335. * a suspending data source is used.
  161336. */
  161337. GLOBAL(boolean)
  161338. jpeg_finish_decompress (j_decompress_ptr cinfo)
  161339. {
  161340. if ((cinfo->global_state == DSTATE_SCANNING ||
  161341. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  161342. /* Terminate final pass of non-buffered mode */
  161343. if (cinfo->output_scanline < cinfo->output_height)
  161344. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161345. (*cinfo->master->finish_output_pass) (cinfo);
  161346. cinfo->global_state = DSTATE_STOPPING;
  161347. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  161348. /* Finishing after a buffered-image operation */
  161349. cinfo->global_state = DSTATE_STOPPING;
  161350. } else if (cinfo->global_state != DSTATE_STOPPING) {
  161351. /* STOPPING = repeat call after a suspension, anything else is error */
  161352. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161353. }
  161354. /* Read until EOI */
  161355. while (! cinfo->inputctl->eoi_reached) {
  161356. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161357. return FALSE; /* Suspend, come back later */
  161358. }
  161359. /* Do final cleanup */
  161360. (*cinfo->src->term_source) (cinfo);
  161361. /* We can use jpeg_abort to release memory and reset global_state */
  161362. jpeg_abort((j_common_ptr) cinfo);
  161363. return TRUE;
  161364. }
  161365. /********* End of inlined file: jdapimin.c *********/
  161366. /********* Start of inlined file: jdatasrc.c *********/
  161367. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  161368. /********* Start of inlined file: jerror.h *********/
  161369. /*
  161370. * To define the enum list of message codes, include this file without
  161371. * defining macro JMESSAGE. To create a message string table, include it
  161372. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161373. */
  161374. #ifndef JMESSAGE
  161375. #ifndef JERROR_H
  161376. /* First time through, define the enum list */
  161377. #define JMAKE_ENUM_LIST
  161378. #else
  161379. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161380. #define JMESSAGE(code,string)
  161381. #endif /* JERROR_H */
  161382. #endif /* JMESSAGE */
  161383. #ifdef JMAKE_ENUM_LIST
  161384. typedef enum {
  161385. #define JMESSAGE(code,string) code ,
  161386. #endif /* JMAKE_ENUM_LIST */
  161387. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161388. /* For maintenance convenience, list is alphabetical by message code name */
  161389. JMESSAGE(JERR_ARITH_NOTIMPL,
  161390. "Sorry, there are legal restrictions on arithmetic coding")
  161391. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161392. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161393. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161394. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161395. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161396. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161397. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161398. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161399. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161400. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161401. JMESSAGE(JERR_BAD_LIB_VERSION,
  161402. "Wrong JPEG library version: library is %d, caller expects %d")
  161403. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161404. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161405. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161406. JMESSAGE(JERR_BAD_PROGRESSION,
  161407. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161408. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161409. "Invalid progressive parameters at scan script entry %d")
  161410. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161411. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161412. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161413. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161414. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161415. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161416. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161417. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161418. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161419. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161420. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161421. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161422. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161423. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161424. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161425. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161426. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161427. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161428. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161429. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161430. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161431. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161432. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161433. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161434. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161435. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161436. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161437. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161438. "Cannot transcode due to multiple use of quantization table %d")
  161439. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161440. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161441. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161442. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161443. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161444. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161445. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161446. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161447. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161448. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161449. JMESSAGE(JERR_QUANT_COMPONENTS,
  161450. "Cannot quantize more than %d color components")
  161451. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161452. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161453. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161454. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161455. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161456. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161457. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161458. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161459. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161460. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161461. JMESSAGE(JERR_TFILE_WRITE,
  161462. "Write failed on temporary file --- out of disk space?")
  161463. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161464. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161465. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161466. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161467. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161468. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161469. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161470. JMESSAGE(JMSG_VERSION, JVERSION)
  161471. JMESSAGE(JTRC_16BIT_TABLES,
  161472. "Caution: quantization tables are too coarse for baseline JPEG")
  161473. JMESSAGE(JTRC_ADOBE,
  161474. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161475. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161476. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161477. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161478. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161479. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161480. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161481. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161482. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161483. JMESSAGE(JTRC_EOI, "End Of Image")
  161484. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161485. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161486. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161487. "Warning: thumbnail image size does not match data length %u")
  161488. JMESSAGE(JTRC_JFIF_EXTENSION,
  161489. "JFIF extension marker: type 0x%02x, length %u")
  161490. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161491. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161492. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161493. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161494. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161495. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161496. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161497. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161498. JMESSAGE(JTRC_RST, "RST%d")
  161499. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161500. "Smoothing not supported with nonstandard sampling ratios")
  161501. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161502. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161503. JMESSAGE(JTRC_SOI, "Start of Image")
  161504. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161505. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161506. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161507. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161508. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161509. JMESSAGE(JTRC_THUMB_JPEG,
  161510. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161511. JMESSAGE(JTRC_THUMB_PALETTE,
  161512. "JFIF extension marker: palette thumbnail image, length %u")
  161513. JMESSAGE(JTRC_THUMB_RGB,
  161514. "JFIF extension marker: RGB thumbnail image, length %u")
  161515. JMESSAGE(JTRC_UNKNOWN_IDS,
  161516. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161517. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161518. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161519. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161520. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161521. "Inconsistent progression sequence for component %d coefficient %d")
  161522. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161523. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161524. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161525. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161526. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161527. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161528. JMESSAGE(JWRN_MUST_RESYNC,
  161529. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161530. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161531. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161532. #ifdef JMAKE_ENUM_LIST
  161533. JMSG_LASTMSGCODE
  161534. } J_MESSAGE_CODE;
  161535. #undef JMAKE_ENUM_LIST
  161536. #endif /* JMAKE_ENUM_LIST */
  161537. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161538. #undef JMESSAGE
  161539. #ifndef JERROR_H
  161540. #define JERROR_H
  161541. /* Macros to simplify using the error and trace message stuff */
  161542. /* The first parameter is either type of cinfo pointer */
  161543. /* Fatal errors (print message and exit) */
  161544. #define ERREXIT(cinfo,code) \
  161545. ((cinfo)->err->msg_code = (code), \
  161546. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161547. #define ERREXIT1(cinfo,code,p1) \
  161548. ((cinfo)->err->msg_code = (code), \
  161549. (cinfo)->err->msg_parm.i[0] = (p1), \
  161550. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161551. #define ERREXIT2(cinfo,code,p1,p2) \
  161552. ((cinfo)->err->msg_code = (code), \
  161553. (cinfo)->err->msg_parm.i[0] = (p1), \
  161554. (cinfo)->err->msg_parm.i[1] = (p2), \
  161555. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161556. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161557. ((cinfo)->err->msg_code = (code), \
  161558. (cinfo)->err->msg_parm.i[0] = (p1), \
  161559. (cinfo)->err->msg_parm.i[1] = (p2), \
  161560. (cinfo)->err->msg_parm.i[2] = (p3), \
  161561. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161562. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161563. ((cinfo)->err->msg_code = (code), \
  161564. (cinfo)->err->msg_parm.i[0] = (p1), \
  161565. (cinfo)->err->msg_parm.i[1] = (p2), \
  161566. (cinfo)->err->msg_parm.i[2] = (p3), \
  161567. (cinfo)->err->msg_parm.i[3] = (p4), \
  161568. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161569. #define ERREXITS(cinfo,code,str) \
  161570. ((cinfo)->err->msg_code = (code), \
  161571. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161572. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161573. #define MAKESTMT(stuff) do { stuff } while (0)
  161574. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161575. #define WARNMS(cinfo,code) \
  161576. ((cinfo)->err->msg_code = (code), \
  161577. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161578. #define WARNMS1(cinfo,code,p1) \
  161579. ((cinfo)->err->msg_code = (code), \
  161580. (cinfo)->err->msg_parm.i[0] = (p1), \
  161581. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161582. #define WARNMS2(cinfo,code,p1,p2) \
  161583. ((cinfo)->err->msg_code = (code), \
  161584. (cinfo)->err->msg_parm.i[0] = (p1), \
  161585. (cinfo)->err->msg_parm.i[1] = (p2), \
  161586. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161587. /* Informational/debugging messages */
  161588. #define TRACEMS(cinfo,lvl,code) \
  161589. ((cinfo)->err->msg_code = (code), \
  161590. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161591. #define TRACEMS1(cinfo,lvl,code,p1) \
  161592. ((cinfo)->err->msg_code = (code), \
  161593. (cinfo)->err->msg_parm.i[0] = (p1), \
  161594. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161595. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161596. ((cinfo)->err->msg_code = (code), \
  161597. (cinfo)->err->msg_parm.i[0] = (p1), \
  161598. (cinfo)->err->msg_parm.i[1] = (p2), \
  161599. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161600. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161601. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161602. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161603. (cinfo)->err->msg_code = (code); \
  161604. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161605. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161606. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161607. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161608. (cinfo)->err->msg_code = (code); \
  161609. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161610. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161611. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161612. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161613. _mp[4] = (p5); \
  161614. (cinfo)->err->msg_code = (code); \
  161615. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161616. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161617. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161618. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161619. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161620. (cinfo)->err->msg_code = (code); \
  161621. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161622. #define TRACEMSS(cinfo,lvl,code,str) \
  161623. ((cinfo)->err->msg_code = (code), \
  161624. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161625. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161626. #endif /* JERROR_H */
  161627. /********* End of inlined file: jerror.h *********/
  161628. /* Expanded data source object for stdio input */
  161629. typedef struct {
  161630. struct jpeg_source_mgr pub; /* public fields */
  161631. FILE * infile; /* source stream */
  161632. JOCTET * buffer; /* start of buffer */
  161633. boolean start_of_file; /* have we gotten any data yet? */
  161634. } my_source_mgr;
  161635. typedef my_source_mgr * my_src_ptr;
  161636. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  161637. /*
  161638. * Initialize source --- called by jpeg_read_header
  161639. * before any data is actually read.
  161640. */
  161641. METHODDEF(void)
  161642. init_source (j_decompress_ptr cinfo)
  161643. {
  161644. my_src_ptr src = (my_src_ptr) cinfo->src;
  161645. /* We reset the empty-input-file flag for each image,
  161646. * but we don't clear the input buffer.
  161647. * This is correct behavior for reading a series of images from one source.
  161648. */
  161649. src->start_of_file = TRUE;
  161650. }
  161651. /*
  161652. * Fill the input buffer --- called whenever buffer is emptied.
  161653. *
  161654. * In typical applications, this should read fresh data into the buffer
  161655. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  161656. * reset the pointer & count to the start of the buffer, and return TRUE
  161657. * indicating that the buffer has been reloaded. It is not necessary to
  161658. * fill the buffer entirely, only to obtain at least one more byte.
  161659. *
  161660. * There is no such thing as an EOF return. If the end of the file has been
  161661. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  161662. * the buffer. In most cases, generating a warning message and inserting a
  161663. * fake EOI marker is the best course of action --- this will allow the
  161664. * decompressor to output however much of the image is there. However,
  161665. * the resulting error message is misleading if the real problem is an empty
  161666. * input file, so we handle that case specially.
  161667. *
  161668. * In applications that need to be able to suspend compression due to input
  161669. * not being available yet, a FALSE return indicates that no more data can be
  161670. * obtained right now, but more may be forthcoming later. In this situation,
  161671. * the decompressor will return to its caller (with an indication of the
  161672. * number of scanlines it has read, if any). The application should resume
  161673. * decompression after it has loaded more data into the input buffer. Note
  161674. * that there are substantial restrictions on the use of suspension --- see
  161675. * the documentation.
  161676. *
  161677. * When suspending, the decompressor will back up to a convenient restart point
  161678. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  161679. * indicate where the restart point will be if the current call returns FALSE.
  161680. * Data beyond this point must be rescanned after resumption, so move it to
  161681. * the front of the buffer rather than discarding it.
  161682. */
  161683. METHODDEF(boolean)
  161684. fill_input_buffer (j_decompress_ptr cinfo)
  161685. {
  161686. my_src_ptr src = (my_src_ptr) cinfo->src;
  161687. size_t nbytes;
  161688. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  161689. if (nbytes <= 0) {
  161690. if (src->start_of_file) /* Treat empty input file as fatal error */
  161691. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  161692. WARNMS(cinfo, JWRN_JPEG_EOF);
  161693. /* Insert a fake EOI marker */
  161694. src->buffer[0] = (JOCTET) 0xFF;
  161695. src->buffer[1] = (JOCTET) JPEG_EOI;
  161696. nbytes = 2;
  161697. }
  161698. src->pub.next_input_byte = src->buffer;
  161699. src->pub.bytes_in_buffer = nbytes;
  161700. src->start_of_file = FALSE;
  161701. return TRUE;
  161702. }
  161703. /*
  161704. * Skip data --- used to skip over a potentially large amount of
  161705. * uninteresting data (such as an APPn marker).
  161706. *
  161707. * Writers of suspendable-input applications must note that skip_input_data
  161708. * is not granted the right to give a suspension return. If the skip extends
  161709. * beyond the data currently in the buffer, the buffer can be marked empty so
  161710. * that the next read will cause a fill_input_buffer call that can suspend.
  161711. * Arranging for additional bytes to be discarded before reloading the input
  161712. * buffer is the application writer's problem.
  161713. */
  161714. METHODDEF(void)
  161715. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  161716. {
  161717. my_src_ptr src = (my_src_ptr) cinfo->src;
  161718. /* Just a dumb implementation for now. Could use fseek() except
  161719. * it doesn't work on pipes. Not clear that being smart is worth
  161720. * any trouble anyway --- large skips are infrequent.
  161721. */
  161722. if (num_bytes > 0) {
  161723. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  161724. num_bytes -= (long) src->pub.bytes_in_buffer;
  161725. (void) fill_input_buffer(cinfo);
  161726. /* note we assume that fill_input_buffer will never return FALSE,
  161727. * so suspension need not be handled.
  161728. */
  161729. }
  161730. src->pub.next_input_byte += (size_t) num_bytes;
  161731. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  161732. }
  161733. }
  161734. /*
  161735. * An additional method that can be provided by data source modules is the
  161736. * resync_to_restart method for error recovery in the presence of RST markers.
  161737. * For the moment, this source module just uses the default resync method
  161738. * provided by the JPEG library. That method assumes that no backtracking
  161739. * is possible.
  161740. */
  161741. /*
  161742. * Terminate source --- called by jpeg_finish_decompress
  161743. * after all data has been read. Often a no-op.
  161744. *
  161745. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  161746. * application must deal with any cleanup that should happen even
  161747. * for error exit.
  161748. */
  161749. METHODDEF(void)
  161750. term_source (j_decompress_ptr cinfo)
  161751. {
  161752. /* no work necessary here */
  161753. }
  161754. /*
  161755. * Prepare for input from a stdio stream.
  161756. * The caller must have already opened the stream, and is responsible
  161757. * for closing it after finishing decompression.
  161758. */
  161759. GLOBAL(void)
  161760. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  161761. {
  161762. my_src_ptr src;
  161763. /* The source object and input buffer are made permanent so that a series
  161764. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  161765. * only before the first one. (If we discarded the buffer at the end of
  161766. * one image, we'd likely lose the start of the next one.)
  161767. * This makes it unsafe to use this manager and a different source
  161768. * manager serially with the same JPEG object. Caveat programmer.
  161769. */
  161770. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  161771. cinfo->src = (struct jpeg_source_mgr *)
  161772. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161773. SIZEOF(my_source_mgr));
  161774. src = (my_src_ptr) cinfo->src;
  161775. src->buffer = (JOCTET *)
  161776. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161777. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  161778. }
  161779. src = (my_src_ptr) cinfo->src;
  161780. src->pub.init_source = init_source;
  161781. src->pub.fill_input_buffer = fill_input_buffer;
  161782. src->pub.skip_input_data = skip_input_data;
  161783. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  161784. src->pub.term_source = term_source;
  161785. src->infile = infile;
  161786. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  161787. src->pub.next_input_byte = NULL; /* until buffer loaded */
  161788. }
  161789. /********* End of inlined file: jdatasrc.c *********/
  161790. /********* Start of inlined file: jdcoefct.c *********/
  161791. #define JPEG_INTERNALS
  161792. /* Block smoothing is only applicable for progressive JPEG, so: */
  161793. #ifndef D_PROGRESSIVE_SUPPORTED
  161794. #undef BLOCK_SMOOTHING_SUPPORTED
  161795. #endif
  161796. /* Private buffer controller object */
  161797. typedef struct {
  161798. struct jpeg_d_coef_controller pub; /* public fields */
  161799. /* These variables keep track of the current location of the input side. */
  161800. /* cinfo->input_iMCU_row is also used for this. */
  161801. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  161802. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161803. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161804. /* The output side's location is represented by cinfo->output_iMCU_row. */
  161805. /* In single-pass modes, it's sufficient to buffer just one MCU.
  161806. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  161807. * and let the entropy decoder write into that workspace each time.
  161808. * (On 80x86, the workspace is FAR even though it's not really very big;
  161809. * this is to keep the module interfaces unchanged when a large coefficient
  161810. * buffer is necessary.)
  161811. * In multi-pass modes, this array points to the current MCU's blocks
  161812. * within the virtual arrays; it is used only by the input side.
  161813. */
  161814. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  161815. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161816. /* In multi-pass modes, we need a virtual block array for each component. */
  161817. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161818. #endif
  161819. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161820. /* When doing block smoothing, we latch coefficient Al values here */
  161821. int * coef_bits_latch;
  161822. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  161823. #endif
  161824. } my_coef_controller3;
  161825. typedef my_coef_controller3 * my_coef_ptr3;
  161826. /* Forward declarations */
  161827. METHODDEF(int) decompress_onepass
  161828. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161829. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161830. METHODDEF(int) decompress_data
  161831. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161832. #endif
  161833. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161834. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  161835. METHODDEF(int) decompress_smooth_data
  161836. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161837. #endif
  161838. LOCAL(void)
  161839. start_iMCU_row3 (j_decompress_ptr cinfo)
  161840. /* Reset within-iMCU-row counters for a new row (input side) */
  161841. {
  161842. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161843. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161844. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161845. * But at the bottom of the image, process only what's left.
  161846. */
  161847. if (cinfo->comps_in_scan > 1) {
  161848. coef->MCU_rows_per_iMCU_row = 1;
  161849. } else {
  161850. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  161851. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161852. else
  161853. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161854. }
  161855. coef->MCU_ctr = 0;
  161856. coef->MCU_vert_offset = 0;
  161857. }
  161858. /*
  161859. * Initialize for an input processing pass.
  161860. */
  161861. METHODDEF(void)
  161862. start_input_pass (j_decompress_ptr cinfo)
  161863. {
  161864. cinfo->input_iMCU_row = 0;
  161865. start_iMCU_row3(cinfo);
  161866. }
  161867. /*
  161868. * Initialize for an output processing pass.
  161869. */
  161870. METHODDEF(void)
  161871. start_output_pass (j_decompress_ptr cinfo)
  161872. {
  161873. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161874. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161875. /* If multipass, check to see whether to use block smoothing on this pass */
  161876. if (coef->pub.coef_arrays != NULL) {
  161877. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  161878. coef->pub.decompress_data = decompress_smooth_data;
  161879. else
  161880. coef->pub.decompress_data = decompress_data;
  161881. }
  161882. #endif
  161883. cinfo->output_iMCU_row = 0;
  161884. }
  161885. /*
  161886. * Decompress and return some data in the single-pass case.
  161887. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  161888. * Input and output must run in lockstep since we have only a one-MCU buffer.
  161889. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  161890. *
  161891. * NB: output_buf contains a plane for each component in image,
  161892. * which we index according to the component's SOF position.
  161893. */
  161894. METHODDEF(int)
  161895. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  161896. {
  161897. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161898. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161899. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161900. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161901. int blkn, ci, xindex, yindex, yoffset, useful_width;
  161902. JSAMPARRAY output_ptr;
  161903. JDIMENSION start_col, output_col;
  161904. jpeg_component_info *compptr;
  161905. inverse_DCT_method_ptr inverse_DCT;
  161906. /* Loop to process as much as one whole iMCU row */
  161907. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161908. yoffset++) {
  161909. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  161910. MCU_col_num++) {
  161911. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  161912. jzero_far((void FAR *) coef->MCU_buffer[0],
  161913. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  161914. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  161915. /* Suspension forced; update state counters and exit */
  161916. coef->MCU_vert_offset = yoffset;
  161917. coef->MCU_ctr = MCU_col_num;
  161918. return JPEG_SUSPENDED;
  161919. }
  161920. /* Determine where data should go in output_buf and do the IDCT thing.
  161921. * We skip dummy blocks at the right and bottom edges (but blkn gets
  161922. * incremented past them!). Note the inner loop relies on having
  161923. * allocated the MCU_buffer[] blocks sequentially.
  161924. */
  161925. blkn = 0; /* index of current DCT block within MCU */
  161926. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161927. compptr = cinfo->cur_comp_info[ci];
  161928. /* Don't bother to IDCT an uninteresting component. */
  161929. if (! compptr->component_needed) {
  161930. blkn += compptr->MCU_blocks;
  161931. continue;
  161932. }
  161933. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  161934. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161935. : compptr->last_col_width;
  161936. output_ptr = output_buf[compptr->component_index] +
  161937. yoffset * compptr->DCT_scaled_size;
  161938. start_col = MCU_col_num * compptr->MCU_sample_width;
  161939. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161940. if (cinfo->input_iMCU_row < last_iMCU_row ||
  161941. yoffset+yindex < compptr->last_row_height) {
  161942. output_col = start_col;
  161943. for (xindex = 0; xindex < useful_width; xindex++) {
  161944. (*inverse_DCT) (cinfo, compptr,
  161945. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  161946. output_ptr, output_col);
  161947. output_col += compptr->DCT_scaled_size;
  161948. }
  161949. }
  161950. blkn += compptr->MCU_width;
  161951. output_ptr += compptr->DCT_scaled_size;
  161952. }
  161953. }
  161954. }
  161955. /* Completed an MCU row, but perhaps not an iMCU row */
  161956. coef->MCU_ctr = 0;
  161957. }
  161958. /* Completed the iMCU row, advance counters for next one */
  161959. cinfo->output_iMCU_row++;
  161960. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  161961. start_iMCU_row3(cinfo);
  161962. return JPEG_ROW_COMPLETED;
  161963. }
  161964. /* Completed the scan */
  161965. (*cinfo->inputctl->finish_input_pass) (cinfo);
  161966. return JPEG_SCAN_COMPLETED;
  161967. }
  161968. /*
  161969. * Dummy consume-input routine for single-pass operation.
  161970. */
  161971. METHODDEF(int)
  161972. dummy_consume_data (j_decompress_ptr cinfo)
  161973. {
  161974. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  161975. }
  161976. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161977. /*
  161978. * Consume input data and store it in the full-image coefficient buffer.
  161979. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  161980. * ie, v_samp_factor block rows for each component in the scan.
  161981. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  161982. */
  161983. METHODDEF(int)
  161984. consume_data (j_decompress_ptr cinfo)
  161985. {
  161986. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161987. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161988. int blkn, ci, xindex, yindex, yoffset;
  161989. JDIMENSION start_col;
  161990. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161991. JBLOCKROW buffer_ptr;
  161992. jpeg_component_info *compptr;
  161993. /* Align the virtual buffers for the components used in this scan. */
  161994. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161995. compptr = cinfo->cur_comp_info[ci];
  161996. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161997. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161998. cinfo->input_iMCU_row * compptr->v_samp_factor,
  161999. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162000. /* Note: entropy decoder expects buffer to be zeroed,
  162001. * but this is handled automatically by the memory manager
  162002. * because we requested a pre-zeroed array.
  162003. */
  162004. }
  162005. /* Loop to process one whole iMCU row */
  162006. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162007. yoffset++) {
  162008. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162009. MCU_col_num++) {
  162010. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162011. blkn = 0; /* index of current DCT block within MCU */
  162012. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162013. compptr = cinfo->cur_comp_info[ci];
  162014. start_col = MCU_col_num * compptr->MCU_width;
  162015. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162016. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162017. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162018. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162019. }
  162020. }
  162021. }
  162022. /* Try to fetch the MCU. */
  162023. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162024. /* Suspension forced; update state counters and exit */
  162025. coef->MCU_vert_offset = yoffset;
  162026. coef->MCU_ctr = MCU_col_num;
  162027. return JPEG_SUSPENDED;
  162028. }
  162029. }
  162030. /* Completed an MCU row, but perhaps not an iMCU row */
  162031. coef->MCU_ctr = 0;
  162032. }
  162033. /* Completed the iMCU row, advance counters for next one */
  162034. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162035. start_iMCU_row3(cinfo);
  162036. return JPEG_ROW_COMPLETED;
  162037. }
  162038. /* Completed the scan */
  162039. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162040. return JPEG_SCAN_COMPLETED;
  162041. }
  162042. /*
  162043. * Decompress and return some data in the multi-pass case.
  162044. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162045. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162046. *
  162047. * NB: output_buf contains a plane for each component in image.
  162048. */
  162049. METHODDEF(int)
  162050. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162051. {
  162052. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162053. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162054. JDIMENSION block_num;
  162055. int ci, block_row, block_rows;
  162056. JBLOCKARRAY buffer;
  162057. JBLOCKROW buffer_ptr;
  162058. JSAMPARRAY output_ptr;
  162059. JDIMENSION output_col;
  162060. jpeg_component_info *compptr;
  162061. inverse_DCT_method_ptr inverse_DCT;
  162062. /* Force some input to be done if we are getting ahead of the input. */
  162063. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  162064. (cinfo->input_scan_number == cinfo->output_scan_number &&
  162065. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  162066. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162067. return JPEG_SUSPENDED;
  162068. }
  162069. /* OK, output from the virtual arrays. */
  162070. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162071. ci++, compptr++) {
  162072. /* Don't bother to IDCT an uninteresting component. */
  162073. if (! compptr->component_needed)
  162074. continue;
  162075. /* Align the virtual buffer for this component. */
  162076. buffer = (*cinfo->mem->access_virt_barray)
  162077. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162078. cinfo->output_iMCU_row * compptr->v_samp_factor,
  162079. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162080. /* Count non-dummy DCT block rows in this iMCU row. */
  162081. if (cinfo->output_iMCU_row < last_iMCU_row)
  162082. block_rows = compptr->v_samp_factor;
  162083. else {
  162084. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162085. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162086. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162087. }
  162088. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162089. output_ptr = output_buf[ci];
  162090. /* Loop over all DCT blocks to be processed. */
  162091. for (block_row = 0; block_row < block_rows; block_row++) {
  162092. buffer_ptr = buffer[block_row];
  162093. output_col = 0;
  162094. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  162095. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  162096. output_ptr, output_col);
  162097. buffer_ptr++;
  162098. output_col += compptr->DCT_scaled_size;
  162099. }
  162100. output_ptr += compptr->DCT_scaled_size;
  162101. }
  162102. }
  162103. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162104. return JPEG_ROW_COMPLETED;
  162105. return JPEG_SCAN_COMPLETED;
  162106. }
  162107. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162108. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162109. /*
  162110. * This code applies interblock smoothing as described by section K.8
  162111. * of the JPEG standard: the first 5 AC coefficients are estimated from
  162112. * the DC values of a DCT block and its 8 neighboring blocks.
  162113. * We apply smoothing only for progressive JPEG decoding, and only if
  162114. * the coefficients it can estimate are not yet known to full precision.
  162115. */
  162116. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  162117. #define Q01_POS 1
  162118. #define Q10_POS 8
  162119. #define Q20_POS 16
  162120. #define Q11_POS 9
  162121. #define Q02_POS 2
  162122. /*
  162123. * Determine whether block smoothing is applicable and safe.
  162124. * We also latch the current states of the coef_bits[] entries for the
  162125. * AC coefficients; otherwise, if the input side of the decompressor
  162126. * advances into a new scan, we might think the coefficients are known
  162127. * more accurately than they really are.
  162128. */
  162129. LOCAL(boolean)
  162130. smoothing_ok (j_decompress_ptr cinfo)
  162131. {
  162132. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162133. boolean smoothing_useful = FALSE;
  162134. int ci, coefi;
  162135. jpeg_component_info *compptr;
  162136. JQUANT_TBL * qtable;
  162137. int * coef_bits;
  162138. int * coef_bits_latch;
  162139. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  162140. return FALSE;
  162141. /* Allocate latch area if not already done */
  162142. if (coef->coef_bits_latch == NULL)
  162143. coef->coef_bits_latch = (int *)
  162144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162145. cinfo->num_components *
  162146. (SAVED_COEFS * SIZEOF(int)));
  162147. coef_bits_latch = coef->coef_bits_latch;
  162148. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162149. ci++, compptr++) {
  162150. /* All components' quantization values must already be latched. */
  162151. if ((qtable = compptr->quant_table) == NULL)
  162152. return FALSE;
  162153. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  162154. if (qtable->quantval[0] == 0 ||
  162155. qtable->quantval[Q01_POS] == 0 ||
  162156. qtable->quantval[Q10_POS] == 0 ||
  162157. qtable->quantval[Q20_POS] == 0 ||
  162158. qtable->quantval[Q11_POS] == 0 ||
  162159. qtable->quantval[Q02_POS] == 0)
  162160. return FALSE;
  162161. /* DC values must be at least partly known for all components. */
  162162. coef_bits = cinfo->coef_bits[ci];
  162163. if (coef_bits[0] < 0)
  162164. return FALSE;
  162165. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  162166. for (coefi = 1; coefi <= 5; coefi++) {
  162167. coef_bits_latch[coefi] = coef_bits[coefi];
  162168. if (coef_bits[coefi] != 0)
  162169. smoothing_useful = TRUE;
  162170. }
  162171. coef_bits_latch += SAVED_COEFS;
  162172. }
  162173. return smoothing_useful;
  162174. }
  162175. /*
  162176. * Variant of decompress_data for use when doing block smoothing.
  162177. */
  162178. METHODDEF(int)
  162179. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162180. {
  162181. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162182. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162183. JDIMENSION block_num, last_block_column;
  162184. int ci, block_row, block_rows, access_rows;
  162185. JBLOCKARRAY buffer;
  162186. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  162187. JSAMPARRAY output_ptr;
  162188. JDIMENSION output_col;
  162189. jpeg_component_info *compptr;
  162190. inverse_DCT_method_ptr inverse_DCT;
  162191. boolean first_row, last_row;
  162192. JBLOCK workspace;
  162193. int *coef_bits;
  162194. JQUANT_TBL *quanttbl;
  162195. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  162196. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  162197. int Al, pred;
  162198. /* Force some input to be done if we are getting ahead of the input. */
  162199. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162200. ! cinfo->inputctl->eoi_reached) {
  162201. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  162202. /* If input is working on current scan, we ordinarily want it to
  162203. * have completed the current row. But if input scan is DC,
  162204. * we want it to keep one row ahead so that next block row's DC
  162205. * values are up to date.
  162206. */
  162207. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  162208. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  162209. break;
  162210. }
  162211. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162212. return JPEG_SUSPENDED;
  162213. }
  162214. /* OK, output from the virtual arrays. */
  162215. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162216. ci++, compptr++) {
  162217. /* Don't bother to IDCT an uninteresting component. */
  162218. if (! compptr->component_needed)
  162219. continue;
  162220. /* Count non-dummy DCT block rows in this iMCU row. */
  162221. if (cinfo->output_iMCU_row < last_iMCU_row) {
  162222. block_rows = compptr->v_samp_factor;
  162223. access_rows = block_rows * 2; /* this and next iMCU row */
  162224. last_row = FALSE;
  162225. } else {
  162226. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162227. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162228. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162229. access_rows = block_rows; /* this iMCU row only */
  162230. last_row = TRUE;
  162231. }
  162232. /* Align the virtual buffer for this component. */
  162233. if (cinfo->output_iMCU_row > 0) {
  162234. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  162235. buffer = (*cinfo->mem->access_virt_barray)
  162236. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162237. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  162238. (JDIMENSION) access_rows, FALSE);
  162239. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  162240. first_row = FALSE;
  162241. } else {
  162242. buffer = (*cinfo->mem->access_virt_barray)
  162243. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162244. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  162245. first_row = TRUE;
  162246. }
  162247. /* Fetch component-dependent info */
  162248. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  162249. quanttbl = compptr->quant_table;
  162250. Q00 = quanttbl->quantval[0];
  162251. Q01 = quanttbl->quantval[Q01_POS];
  162252. Q10 = quanttbl->quantval[Q10_POS];
  162253. Q20 = quanttbl->quantval[Q20_POS];
  162254. Q11 = quanttbl->quantval[Q11_POS];
  162255. Q02 = quanttbl->quantval[Q02_POS];
  162256. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162257. output_ptr = output_buf[ci];
  162258. /* Loop over all DCT blocks to be processed. */
  162259. for (block_row = 0; block_row < block_rows; block_row++) {
  162260. buffer_ptr = buffer[block_row];
  162261. if (first_row && block_row == 0)
  162262. prev_block_row = buffer_ptr;
  162263. else
  162264. prev_block_row = buffer[block_row-1];
  162265. if (last_row && block_row == block_rows-1)
  162266. next_block_row = buffer_ptr;
  162267. else
  162268. next_block_row = buffer[block_row+1];
  162269. /* We fetch the surrounding DC values using a sliding-register approach.
  162270. * Initialize all nine here so as to do the right thing on narrow pics.
  162271. */
  162272. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  162273. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  162274. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  162275. output_col = 0;
  162276. last_block_column = compptr->width_in_blocks - 1;
  162277. for (block_num = 0; block_num <= last_block_column; block_num++) {
  162278. /* Fetch current DCT block into workspace so we can modify it. */
  162279. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  162280. /* Update DC values */
  162281. if (block_num < last_block_column) {
  162282. DC3 = (int) prev_block_row[1][0];
  162283. DC6 = (int) buffer_ptr[1][0];
  162284. DC9 = (int) next_block_row[1][0];
  162285. }
  162286. /* Compute coefficient estimates per K.8.
  162287. * An estimate is applied only if coefficient is still zero,
  162288. * and is not known to be fully accurate.
  162289. */
  162290. /* AC01 */
  162291. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  162292. num = 36 * Q00 * (DC4 - DC6);
  162293. if (num >= 0) {
  162294. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  162295. if (Al > 0 && pred >= (1<<Al))
  162296. pred = (1<<Al)-1;
  162297. } else {
  162298. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  162299. if (Al > 0 && pred >= (1<<Al))
  162300. pred = (1<<Al)-1;
  162301. pred = -pred;
  162302. }
  162303. workspace[1] = (JCOEF) pred;
  162304. }
  162305. /* AC10 */
  162306. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  162307. num = 36 * Q00 * (DC2 - DC8);
  162308. if (num >= 0) {
  162309. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  162310. if (Al > 0 && pred >= (1<<Al))
  162311. pred = (1<<Al)-1;
  162312. } else {
  162313. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  162314. if (Al > 0 && pred >= (1<<Al))
  162315. pred = (1<<Al)-1;
  162316. pred = -pred;
  162317. }
  162318. workspace[8] = (JCOEF) pred;
  162319. }
  162320. /* AC20 */
  162321. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  162322. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  162323. if (num >= 0) {
  162324. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  162325. if (Al > 0 && pred >= (1<<Al))
  162326. pred = (1<<Al)-1;
  162327. } else {
  162328. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  162329. if (Al > 0 && pred >= (1<<Al))
  162330. pred = (1<<Al)-1;
  162331. pred = -pred;
  162332. }
  162333. workspace[16] = (JCOEF) pred;
  162334. }
  162335. /* AC11 */
  162336. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  162337. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  162338. if (num >= 0) {
  162339. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  162340. if (Al > 0 && pred >= (1<<Al))
  162341. pred = (1<<Al)-1;
  162342. } else {
  162343. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  162344. if (Al > 0 && pred >= (1<<Al))
  162345. pred = (1<<Al)-1;
  162346. pred = -pred;
  162347. }
  162348. workspace[9] = (JCOEF) pred;
  162349. }
  162350. /* AC02 */
  162351. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  162352. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  162353. if (num >= 0) {
  162354. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  162355. if (Al > 0 && pred >= (1<<Al))
  162356. pred = (1<<Al)-1;
  162357. } else {
  162358. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  162359. if (Al > 0 && pred >= (1<<Al))
  162360. pred = (1<<Al)-1;
  162361. pred = -pred;
  162362. }
  162363. workspace[2] = (JCOEF) pred;
  162364. }
  162365. /* OK, do the IDCT */
  162366. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  162367. output_ptr, output_col);
  162368. /* Advance for next column */
  162369. DC1 = DC2; DC2 = DC3;
  162370. DC4 = DC5; DC5 = DC6;
  162371. DC7 = DC8; DC8 = DC9;
  162372. buffer_ptr++, prev_block_row++, next_block_row++;
  162373. output_col += compptr->DCT_scaled_size;
  162374. }
  162375. output_ptr += compptr->DCT_scaled_size;
  162376. }
  162377. }
  162378. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162379. return JPEG_ROW_COMPLETED;
  162380. return JPEG_SCAN_COMPLETED;
  162381. }
  162382. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  162383. /*
  162384. * Initialize coefficient buffer controller.
  162385. */
  162386. GLOBAL(void)
  162387. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  162388. {
  162389. my_coef_ptr3 coef;
  162390. coef = (my_coef_ptr3)
  162391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162392. SIZEOF(my_coef_controller3));
  162393. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  162394. coef->pub.start_input_pass = start_input_pass;
  162395. coef->pub.start_output_pass = start_output_pass;
  162396. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162397. coef->coef_bits_latch = NULL;
  162398. #endif
  162399. /* Create the coefficient buffer. */
  162400. if (need_full_buffer) {
  162401. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162402. /* Allocate a full-image virtual array for each component, */
  162403. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162404. /* Note we ask for a pre-zeroed array. */
  162405. int ci, access_rows;
  162406. jpeg_component_info *compptr;
  162407. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162408. ci++, compptr++) {
  162409. access_rows = compptr->v_samp_factor;
  162410. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162411. /* If block smoothing could be used, need a bigger window */
  162412. if (cinfo->progressive_mode)
  162413. access_rows *= 3;
  162414. #endif
  162415. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162416. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  162417. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162418. (long) compptr->h_samp_factor),
  162419. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162420. (long) compptr->v_samp_factor),
  162421. (JDIMENSION) access_rows);
  162422. }
  162423. coef->pub.consume_data = consume_data;
  162424. coef->pub.decompress_data = decompress_data;
  162425. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  162426. #else
  162427. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162428. #endif
  162429. } else {
  162430. /* We only need a single-MCU buffer. */
  162431. JBLOCKROW buffer;
  162432. int i;
  162433. buffer = (JBLOCKROW)
  162434. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162435. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162436. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  162437. coef->MCU_buffer[i] = buffer + i;
  162438. }
  162439. coef->pub.consume_data = dummy_consume_data;
  162440. coef->pub.decompress_data = decompress_onepass;
  162441. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  162442. }
  162443. }
  162444. /********* End of inlined file: jdcoefct.c *********/
  162445. #undef FIX
  162446. /********* Start of inlined file: jdcolor.c *********/
  162447. #define JPEG_INTERNALS
  162448. /* Private subobject */
  162449. typedef struct {
  162450. struct jpeg_color_deconverter pub; /* public fields */
  162451. /* Private state for YCC->RGB conversion */
  162452. int * Cr_r_tab; /* => table for Cr to R conversion */
  162453. int * Cb_b_tab; /* => table for Cb to B conversion */
  162454. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  162455. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  162456. } my_color_deconverter2;
  162457. typedef my_color_deconverter2 * my_cconvert_ptr2;
  162458. /**************** YCbCr -> RGB conversion: most common case **************/
  162459. /*
  162460. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162461. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162462. * The conversion equations to be implemented are therefore
  162463. * R = Y + 1.40200 * Cr
  162464. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  162465. * B = Y + 1.77200 * Cb
  162466. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  162467. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162468. *
  162469. * To avoid floating-point arithmetic, we represent the fractional constants
  162470. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162471. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162472. * Notice that Y, being an integral input, does not contribute any fraction
  162473. * so it need not participate in the rounding.
  162474. *
  162475. * For even more speed, we avoid doing any multiplications in the inner loop
  162476. * by precalculating the constants times Cb and Cr for all possible values.
  162477. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162478. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162479. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162480. * colorspace anyway.
  162481. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  162482. * values for the G calculation are left scaled up, since we must add them
  162483. * together before rounding.
  162484. */
  162485. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162486. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162487. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162488. /*
  162489. * Initialize tables for YCC->RGB colorspace conversion.
  162490. */
  162491. LOCAL(void)
  162492. build_ycc_rgb_table (j_decompress_ptr cinfo)
  162493. {
  162494. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162495. int i;
  162496. INT32 x;
  162497. SHIFT_TEMPS
  162498. cconvert->Cr_r_tab = (int *)
  162499. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162500. (MAXJSAMPLE+1) * SIZEOF(int));
  162501. cconvert->Cb_b_tab = (int *)
  162502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162503. (MAXJSAMPLE+1) * SIZEOF(int));
  162504. cconvert->Cr_g_tab = (INT32 *)
  162505. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162506. (MAXJSAMPLE+1) * SIZEOF(INT32));
  162507. cconvert->Cb_g_tab = (INT32 *)
  162508. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162509. (MAXJSAMPLE+1) * SIZEOF(INT32));
  162510. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  162511. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  162512. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  162513. /* Cr=>R value is nearest int to 1.40200 * x */
  162514. cconvert->Cr_r_tab[i] = (int)
  162515. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  162516. /* Cb=>B value is nearest int to 1.77200 * x */
  162517. cconvert->Cb_b_tab[i] = (int)
  162518. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  162519. /* Cr=>G value is scaled-up -0.71414 * x */
  162520. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  162521. /* Cb=>G value is scaled-up -0.34414 * x */
  162522. /* We also add in ONE_HALF so that need not do it in inner loop */
  162523. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  162524. }
  162525. }
  162526. /*
  162527. * Convert some rows of samples to the output colorspace.
  162528. *
  162529. * Note that we change from noninterleaved, one-plane-per-component format
  162530. * to interleaved-pixel format. The output buffer is therefore three times
  162531. * as wide as the input buffer.
  162532. * A starting row offset is provided only for the input buffer. The caller
  162533. * can easily adjust the passed output_buf value to accommodate any row
  162534. * offset required on that side.
  162535. */
  162536. METHODDEF(void)
  162537. ycc_rgb_convert (j_decompress_ptr cinfo,
  162538. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162539. JSAMPARRAY output_buf, int num_rows)
  162540. {
  162541. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162542. register int y, cb, cr;
  162543. register JSAMPROW outptr;
  162544. register JSAMPROW inptr0, inptr1, inptr2;
  162545. register JDIMENSION col;
  162546. JDIMENSION num_cols = cinfo->output_width;
  162547. /* copy these pointers into registers if possible */
  162548. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  162549. register int * Crrtab = cconvert->Cr_r_tab;
  162550. register int * Cbbtab = cconvert->Cb_b_tab;
  162551. register INT32 * Crgtab = cconvert->Cr_g_tab;
  162552. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  162553. SHIFT_TEMPS
  162554. while (--num_rows >= 0) {
  162555. inptr0 = input_buf[0][input_row];
  162556. inptr1 = input_buf[1][input_row];
  162557. inptr2 = input_buf[2][input_row];
  162558. input_row++;
  162559. outptr = *output_buf++;
  162560. for (col = 0; col < num_cols; col++) {
  162561. y = GETJSAMPLE(inptr0[col]);
  162562. cb = GETJSAMPLE(inptr1[col]);
  162563. cr = GETJSAMPLE(inptr2[col]);
  162564. /* Range-limiting is essential due to noise introduced by DCT losses. */
  162565. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  162566. outptr[RGB_GREEN] = range_limit[y +
  162567. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  162568. SCALEBITS))];
  162569. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  162570. outptr += RGB_PIXELSIZE;
  162571. }
  162572. }
  162573. }
  162574. /**************** Cases other than YCbCr -> RGB **************/
  162575. /*
  162576. * Color conversion for no colorspace change: just copy the data,
  162577. * converting from separate-planes to interleaved representation.
  162578. */
  162579. METHODDEF(void)
  162580. null_convert2 (j_decompress_ptr cinfo,
  162581. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162582. JSAMPARRAY output_buf, int num_rows)
  162583. {
  162584. register JSAMPROW inptr, outptr;
  162585. register JDIMENSION count;
  162586. register int num_components = cinfo->num_components;
  162587. JDIMENSION num_cols = cinfo->output_width;
  162588. int ci;
  162589. while (--num_rows >= 0) {
  162590. for (ci = 0; ci < num_components; ci++) {
  162591. inptr = input_buf[ci][input_row];
  162592. outptr = output_buf[0] + ci;
  162593. for (count = num_cols; count > 0; count--) {
  162594. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  162595. outptr += num_components;
  162596. }
  162597. }
  162598. input_row++;
  162599. output_buf++;
  162600. }
  162601. }
  162602. /*
  162603. * Color conversion for grayscale: just copy the data.
  162604. * This also works for YCbCr -> grayscale conversion, in which
  162605. * we just copy the Y (luminance) component and ignore chrominance.
  162606. */
  162607. METHODDEF(void)
  162608. grayscale_convert2 (j_decompress_ptr cinfo,
  162609. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162610. JSAMPARRAY output_buf, int num_rows)
  162611. {
  162612. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  162613. num_rows, cinfo->output_width);
  162614. }
  162615. /*
  162616. * Convert grayscale to RGB: just duplicate the graylevel three times.
  162617. * This is provided to support applications that don't want to cope
  162618. * with grayscale as a separate case.
  162619. */
  162620. METHODDEF(void)
  162621. gray_rgb_convert (j_decompress_ptr cinfo,
  162622. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162623. JSAMPARRAY output_buf, int num_rows)
  162624. {
  162625. register JSAMPROW inptr, outptr;
  162626. register JDIMENSION col;
  162627. JDIMENSION num_cols = cinfo->output_width;
  162628. while (--num_rows >= 0) {
  162629. inptr = input_buf[0][input_row++];
  162630. outptr = *output_buf++;
  162631. for (col = 0; col < num_cols; col++) {
  162632. /* We can dispense with GETJSAMPLE() here */
  162633. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  162634. outptr += RGB_PIXELSIZE;
  162635. }
  162636. }
  162637. }
  162638. /*
  162639. * Adobe-style YCCK->CMYK conversion.
  162640. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  162641. * conversion as above, while passing K (black) unchanged.
  162642. * We assume build_ycc_rgb_table has been called.
  162643. */
  162644. METHODDEF(void)
  162645. ycck_cmyk_convert (j_decompress_ptr cinfo,
  162646. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162647. JSAMPARRAY output_buf, int num_rows)
  162648. {
  162649. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162650. register int y, cb, cr;
  162651. register JSAMPROW outptr;
  162652. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  162653. register JDIMENSION col;
  162654. JDIMENSION num_cols = cinfo->output_width;
  162655. /* copy these pointers into registers if possible */
  162656. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  162657. register int * Crrtab = cconvert->Cr_r_tab;
  162658. register int * Cbbtab = cconvert->Cb_b_tab;
  162659. register INT32 * Crgtab = cconvert->Cr_g_tab;
  162660. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  162661. SHIFT_TEMPS
  162662. while (--num_rows >= 0) {
  162663. inptr0 = input_buf[0][input_row];
  162664. inptr1 = input_buf[1][input_row];
  162665. inptr2 = input_buf[2][input_row];
  162666. inptr3 = input_buf[3][input_row];
  162667. input_row++;
  162668. outptr = *output_buf++;
  162669. for (col = 0; col < num_cols; col++) {
  162670. y = GETJSAMPLE(inptr0[col]);
  162671. cb = GETJSAMPLE(inptr1[col]);
  162672. cr = GETJSAMPLE(inptr2[col]);
  162673. /* Range-limiting is essential due to noise introduced by DCT losses. */
  162674. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  162675. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  162676. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  162677. SCALEBITS)))];
  162678. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  162679. /* K passes through unchanged */
  162680. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  162681. outptr += 4;
  162682. }
  162683. }
  162684. }
  162685. /*
  162686. * Empty method for start_pass.
  162687. */
  162688. METHODDEF(void)
  162689. start_pass_dcolor (j_decompress_ptr cinfo)
  162690. {
  162691. /* no work needed */
  162692. }
  162693. /*
  162694. * Module initialization routine for output colorspace conversion.
  162695. */
  162696. GLOBAL(void)
  162697. jinit_color_deconverter (j_decompress_ptr cinfo)
  162698. {
  162699. my_cconvert_ptr2 cconvert;
  162700. int ci;
  162701. cconvert = (my_cconvert_ptr2)
  162702. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162703. SIZEOF(my_color_deconverter2));
  162704. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  162705. cconvert->pub.start_pass = start_pass_dcolor;
  162706. /* Make sure num_components agrees with jpeg_color_space */
  162707. switch (cinfo->jpeg_color_space) {
  162708. case JCS_GRAYSCALE:
  162709. if (cinfo->num_components != 1)
  162710. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162711. break;
  162712. case JCS_RGB:
  162713. case JCS_YCbCr:
  162714. if (cinfo->num_components != 3)
  162715. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162716. break;
  162717. case JCS_CMYK:
  162718. case JCS_YCCK:
  162719. if (cinfo->num_components != 4)
  162720. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162721. break;
  162722. default: /* JCS_UNKNOWN can be anything */
  162723. if (cinfo->num_components < 1)
  162724. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162725. break;
  162726. }
  162727. /* Set out_color_components and conversion method based on requested space.
  162728. * Also clear the component_needed flags for any unused components,
  162729. * so that earlier pipeline stages can avoid useless computation.
  162730. */
  162731. switch (cinfo->out_color_space) {
  162732. case JCS_GRAYSCALE:
  162733. cinfo->out_color_components = 1;
  162734. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  162735. cinfo->jpeg_color_space == JCS_YCbCr) {
  162736. cconvert->pub.color_convert = grayscale_convert2;
  162737. /* For color->grayscale conversion, only the Y (0) component is needed */
  162738. for (ci = 1; ci < cinfo->num_components; ci++)
  162739. cinfo->comp_info[ci].component_needed = FALSE;
  162740. } else
  162741. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162742. break;
  162743. case JCS_RGB:
  162744. cinfo->out_color_components = RGB_PIXELSIZE;
  162745. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  162746. cconvert->pub.color_convert = ycc_rgb_convert;
  162747. build_ycc_rgb_table(cinfo);
  162748. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  162749. cconvert->pub.color_convert = gray_rgb_convert;
  162750. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  162751. cconvert->pub.color_convert = null_convert2;
  162752. } else
  162753. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162754. break;
  162755. case JCS_CMYK:
  162756. cinfo->out_color_components = 4;
  162757. if (cinfo->jpeg_color_space == JCS_YCCK) {
  162758. cconvert->pub.color_convert = ycck_cmyk_convert;
  162759. build_ycc_rgb_table(cinfo);
  162760. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  162761. cconvert->pub.color_convert = null_convert2;
  162762. } else
  162763. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162764. break;
  162765. default:
  162766. /* Permit null conversion to same output space */
  162767. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  162768. cinfo->out_color_components = cinfo->num_components;
  162769. cconvert->pub.color_convert = null_convert2;
  162770. } else /* unsupported non-null conversion */
  162771. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162772. break;
  162773. }
  162774. if (cinfo->quantize_colors)
  162775. cinfo->output_components = 1; /* single colormapped output component */
  162776. else
  162777. cinfo->output_components = cinfo->out_color_components;
  162778. }
  162779. /********* End of inlined file: jdcolor.c *********/
  162780. #undef FIX
  162781. /********* Start of inlined file: jddctmgr.c *********/
  162782. #define JPEG_INTERNALS
  162783. /*
  162784. * The decompressor input side (jdinput.c) saves away the appropriate
  162785. * quantization table for each component at the start of the first scan
  162786. * involving that component. (This is necessary in order to correctly
  162787. * decode files that reuse Q-table slots.)
  162788. * When we are ready to make an output pass, the saved Q-table is converted
  162789. * to a multiplier table that will actually be used by the IDCT routine.
  162790. * The multiplier table contents are IDCT-method-dependent. To support
  162791. * application changes in IDCT method between scans, we can remake the
  162792. * multiplier tables if necessary.
  162793. * In buffered-image mode, the first output pass may occur before any data
  162794. * has been seen for some components, and thus before their Q-tables have
  162795. * been saved away. To handle this case, multiplier tables are preset
  162796. * to zeroes; the result of the IDCT will be a neutral gray level.
  162797. */
  162798. /* Private subobject for this module */
  162799. typedef struct {
  162800. struct jpeg_inverse_dct pub; /* public fields */
  162801. /* This array contains the IDCT method code that each multiplier table
  162802. * is currently set up for, or -1 if it's not yet set up.
  162803. * The actual multiplier tables are pointed to by dct_table in the
  162804. * per-component comp_info structures.
  162805. */
  162806. int cur_method[MAX_COMPONENTS];
  162807. } my_idct_controller;
  162808. typedef my_idct_controller * my_idct_ptr;
  162809. /* Allocated multiplier tables: big enough for any supported variant */
  162810. typedef union {
  162811. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  162812. #ifdef DCT_IFAST_SUPPORTED
  162813. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  162814. #endif
  162815. #ifdef DCT_FLOAT_SUPPORTED
  162816. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  162817. #endif
  162818. } multiplier_table;
  162819. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  162820. * so be sure to compile that code if either ISLOW or SCALING is requested.
  162821. */
  162822. #ifdef DCT_ISLOW_SUPPORTED
  162823. #define PROVIDE_ISLOW_TABLES
  162824. #else
  162825. #ifdef IDCT_SCALING_SUPPORTED
  162826. #define PROVIDE_ISLOW_TABLES
  162827. #endif
  162828. #endif
  162829. /*
  162830. * Prepare for an output pass.
  162831. * Here we select the proper IDCT routine for each component and build
  162832. * a matching multiplier table.
  162833. */
  162834. METHODDEF(void)
  162835. start_pass (j_decompress_ptr cinfo)
  162836. {
  162837. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  162838. int ci, i;
  162839. jpeg_component_info *compptr;
  162840. int method = 0;
  162841. inverse_DCT_method_ptr method_ptr = NULL;
  162842. JQUANT_TBL * qtbl;
  162843. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162844. ci++, compptr++) {
  162845. /* Select the proper IDCT routine for this component's scaling */
  162846. switch (compptr->DCT_scaled_size) {
  162847. #ifdef IDCT_SCALING_SUPPORTED
  162848. case 1:
  162849. method_ptr = jpeg_idct_1x1;
  162850. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162851. break;
  162852. case 2:
  162853. method_ptr = jpeg_idct_2x2;
  162854. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162855. break;
  162856. case 4:
  162857. method_ptr = jpeg_idct_4x4;
  162858. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162859. break;
  162860. #endif
  162861. case DCTSIZE:
  162862. switch (cinfo->dct_method) {
  162863. #ifdef DCT_ISLOW_SUPPORTED
  162864. case JDCT_ISLOW:
  162865. method_ptr = jpeg_idct_islow;
  162866. method = JDCT_ISLOW;
  162867. break;
  162868. #endif
  162869. #ifdef DCT_IFAST_SUPPORTED
  162870. case JDCT_IFAST:
  162871. method_ptr = jpeg_idct_ifast;
  162872. method = JDCT_IFAST;
  162873. break;
  162874. #endif
  162875. #ifdef DCT_FLOAT_SUPPORTED
  162876. case JDCT_FLOAT:
  162877. method_ptr = jpeg_idct_float;
  162878. method = JDCT_FLOAT;
  162879. break;
  162880. #endif
  162881. default:
  162882. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162883. break;
  162884. }
  162885. break;
  162886. default:
  162887. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  162888. break;
  162889. }
  162890. idct->pub.inverse_DCT[ci] = method_ptr;
  162891. /* Create multiplier table from quant table.
  162892. * However, we can skip this if the component is uninteresting
  162893. * or if we already built the table. Also, if no quant table
  162894. * has yet been saved for the component, we leave the
  162895. * multiplier table all-zero; we'll be reading zeroes from the
  162896. * coefficient controller's buffer anyway.
  162897. */
  162898. if (! compptr->component_needed || idct->cur_method[ci] == method)
  162899. continue;
  162900. qtbl = compptr->quant_table;
  162901. if (qtbl == NULL) /* happens if no data yet for component */
  162902. continue;
  162903. idct->cur_method[ci] = method;
  162904. switch (method) {
  162905. #ifdef PROVIDE_ISLOW_TABLES
  162906. case JDCT_ISLOW:
  162907. {
  162908. /* For LL&M IDCT method, multipliers are equal to raw quantization
  162909. * coefficients, but are stored as ints to ensure access efficiency.
  162910. */
  162911. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  162912. for (i = 0; i < DCTSIZE2; i++) {
  162913. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  162914. }
  162915. }
  162916. break;
  162917. #endif
  162918. #ifdef DCT_IFAST_SUPPORTED
  162919. case JDCT_IFAST:
  162920. {
  162921. /* For AA&N IDCT method, multipliers are equal to quantization
  162922. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162923. * scalefactor[0] = 1
  162924. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162925. * For integer operation, the multiplier table is to be scaled by
  162926. * IFAST_SCALE_BITS.
  162927. */
  162928. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  162929. #define CONST_BITS 14
  162930. static const INT16 aanscales[DCTSIZE2] = {
  162931. /* precomputed values scaled up by 14 bits */
  162932. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162933. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162934. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162935. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162936. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162937. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162938. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162939. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162940. };
  162941. SHIFT_TEMPS
  162942. for (i = 0; i < DCTSIZE2; i++) {
  162943. ifmtbl[i] = (IFAST_MULT_TYPE)
  162944. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162945. (INT32) aanscales[i]),
  162946. CONST_BITS-IFAST_SCALE_BITS);
  162947. }
  162948. }
  162949. break;
  162950. #endif
  162951. #ifdef DCT_FLOAT_SUPPORTED
  162952. case JDCT_FLOAT:
  162953. {
  162954. /* For float AA&N IDCT method, multipliers are equal to quantization
  162955. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162956. * scalefactor[0] = 1
  162957. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162958. */
  162959. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  162960. int row, col;
  162961. static const double aanscalefactor[DCTSIZE] = {
  162962. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162963. 1.0, 0.785694958, 0.541196100, 0.275899379
  162964. };
  162965. i = 0;
  162966. for (row = 0; row < DCTSIZE; row++) {
  162967. for (col = 0; col < DCTSIZE; col++) {
  162968. fmtbl[i] = (FLOAT_MULT_TYPE)
  162969. ((double) qtbl->quantval[i] *
  162970. aanscalefactor[row] * aanscalefactor[col]);
  162971. i++;
  162972. }
  162973. }
  162974. }
  162975. break;
  162976. #endif
  162977. default:
  162978. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162979. break;
  162980. }
  162981. }
  162982. }
  162983. /*
  162984. * Initialize IDCT manager.
  162985. */
  162986. GLOBAL(void)
  162987. jinit_inverse_dct (j_decompress_ptr cinfo)
  162988. {
  162989. my_idct_ptr idct;
  162990. int ci;
  162991. jpeg_component_info *compptr;
  162992. idct = (my_idct_ptr)
  162993. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162994. SIZEOF(my_idct_controller));
  162995. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  162996. idct->pub.start_pass = start_pass;
  162997. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162998. ci++, compptr++) {
  162999. /* Allocate and pre-zero a multiplier table for each component */
  163000. compptr->dct_table =
  163001. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163002. SIZEOF(multiplier_table));
  163003. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  163004. /* Mark multiplier table not yet set up for any method */
  163005. idct->cur_method[ci] = -1;
  163006. }
  163007. }
  163008. /********* End of inlined file: jddctmgr.c *********/
  163009. #undef CONST_BITS
  163010. #undef ASSIGN_STATE
  163011. /********* Start of inlined file: jdhuff.c *********/
  163012. #define JPEG_INTERNALS
  163013. /********* Start of inlined file: jdhuff.h *********/
  163014. /* Short forms of external names for systems with brain-damaged linkers. */
  163015. #ifndef __jdhuff_h__
  163016. #define __jdhuff_h__
  163017. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163018. #define jpeg_make_d_derived_tbl jMkDDerived
  163019. #define jpeg_fill_bit_buffer jFilBitBuf
  163020. #define jpeg_huff_decode jHufDecode
  163021. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163022. /* Derived data constructed for each Huffman table */
  163023. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  163024. typedef struct {
  163025. /* Basic tables: (element [0] of each array is unused) */
  163026. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  163027. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  163028. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  163029. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  163030. * the smallest code of length k; so given a code of length k, the
  163031. * corresponding symbol is huffval[code + valoffset[k]]
  163032. */
  163033. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  163034. JHUFF_TBL *pub;
  163035. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  163036. * the input data stream. If the next Huffman code is no more
  163037. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  163038. * the corresponding symbol directly from these tables.
  163039. */
  163040. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  163041. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  163042. } d_derived_tbl;
  163043. /* Expand a Huffman table definition into the derived format */
  163044. EXTERN(void) jpeg_make_d_derived_tbl
  163045. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  163046. d_derived_tbl ** pdtbl));
  163047. /*
  163048. * Fetching the next N bits from the input stream is a time-critical operation
  163049. * for the Huffman decoders. We implement it with a combination of inline
  163050. * macros and out-of-line subroutines. Note that N (the number of bits
  163051. * demanded at one time) never exceeds 15 for JPEG use.
  163052. *
  163053. * We read source bytes into get_buffer and dole out bits as needed.
  163054. * If get_buffer already contains enough bits, they are fetched in-line
  163055. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  163056. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  163057. * as full as possible (not just to the number of bits needed; this
  163058. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  163059. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  163060. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  163061. * at least the requested number of bits --- dummy zeroes are inserted if
  163062. * necessary.
  163063. */
  163064. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  163065. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  163066. /* If long is > 32 bits on your machine, and shifting/masking longs is
  163067. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  163068. * appropriately should be a win. Unfortunately we can't define the size
  163069. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  163070. * because not all machines measure sizeof in 8-bit bytes.
  163071. */
  163072. typedef struct { /* Bitreading state saved across MCUs */
  163073. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163074. int bits_left; /* # of unused bits in it */
  163075. } bitread_perm_state;
  163076. typedef struct { /* Bitreading working state within an MCU */
  163077. /* Current data source location */
  163078. /* We need a copy, rather than munging the original, in case of suspension */
  163079. const JOCTET * next_input_byte; /* => next byte to read from source */
  163080. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  163081. /* Bit input buffer --- note these values are kept in register variables,
  163082. * not in this struct, inside the inner loops.
  163083. */
  163084. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163085. int bits_left; /* # of unused bits in it */
  163086. /* Pointer needed by jpeg_fill_bit_buffer. */
  163087. j_decompress_ptr cinfo; /* back link to decompress master record */
  163088. } bitread_working_state;
  163089. /* Macros to declare and load/save bitread local variables. */
  163090. #define BITREAD_STATE_VARS \
  163091. register bit_buf_type get_buffer; \
  163092. register int bits_left; \
  163093. bitread_working_state br_state
  163094. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  163095. br_state.cinfo = cinfop; \
  163096. br_state.next_input_byte = cinfop->src->next_input_byte; \
  163097. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  163098. get_buffer = permstate.get_buffer; \
  163099. bits_left = permstate.bits_left;
  163100. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  163101. cinfop->src->next_input_byte = br_state.next_input_byte; \
  163102. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  163103. permstate.get_buffer = get_buffer; \
  163104. permstate.bits_left = bits_left
  163105. /*
  163106. * These macros provide the in-line portion of bit fetching.
  163107. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  163108. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  163109. * The variables get_buffer and bits_left are assumed to be locals,
  163110. * but the state struct might not be (jpeg_huff_decode needs this).
  163111. * CHECK_BIT_BUFFER(state,n,action);
  163112. * Ensure there are N bits in get_buffer; if suspend, take action.
  163113. * val = GET_BITS(n);
  163114. * Fetch next N bits.
  163115. * val = PEEK_BITS(n);
  163116. * Fetch next N bits without removing them from the buffer.
  163117. * DROP_BITS(n);
  163118. * Discard next N bits.
  163119. * The value N should be a simple variable, not an expression, because it
  163120. * is evaluated multiple times.
  163121. */
  163122. #define CHECK_BIT_BUFFER(state,nbits,action) \
  163123. { if (bits_left < (nbits)) { \
  163124. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  163125. { action; } \
  163126. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  163127. #define GET_BITS(nbits) \
  163128. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  163129. #define PEEK_BITS(nbits) \
  163130. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  163131. #define DROP_BITS(nbits) \
  163132. (bits_left -= (nbits))
  163133. /* Load up the bit buffer to a depth of at least nbits */
  163134. EXTERN(boolean) jpeg_fill_bit_buffer
  163135. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163136. register int bits_left, int nbits));
  163137. /*
  163138. * Code for extracting next Huffman-coded symbol from input bit stream.
  163139. * Again, this is time-critical and we make the main paths be macros.
  163140. *
  163141. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  163142. * without looping. Usually, more than 95% of the Huffman codes will be 8
  163143. * or fewer bits long. The few overlength codes are handled with a loop,
  163144. * which need not be inline code.
  163145. *
  163146. * Notes about the HUFF_DECODE macro:
  163147. * 1. Near the end of the data segment, we may fail to get enough bits
  163148. * for a lookahead. In that case, we do it the hard way.
  163149. * 2. If the lookahead table contains no entry, the next code must be
  163150. * more than HUFF_LOOKAHEAD bits long.
  163151. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  163152. */
  163153. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  163154. { register int nb, look; \
  163155. if (bits_left < HUFF_LOOKAHEAD) { \
  163156. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  163157. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163158. if (bits_left < HUFF_LOOKAHEAD) { \
  163159. nb = 1; goto slowlabel; \
  163160. } \
  163161. } \
  163162. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  163163. if ((nb = htbl->look_nbits[look]) != 0) { \
  163164. DROP_BITS(nb); \
  163165. result = htbl->look_sym[look]; \
  163166. } else { \
  163167. nb = HUFF_LOOKAHEAD+1; \
  163168. slowlabel: \
  163169. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  163170. { failaction; } \
  163171. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163172. } \
  163173. }
  163174. /* Out-of-line case for Huffman code fetching */
  163175. EXTERN(int) jpeg_huff_decode
  163176. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163177. register int bits_left, d_derived_tbl * htbl, int min_bits));
  163178. #endif
  163179. /********* End of inlined file: jdhuff.h *********/
  163180. /* Declarations shared with jdphuff.c */
  163181. /*
  163182. * Expanded entropy decoder object for Huffman decoding.
  163183. *
  163184. * The savable_state subrecord contains fields that change within an MCU,
  163185. * but must not be updated permanently until we complete the MCU.
  163186. */
  163187. typedef struct {
  163188. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163189. } savable_state2;
  163190. /* This macro is to work around compilers with missing or broken
  163191. * structure assignment. You'll need to fix this code if you have
  163192. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163193. */
  163194. #ifndef NO_STRUCT_ASSIGN
  163195. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163196. #else
  163197. #if MAX_COMPS_IN_SCAN == 4
  163198. #define ASSIGN_STATE(dest,src) \
  163199. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  163200. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163201. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163202. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163203. #endif
  163204. #endif
  163205. typedef struct {
  163206. struct jpeg_entropy_decoder pub; /* public fields */
  163207. /* These fields are loaded into local variables at start of each MCU.
  163208. * In case of suspension, we exit WITHOUT updating them.
  163209. */
  163210. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  163211. savable_state2 saved; /* Other state at start of MCU */
  163212. /* These fields are NOT loaded into local working state. */
  163213. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163214. /* Pointers to derived tables (these workspaces have image lifespan) */
  163215. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163216. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163217. /* Precalculated info set up by start_pass for use in decode_mcu: */
  163218. /* Pointers to derived tables to be used for each block within an MCU */
  163219. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163220. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163221. /* Whether we care about the DC and AC coefficient values for each block */
  163222. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  163223. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  163224. } huff_entropy_decoder2;
  163225. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  163226. /*
  163227. * Initialize for a Huffman-compressed scan.
  163228. */
  163229. METHODDEF(void)
  163230. start_pass_huff_decoder (j_decompress_ptr cinfo)
  163231. {
  163232. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163233. int ci, blkn, dctbl, actbl;
  163234. jpeg_component_info * compptr;
  163235. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  163236. * This ought to be an error condition, but we make it a warning because
  163237. * there are some baseline files out there with all zeroes in these bytes.
  163238. */
  163239. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  163240. cinfo->Ah != 0 || cinfo->Al != 0)
  163241. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  163242. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163243. compptr = cinfo->cur_comp_info[ci];
  163244. dctbl = compptr->dc_tbl_no;
  163245. actbl = compptr->ac_tbl_no;
  163246. /* Compute derived values for Huffman tables */
  163247. /* We may do this more than once for a table, but it's not expensive */
  163248. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  163249. & entropy->dc_derived_tbls[dctbl]);
  163250. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  163251. & entropy->ac_derived_tbls[actbl]);
  163252. /* Initialize DC predictions to 0 */
  163253. entropy->saved.last_dc_val[ci] = 0;
  163254. }
  163255. /* Precalculate decoding info for each block in an MCU of this scan */
  163256. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163257. ci = cinfo->MCU_membership[blkn];
  163258. compptr = cinfo->cur_comp_info[ci];
  163259. /* Precalculate which table to use for each block */
  163260. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  163261. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  163262. /* Decide whether we really care about the coefficient values */
  163263. if (compptr->component_needed) {
  163264. entropy->dc_needed[blkn] = TRUE;
  163265. /* we don't need the ACs if producing a 1/8th-size image */
  163266. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  163267. } else {
  163268. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  163269. }
  163270. }
  163271. /* Initialize bitread state variables */
  163272. entropy->bitstate.bits_left = 0;
  163273. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  163274. entropy->pub.insufficient_data = FALSE;
  163275. /* Initialize restart counter */
  163276. entropy->restarts_to_go = cinfo->restart_interval;
  163277. }
  163278. /*
  163279. * Compute the derived values for a Huffman table.
  163280. * This routine also performs some validation checks on the table.
  163281. *
  163282. * Note this is also used by jdphuff.c.
  163283. */
  163284. GLOBAL(void)
  163285. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  163286. d_derived_tbl ** pdtbl)
  163287. {
  163288. JHUFF_TBL *htbl;
  163289. d_derived_tbl *dtbl;
  163290. int p, i, l, si, numsymbols;
  163291. int lookbits, ctr;
  163292. char huffsize[257];
  163293. unsigned int huffcode[257];
  163294. unsigned int code;
  163295. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163296. * paralleling the order of the symbols themselves in htbl->huffval[].
  163297. */
  163298. /* Find the input Huffman table */
  163299. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163300. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163301. htbl =
  163302. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163303. if (htbl == NULL)
  163304. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163305. /* Allocate a workspace if we haven't already done so. */
  163306. if (*pdtbl == NULL)
  163307. *pdtbl = (d_derived_tbl *)
  163308. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163309. SIZEOF(d_derived_tbl));
  163310. dtbl = *pdtbl;
  163311. dtbl->pub = htbl; /* fill in back link */
  163312. /* Figure C.1: make table of Huffman code length for each symbol */
  163313. p = 0;
  163314. for (l = 1; l <= 16; l++) {
  163315. i = (int) htbl->bits[l];
  163316. if (i < 0 || p + i > 256) /* protect against table overrun */
  163317. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163318. while (i--)
  163319. huffsize[p++] = (char) l;
  163320. }
  163321. huffsize[p] = 0;
  163322. numsymbols = p;
  163323. /* Figure C.2: generate the codes themselves */
  163324. /* We also validate that the counts represent a legal Huffman code tree. */
  163325. code = 0;
  163326. si = huffsize[0];
  163327. p = 0;
  163328. while (huffsize[p]) {
  163329. while (((int) huffsize[p]) == si) {
  163330. huffcode[p++] = code;
  163331. code++;
  163332. }
  163333. /* code is now 1 more than the last code used for codelength si; but
  163334. * it must still fit in si bits, since no code is allowed to be all ones.
  163335. */
  163336. if (((INT32) code) >= (((INT32) 1) << si))
  163337. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163338. code <<= 1;
  163339. si++;
  163340. }
  163341. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  163342. p = 0;
  163343. for (l = 1; l <= 16; l++) {
  163344. if (htbl->bits[l]) {
  163345. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  163346. * minus the minimum code of length l
  163347. */
  163348. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  163349. p += htbl->bits[l];
  163350. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  163351. } else {
  163352. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  163353. }
  163354. }
  163355. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  163356. /* Compute lookahead tables to speed up decoding.
  163357. * First we set all the table entries to 0, indicating "too long";
  163358. * then we iterate through the Huffman codes that are short enough and
  163359. * fill in all the entries that correspond to bit sequences starting
  163360. * with that code.
  163361. */
  163362. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  163363. p = 0;
  163364. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  163365. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  163366. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  163367. /* Generate left-justified code followed by all possible bit sequences */
  163368. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  163369. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  163370. dtbl->look_nbits[lookbits] = l;
  163371. dtbl->look_sym[lookbits] = htbl->huffval[p];
  163372. lookbits++;
  163373. }
  163374. }
  163375. }
  163376. /* Validate symbols as being reasonable.
  163377. * For AC tables, we make no check, but accept all byte values 0..255.
  163378. * For DC tables, we require the symbols to be in range 0..15.
  163379. * (Tighter bounds could be applied depending on the data depth and mode,
  163380. * but this is sufficient to ensure safe decoding.)
  163381. */
  163382. if (isDC) {
  163383. for (i = 0; i < numsymbols; i++) {
  163384. int sym = htbl->huffval[i];
  163385. if (sym < 0 || sym > 15)
  163386. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163387. }
  163388. }
  163389. }
  163390. /*
  163391. * Out-of-line code for bit fetching (shared with jdphuff.c).
  163392. * See jdhuff.h for info about usage.
  163393. * Note: current values of get_buffer and bits_left are passed as parameters,
  163394. * but are returned in the corresponding fields of the state struct.
  163395. *
  163396. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  163397. * of get_buffer to be used. (On machines with wider words, an even larger
  163398. * buffer could be used.) However, on some machines 32-bit shifts are
  163399. * quite slow and take time proportional to the number of places shifted.
  163400. * (This is true with most PC compilers, for instance.) In this case it may
  163401. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  163402. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  163403. */
  163404. #ifdef SLOW_SHIFT_32
  163405. #define MIN_GET_BITS 15 /* minimum allowable value */
  163406. #else
  163407. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  163408. #endif
  163409. GLOBAL(boolean)
  163410. jpeg_fill_bit_buffer (bitread_working_state * state,
  163411. register bit_buf_type get_buffer, register int bits_left,
  163412. int nbits)
  163413. /* Load up the bit buffer to a depth of at least nbits */
  163414. {
  163415. /* Copy heavily used state fields into locals (hopefully registers) */
  163416. register const JOCTET * next_input_byte = state->next_input_byte;
  163417. register size_t bytes_in_buffer = state->bytes_in_buffer;
  163418. j_decompress_ptr cinfo = state->cinfo;
  163419. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  163420. /* (It is assumed that no request will be for more than that many bits.) */
  163421. /* We fail to do so only if we hit a marker or are forced to suspend. */
  163422. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  163423. while (bits_left < MIN_GET_BITS) {
  163424. register int c;
  163425. /* Attempt to read a byte */
  163426. if (bytes_in_buffer == 0) {
  163427. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  163428. return FALSE;
  163429. next_input_byte = cinfo->src->next_input_byte;
  163430. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  163431. }
  163432. bytes_in_buffer--;
  163433. c = GETJOCTET(*next_input_byte++);
  163434. /* If it's 0xFF, check and discard stuffed zero byte */
  163435. if (c == 0xFF) {
  163436. /* Loop here to discard any padding FF's on terminating marker,
  163437. * so that we can save a valid unread_marker value. NOTE: we will
  163438. * accept multiple FF's followed by a 0 as meaning a single FF data
  163439. * byte. This data pattern is not valid according to the standard.
  163440. */
  163441. do {
  163442. if (bytes_in_buffer == 0) {
  163443. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  163444. return FALSE;
  163445. next_input_byte = cinfo->src->next_input_byte;
  163446. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  163447. }
  163448. bytes_in_buffer--;
  163449. c = GETJOCTET(*next_input_byte++);
  163450. } while (c == 0xFF);
  163451. if (c == 0) {
  163452. /* Found FF/00, which represents an FF data byte */
  163453. c = 0xFF;
  163454. } else {
  163455. /* Oops, it's actually a marker indicating end of compressed data.
  163456. * Save the marker code for later use.
  163457. * Fine point: it might appear that we should save the marker into
  163458. * bitread working state, not straight into permanent state. But
  163459. * once we have hit a marker, we cannot need to suspend within the
  163460. * current MCU, because we will read no more bytes from the data
  163461. * source. So it is OK to update permanent state right away.
  163462. */
  163463. cinfo->unread_marker = c;
  163464. /* See if we need to insert some fake zero bits. */
  163465. goto no_more_bytes;
  163466. }
  163467. }
  163468. /* OK, load c into get_buffer */
  163469. get_buffer = (get_buffer << 8) | c;
  163470. bits_left += 8;
  163471. } /* end while */
  163472. } else {
  163473. no_more_bytes:
  163474. /* We get here if we've read the marker that terminates the compressed
  163475. * data segment. There should be enough bits in the buffer register
  163476. * to satisfy the request; if so, no problem.
  163477. */
  163478. if (nbits > bits_left) {
  163479. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  163480. * the data stream, so that we can produce some kind of image.
  163481. * We use a nonvolatile flag to ensure that only one warning message
  163482. * appears per data segment.
  163483. */
  163484. if (! cinfo->entropy->insufficient_data) {
  163485. WARNMS(cinfo, JWRN_HIT_MARKER);
  163486. cinfo->entropy->insufficient_data = TRUE;
  163487. }
  163488. /* Fill the buffer with zero bits */
  163489. get_buffer <<= MIN_GET_BITS - bits_left;
  163490. bits_left = MIN_GET_BITS;
  163491. }
  163492. }
  163493. /* Unload the local registers */
  163494. state->next_input_byte = next_input_byte;
  163495. state->bytes_in_buffer = bytes_in_buffer;
  163496. state->get_buffer = get_buffer;
  163497. state->bits_left = bits_left;
  163498. return TRUE;
  163499. }
  163500. /*
  163501. * Out-of-line code for Huffman code decoding.
  163502. * See jdhuff.h for info about usage.
  163503. */
  163504. GLOBAL(int)
  163505. jpeg_huff_decode (bitread_working_state * state,
  163506. register bit_buf_type get_buffer, register int bits_left,
  163507. d_derived_tbl * htbl, int min_bits)
  163508. {
  163509. register int l = min_bits;
  163510. register INT32 code;
  163511. /* HUFF_DECODE has determined that the code is at least min_bits */
  163512. /* bits long, so fetch that many bits in one swoop. */
  163513. CHECK_BIT_BUFFER(*state, l, return -1);
  163514. code = GET_BITS(l);
  163515. /* Collect the rest of the Huffman code one bit at a time. */
  163516. /* This is per Figure F.16 in the JPEG spec. */
  163517. while (code > htbl->maxcode[l]) {
  163518. code <<= 1;
  163519. CHECK_BIT_BUFFER(*state, 1, return -1);
  163520. code |= GET_BITS(1);
  163521. l++;
  163522. }
  163523. /* Unload the local registers */
  163524. state->get_buffer = get_buffer;
  163525. state->bits_left = bits_left;
  163526. /* With garbage input we may reach the sentinel value l = 17. */
  163527. if (l > 16) {
  163528. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  163529. return 0; /* fake a zero as the safest result */
  163530. }
  163531. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  163532. }
  163533. /*
  163534. * Check for a restart marker & resynchronize decoder.
  163535. * Returns FALSE if must suspend.
  163536. */
  163537. LOCAL(boolean)
  163538. process_restart (j_decompress_ptr cinfo)
  163539. {
  163540. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163541. int ci;
  163542. /* Throw away any unused bits remaining in bit buffer; */
  163543. /* include any full bytes in next_marker's count of discarded bytes */
  163544. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  163545. entropy->bitstate.bits_left = 0;
  163546. /* Advance past the RSTn marker */
  163547. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  163548. return FALSE;
  163549. /* Re-initialize DC predictions to 0 */
  163550. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163551. entropy->saved.last_dc_val[ci] = 0;
  163552. /* Reset restart counter */
  163553. entropy->restarts_to_go = cinfo->restart_interval;
  163554. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  163555. * against a marker. In that case we will end up treating the next data
  163556. * segment as empty, and we can avoid producing bogus output pixels by
  163557. * leaving the flag set.
  163558. */
  163559. if (cinfo->unread_marker == 0)
  163560. entropy->pub.insufficient_data = FALSE;
  163561. return TRUE;
  163562. }
  163563. /*
  163564. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  163565. * The coefficients are reordered from zigzag order into natural array order,
  163566. * but are not dequantized.
  163567. *
  163568. * The i'th block of the MCU is stored into the block pointed to by
  163569. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  163570. * (Wholesale zeroing is usually a little faster than retail...)
  163571. *
  163572. * Returns FALSE if data source requested suspension. In that case no
  163573. * changes have been made to permanent state. (Exception: some output
  163574. * coefficients may already have been assigned. This is harmless for
  163575. * this module, since we'll just re-assign them on the next call.)
  163576. */
  163577. METHODDEF(boolean)
  163578. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  163579. {
  163580. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163581. int blkn;
  163582. BITREAD_STATE_VARS;
  163583. savable_state2 state;
  163584. /* Process restart marker if needed; may have to suspend */
  163585. if (cinfo->restart_interval) {
  163586. if (entropy->restarts_to_go == 0)
  163587. if (! process_restart(cinfo))
  163588. return FALSE;
  163589. }
  163590. /* If we've run out of data, just leave the MCU set to zeroes.
  163591. * This way, we return uniform gray for the remainder of the segment.
  163592. */
  163593. if (! entropy->pub.insufficient_data) {
  163594. /* Load up working state */
  163595. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  163596. ASSIGN_STATE(state, entropy->saved);
  163597. /* Outer loop handles each block in the MCU */
  163598. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163599. JBLOCKROW block = MCU_data[blkn];
  163600. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  163601. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  163602. register int s, k, r;
  163603. /* Decode a single block's worth of coefficients */
  163604. /* Section F.2.2.1: decode the DC coefficient difference */
  163605. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  163606. if (s) {
  163607. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163608. r = GET_BITS(s);
  163609. s = HUFF_EXTEND(r, s);
  163610. }
  163611. if (entropy->dc_needed[blkn]) {
  163612. /* Convert DC difference to actual value, update last_dc_val */
  163613. int ci = cinfo->MCU_membership[blkn];
  163614. s += state.last_dc_val[ci];
  163615. state.last_dc_val[ci] = s;
  163616. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  163617. (*block)[0] = (JCOEF) s;
  163618. }
  163619. if (entropy->ac_needed[blkn]) {
  163620. /* Section F.2.2.2: decode the AC coefficients */
  163621. /* Since zeroes are skipped, output area must be cleared beforehand */
  163622. for (k = 1; k < DCTSIZE2; k++) {
  163623. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  163624. r = s >> 4;
  163625. s &= 15;
  163626. if (s) {
  163627. k += r;
  163628. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163629. r = GET_BITS(s);
  163630. s = HUFF_EXTEND(r, s);
  163631. /* Output coefficient in natural (dezigzagged) order.
  163632. * Note: the extra entries in jpeg_natural_order[] will save us
  163633. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  163634. */
  163635. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  163636. } else {
  163637. if (r != 15)
  163638. break;
  163639. k += 15;
  163640. }
  163641. }
  163642. } else {
  163643. /* Section F.2.2.2: decode the AC coefficients */
  163644. /* In this path we just discard the values */
  163645. for (k = 1; k < DCTSIZE2; k++) {
  163646. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  163647. r = s >> 4;
  163648. s &= 15;
  163649. if (s) {
  163650. k += r;
  163651. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163652. DROP_BITS(s);
  163653. } else {
  163654. if (r != 15)
  163655. break;
  163656. k += 15;
  163657. }
  163658. }
  163659. }
  163660. }
  163661. /* Completed MCU, so update state */
  163662. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  163663. ASSIGN_STATE(entropy->saved, state);
  163664. }
  163665. /* Account for restart interval (no-op if not using restarts) */
  163666. entropy->restarts_to_go--;
  163667. return TRUE;
  163668. }
  163669. /*
  163670. * Module initialization routine for Huffman entropy decoding.
  163671. */
  163672. GLOBAL(void)
  163673. jinit_huff_decoder (j_decompress_ptr cinfo)
  163674. {
  163675. huff_entropy_ptr2 entropy;
  163676. int i;
  163677. entropy = (huff_entropy_ptr2)
  163678. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163679. SIZEOF(huff_entropy_decoder2));
  163680. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  163681. entropy->pub.start_pass = start_pass_huff_decoder;
  163682. entropy->pub.decode_mcu = decode_mcu;
  163683. /* Mark tables unallocated */
  163684. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163685. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163686. }
  163687. }
  163688. /********* End of inlined file: jdhuff.c *********/
  163689. /********* Start of inlined file: jdinput.c *********/
  163690. #define JPEG_INTERNALS
  163691. /* Private state */
  163692. typedef struct {
  163693. struct jpeg_input_controller pub; /* public fields */
  163694. boolean inheaders; /* TRUE until first SOS is reached */
  163695. } my_input_controller;
  163696. typedef my_input_controller * my_inputctl_ptr;
  163697. /* Forward declarations */
  163698. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  163699. /*
  163700. * Routines to calculate various quantities related to the size of the image.
  163701. */
  163702. LOCAL(void)
  163703. initial_setup2 (j_decompress_ptr cinfo)
  163704. /* Called once, when first SOS marker is reached */
  163705. {
  163706. int ci;
  163707. jpeg_component_info *compptr;
  163708. /* Make sure image isn't bigger than I can handle */
  163709. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163710. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163711. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163712. /* For now, precision must match compiled-in value... */
  163713. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163714. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163715. /* Check that number of components won't exceed internal array sizes */
  163716. if (cinfo->num_components > MAX_COMPONENTS)
  163717. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163718. MAX_COMPONENTS);
  163719. /* Compute maximum sampling factors; check factor validity */
  163720. cinfo->max_h_samp_factor = 1;
  163721. cinfo->max_v_samp_factor = 1;
  163722. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163723. ci++, compptr++) {
  163724. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163725. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163726. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163727. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163728. compptr->h_samp_factor);
  163729. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163730. compptr->v_samp_factor);
  163731. }
  163732. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  163733. * In the full decompressor, this will be overridden by jdmaster.c;
  163734. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  163735. */
  163736. cinfo->min_DCT_scaled_size = DCTSIZE;
  163737. /* Compute dimensions of components */
  163738. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163739. ci++, compptr++) {
  163740. compptr->DCT_scaled_size = DCTSIZE;
  163741. /* Size in DCT blocks */
  163742. compptr->width_in_blocks = (JDIMENSION)
  163743. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163744. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163745. compptr->height_in_blocks = (JDIMENSION)
  163746. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163747. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163748. /* downsampled_width and downsampled_height will also be overridden by
  163749. * jdmaster.c if we are doing full decompression. The transcoder library
  163750. * doesn't use these values, but the calling application might.
  163751. */
  163752. /* Size in samples */
  163753. compptr->downsampled_width = (JDIMENSION)
  163754. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163755. (long) cinfo->max_h_samp_factor);
  163756. compptr->downsampled_height = (JDIMENSION)
  163757. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163758. (long) cinfo->max_v_samp_factor);
  163759. /* Mark component needed, until color conversion says otherwise */
  163760. compptr->component_needed = TRUE;
  163761. /* Mark no quantization table yet saved for component */
  163762. compptr->quant_table = NULL;
  163763. }
  163764. /* Compute number of fully interleaved MCU rows. */
  163765. cinfo->total_iMCU_rows = (JDIMENSION)
  163766. jdiv_round_up((long) cinfo->image_height,
  163767. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163768. /* Decide whether file contains multiple scans */
  163769. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  163770. cinfo->inputctl->has_multiple_scans = TRUE;
  163771. else
  163772. cinfo->inputctl->has_multiple_scans = FALSE;
  163773. }
  163774. LOCAL(void)
  163775. per_scan_setup2 (j_decompress_ptr cinfo)
  163776. /* Do computations that are needed before processing a JPEG scan */
  163777. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  163778. {
  163779. int ci, mcublks, tmp;
  163780. jpeg_component_info *compptr;
  163781. if (cinfo->comps_in_scan == 1) {
  163782. /* Noninterleaved (single-component) scan */
  163783. compptr = cinfo->cur_comp_info[0];
  163784. /* Overall image size in MCUs */
  163785. cinfo->MCUs_per_row = compptr->width_in_blocks;
  163786. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  163787. /* For noninterleaved scan, always one block per MCU */
  163788. compptr->MCU_width = 1;
  163789. compptr->MCU_height = 1;
  163790. compptr->MCU_blocks = 1;
  163791. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  163792. compptr->last_col_width = 1;
  163793. /* For noninterleaved scans, it is convenient to define last_row_height
  163794. * as the number of block rows present in the last iMCU row.
  163795. */
  163796. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163797. if (tmp == 0) tmp = compptr->v_samp_factor;
  163798. compptr->last_row_height = tmp;
  163799. /* Prepare array describing MCU composition */
  163800. cinfo->blocks_in_MCU = 1;
  163801. cinfo->MCU_membership[0] = 0;
  163802. } else {
  163803. /* Interleaved (multi-component) scan */
  163804. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  163805. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  163806. MAX_COMPS_IN_SCAN);
  163807. /* Overall image size in MCUs */
  163808. cinfo->MCUs_per_row = (JDIMENSION)
  163809. jdiv_round_up((long) cinfo->image_width,
  163810. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  163811. cinfo->MCU_rows_in_scan = (JDIMENSION)
  163812. jdiv_round_up((long) cinfo->image_height,
  163813. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163814. cinfo->blocks_in_MCU = 0;
  163815. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163816. compptr = cinfo->cur_comp_info[ci];
  163817. /* Sampling factors give # of blocks of component in each MCU */
  163818. compptr->MCU_width = compptr->h_samp_factor;
  163819. compptr->MCU_height = compptr->v_samp_factor;
  163820. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  163821. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  163822. /* Figure number of non-dummy blocks in last MCU column & row */
  163823. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  163824. if (tmp == 0) tmp = compptr->MCU_width;
  163825. compptr->last_col_width = tmp;
  163826. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  163827. if (tmp == 0) tmp = compptr->MCU_height;
  163828. compptr->last_row_height = tmp;
  163829. /* Prepare array describing MCU composition */
  163830. mcublks = compptr->MCU_blocks;
  163831. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  163832. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  163833. while (mcublks-- > 0) {
  163834. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  163835. }
  163836. }
  163837. }
  163838. }
  163839. /*
  163840. * Save away a copy of the Q-table referenced by each component present
  163841. * in the current scan, unless already saved during a prior scan.
  163842. *
  163843. * In a multiple-scan JPEG file, the encoder could assign different components
  163844. * the same Q-table slot number, but change table definitions between scans
  163845. * so that each component uses a different Q-table. (The IJG encoder is not
  163846. * currently capable of doing this, but other encoders might.) Since we want
  163847. * to be able to dequantize all the components at the end of the file, this
  163848. * means that we have to save away the table actually used for each component.
  163849. * We do this by copying the table at the start of the first scan containing
  163850. * the component.
  163851. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  163852. * slot between scans of a component using that slot. If the encoder does so
  163853. * anyway, this decoder will simply use the Q-table values that were current
  163854. * at the start of the first scan for the component.
  163855. *
  163856. * The decompressor output side looks only at the saved quant tables,
  163857. * not at the current Q-table slots.
  163858. */
  163859. LOCAL(void)
  163860. latch_quant_tables (j_decompress_ptr cinfo)
  163861. {
  163862. int ci, qtblno;
  163863. jpeg_component_info *compptr;
  163864. JQUANT_TBL * qtbl;
  163865. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163866. compptr = cinfo->cur_comp_info[ci];
  163867. /* No work if we already saved Q-table for this component */
  163868. if (compptr->quant_table != NULL)
  163869. continue;
  163870. /* Make sure specified quantization table is present */
  163871. qtblno = compptr->quant_tbl_no;
  163872. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163873. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163874. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163875. /* OK, save away the quantization table */
  163876. qtbl = (JQUANT_TBL *)
  163877. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163878. SIZEOF(JQUANT_TBL));
  163879. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  163880. compptr->quant_table = qtbl;
  163881. }
  163882. }
  163883. /*
  163884. * Initialize the input modules to read a scan of compressed data.
  163885. * The first call to this is done by jdmaster.c after initializing
  163886. * the entire decompressor (during jpeg_start_decompress).
  163887. * Subsequent calls come from consume_markers, below.
  163888. */
  163889. METHODDEF(void)
  163890. start_input_pass2 (j_decompress_ptr cinfo)
  163891. {
  163892. per_scan_setup2(cinfo);
  163893. latch_quant_tables(cinfo);
  163894. (*cinfo->entropy->start_pass) (cinfo);
  163895. (*cinfo->coef->start_input_pass) (cinfo);
  163896. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  163897. }
  163898. /*
  163899. * Finish up after inputting a compressed-data scan.
  163900. * This is called by the coefficient controller after it's read all
  163901. * the expected data of the scan.
  163902. */
  163903. METHODDEF(void)
  163904. finish_input_pass (j_decompress_ptr cinfo)
  163905. {
  163906. cinfo->inputctl->consume_input = consume_markers;
  163907. }
  163908. /*
  163909. * Read JPEG markers before, between, or after compressed-data scans.
  163910. * Change state as necessary when a new scan is reached.
  163911. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  163912. *
  163913. * The consume_input method pointer points either here or to the
  163914. * coefficient controller's consume_data routine, depending on whether
  163915. * we are reading a compressed data segment or inter-segment markers.
  163916. */
  163917. METHODDEF(int)
  163918. consume_markers (j_decompress_ptr cinfo)
  163919. {
  163920. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  163921. int val;
  163922. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  163923. return JPEG_REACHED_EOI;
  163924. val = (*cinfo->marker->read_markers) (cinfo);
  163925. switch (val) {
  163926. case JPEG_REACHED_SOS: /* Found SOS */
  163927. if (inputctl->inheaders) { /* 1st SOS */
  163928. initial_setup2(cinfo);
  163929. inputctl->inheaders = FALSE;
  163930. /* Note: start_input_pass must be called by jdmaster.c
  163931. * before any more input can be consumed. jdapimin.c is
  163932. * responsible for enforcing this sequencing.
  163933. */
  163934. } else { /* 2nd or later SOS marker */
  163935. if (! inputctl->pub.has_multiple_scans)
  163936. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  163937. start_input_pass2(cinfo);
  163938. }
  163939. break;
  163940. case JPEG_REACHED_EOI: /* Found EOI */
  163941. inputctl->pub.eoi_reached = TRUE;
  163942. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  163943. if (cinfo->marker->saw_SOF)
  163944. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  163945. } else {
  163946. /* Prevent infinite loop in coef ctlr's decompress_data routine
  163947. * if user set output_scan_number larger than number of scans.
  163948. */
  163949. if (cinfo->output_scan_number > cinfo->input_scan_number)
  163950. cinfo->output_scan_number = cinfo->input_scan_number;
  163951. }
  163952. break;
  163953. case JPEG_SUSPENDED:
  163954. break;
  163955. }
  163956. return val;
  163957. }
  163958. /*
  163959. * Reset state to begin a fresh datastream.
  163960. */
  163961. METHODDEF(void)
  163962. reset_input_controller (j_decompress_ptr cinfo)
  163963. {
  163964. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  163965. inputctl->pub.consume_input = consume_markers;
  163966. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  163967. inputctl->pub.eoi_reached = FALSE;
  163968. inputctl->inheaders = TRUE;
  163969. /* Reset other modules */
  163970. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  163971. (*cinfo->marker->reset_marker_reader) (cinfo);
  163972. /* Reset progression state -- would be cleaner if entropy decoder did this */
  163973. cinfo->coef_bits = NULL;
  163974. }
  163975. /*
  163976. * Initialize the input controller module.
  163977. * This is called only once, when the decompression object is created.
  163978. */
  163979. GLOBAL(void)
  163980. jinit_input_controller (j_decompress_ptr cinfo)
  163981. {
  163982. my_inputctl_ptr inputctl;
  163983. /* Create subobject in permanent pool */
  163984. inputctl = (my_inputctl_ptr)
  163985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  163986. SIZEOF(my_input_controller));
  163987. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  163988. /* Initialize method pointers */
  163989. inputctl->pub.consume_input = consume_markers;
  163990. inputctl->pub.reset_input_controller = reset_input_controller;
  163991. inputctl->pub.start_input_pass = start_input_pass2;
  163992. inputctl->pub.finish_input_pass = finish_input_pass;
  163993. /* Initialize state: can't use reset_input_controller since we don't
  163994. * want to try to reset other modules yet.
  163995. */
  163996. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  163997. inputctl->pub.eoi_reached = FALSE;
  163998. inputctl->inheaders = TRUE;
  163999. }
  164000. /********* End of inlined file: jdinput.c *********/
  164001. /********* Start of inlined file: jdmainct.c *********/
  164002. #define JPEG_INTERNALS
  164003. /*
  164004. * In the current system design, the main buffer need never be a full-image
  164005. * buffer; any full-height buffers will be found inside the coefficient or
  164006. * postprocessing controllers. Nonetheless, the main controller is not
  164007. * trivial. Its responsibility is to provide context rows for upsampling/
  164008. * rescaling, and doing this in an efficient fashion is a bit tricky.
  164009. *
  164010. * Postprocessor input data is counted in "row groups". A row group
  164011. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  164012. * sample rows of each component. (We require DCT_scaled_size values to be
  164013. * chosen such that these numbers are integers. In practice DCT_scaled_size
  164014. * values will likely be powers of two, so we actually have the stronger
  164015. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  164016. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  164017. * row group (times any additional scale factor that the upsampler is
  164018. * applying).
  164019. *
  164020. * The coefficient controller will deliver data to us one iMCU row at a time;
  164021. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  164022. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  164023. * to one row of MCUs when the image is fully interleaved.) Note that the
  164024. * number of sample rows varies across components, but the number of row
  164025. * groups does not. Some garbage sample rows may be included in the last iMCU
  164026. * row at the bottom of the image.
  164027. *
  164028. * Depending on the vertical scaling algorithm used, the upsampler may need
  164029. * access to the sample row(s) above and below its current input row group.
  164030. * The upsampler is required to set need_context_rows TRUE at global selection
  164031. * time if so. When need_context_rows is FALSE, this controller can simply
  164032. * obtain one iMCU row at a time from the coefficient controller and dole it
  164033. * out as row groups to the postprocessor.
  164034. *
  164035. * When need_context_rows is TRUE, this controller guarantees that the buffer
  164036. * passed to postprocessing contains at least one row group's worth of samples
  164037. * above and below the row group(s) being processed. Note that the context
  164038. * rows "above" the first passed row group appear at negative row offsets in
  164039. * the passed buffer. At the top and bottom of the image, the required
  164040. * context rows are manufactured by duplicating the first or last real sample
  164041. * row; this avoids having special cases in the upsampling inner loops.
  164042. *
  164043. * The amount of context is fixed at one row group just because that's a
  164044. * convenient number for this controller to work with. The existing
  164045. * upsamplers really only need one sample row of context. An upsampler
  164046. * supporting arbitrary output rescaling might wish for more than one row
  164047. * group of context when shrinking the image; tough, we don't handle that.
  164048. * (This is justified by the assumption that downsizing will be handled mostly
  164049. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  164050. * the upsample step needn't be much less than one.)
  164051. *
  164052. * To provide the desired context, we have to retain the last two row groups
  164053. * of one iMCU row while reading in the next iMCU row. (The last row group
  164054. * can't be processed until we have another row group for its below-context,
  164055. * and so we have to save the next-to-last group too for its above-context.)
  164056. * We could do this most simply by copying data around in our buffer, but
  164057. * that'd be very slow. We can avoid copying any data by creating a rather
  164058. * strange pointer structure. Here's how it works. We allocate a workspace
  164059. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  164060. * of row groups per iMCU row). We create two sets of redundant pointers to
  164061. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  164062. * pointer lists look like this:
  164063. * M+1 M-1
  164064. * master pointer --> 0 master pointer --> 0
  164065. * 1 1
  164066. * ... ...
  164067. * M-3 M-3
  164068. * M-2 M
  164069. * M-1 M+1
  164070. * M M-2
  164071. * M+1 M-1
  164072. * 0 0
  164073. * We read alternate iMCU rows using each master pointer; thus the last two
  164074. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  164075. * The pointer lists are set up so that the required context rows appear to
  164076. * be adjacent to the proper places when we pass the pointer lists to the
  164077. * upsampler.
  164078. *
  164079. * The above pictures describe the normal state of the pointer lists.
  164080. * At top and bottom of the image, we diddle the pointer lists to duplicate
  164081. * the first or last sample row as necessary (this is cheaper than copying
  164082. * sample rows around).
  164083. *
  164084. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  164085. * situation each iMCU row provides only one row group so the buffering logic
  164086. * must be different (eg, we must read two iMCU rows before we can emit the
  164087. * first row group). For now, we simply do not support providing context
  164088. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  164089. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  164090. * want it quick and dirty, so a context-free upsampler is sufficient.
  164091. */
  164092. /* Private buffer controller object */
  164093. typedef struct {
  164094. struct jpeg_d_main_controller pub; /* public fields */
  164095. /* Pointer to allocated workspace (M or M+2 row groups). */
  164096. JSAMPARRAY buffer[MAX_COMPONENTS];
  164097. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  164098. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  164099. /* Remaining fields are only used in the context case. */
  164100. /* These are the master pointers to the funny-order pointer lists. */
  164101. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  164102. int whichptr; /* indicates which pointer set is now in use */
  164103. int context_state; /* process_data state machine status */
  164104. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  164105. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  164106. } my_main_controller4;
  164107. typedef my_main_controller4 * my_main_ptr4;
  164108. /* context_state values: */
  164109. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  164110. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  164111. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  164112. /* Forward declarations */
  164113. METHODDEF(void) process_data_simple_main2
  164114. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164115. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164116. METHODDEF(void) process_data_context_main
  164117. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164118. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164119. #ifdef QUANT_2PASS_SUPPORTED
  164120. METHODDEF(void) process_data_crank_post
  164121. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164122. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164123. #endif
  164124. LOCAL(void)
  164125. alloc_funny_pointers (j_decompress_ptr cinfo)
  164126. /* Allocate space for the funny pointer lists.
  164127. * This is done only once, not once per pass.
  164128. */
  164129. {
  164130. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164131. int ci, rgroup;
  164132. int M = cinfo->min_DCT_scaled_size;
  164133. jpeg_component_info *compptr;
  164134. JSAMPARRAY xbuf;
  164135. /* Get top-level space for component array pointers.
  164136. * We alloc both arrays with one call to save a few cycles.
  164137. */
  164138. main_->xbuffer[0] = (JSAMPIMAGE)
  164139. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164140. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  164141. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  164142. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164143. ci++, compptr++) {
  164144. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164145. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164146. /* Get space for pointer lists --- M+4 row groups in each list.
  164147. * We alloc both pointer lists with one call to save a few cycles.
  164148. */
  164149. xbuf = (JSAMPARRAY)
  164150. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164151. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  164152. xbuf += rgroup; /* want one row group at negative offsets */
  164153. main_->xbuffer[0][ci] = xbuf;
  164154. xbuf += rgroup * (M + 4);
  164155. main_->xbuffer[1][ci] = xbuf;
  164156. }
  164157. }
  164158. LOCAL(void)
  164159. make_funny_pointers (j_decompress_ptr cinfo)
  164160. /* Create the funny pointer lists discussed in the comments above.
  164161. * The actual workspace is already allocated (in main->buffer),
  164162. * and the space for the pointer lists is allocated too.
  164163. * This routine just fills in the curiously ordered lists.
  164164. * This will be repeated at the beginning of each pass.
  164165. */
  164166. {
  164167. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164168. int ci, i, rgroup;
  164169. int M = cinfo->min_DCT_scaled_size;
  164170. jpeg_component_info *compptr;
  164171. JSAMPARRAY buf, xbuf0, xbuf1;
  164172. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164173. ci++, compptr++) {
  164174. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164175. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164176. xbuf0 = main_->xbuffer[0][ci];
  164177. xbuf1 = main_->xbuffer[1][ci];
  164178. /* First copy the workspace pointers as-is */
  164179. buf = main_->buffer[ci];
  164180. for (i = 0; i < rgroup * (M + 2); i++) {
  164181. xbuf0[i] = xbuf1[i] = buf[i];
  164182. }
  164183. /* In the second list, put the last four row groups in swapped order */
  164184. for (i = 0; i < rgroup * 2; i++) {
  164185. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  164186. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  164187. }
  164188. /* The wraparound pointers at top and bottom will be filled later
  164189. * (see set_wraparound_pointers, below). Initially we want the "above"
  164190. * pointers to duplicate the first actual data line. This only needs
  164191. * to happen in xbuffer[0].
  164192. */
  164193. for (i = 0; i < rgroup; i++) {
  164194. xbuf0[i - rgroup] = xbuf0[0];
  164195. }
  164196. }
  164197. }
  164198. LOCAL(void)
  164199. set_wraparound_pointers (j_decompress_ptr cinfo)
  164200. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  164201. * This changes the pointer list state from top-of-image to the normal state.
  164202. */
  164203. {
  164204. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164205. int ci, i, rgroup;
  164206. int M = cinfo->min_DCT_scaled_size;
  164207. jpeg_component_info *compptr;
  164208. JSAMPARRAY xbuf0, xbuf1;
  164209. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164210. ci++, compptr++) {
  164211. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164212. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164213. xbuf0 = main_->xbuffer[0][ci];
  164214. xbuf1 = main_->xbuffer[1][ci];
  164215. for (i = 0; i < rgroup; i++) {
  164216. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  164217. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  164218. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  164219. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  164220. }
  164221. }
  164222. }
  164223. LOCAL(void)
  164224. set_bottom_pointers (j_decompress_ptr cinfo)
  164225. /* Change the pointer lists to duplicate the last sample row at the bottom
  164226. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  164227. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  164228. */
  164229. {
  164230. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164231. int ci, i, rgroup, iMCUheight, rows_left;
  164232. jpeg_component_info *compptr;
  164233. JSAMPARRAY xbuf;
  164234. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164235. ci++, compptr++) {
  164236. /* Count sample rows in one iMCU row and in one row group */
  164237. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  164238. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  164239. /* Count nondummy sample rows remaining for this component */
  164240. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  164241. if (rows_left == 0) rows_left = iMCUheight;
  164242. /* Count nondummy row groups. Should get same answer for each component,
  164243. * so we need only do it once.
  164244. */
  164245. if (ci == 0) {
  164246. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  164247. }
  164248. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  164249. * last partial rowgroup and ensures at least one full rowgroup of context.
  164250. */
  164251. xbuf = main_->xbuffer[main_->whichptr][ci];
  164252. for (i = 0; i < rgroup * 2; i++) {
  164253. xbuf[rows_left + i] = xbuf[rows_left-1];
  164254. }
  164255. }
  164256. }
  164257. /*
  164258. * Initialize for a processing pass.
  164259. */
  164260. METHODDEF(void)
  164261. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  164262. {
  164263. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164264. switch (pass_mode) {
  164265. case JBUF_PASS_THRU:
  164266. if (cinfo->upsample->need_context_rows) {
  164267. main_->pub.process_data = process_data_context_main;
  164268. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  164269. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  164270. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164271. main_->iMCU_row_ctr = 0;
  164272. } else {
  164273. /* Simple case with no context needed */
  164274. main_->pub.process_data = process_data_simple_main2;
  164275. }
  164276. main_->buffer_full = FALSE; /* Mark buffer empty */
  164277. main_->rowgroup_ctr = 0;
  164278. break;
  164279. #ifdef QUANT_2PASS_SUPPORTED
  164280. case JBUF_CRANK_DEST:
  164281. /* For last pass of 2-pass quantization, just crank the postprocessor */
  164282. main_->pub.process_data = process_data_crank_post;
  164283. break;
  164284. #endif
  164285. default:
  164286. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164287. break;
  164288. }
  164289. }
  164290. /*
  164291. * Process some data.
  164292. * This handles the simple case where no context is required.
  164293. */
  164294. METHODDEF(void)
  164295. process_data_simple_main2 (j_decompress_ptr cinfo,
  164296. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164297. JDIMENSION out_rows_avail)
  164298. {
  164299. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164300. JDIMENSION rowgroups_avail;
  164301. /* Read input data if we haven't filled the main buffer yet */
  164302. if (! main_->buffer_full) {
  164303. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  164304. return; /* suspension forced, can do nothing more */
  164305. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  164306. }
  164307. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  164308. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  164309. /* Note: at the bottom of the image, we may pass extra garbage row groups
  164310. * to the postprocessor. The postprocessor has to check for bottom
  164311. * of image anyway (at row resolution), so no point in us doing it too.
  164312. */
  164313. /* Feed the postprocessor */
  164314. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  164315. &main_->rowgroup_ctr, rowgroups_avail,
  164316. output_buf, out_row_ctr, out_rows_avail);
  164317. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  164318. if (main_->rowgroup_ctr >= rowgroups_avail) {
  164319. main_->buffer_full = FALSE;
  164320. main_->rowgroup_ctr = 0;
  164321. }
  164322. }
  164323. /*
  164324. * Process some data.
  164325. * This handles the case where context rows must be provided.
  164326. */
  164327. METHODDEF(void)
  164328. process_data_context_main (j_decompress_ptr cinfo,
  164329. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164330. JDIMENSION out_rows_avail)
  164331. {
  164332. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164333. /* Read input data if we haven't filled the main buffer yet */
  164334. if (! main_->buffer_full) {
  164335. if (! (*cinfo->coef->decompress_data) (cinfo,
  164336. main_->xbuffer[main_->whichptr]))
  164337. return; /* suspension forced, can do nothing more */
  164338. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  164339. main_->iMCU_row_ctr++; /* count rows received */
  164340. }
  164341. /* Postprocessor typically will not swallow all the input data it is handed
  164342. * in one call (due to filling the output buffer first). Must be prepared
  164343. * to exit and restart. This switch lets us keep track of how far we got.
  164344. * Note that each case falls through to the next on successful completion.
  164345. */
  164346. switch (main_->context_state) {
  164347. case CTX_POSTPONED_ROW:
  164348. /* Call postprocessor using previously set pointers for postponed row */
  164349. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  164350. &main_->rowgroup_ctr, main_->rowgroups_avail,
  164351. output_buf, out_row_ctr, out_rows_avail);
  164352. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  164353. return; /* Need to suspend */
  164354. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164355. if (*out_row_ctr >= out_rows_avail)
  164356. return; /* Postprocessor exactly filled output buf */
  164357. /*FALLTHROUGH*/
  164358. case CTX_PREPARE_FOR_IMCU:
  164359. /* Prepare to process first M-1 row groups of this iMCU row */
  164360. main_->rowgroup_ctr = 0;
  164361. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  164362. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  164363. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  164364. */
  164365. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  164366. set_bottom_pointers(cinfo);
  164367. main_->context_state = CTX_PROCESS_IMCU;
  164368. /*FALLTHROUGH*/
  164369. case CTX_PROCESS_IMCU:
  164370. /* Call postprocessor using previously set pointers */
  164371. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  164372. &main_->rowgroup_ctr, main_->rowgroups_avail,
  164373. output_buf, out_row_ctr, out_rows_avail);
  164374. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  164375. return; /* Need to suspend */
  164376. /* After the first iMCU, change wraparound pointers to normal state */
  164377. if (main_->iMCU_row_ctr == 1)
  164378. set_wraparound_pointers(cinfo);
  164379. /* Prepare to load new iMCU row using other xbuffer list */
  164380. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  164381. main_->buffer_full = FALSE;
  164382. /* Still need to process last row group of this iMCU row, */
  164383. /* which is saved at index M+1 of the other xbuffer */
  164384. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  164385. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  164386. main_->context_state = CTX_POSTPONED_ROW;
  164387. }
  164388. }
  164389. /*
  164390. * Process some data.
  164391. * Final pass of two-pass quantization: just call the postprocessor.
  164392. * Source data will be the postprocessor controller's internal buffer.
  164393. */
  164394. #ifdef QUANT_2PASS_SUPPORTED
  164395. METHODDEF(void)
  164396. process_data_crank_post (j_decompress_ptr cinfo,
  164397. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164398. JDIMENSION out_rows_avail)
  164399. {
  164400. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  164401. (JDIMENSION *) NULL, (JDIMENSION) 0,
  164402. output_buf, out_row_ctr, out_rows_avail);
  164403. }
  164404. #endif /* QUANT_2PASS_SUPPORTED */
  164405. /*
  164406. * Initialize main buffer controller.
  164407. */
  164408. GLOBAL(void)
  164409. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164410. {
  164411. my_main_ptr4 main_;
  164412. int ci, rgroup, ngroups;
  164413. jpeg_component_info *compptr;
  164414. main_ = (my_main_ptr4)
  164415. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164416. SIZEOF(my_main_controller4));
  164417. cinfo->main = (struct jpeg_d_main_controller *) main_;
  164418. main_->pub.start_pass = start_pass_main2;
  164419. if (need_full_buffer) /* shouldn't happen */
  164420. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164421. /* Allocate the workspace.
  164422. * ngroups is the number of row groups we need.
  164423. */
  164424. if (cinfo->upsample->need_context_rows) {
  164425. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  164426. ERREXIT(cinfo, JERR_NOTIMPL);
  164427. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  164428. ngroups = cinfo->min_DCT_scaled_size + 2;
  164429. } else {
  164430. ngroups = cinfo->min_DCT_scaled_size;
  164431. }
  164432. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164433. ci++, compptr++) {
  164434. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164435. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164436. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164437. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164438. compptr->width_in_blocks * compptr->DCT_scaled_size,
  164439. (JDIMENSION) (rgroup * ngroups));
  164440. }
  164441. }
  164442. /********* End of inlined file: jdmainct.c *********/
  164443. /********* Start of inlined file: jdmarker.c *********/
  164444. #define JPEG_INTERNALS
  164445. /* Private state */
  164446. typedef struct {
  164447. struct jpeg_marker_reader pub; /* public fields */
  164448. /* Application-overridable marker processing methods */
  164449. jpeg_marker_parser_method process_COM;
  164450. jpeg_marker_parser_method process_APPn[16];
  164451. /* Limit on marker data length to save for each marker type */
  164452. unsigned int length_limit_COM;
  164453. unsigned int length_limit_APPn[16];
  164454. /* Status of COM/APPn marker saving */
  164455. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  164456. unsigned int bytes_read; /* data bytes read so far in marker */
  164457. /* Note: cur_marker is not linked into marker_list until it's all read. */
  164458. } my_marker_reader;
  164459. typedef my_marker_reader * my_marker_ptr2;
  164460. /*
  164461. * Macros for fetching data from the data source module.
  164462. *
  164463. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  164464. * the current restart point; we update them only when we have reached a
  164465. * suitable place to restart if a suspension occurs.
  164466. */
  164467. /* Declare and initialize local copies of input pointer/count */
  164468. #define INPUT_VARS(cinfo) \
  164469. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  164470. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  164471. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  164472. /* Unload the local copies --- do this only at a restart boundary */
  164473. #define INPUT_SYNC(cinfo) \
  164474. ( datasrc->next_input_byte = next_input_byte, \
  164475. datasrc->bytes_in_buffer = bytes_in_buffer )
  164476. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  164477. #define INPUT_RELOAD(cinfo) \
  164478. ( next_input_byte = datasrc->next_input_byte, \
  164479. bytes_in_buffer = datasrc->bytes_in_buffer )
  164480. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  164481. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  164482. * but we must reload the local copies after a successful fill.
  164483. */
  164484. #define MAKE_BYTE_AVAIL(cinfo,action) \
  164485. if (bytes_in_buffer == 0) { \
  164486. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  164487. { action; } \
  164488. INPUT_RELOAD(cinfo); \
  164489. }
  164490. /* Read a byte into variable V.
  164491. * If must suspend, take the specified action (typically "return FALSE").
  164492. */
  164493. #define INPUT_BYTE(cinfo,V,action) \
  164494. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  164495. bytes_in_buffer--; \
  164496. V = GETJOCTET(*next_input_byte++); )
  164497. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  164498. * V should be declared unsigned int or perhaps INT32.
  164499. */
  164500. #define INPUT_2BYTES(cinfo,V,action) \
  164501. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  164502. bytes_in_buffer--; \
  164503. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  164504. MAKE_BYTE_AVAIL(cinfo,action); \
  164505. bytes_in_buffer--; \
  164506. V += GETJOCTET(*next_input_byte++); )
  164507. /*
  164508. * Routines to process JPEG markers.
  164509. *
  164510. * Entry condition: JPEG marker itself has been read and its code saved
  164511. * in cinfo->unread_marker; input restart point is just after the marker.
  164512. *
  164513. * Exit: if return TRUE, have read and processed any parameters, and have
  164514. * updated the restart point to point after the parameters.
  164515. * If return FALSE, was forced to suspend before reaching end of
  164516. * marker parameters; restart point has not been moved. Same routine
  164517. * will be called again after application supplies more input data.
  164518. *
  164519. * This approach to suspension assumes that all of a marker's parameters
  164520. * can fit into a single input bufferload. This should hold for "normal"
  164521. * markers. Some COM/APPn markers might have large parameter segments
  164522. * that might not fit. If we are simply dropping such a marker, we use
  164523. * skip_input_data to get past it, and thereby put the problem on the
  164524. * source manager's shoulders. If we are saving the marker's contents
  164525. * into memory, we use a slightly different convention: when forced to
  164526. * suspend, the marker processor updates the restart point to the end of
  164527. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  164528. * On resumption, cinfo->unread_marker still contains the marker code,
  164529. * but the data source will point to the next chunk of marker data.
  164530. * The marker processor must retain internal state to deal with this.
  164531. *
  164532. * Note that we don't bother to avoid duplicate trace messages if a
  164533. * suspension occurs within marker parameters. Other side effects
  164534. * require more care.
  164535. */
  164536. LOCAL(boolean)
  164537. get_soi (j_decompress_ptr cinfo)
  164538. /* Process an SOI marker */
  164539. {
  164540. int i;
  164541. TRACEMS(cinfo, 1, JTRC_SOI);
  164542. if (cinfo->marker->saw_SOI)
  164543. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  164544. /* Reset all parameters that are defined to be reset by SOI */
  164545. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164546. cinfo->arith_dc_L[i] = 0;
  164547. cinfo->arith_dc_U[i] = 1;
  164548. cinfo->arith_ac_K[i] = 5;
  164549. }
  164550. cinfo->restart_interval = 0;
  164551. /* Set initial assumptions for colorspace etc */
  164552. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164553. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  164554. cinfo->saw_JFIF_marker = FALSE;
  164555. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  164556. cinfo->JFIF_minor_version = 1;
  164557. cinfo->density_unit = 0;
  164558. cinfo->X_density = 1;
  164559. cinfo->Y_density = 1;
  164560. cinfo->saw_Adobe_marker = FALSE;
  164561. cinfo->Adobe_transform = 0;
  164562. cinfo->marker->saw_SOI = TRUE;
  164563. return TRUE;
  164564. }
  164565. LOCAL(boolean)
  164566. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  164567. /* Process a SOFn marker */
  164568. {
  164569. INT32 length;
  164570. int c, ci;
  164571. jpeg_component_info * compptr;
  164572. INPUT_VARS(cinfo);
  164573. cinfo->progressive_mode = is_prog;
  164574. cinfo->arith_code = is_arith;
  164575. INPUT_2BYTES(cinfo, length, return FALSE);
  164576. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  164577. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  164578. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  164579. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  164580. length -= 8;
  164581. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  164582. (int) cinfo->image_width, (int) cinfo->image_height,
  164583. cinfo->num_components);
  164584. if (cinfo->marker->saw_SOF)
  164585. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  164586. /* We don't support files in which the image height is initially specified */
  164587. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  164588. /* might as well have a general sanity check. */
  164589. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164590. || cinfo->num_components <= 0)
  164591. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164592. if (length != (cinfo->num_components * 3))
  164593. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164594. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  164595. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  164596. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164597. cinfo->num_components * SIZEOF(jpeg_component_info));
  164598. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164599. ci++, compptr++) {
  164600. compptr->component_index = ci;
  164601. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  164602. INPUT_BYTE(cinfo, c, return FALSE);
  164603. compptr->h_samp_factor = (c >> 4) & 15;
  164604. compptr->v_samp_factor = (c ) & 15;
  164605. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  164606. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  164607. compptr->component_id, compptr->h_samp_factor,
  164608. compptr->v_samp_factor, compptr->quant_tbl_no);
  164609. }
  164610. cinfo->marker->saw_SOF = TRUE;
  164611. INPUT_SYNC(cinfo);
  164612. return TRUE;
  164613. }
  164614. LOCAL(boolean)
  164615. get_sos (j_decompress_ptr cinfo)
  164616. /* Process a SOS marker */
  164617. {
  164618. INT32 length;
  164619. int i, ci, n, c, cc;
  164620. jpeg_component_info * compptr;
  164621. INPUT_VARS(cinfo);
  164622. if (! cinfo->marker->saw_SOF)
  164623. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  164624. INPUT_2BYTES(cinfo, length, return FALSE);
  164625. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  164626. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  164627. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  164628. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164629. cinfo->comps_in_scan = n;
  164630. /* Collect the component-spec parameters */
  164631. for (i = 0; i < n; i++) {
  164632. INPUT_BYTE(cinfo, cc, return FALSE);
  164633. INPUT_BYTE(cinfo, c, return FALSE);
  164634. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164635. ci++, compptr++) {
  164636. if (cc == compptr->component_id)
  164637. goto id_found;
  164638. }
  164639. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  164640. id_found:
  164641. cinfo->cur_comp_info[i] = compptr;
  164642. compptr->dc_tbl_no = (c >> 4) & 15;
  164643. compptr->ac_tbl_no = (c ) & 15;
  164644. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  164645. compptr->dc_tbl_no, compptr->ac_tbl_no);
  164646. }
  164647. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  164648. INPUT_BYTE(cinfo, c, return FALSE);
  164649. cinfo->Ss = c;
  164650. INPUT_BYTE(cinfo, c, return FALSE);
  164651. cinfo->Se = c;
  164652. INPUT_BYTE(cinfo, c, return FALSE);
  164653. cinfo->Ah = (c >> 4) & 15;
  164654. cinfo->Al = (c ) & 15;
  164655. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  164656. cinfo->Ah, cinfo->Al);
  164657. /* Prepare to scan data & restart markers */
  164658. cinfo->marker->next_restart_num = 0;
  164659. /* Count another SOS marker */
  164660. cinfo->input_scan_number++;
  164661. INPUT_SYNC(cinfo);
  164662. return TRUE;
  164663. }
  164664. #ifdef D_ARITH_CODING_SUPPORTED
  164665. LOCAL(boolean)
  164666. get_dac (j_decompress_ptr cinfo)
  164667. /* Process a DAC marker */
  164668. {
  164669. INT32 length;
  164670. int index, val;
  164671. INPUT_VARS(cinfo);
  164672. INPUT_2BYTES(cinfo, length, return FALSE);
  164673. length -= 2;
  164674. while (length > 0) {
  164675. INPUT_BYTE(cinfo, index, return FALSE);
  164676. INPUT_BYTE(cinfo, val, return FALSE);
  164677. length -= 2;
  164678. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  164679. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  164680. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  164681. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  164682. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  164683. } else { /* define DC table */
  164684. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  164685. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  164686. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  164687. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  164688. }
  164689. }
  164690. if (length != 0)
  164691. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164692. INPUT_SYNC(cinfo);
  164693. return TRUE;
  164694. }
  164695. #else /* ! D_ARITH_CODING_SUPPORTED */
  164696. #define get_dac(cinfo) skip_variable(cinfo)
  164697. #endif /* D_ARITH_CODING_SUPPORTED */
  164698. LOCAL(boolean)
  164699. get_dht (j_decompress_ptr cinfo)
  164700. /* Process a DHT marker */
  164701. {
  164702. INT32 length;
  164703. UINT8 bits[17];
  164704. UINT8 huffval[256];
  164705. int i, index, count;
  164706. JHUFF_TBL **htblptr;
  164707. INPUT_VARS(cinfo);
  164708. INPUT_2BYTES(cinfo, length, return FALSE);
  164709. length -= 2;
  164710. while (length > 16) {
  164711. INPUT_BYTE(cinfo, index, return FALSE);
  164712. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  164713. bits[0] = 0;
  164714. count = 0;
  164715. for (i = 1; i <= 16; i++) {
  164716. INPUT_BYTE(cinfo, bits[i], return FALSE);
  164717. count += bits[i];
  164718. }
  164719. length -= 1 + 16;
  164720. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  164721. bits[1], bits[2], bits[3], bits[4],
  164722. bits[5], bits[6], bits[7], bits[8]);
  164723. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  164724. bits[9], bits[10], bits[11], bits[12],
  164725. bits[13], bits[14], bits[15], bits[16]);
  164726. /* Here we just do minimal validation of the counts to avoid walking
  164727. * off the end of our table space. jdhuff.c will check more carefully.
  164728. */
  164729. if (count > 256 || ((INT32) count) > length)
  164730. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164731. for (i = 0; i < count; i++)
  164732. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  164733. length -= count;
  164734. if (index & 0x10) { /* AC table definition */
  164735. index -= 0x10;
  164736. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  164737. } else { /* DC table definition */
  164738. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  164739. }
  164740. if (index < 0 || index >= NUM_HUFF_TBLS)
  164741. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  164742. if (*htblptr == NULL)
  164743. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164744. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164745. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  164746. }
  164747. if (length != 0)
  164748. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164749. INPUT_SYNC(cinfo);
  164750. return TRUE;
  164751. }
  164752. LOCAL(boolean)
  164753. get_dqt (j_decompress_ptr cinfo)
  164754. /* Process a DQT marker */
  164755. {
  164756. INT32 length;
  164757. int n, i, prec;
  164758. unsigned int tmp;
  164759. JQUANT_TBL *quant_ptr;
  164760. INPUT_VARS(cinfo);
  164761. INPUT_2BYTES(cinfo, length, return FALSE);
  164762. length -= 2;
  164763. while (length > 0) {
  164764. INPUT_BYTE(cinfo, n, return FALSE);
  164765. prec = n >> 4;
  164766. n &= 0x0F;
  164767. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  164768. if (n >= NUM_QUANT_TBLS)
  164769. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  164770. if (cinfo->quant_tbl_ptrs[n] == NULL)
  164771. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164772. quant_ptr = cinfo->quant_tbl_ptrs[n];
  164773. for (i = 0; i < DCTSIZE2; i++) {
  164774. if (prec)
  164775. INPUT_2BYTES(cinfo, tmp, return FALSE);
  164776. else
  164777. INPUT_BYTE(cinfo, tmp, return FALSE);
  164778. /* We convert the zigzag-order table to natural array order. */
  164779. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  164780. }
  164781. if (cinfo->err->trace_level >= 2) {
  164782. for (i = 0; i < DCTSIZE2; i += 8) {
  164783. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  164784. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  164785. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  164786. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  164787. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  164788. }
  164789. }
  164790. length -= DCTSIZE2+1;
  164791. if (prec) length -= DCTSIZE2;
  164792. }
  164793. if (length != 0)
  164794. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164795. INPUT_SYNC(cinfo);
  164796. return TRUE;
  164797. }
  164798. LOCAL(boolean)
  164799. get_dri (j_decompress_ptr cinfo)
  164800. /* Process a DRI marker */
  164801. {
  164802. INT32 length;
  164803. unsigned int tmp;
  164804. INPUT_VARS(cinfo);
  164805. INPUT_2BYTES(cinfo, length, return FALSE);
  164806. if (length != 4)
  164807. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164808. INPUT_2BYTES(cinfo, tmp, return FALSE);
  164809. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  164810. cinfo->restart_interval = tmp;
  164811. INPUT_SYNC(cinfo);
  164812. return TRUE;
  164813. }
  164814. /*
  164815. * Routines for processing APPn and COM markers.
  164816. * These are either saved in memory or discarded, per application request.
  164817. * APP0 and APP14 are specially checked to see if they are
  164818. * JFIF and Adobe markers, respectively.
  164819. */
  164820. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  164821. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  164822. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  164823. LOCAL(void)
  164824. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  164825. unsigned int datalen, INT32 remaining)
  164826. /* Examine first few bytes from an APP0.
  164827. * Take appropriate action if it is a JFIF marker.
  164828. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  164829. */
  164830. {
  164831. INT32 totallen = (INT32) datalen + remaining;
  164832. if (datalen >= APP0_DATA_LEN &&
  164833. GETJOCTET(data[0]) == 0x4A &&
  164834. GETJOCTET(data[1]) == 0x46 &&
  164835. GETJOCTET(data[2]) == 0x49 &&
  164836. GETJOCTET(data[3]) == 0x46 &&
  164837. GETJOCTET(data[4]) == 0) {
  164838. /* Found JFIF APP0 marker: save info */
  164839. cinfo->saw_JFIF_marker = TRUE;
  164840. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  164841. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  164842. cinfo->density_unit = GETJOCTET(data[7]);
  164843. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  164844. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  164845. /* Check version.
  164846. * Major version must be 1, anything else signals an incompatible change.
  164847. * (We used to treat this as an error, but now it's a nonfatal warning,
  164848. * because some bozo at Hijaak couldn't read the spec.)
  164849. * Minor version should be 0..2, but process anyway if newer.
  164850. */
  164851. if (cinfo->JFIF_major_version != 1)
  164852. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  164853. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  164854. /* Generate trace messages */
  164855. TRACEMS5(cinfo, 1, JTRC_JFIF,
  164856. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  164857. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  164858. /* Validate thumbnail dimensions and issue appropriate messages */
  164859. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  164860. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  164861. GETJOCTET(data[12]), GETJOCTET(data[13]));
  164862. totallen -= APP0_DATA_LEN;
  164863. if (totallen !=
  164864. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  164865. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  164866. } else if (datalen >= 6 &&
  164867. GETJOCTET(data[0]) == 0x4A &&
  164868. GETJOCTET(data[1]) == 0x46 &&
  164869. GETJOCTET(data[2]) == 0x58 &&
  164870. GETJOCTET(data[3]) == 0x58 &&
  164871. GETJOCTET(data[4]) == 0) {
  164872. /* Found JFIF "JFXX" extension APP0 marker */
  164873. /* The library doesn't actually do anything with these,
  164874. * but we try to produce a helpful trace message.
  164875. */
  164876. switch (GETJOCTET(data[5])) {
  164877. case 0x10:
  164878. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  164879. break;
  164880. case 0x11:
  164881. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  164882. break;
  164883. case 0x13:
  164884. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  164885. break;
  164886. default:
  164887. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  164888. GETJOCTET(data[5]), (int) totallen);
  164889. break;
  164890. }
  164891. } else {
  164892. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  164893. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  164894. }
  164895. }
  164896. LOCAL(void)
  164897. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  164898. unsigned int datalen, INT32 remaining)
  164899. /* Examine first few bytes from an APP14.
  164900. * Take appropriate action if it is an Adobe marker.
  164901. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  164902. */
  164903. {
  164904. unsigned int version, flags0, flags1, transform;
  164905. if (datalen >= APP14_DATA_LEN &&
  164906. GETJOCTET(data[0]) == 0x41 &&
  164907. GETJOCTET(data[1]) == 0x64 &&
  164908. GETJOCTET(data[2]) == 0x6F &&
  164909. GETJOCTET(data[3]) == 0x62 &&
  164910. GETJOCTET(data[4]) == 0x65) {
  164911. /* Found Adobe APP14 marker */
  164912. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  164913. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  164914. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  164915. transform = GETJOCTET(data[11]);
  164916. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  164917. cinfo->saw_Adobe_marker = TRUE;
  164918. cinfo->Adobe_transform = (UINT8) transform;
  164919. } else {
  164920. /* Start of APP14 does not match "Adobe", or too short */
  164921. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  164922. }
  164923. }
  164924. METHODDEF(boolean)
  164925. get_interesting_appn (j_decompress_ptr cinfo)
  164926. /* Process an APP0 or APP14 marker without saving it */
  164927. {
  164928. INT32 length;
  164929. JOCTET b[APPN_DATA_LEN];
  164930. unsigned int i, numtoread;
  164931. INPUT_VARS(cinfo);
  164932. INPUT_2BYTES(cinfo, length, return FALSE);
  164933. length -= 2;
  164934. /* get the interesting part of the marker data */
  164935. if (length >= APPN_DATA_LEN)
  164936. numtoread = APPN_DATA_LEN;
  164937. else if (length > 0)
  164938. numtoread = (unsigned int) length;
  164939. else
  164940. numtoread = 0;
  164941. for (i = 0; i < numtoread; i++)
  164942. INPUT_BYTE(cinfo, b[i], return FALSE);
  164943. length -= numtoread;
  164944. /* process it */
  164945. switch (cinfo->unread_marker) {
  164946. case M_APP0:
  164947. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  164948. break;
  164949. case M_APP14:
  164950. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  164951. break;
  164952. default:
  164953. /* can't get here unless jpeg_save_markers chooses wrong processor */
  164954. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  164955. break;
  164956. }
  164957. /* skip any remaining data -- could be lots */
  164958. INPUT_SYNC(cinfo);
  164959. if (length > 0)
  164960. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  164961. return TRUE;
  164962. }
  164963. #ifdef SAVE_MARKERS_SUPPORTED
  164964. METHODDEF(boolean)
  164965. save_marker (j_decompress_ptr cinfo)
  164966. /* Save an APPn or COM marker into the marker list */
  164967. {
  164968. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  164969. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  164970. unsigned int bytes_read, data_length;
  164971. JOCTET FAR * data;
  164972. INT32 length = 0;
  164973. INPUT_VARS(cinfo);
  164974. if (cur_marker == NULL) {
  164975. /* begin reading a marker */
  164976. INPUT_2BYTES(cinfo, length, return FALSE);
  164977. length -= 2;
  164978. if (length >= 0) { /* watch out for bogus length word */
  164979. /* figure out how much we want to save */
  164980. unsigned int limit;
  164981. if (cinfo->unread_marker == (int) M_COM)
  164982. limit = marker->length_limit_COM;
  164983. else
  164984. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  164985. if ((unsigned int) length < limit)
  164986. limit = (unsigned int) length;
  164987. /* allocate and initialize the marker item */
  164988. cur_marker = (jpeg_saved_marker_ptr)
  164989. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164990. SIZEOF(struct jpeg_marker_struct) + limit);
  164991. cur_marker->next = NULL;
  164992. cur_marker->marker = (UINT8) cinfo->unread_marker;
  164993. cur_marker->original_length = (unsigned int) length;
  164994. cur_marker->data_length = limit;
  164995. /* data area is just beyond the jpeg_marker_struct */
  164996. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  164997. marker->cur_marker = cur_marker;
  164998. marker->bytes_read = 0;
  164999. bytes_read = 0;
  165000. data_length = limit;
  165001. } else {
  165002. /* deal with bogus length word */
  165003. bytes_read = data_length = 0;
  165004. data = NULL;
  165005. }
  165006. } else {
  165007. /* resume reading a marker */
  165008. bytes_read = marker->bytes_read;
  165009. data_length = cur_marker->data_length;
  165010. data = cur_marker->data + bytes_read;
  165011. }
  165012. while (bytes_read < data_length) {
  165013. INPUT_SYNC(cinfo); /* move the restart point to here */
  165014. marker->bytes_read = bytes_read;
  165015. /* If there's not at least one byte in buffer, suspend */
  165016. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  165017. /* Copy bytes with reasonable rapidity */
  165018. while (bytes_read < data_length && bytes_in_buffer > 0) {
  165019. *data++ = *next_input_byte++;
  165020. bytes_in_buffer--;
  165021. bytes_read++;
  165022. }
  165023. }
  165024. /* Done reading what we want to read */
  165025. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  165026. /* Add new marker to end of list */
  165027. if (cinfo->marker_list == NULL) {
  165028. cinfo->marker_list = cur_marker;
  165029. } else {
  165030. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  165031. while (prev->next != NULL)
  165032. prev = prev->next;
  165033. prev->next = cur_marker;
  165034. }
  165035. /* Reset pointer & calc remaining data length */
  165036. data = cur_marker->data;
  165037. length = cur_marker->original_length - data_length;
  165038. }
  165039. /* Reset to initial state for next marker */
  165040. marker->cur_marker = NULL;
  165041. /* Process the marker if interesting; else just make a generic trace msg */
  165042. switch (cinfo->unread_marker) {
  165043. case M_APP0:
  165044. examine_app0(cinfo, data, data_length, length);
  165045. break;
  165046. case M_APP14:
  165047. examine_app14(cinfo, data, data_length, length);
  165048. break;
  165049. default:
  165050. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  165051. (int) (data_length + length));
  165052. break;
  165053. }
  165054. /* skip any remaining data -- could be lots */
  165055. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165056. if (length > 0)
  165057. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165058. return TRUE;
  165059. }
  165060. #endif /* SAVE_MARKERS_SUPPORTED */
  165061. METHODDEF(boolean)
  165062. skip_variable (j_decompress_ptr cinfo)
  165063. /* Skip over an unknown or uninteresting variable-length marker */
  165064. {
  165065. INT32 length;
  165066. INPUT_VARS(cinfo);
  165067. INPUT_2BYTES(cinfo, length, return FALSE);
  165068. length -= 2;
  165069. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  165070. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165071. if (length > 0)
  165072. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165073. return TRUE;
  165074. }
  165075. /*
  165076. * Find the next JPEG marker, save it in cinfo->unread_marker.
  165077. * Returns FALSE if had to suspend before reaching a marker;
  165078. * in that case cinfo->unread_marker is unchanged.
  165079. *
  165080. * Note that the result might not be a valid marker code,
  165081. * but it will never be 0 or FF.
  165082. */
  165083. LOCAL(boolean)
  165084. next_marker (j_decompress_ptr cinfo)
  165085. {
  165086. int c;
  165087. INPUT_VARS(cinfo);
  165088. for (;;) {
  165089. INPUT_BYTE(cinfo, c, return FALSE);
  165090. /* Skip any non-FF bytes.
  165091. * This may look a bit inefficient, but it will not occur in a valid file.
  165092. * We sync after each discarded byte so that a suspending data source
  165093. * can discard the byte from its buffer.
  165094. */
  165095. while (c != 0xFF) {
  165096. cinfo->marker->discarded_bytes++;
  165097. INPUT_SYNC(cinfo);
  165098. INPUT_BYTE(cinfo, c, return FALSE);
  165099. }
  165100. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  165101. * pad bytes, so don't count them in discarded_bytes. We assume there
  165102. * will not be so many consecutive FF bytes as to overflow a suspending
  165103. * data source's input buffer.
  165104. */
  165105. do {
  165106. INPUT_BYTE(cinfo, c, return FALSE);
  165107. } while (c == 0xFF);
  165108. if (c != 0)
  165109. break; /* found a valid marker, exit loop */
  165110. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  165111. * Discard it and loop back to try again.
  165112. */
  165113. cinfo->marker->discarded_bytes += 2;
  165114. INPUT_SYNC(cinfo);
  165115. }
  165116. if (cinfo->marker->discarded_bytes != 0) {
  165117. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  165118. cinfo->marker->discarded_bytes = 0;
  165119. }
  165120. cinfo->unread_marker = c;
  165121. INPUT_SYNC(cinfo);
  165122. return TRUE;
  165123. }
  165124. LOCAL(boolean)
  165125. first_marker (j_decompress_ptr cinfo)
  165126. /* Like next_marker, but used to obtain the initial SOI marker. */
  165127. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  165128. * we might well scan an entire input file before realizing it ain't JPEG.
  165129. * If an application wants to process non-JFIF files, it must seek to the
  165130. * SOI before calling the JPEG library.
  165131. */
  165132. {
  165133. int c, c2;
  165134. INPUT_VARS(cinfo);
  165135. INPUT_BYTE(cinfo, c, return FALSE);
  165136. INPUT_BYTE(cinfo, c2, return FALSE);
  165137. if (c != 0xFF || c2 != (int) M_SOI)
  165138. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  165139. cinfo->unread_marker = c2;
  165140. INPUT_SYNC(cinfo);
  165141. return TRUE;
  165142. }
  165143. /*
  165144. * Read markers until SOS or EOI.
  165145. *
  165146. * Returns same codes as are defined for jpeg_consume_input:
  165147. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165148. */
  165149. METHODDEF(int)
  165150. read_markers (j_decompress_ptr cinfo)
  165151. {
  165152. /* Outer loop repeats once for each marker. */
  165153. for (;;) {
  165154. /* Collect the marker proper, unless we already did. */
  165155. /* NB: first_marker() enforces the requirement that SOI appear first. */
  165156. if (cinfo->unread_marker == 0) {
  165157. if (! cinfo->marker->saw_SOI) {
  165158. if (! first_marker(cinfo))
  165159. return JPEG_SUSPENDED;
  165160. } else {
  165161. if (! next_marker(cinfo))
  165162. return JPEG_SUSPENDED;
  165163. }
  165164. }
  165165. /* At this point cinfo->unread_marker contains the marker code and the
  165166. * input point is just past the marker proper, but before any parameters.
  165167. * A suspension will cause us to return with this state still true.
  165168. */
  165169. switch (cinfo->unread_marker) {
  165170. case M_SOI:
  165171. if (! get_soi(cinfo))
  165172. return JPEG_SUSPENDED;
  165173. break;
  165174. case M_SOF0: /* Baseline */
  165175. case M_SOF1: /* Extended sequential, Huffman */
  165176. if (! get_sof(cinfo, FALSE, FALSE))
  165177. return JPEG_SUSPENDED;
  165178. break;
  165179. case M_SOF2: /* Progressive, Huffman */
  165180. if (! get_sof(cinfo, TRUE, FALSE))
  165181. return JPEG_SUSPENDED;
  165182. break;
  165183. case M_SOF9: /* Extended sequential, arithmetic */
  165184. if (! get_sof(cinfo, FALSE, TRUE))
  165185. return JPEG_SUSPENDED;
  165186. break;
  165187. case M_SOF10: /* Progressive, arithmetic */
  165188. if (! get_sof(cinfo, TRUE, TRUE))
  165189. return JPEG_SUSPENDED;
  165190. break;
  165191. /* Currently unsupported SOFn types */
  165192. case M_SOF3: /* Lossless, Huffman */
  165193. case M_SOF5: /* Differential sequential, Huffman */
  165194. case M_SOF6: /* Differential progressive, Huffman */
  165195. case M_SOF7: /* Differential lossless, Huffman */
  165196. case M_JPG: /* Reserved for JPEG extensions */
  165197. case M_SOF11: /* Lossless, arithmetic */
  165198. case M_SOF13: /* Differential sequential, arithmetic */
  165199. case M_SOF14: /* Differential progressive, arithmetic */
  165200. case M_SOF15: /* Differential lossless, arithmetic */
  165201. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  165202. break;
  165203. case M_SOS:
  165204. if (! get_sos(cinfo))
  165205. return JPEG_SUSPENDED;
  165206. cinfo->unread_marker = 0; /* processed the marker */
  165207. return JPEG_REACHED_SOS;
  165208. case M_EOI:
  165209. TRACEMS(cinfo, 1, JTRC_EOI);
  165210. cinfo->unread_marker = 0; /* processed the marker */
  165211. return JPEG_REACHED_EOI;
  165212. case M_DAC:
  165213. if (! get_dac(cinfo))
  165214. return JPEG_SUSPENDED;
  165215. break;
  165216. case M_DHT:
  165217. if (! get_dht(cinfo))
  165218. return JPEG_SUSPENDED;
  165219. break;
  165220. case M_DQT:
  165221. if (! get_dqt(cinfo))
  165222. return JPEG_SUSPENDED;
  165223. break;
  165224. case M_DRI:
  165225. if (! get_dri(cinfo))
  165226. return JPEG_SUSPENDED;
  165227. break;
  165228. case M_APP0:
  165229. case M_APP1:
  165230. case M_APP2:
  165231. case M_APP3:
  165232. case M_APP4:
  165233. case M_APP5:
  165234. case M_APP6:
  165235. case M_APP7:
  165236. case M_APP8:
  165237. case M_APP9:
  165238. case M_APP10:
  165239. case M_APP11:
  165240. case M_APP12:
  165241. case M_APP13:
  165242. case M_APP14:
  165243. case M_APP15:
  165244. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  165245. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  165246. return JPEG_SUSPENDED;
  165247. break;
  165248. case M_COM:
  165249. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  165250. return JPEG_SUSPENDED;
  165251. break;
  165252. case M_RST0: /* these are all parameterless */
  165253. case M_RST1:
  165254. case M_RST2:
  165255. case M_RST3:
  165256. case M_RST4:
  165257. case M_RST5:
  165258. case M_RST6:
  165259. case M_RST7:
  165260. case M_TEM:
  165261. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  165262. break;
  165263. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  165264. if (! skip_variable(cinfo))
  165265. return JPEG_SUSPENDED;
  165266. break;
  165267. default: /* must be DHP, EXP, JPGn, or RESn */
  165268. /* For now, we treat the reserved markers as fatal errors since they are
  165269. * likely to be used to signal incompatible JPEG Part 3 extensions.
  165270. * Once the JPEG 3 version-number marker is well defined, this code
  165271. * ought to change!
  165272. */
  165273. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165274. break;
  165275. }
  165276. /* Successfully processed marker, so reset state variable */
  165277. cinfo->unread_marker = 0;
  165278. } /* end loop */
  165279. }
  165280. /*
  165281. * Read a restart marker, which is expected to appear next in the datastream;
  165282. * if the marker is not there, take appropriate recovery action.
  165283. * Returns FALSE if suspension is required.
  165284. *
  165285. * This is called by the entropy decoder after it has read an appropriate
  165286. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  165287. * has already read a marker from the data source. Under normal conditions
  165288. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  165289. * it holds a marker which the decoder will be unable to read past.
  165290. */
  165291. METHODDEF(boolean)
  165292. read_restart_marker (j_decompress_ptr cinfo)
  165293. {
  165294. /* Obtain a marker unless we already did. */
  165295. /* Note that next_marker will complain if it skips any data. */
  165296. if (cinfo->unread_marker == 0) {
  165297. if (! next_marker(cinfo))
  165298. return FALSE;
  165299. }
  165300. if (cinfo->unread_marker ==
  165301. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  165302. /* Normal case --- swallow the marker and let entropy decoder continue */
  165303. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  165304. cinfo->unread_marker = 0;
  165305. } else {
  165306. /* Uh-oh, the restart markers have been messed up. */
  165307. /* Let the data source manager determine how to resync. */
  165308. if (! (*cinfo->src->resync_to_restart) (cinfo,
  165309. cinfo->marker->next_restart_num))
  165310. return FALSE;
  165311. }
  165312. /* Update next-restart state */
  165313. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  165314. return TRUE;
  165315. }
  165316. /*
  165317. * This is the default resync_to_restart method for data source managers
  165318. * to use if they don't have any better approach. Some data source managers
  165319. * may be able to back up, or may have additional knowledge about the data
  165320. * which permits a more intelligent recovery strategy; such managers would
  165321. * presumably supply their own resync method.
  165322. *
  165323. * read_restart_marker calls resync_to_restart if it finds a marker other than
  165324. * the restart marker it was expecting. (This code is *not* used unless
  165325. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  165326. * the marker code actually found (might be anything, except 0 or FF).
  165327. * The desired restart marker number (0..7) is passed as a parameter.
  165328. * This routine is supposed to apply whatever error recovery strategy seems
  165329. * appropriate in order to position the input stream to the next data segment.
  165330. * Note that cinfo->unread_marker is treated as a marker appearing before
  165331. * the current data-source input point; usually it should be reset to zero
  165332. * before returning.
  165333. * Returns FALSE if suspension is required.
  165334. *
  165335. * This implementation is substantially constrained by wanting to treat the
  165336. * input as a data stream; this means we can't back up. Therefore, we have
  165337. * only the following actions to work with:
  165338. * 1. Simply discard the marker and let the entropy decoder resume at next
  165339. * byte of file.
  165340. * 2. Read forward until we find another marker, discarding intervening
  165341. * data. (In theory we could look ahead within the current bufferload,
  165342. * without having to discard data if we don't find the desired marker.
  165343. * This idea is not implemented here, in part because it makes behavior
  165344. * dependent on buffer size and chance buffer-boundary positions.)
  165345. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  165346. * This will cause the entropy decoder to process an empty data segment,
  165347. * inserting dummy zeroes, and then we will reprocess the marker.
  165348. *
  165349. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  165350. * appropriate if the found marker is a future restart marker (indicating
  165351. * that we have missed the desired restart marker, probably because it got
  165352. * corrupted).
  165353. * We apply #2 or #3 if the found marker is a restart marker no more than
  165354. * two counts behind or ahead of the expected one. We also apply #2 if the
  165355. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  165356. * If the found marker is a restart marker more than 2 counts away, we do #1
  165357. * (too much risk that the marker is erroneous; with luck we will be able to
  165358. * resync at some future point).
  165359. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  165360. * overrunning the end of a scan. An implementation limited to single-scan
  165361. * files might find it better to apply #2 for markers other than EOI, since
  165362. * any other marker would have to be bogus data in that case.
  165363. */
  165364. GLOBAL(boolean)
  165365. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  165366. {
  165367. int marker = cinfo->unread_marker;
  165368. int action = 1;
  165369. /* Always put up a warning. */
  165370. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  165371. /* Outer loop handles repeated decision after scanning forward. */
  165372. for (;;) {
  165373. if (marker < (int) M_SOF0)
  165374. action = 2; /* invalid marker */
  165375. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  165376. action = 3; /* valid non-restart marker */
  165377. else {
  165378. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  165379. marker == ((int) M_RST0 + ((desired+2) & 7)))
  165380. action = 3; /* one of the next two expected restarts */
  165381. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  165382. marker == ((int) M_RST0 + ((desired-2) & 7)))
  165383. action = 2; /* a prior restart, so advance */
  165384. else
  165385. action = 1; /* desired restart or too far away */
  165386. }
  165387. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  165388. switch (action) {
  165389. case 1:
  165390. /* Discard marker and let entropy decoder resume processing. */
  165391. cinfo->unread_marker = 0;
  165392. return TRUE;
  165393. case 2:
  165394. /* Scan to the next marker, and repeat the decision loop. */
  165395. if (! next_marker(cinfo))
  165396. return FALSE;
  165397. marker = cinfo->unread_marker;
  165398. break;
  165399. case 3:
  165400. /* Return without advancing past this marker. */
  165401. /* Entropy decoder will be forced to process an empty segment. */
  165402. return TRUE;
  165403. }
  165404. } /* end loop */
  165405. }
  165406. /*
  165407. * Reset marker processing state to begin a fresh datastream.
  165408. */
  165409. METHODDEF(void)
  165410. reset_marker_reader (j_decompress_ptr cinfo)
  165411. {
  165412. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165413. cinfo->comp_info = NULL; /* until allocated by get_sof */
  165414. cinfo->input_scan_number = 0; /* no SOS seen yet */
  165415. cinfo->unread_marker = 0; /* no pending marker */
  165416. marker->pub.saw_SOI = FALSE; /* set internal state too */
  165417. marker->pub.saw_SOF = FALSE;
  165418. marker->pub.discarded_bytes = 0;
  165419. marker->cur_marker = NULL;
  165420. }
  165421. /*
  165422. * Initialize the marker reader module.
  165423. * This is called only once, when the decompression object is created.
  165424. */
  165425. GLOBAL(void)
  165426. jinit_marker_reader (j_decompress_ptr cinfo)
  165427. {
  165428. my_marker_ptr2 marker;
  165429. int i;
  165430. /* Create subobject in permanent pool */
  165431. marker = (my_marker_ptr2)
  165432. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165433. SIZEOF(my_marker_reader));
  165434. cinfo->marker = (struct jpeg_marker_reader *) marker;
  165435. /* Initialize public method pointers */
  165436. marker->pub.reset_marker_reader = reset_marker_reader;
  165437. marker->pub.read_markers = read_markers;
  165438. marker->pub.read_restart_marker = read_restart_marker;
  165439. /* Initialize COM/APPn processing.
  165440. * By default, we examine and then discard APP0 and APP14,
  165441. * but simply discard COM and all other APPn.
  165442. */
  165443. marker->process_COM = skip_variable;
  165444. marker->length_limit_COM = 0;
  165445. for (i = 0; i < 16; i++) {
  165446. marker->process_APPn[i] = skip_variable;
  165447. marker->length_limit_APPn[i] = 0;
  165448. }
  165449. marker->process_APPn[0] = get_interesting_appn;
  165450. marker->process_APPn[14] = get_interesting_appn;
  165451. /* Reset marker processing state */
  165452. reset_marker_reader(cinfo);
  165453. }
  165454. /*
  165455. * Control saving of COM and APPn markers into marker_list.
  165456. */
  165457. #ifdef SAVE_MARKERS_SUPPORTED
  165458. GLOBAL(void)
  165459. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  165460. unsigned int length_limit)
  165461. {
  165462. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165463. long maxlength;
  165464. jpeg_marker_parser_method processor;
  165465. /* Length limit mustn't be larger than what we can allocate
  165466. * (should only be a concern in a 16-bit environment).
  165467. */
  165468. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  165469. if (((long) length_limit) > maxlength)
  165470. length_limit = (unsigned int) maxlength;
  165471. /* Choose processor routine to use.
  165472. * APP0/APP14 have special requirements.
  165473. */
  165474. if (length_limit) {
  165475. processor = save_marker;
  165476. /* If saving APP0/APP14, save at least enough for our internal use. */
  165477. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  165478. length_limit = APP0_DATA_LEN;
  165479. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  165480. length_limit = APP14_DATA_LEN;
  165481. } else {
  165482. processor = skip_variable;
  165483. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  165484. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  165485. processor = get_interesting_appn;
  165486. }
  165487. if (marker_code == (int) M_COM) {
  165488. marker->process_COM = processor;
  165489. marker->length_limit_COM = length_limit;
  165490. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  165491. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  165492. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  165493. } else
  165494. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  165495. }
  165496. #endif /* SAVE_MARKERS_SUPPORTED */
  165497. /*
  165498. * Install a special processing method for COM or APPn markers.
  165499. */
  165500. GLOBAL(void)
  165501. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  165502. jpeg_marker_parser_method routine)
  165503. {
  165504. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165505. if (marker_code == (int) M_COM)
  165506. marker->process_COM = routine;
  165507. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  165508. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  165509. else
  165510. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  165511. }
  165512. /********* End of inlined file: jdmarker.c *********/
  165513. /********* Start of inlined file: jdmaster.c *********/
  165514. #define JPEG_INTERNALS
  165515. /* Private state */
  165516. typedef struct {
  165517. struct jpeg_decomp_master pub; /* public fields */
  165518. int pass_number; /* # of passes completed */
  165519. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  165520. /* Saved references to initialized quantizer modules,
  165521. * in case we need to switch modes.
  165522. */
  165523. struct jpeg_color_quantizer * quantizer_1pass;
  165524. struct jpeg_color_quantizer * quantizer_2pass;
  165525. } my_decomp_master;
  165526. typedef my_decomp_master * my_master_ptr6;
  165527. /*
  165528. * Determine whether merged upsample/color conversion should be used.
  165529. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  165530. */
  165531. LOCAL(boolean)
  165532. use_merged_upsample (j_decompress_ptr cinfo)
  165533. {
  165534. #ifdef UPSAMPLE_MERGING_SUPPORTED
  165535. /* Merging is the equivalent of plain box-filter upsampling */
  165536. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  165537. return FALSE;
  165538. /* jdmerge.c only supports YCC=>RGB color conversion */
  165539. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  165540. cinfo->out_color_space != JCS_RGB ||
  165541. cinfo->out_color_components != RGB_PIXELSIZE)
  165542. return FALSE;
  165543. /* and it only handles 2h1v or 2h2v sampling ratios */
  165544. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  165545. cinfo->comp_info[1].h_samp_factor != 1 ||
  165546. cinfo->comp_info[2].h_samp_factor != 1 ||
  165547. cinfo->comp_info[0].v_samp_factor > 2 ||
  165548. cinfo->comp_info[1].v_samp_factor != 1 ||
  165549. cinfo->comp_info[2].v_samp_factor != 1)
  165550. return FALSE;
  165551. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  165552. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  165553. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  165554. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  165555. return FALSE;
  165556. /* ??? also need to test for upsample-time rescaling, when & if supported */
  165557. return TRUE; /* by golly, it'll work... */
  165558. #else
  165559. return FALSE;
  165560. #endif
  165561. }
  165562. /*
  165563. * Compute output image dimensions and related values.
  165564. * NOTE: this is exported for possible use by application.
  165565. * Hence it mustn't do anything that can't be done twice.
  165566. * Also note that it may be called before the master module is initialized!
  165567. */
  165568. GLOBAL(void)
  165569. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  165570. /* Do computations that are needed before master selection phase */
  165571. {
  165572. #ifdef IDCT_SCALING_SUPPORTED
  165573. int ci;
  165574. jpeg_component_info *compptr;
  165575. #endif
  165576. /* Prevent application from calling me at wrong times */
  165577. if (cinfo->global_state != DSTATE_READY)
  165578. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165579. #ifdef IDCT_SCALING_SUPPORTED
  165580. /* Compute actual output image dimensions and DCT scaling choices. */
  165581. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  165582. /* Provide 1/8 scaling */
  165583. cinfo->output_width = (JDIMENSION)
  165584. jdiv_round_up((long) cinfo->image_width, 8L);
  165585. cinfo->output_height = (JDIMENSION)
  165586. jdiv_round_up((long) cinfo->image_height, 8L);
  165587. cinfo->min_DCT_scaled_size = 1;
  165588. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  165589. /* Provide 1/4 scaling */
  165590. cinfo->output_width = (JDIMENSION)
  165591. jdiv_round_up((long) cinfo->image_width, 4L);
  165592. cinfo->output_height = (JDIMENSION)
  165593. jdiv_round_up((long) cinfo->image_height, 4L);
  165594. cinfo->min_DCT_scaled_size = 2;
  165595. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  165596. /* Provide 1/2 scaling */
  165597. cinfo->output_width = (JDIMENSION)
  165598. jdiv_round_up((long) cinfo->image_width, 2L);
  165599. cinfo->output_height = (JDIMENSION)
  165600. jdiv_round_up((long) cinfo->image_height, 2L);
  165601. cinfo->min_DCT_scaled_size = 4;
  165602. } else {
  165603. /* Provide 1/1 scaling */
  165604. cinfo->output_width = cinfo->image_width;
  165605. cinfo->output_height = cinfo->image_height;
  165606. cinfo->min_DCT_scaled_size = DCTSIZE;
  165607. }
  165608. /* In selecting the actual DCT scaling for each component, we try to
  165609. * scale up the chroma components via IDCT scaling rather than upsampling.
  165610. * This saves time if the upsampler gets to use 1:1 scaling.
  165611. * Note this code assumes that the supported DCT scalings are powers of 2.
  165612. */
  165613. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165614. ci++, compptr++) {
  165615. int ssize = cinfo->min_DCT_scaled_size;
  165616. while (ssize < DCTSIZE &&
  165617. (compptr->h_samp_factor * ssize * 2 <=
  165618. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  165619. (compptr->v_samp_factor * ssize * 2 <=
  165620. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  165621. ssize = ssize * 2;
  165622. }
  165623. compptr->DCT_scaled_size = ssize;
  165624. }
  165625. /* Recompute downsampled dimensions of components;
  165626. * application needs to know these if using raw downsampled data.
  165627. */
  165628. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165629. ci++, compptr++) {
  165630. /* Size in samples, after IDCT scaling */
  165631. compptr->downsampled_width = (JDIMENSION)
  165632. jdiv_round_up((long) cinfo->image_width *
  165633. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  165634. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165635. compptr->downsampled_height = (JDIMENSION)
  165636. jdiv_round_up((long) cinfo->image_height *
  165637. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  165638. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165639. }
  165640. #else /* !IDCT_SCALING_SUPPORTED */
  165641. /* Hardwire it to "no scaling" */
  165642. cinfo->output_width = cinfo->image_width;
  165643. cinfo->output_height = cinfo->image_height;
  165644. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  165645. * and has computed unscaled downsampled_width and downsampled_height.
  165646. */
  165647. #endif /* IDCT_SCALING_SUPPORTED */
  165648. /* Report number of components in selected colorspace. */
  165649. /* Probably this should be in the color conversion module... */
  165650. switch (cinfo->out_color_space) {
  165651. case JCS_GRAYSCALE:
  165652. cinfo->out_color_components = 1;
  165653. break;
  165654. case JCS_RGB:
  165655. #if RGB_PIXELSIZE != 3
  165656. cinfo->out_color_components = RGB_PIXELSIZE;
  165657. break;
  165658. #endif /* else share code with YCbCr */
  165659. case JCS_YCbCr:
  165660. cinfo->out_color_components = 3;
  165661. break;
  165662. case JCS_CMYK:
  165663. case JCS_YCCK:
  165664. cinfo->out_color_components = 4;
  165665. break;
  165666. default: /* else must be same colorspace as in file */
  165667. cinfo->out_color_components = cinfo->num_components;
  165668. break;
  165669. }
  165670. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  165671. cinfo->out_color_components);
  165672. /* See if upsampler will want to emit more than one row at a time */
  165673. if (use_merged_upsample(cinfo))
  165674. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  165675. else
  165676. cinfo->rec_outbuf_height = 1;
  165677. }
  165678. /*
  165679. * Several decompression processes need to range-limit values to the range
  165680. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  165681. * due to noise introduced by quantization, roundoff error, etc. These
  165682. * processes are inner loops and need to be as fast as possible. On most
  165683. * machines, particularly CPUs with pipelines or instruction prefetch,
  165684. * a (subscript-check-less) C table lookup
  165685. * x = sample_range_limit[x];
  165686. * is faster than explicit tests
  165687. * if (x < 0) x = 0;
  165688. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  165689. * These processes all use a common table prepared by the routine below.
  165690. *
  165691. * For most steps we can mathematically guarantee that the initial value
  165692. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  165693. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  165694. * limiting step (just after the IDCT), a wildly out-of-range value is
  165695. * possible if the input data is corrupt. To avoid any chance of indexing
  165696. * off the end of memory and getting a bad-pointer trap, we perform the
  165697. * post-IDCT limiting thus:
  165698. * x = range_limit[x & MASK];
  165699. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  165700. * samples. Under normal circumstances this is more than enough range and
  165701. * a correct output will be generated; with bogus input data the mask will
  165702. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  165703. * For the post-IDCT step, we want to convert the data from signed to unsigned
  165704. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  165705. * So the post-IDCT limiting table ends up looking like this:
  165706. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  165707. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  165708. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  165709. * 0,1,...,CENTERJSAMPLE-1
  165710. * Negative inputs select values from the upper half of the table after
  165711. * masking.
  165712. *
  165713. * We can save some space by overlapping the start of the post-IDCT table
  165714. * with the simpler range limiting table. The post-IDCT table begins at
  165715. * sample_range_limit + CENTERJSAMPLE.
  165716. *
  165717. * Note that the table is allocated in near data space on PCs; it's small
  165718. * enough and used often enough to justify this.
  165719. */
  165720. LOCAL(void)
  165721. prepare_range_limit_table (j_decompress_ptr cinfo)
  165722. /* Allocate and fill in the sample_range_limit table */
  165723. {
  165724. JSAMPLE * table;
  165725. int i;
  165726. table = (JSAMPLE *)
  165727. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165728. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  165729. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  165730. cinfo->sample_range_limit = table;
  165731. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  165732. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  165733. /* Main part of "simple" table: limit[x] = x */
  165734. for (i = 0; i <= MAXJSAMPLE; i++)
  165735. table[i] = (JSAMPLE) i;
  165736. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  165737. /* End of simple table, rest of first half of post-IDCT table */
  165738. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  165739. table[i] = MAXJSAMPLE;
  165740. /* Second half of post-IDCT table */
  165741. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  165742. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  165743. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  165744. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  165745. }
  165746. /*
  165747. * Master selection of decompression modules.
  165748. * This is done once at jpeg_start_decompress time. We determine
  165749. * which modules will be used and give them appropriate initialization calls.
  165750. * We also initialize the decompressor input side to begin consuming data.
  165751. *
  165752. * Since jpeg_read_header has finished, we know what is in the SOF
  165753. * and (first) SOS markers. We also have all the application parameter
  165754. * settings.
  165755. */
  165756. LOCAL(void)
  165757. master_selection (j_decompress_ptr cinfo)
  165758. {
  165759. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165760. boolean use_c_buffer;
  165761. long samplesperrow;
  165762. JDIMENSION jd_samplesperrow;
  165763. /* Initialize dimensions and other stuff */
  165764. jpeg_calc_output_dimensions(cinfo);
  165765. prepare_range_limit_table(cinfo);
  165766. /* Width of an output scanline must be representable as JDIMENSION. */
  165767. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  165768. jd_samplesperrow = (JDIMENSION) samplesperrow;
  165769. if ((long) jd_samplesperrow != samplesperrow)
  165770. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  165771. /* Initialize my private state */
  165772. master->pass_number = 0;
  165773. master->using_merged_upsample = use_merged_upsample(cinfo);
  165774. /* Color quantizer selection */
  165775. master->quantizer_1pass = NULL;
  165776. master->quantizer_2pass = NULL;
  165777. /* No mode changes if not using buffered-image mode. */
  165778. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  165779. cinfo->enable_1pass_quant = FALSE;
  165780. cinfo->enable_external_quant = FALSE;
  165781. cinfo->enable_2pass_quant = FALSE;
  165782. }
  165783. if (cinfo->quantize_colors) {
  165784. if (cinfo->raw_data_out)
  165785. ERREXIT(cinfo, JERR_NOTIMPL);
  165786. /* 2-pass quantizer only works in 3-component color space. */
  165787. if (cinfo->out_color_components != 3) {
  165788. cinfo->enable_1pass_quant = TRUE;
  165789. cinfo->enable_external_quant = FALSE;
  165790. cinfo->enable_2pass_quant = FALSE;
  165791. cinfo->colormap = NULL;
  165792. } else if (cinfo->colormap != NULL) {
  165793. cinfo->enable_external_quant = TRUE;
  165794. } else if (cinfo->two_pass_quantize) {
  165795. cinfo->enable_2pass_quant = TRUE;
  165796. } else {
  165797. cinfo->enable_1pass_quant = TRUE;
  165798. }
  165799. if (cinfo->enable_1pass_quant) {
  165800. #ifdef QUANT_1PASS_SUPPORTED
  165801. jinit_1pass_quantizer(cinfo);
  165802. master->quantizer_1pass = cinfo->cquantize;
  165803. #else
  165804. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165805. #endif
  165806. }
  165807. /* We use the 2-pass code to map to external colormaps. */
  165808. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  165809. #ifdef QUANT_2PASS_SUPPORTED
  165810. jinit_2pass_quantizer(cinfo);
  165811. master->quantizer_2pass = cinfo->cquantize;
  165812. #else
  165813. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165814. #endif
  165815. }
  165816. /* If both quantizers are initialized, the 2-pass one is left active;
  165817. * this is necessary for starting with quantization to an external map.
  165818. */
  165819. }
  165820. /* Post-processing: in particular, color conversion first */
  165821. if (! cinfo->raw_data_out) {
  165822. if (master->using_merged_upsample) {
  165823. #ifdef UPSAMPLE_MERGING_SUPPORTED
  165824. jinit_merged_upsampler(cinfo); /* does color conversion too */
  165825. #else
  165826. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165827. #endif
  165828. } else {
  165829. jinit_color_deconverter(cinfo);
  165830. jinit_upsampler(cinfo);
  165831. }
  165832. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  165833. }
  165834. /* Inverse DCT */
  165835. jinit_inverse_dct(cinfo);
  165836. /* Entropy decoding: either Huffman or arithmetic coding. */
  165837. if (cinfo->arith_code) {
  165838. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  165839. } else {
  165840. if (cinfo->progressive_mode) {
  165841. #ifdef D_PROGRESSIVE_SUPPORTED
  165842. jinit_phuff_decoder(cinfo);
  165843. #else
  165844. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165845. #endif
  165846. } else
  165847. jinit_huff_decoder(cinfo);
  165848. }
  165849. /* Initialize principal buffer controllers. */
  165850. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  165851. jinit_d_coef_controller(cinfo, use_c_buffer);
  165852. if (! cinfo->raw_data_out)
  165853. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  165854. /* We can now tell the memory manager to allocate virtual arrays. */
  165855. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  165856. /* Initialize input side of decompressor to consume first scan. */
  165857. (*cinfo->inputctl->start_input_pass) (cinfo);
  165858. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165859. /* If jpeg_start_decompress will read the whole file, initialize
  165860. * progress monitoring appropriately. The input step is counted
  165861. * as one pass.
  165862. */
  165863. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  165864. cinfo->inputctl->has_multiple_scans) {
  165865. int nscans;
  165866. /* Estimate number of scans to set pass_limit. */
  165867. if (cinfo->progressive_mode) {
  165868. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  165869. nscans = 2 + 3 * cinfo->num_components;
  165870. } else {
  165871. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  165872. nscans = cinfo->num_components;
  165873. }
  165874. cinfo->progress->pass_counter = 0L;
  165875. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  165876. cinfo->progress->completed_passes = 0;
  165877. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  165878. /* Count the input pass as done */
  165879. master->pass_number++;
  165880. }
  165881. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165882. }
  165883. /*
  165884. * Per-pass setup.
  165885. * This is called at the beginning of each output pass. We determine which
  165886. * modules will be active during this pass and give them appropriate
  165887. * start_pass calls. We also set is_dummy_pass to indicate whether this
  165888. * is a "real" output pass or a dummy pass for color quantization.
  165889. * (In the latter case, jdapistd.c will crank the pass to completion.)
  165890. */
  165891. METHODDEF(void)
  165892. prepare_for_output_pass (j_decompress_ptr cinfo)
  165893. {
  165894. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165895. if (master->pub.is_dummy_pass) {
  165896. #ifdef QUANT_2PASS_SUPPORTED
  165897. /* Final pass of 2-pass quantization */
  165898. master->pub.is_dummy_pass = FALSE;
  165899. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  165900. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  165901. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  165902. #else
  165903. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165904. #endif /* QUANT_2PASS_SUPPORTED */
  165905. } else {
  165906. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  165907. /* Select new quantization method */
  165908. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  165909. cinfo->cquantize = master->quantizer_2pass;
  165910. master->pub.is_dummy_pass = TRUE;
  165911. } else if (cinfo->enable_1pass_quant) {
  165912. cinfo->cquantize = master->quantizer_1pass;
  165913. } else {
  165914. ERREXIT(cinfo, JERR_MODE_CHANGE);
  165915. }
  165916. }
  165917. (*cinfo->idct->start_pass) (cinfo);
  165918. (*cinfo->coef->start_output_pass) (cinfo);
  165919. if (! cinfo->raw_data_out) {
  165920. if (! master->using_merged_upsample)
  165921. (*cinfo->cconvert->start_pass) (cinfo);
  165922. (*cinfo->upsample->start_pass) (cinfo);
  165923. if (cinfo->quantize_colors)
  165924. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  165925. (*cinfo->post->start_pass) (cinfo,
  165926. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165927. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165928. }
  165929. }
  165930. /* Set up progress monitor's pass info if present */
  165931. if (cinfo->progress != NULL) {
  165932. cinfo->progress->completed_passes = master->pass_number;
  165933. cinfo->progress->total_passes = master->pass_number +
  165934. (master->pub.is_dummy_pass ? 2 : 1);
  165935. /* In buffered-image mode, we assume one more output pass if EOI not
  165936. * yet reached, but no more passes if EOI has been reached.
  165937. */
  165938. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  165939. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  165940. }
  165941. }
  165942. }
  165943. /*
  165944. * Finish up at end of an output pass.
  165945. */
  165946. METHODDEF(void)
  165947. finish_output_pass (j_decompress_ptr cinfo)
  165948. {
  165949. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165950. if (cinfo->quantize_colors)
  165951. (*cinfo->cquantize->finish_pass) (cinfo);
  165952. master->pass_number++;
  165953. }
  165954. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165955. /*
  165956. * Switch to a new external colormap between output passes.
  165957. */
  165958. GLOBAL(void)
  165959. jpeg_new_colormap (j_decompress_ptr cinfo)
  165960. {
  165961. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165962. /* Prevent application from calling me at wrong times */
  165963. if (cinfo->global_state != DSTATE_BUFIMAGE)
  165964. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165965. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  165966. cinfo->colormap != NULL) {
  165967. /* Select 2-pass quantizer for external colormap use */
  165968. cinfo->cquantize = master->quantizer_2pass;
  165969. /* Notify quantizer of colormap change */
  165970. (*cinfo->cquantize->new_color_map) (cinfo);
  165971. master->pub.is_dummy_pass = FALSE; /* just in case */
  165972. } else
  165973. ERREXIT(cinfo, JERR_MODE_CHANGE);
  165974. }
  165975. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165976. /*
  165977. * Initialize master decompression control and select active modules.
  165978. * This is performed at the start of jpeg_start_decompress.
  165979. */
  165980. GLOBAL(void)
  165981. jinit_master_decompress (j_decompress_ptr cinfo)
  165982. {
  165983. my_master_ptr6 master;
  165984. master = (my_master_ptr6)
  165985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165986. SIZEOF(my_decomp_master));
  165987. cinfo->master = (struct jpeg_decomp_master *) master;
  165988. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  165989. master->pub.finish_output_pass = finish_output_pass;
  165990. master->pub.is_dummy_pass = FALSE;
  165991. master_selection(cinfo);
  165992. }
  165993. /********* End of inlined file: jdmaster.c *********/
  165994. #undef FIX
  165995. /********* Start of inlined file: jdmerge.c *********/
  165996. #define JPEG_INTERNALS
  165997. #ifdef UPSAMPLE_MERGING_SUPPORTED
  165998. /* Private subobject */
  165999. typedef struct {
  166000. struct jpeg_upsampler pub; /* public fields */
  166001. /* Pointer to routine to do actual upsampling/conversion of one row group */
  166002. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  166003. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166004. JSAMPARRAY output_buf));
  166005. /* Private state for YCC->RGB conversion */
  166006. int * Cr_r_tab; /* => table for Cr to R conversion */
  166007. int * Cb_b_tab; /* => table for Cb to B conversion */
  166008. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166009. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166010. /* For 2:1 vertical sampling, we produce two output rows at a time.
  166011. * We need a "spare" row buffer to hold the second output row if the
  166012. * application provides just a one-row buffer; we also use the spare
  166013. * to discard the dummy last row if the image height is odd.
  166014. */
  166015. JSAMPROW spare_row;
  166016. boolean spare_full; /* T if spare buffer is occupied */
  166017. JDIMENSION out_row_width; /* samples per output row */
  166018. JDIMENSION rows_to_go; /* counts rows remaining in image */
  166019. } my_upsampler;
  166020. typedef my_upsampler * my_upsample_ptr;
  166021. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166022. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166023. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166024. /*
  166025. * Initialize tables for YCC->RGB colorspace conversion.
  166026. * This is taken directly from jdcolor.c; see that file for more info.
  166027. */
  166028. LOCAL(void)
  166029. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  166030. {
  166031. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166032. int i;
  166033. INT32 x;
  166034. SHIFT_TEMPS
  166035. upsample->Cr_r_tab = (int *)
  166036. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166037. (MAXJSAMPLE+1) * SIZEOF(int));
  166038. upsample->Cb_b_tab = (int *)
  166039. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166040. (MAXJSAMPLE+1) * SIZEOF(int));
  166041. upsample->Cr_g_tab = (INT32 *)
  166042. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166043. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166044. upsample->Cb_g_tab = (INT32 *)
  166045. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166046. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166047. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166048. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166049. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166050. /* Cr=>R value is nearest int to 1.40200 * x */
  166051. upsample->Cr_r_tab[i] = (int)
  166052. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166053. /* Cb=>B value is nearest int to 1.77200 * x */
  166054. upsample->Cb_b_tab[i] = (int)
  166055. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166056. /* Cr=>G value is scaled-up -0.71414 * x */
  166057. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166058. /* Cb=>G value is scaled-up -0.34414 * x */
  166059. /* We also add in ONE_HALF so that need not do it in inner loop */
  166060. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166061. }
  166062. }
  166063. /*
  166064. * Initialize for an upsampling pass.
  166065. */
  166066. METHODDEF(void)
  166067. start_pass_merged_upsample (j_decompress_ptr cinfo)
  166068. {
  166069. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166070. /* Mark the spare buffer empty */
  166071. upsample->spare_full = FALSE;
  166072. /* Initialize total-height counter for detecting bottom of image */
  166073. upsample->rows_to_go = cinfo->output_height;
  166074. }
  166075. /*
  166076. * Control routine to do upsampling (and color conversion).
  166077. *
  166078. * The control routine just handles the row buffering considerations.
  166079. */
  166080. METHODDEF(void)
  166081. merged_2v_upsample (j_decompress_ptr cinfo,
  166082. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166083. JDIMENSION in_row_groups_avail,
  166084. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166085. JDIMENSION out_rows_avail)
  166086. /* 2:1 vertical sampling case: may need a spare row. */
  166087. {
  166088. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166089. JSAMPROW work_ptrs[2];
  166090. JDIMENSION num_rows; /* number of rows returned to caller */
  166091. if (upsample->spare_full) {
  166092. /* If we have a spare row saved from a previous cycle, just return it. */
  166093. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  166094. 1, upsample->out_row_width);
  166095. num_rows = 1;
  166096. upsample->spare_full = FALSE;
  166097. } else {
  166098. /* Figure number of rows to return to caller. */
  166099. num_rows = 2;
  166100. /* Not more than the distance to the end of the image. */
  166101. if (num_rows > upsample->rows_to_go)
  166102. num_rows = upsample->rows_to_go;
  166103. /* And not more than what the client can accept: */
  166104. out_rows_avail -= *out_row_ctr;
  166105. if (num_rows > out_rows_avail)
  166106. num_rows = out_rows_avail;
  166107. /* Create output pointer array for upsampler. */
  166108. work_ptrs[0] = output_buf[*out_row_ctr];
  166109. if (num_rows > 1) {
  166110. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  166111. } else {
  166112. work_ptrs[1] = upsample->spare_row;
  166113. upsample->spare_full = TRUE;
  166114. }
  166115. /* Now do the upsampling. */
  166116. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  166117. }
  166118. /* Adjust counts */
  166119. *out_row_ctr += num_rows;
  166120. upsample->rows_to_go -= num_rows;
  166121. /* When the buffer is emptied, declare this input row group consumed */
  166122. if (! upsample->spare_full)
  166123. (*in_row_group_ctr)++;
  166124. }
  166125. METHODDEF(void)
  166126. merged_1v_upsample (j_decompress_ptr cinfo,
  166127. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166128. JDIMENSION in_row_groups_avail,
  166129. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166130. JDIMENSION out_rows_avail)
  166131. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  166132. {
  166133. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166134. /* Just do the upsampling. */
  166135. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  166136. output_buf + *out_row_ctr);
  166137. /* Adjust counts */
  166138. (*out_row_ctr)++;
  166139. (*in_row_group_ctr)++;
  166140. }
  166141. /*
  166142. * These are the routines invoked by the control routines to do
  166143. * the actual upsampling/conversion. One row group is processed per call.
  166144. *
  166145. * Note: since we may be writing directly into application-supplied buffers,
  166146. * we have to be honest about the output width; we can't assume the buffer
  166147. * has been rounded up to an even width.
  166148. */
  166149. /*
  166150. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  166151. */
  166152. METHODDEF(void)
  166153. h2v1_merged_upsample (j_decompress_ptr cinfo,
  166154. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166155. JSAMPARRAY output_buf)
  166156. {
  166157. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166158. register int y, cred, cgreen, cblue;
  166159. int cb, cr;
  166160. register JSAMPROW outptr;
  166161. JSAMPROW inptr0, inptr1, inptr2;
  166162. JDIMENSION col;
  166163. /* copy these pointers into registers if possible */
  166164. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166165. int * Crrtab = upsample->Cr_r_tab;
  166166. int * Cbbtab = upsample->Cb_b_tab;
  166167. INT32 * Crgtab = upsample->Cr_g_tab;
  166168. INT32 * Cbgtab = upsample->Cb_g_tab;
  166169. SHIFT_TEMPS
  166170. inptr0 = input_buf[0][in_row_group_ctr];
  166171. inptr1 = input_buf[1][in_row_group_ctr];
  166172. inptr2 = input_buf[2][in_row_group_ctr];
  166173. outptr = output_buf[0];
  166174. /* Loop for each pair of output pixels */
  166175. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166176. /* Do the chroma part of the calculation */
  166177. cb = GETJSAMPLE(*inptr1++);
  166178. cr = GETJSAMPLE(*inptr2++);
  166179. cred = Crrtab[cr];
  166180. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166181. cblue = Cbbtab[cb];
  166182. /* Fetch 2 Y values and emit 2 pixels */
  166183. y = GETJSAMPLE(*inptr0++);
  166184. outptr[RGB_RED] = range_limit[y + cred];
  166185. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166186. outptr[RGB_BLUE] = range_limit[y + cblue];
  166187. outptr += RGB_PIXELSIZE;
  166188. y = GETJSAMPLE(*inptr0++);
  166189. outptr[RGB_RED] = range_limit[y + cred];
  166190. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166191. outptr[RGB_BLUE] = range_limit[y + cblue];
  166192. outptr += RGB_PIXELSIZE;
  166193. }
  166194. /* If image width is odd, do the last output column separately */
  166195. if (cinfo->output_width & 1) {
  166196. cb = GETJSAMPLE(*inptr1);
  166197. cr = GETJSAMPLE(*inptr2);
  166198. cred = Crrtab[cr];
  166199. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166200. cblue = Cbbtab[cb];
  166201. y = GETJSAMPLE(*inptr0);
  166202. outptr[RGB_RED] = range_limit[y + cred];
  166203. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166204. outptr[RGB_BLUE] = range_limit[y + cblue];
  166205. }
  166206. }
  166207. /*
  166208. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  166209. */
  166210. METHODDEF(void)
  166211. h2v2_merged_upsample (j_decompress_ptr cinfo,
  166212. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166213. JSAMPARRAY output_buf)
  166214. {
  166215. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166216. register int y, cred, cgreen, cblue;
  166217. int cb, cr;
  166218. register JSAMPROW outptr0, outptr1;
  166219. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  166220. JDIMENSION col;
  166221. /* copy these pointers into registers if possible */
  166222. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166223. int * Crrtab = upsample->Cr_r_tab;
  166224. int * Cbbtab = upsample->Cb_b_tab;
  166225. INT32 * Crgtab = upsample->Cr_g_tab;
  166226. INT32 * Cbgtab = upsample->Cb_g_tab;
  166227. SHIFT_TEMPS
  166228. inptr00 = input_buf[0][in_row_group_ctr*2];
  166229. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  166230. inptr1 = input_buf[1][in_row_group_ctr];
  166231. inptr2 = input_buf[2][in_row_group_ctr];
  166232. outptr0 = output_buf[0];
  166233. outptr1 = output_buf[1];
  166234. /* Loop for each group of output pixels */
  166235. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166236. /* Do the chroma part of the calculation */
  166237. cb = GETJSAMPLE(*inptr1++);
  166238. cr = GETJSAMPLE(*inptr2++);
  166239. cred = Crrtab[cr];
  166240. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166241. cblue = Cbbtab[cb];
  166242. /* Fetch 4 Y values and emit 4 pixels */
  166243. y = GETJSAMPLE(*inptr00++);
  166244. outptr0[RGB_RED] = range_limit[y + cred];
  166245. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166246. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166247. outptr0 += RGB_PIXELSIZE;
  166248. y = GETJSAMPLE(*inptr00++);
  166249. outptr0[RGB_RED] = range_limit[y + cred];
  166250. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166251. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166252. outptr0 += RGB_PIXELSIZE;
  166253. y = GETJSAMPLE(*inptr01++);
  166254. outptr1[RGB_RED] = range_limit[y + cred];
  166255. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166256. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166257. outptr1 += RGB_PIXELSIZE;
  166258. y = GETJSAMPLE(*inptr01++);
  166259. outptr1[RGB_RED] = range_limit[y + cred];
  166260. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166261. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166262. outptr1 += RGB_PIXELSIZE;
  166263. }
  166264. /* If image width is odd, do the last output column separately */
  166265. if (cinfo->output_width & 1) {
  166266. cb = GETJSAMPLE(*inptr1);
  166267. cr = GETJSAMPLE(*inptr2);
  166268. cred = Crrtab[cr];
  166269. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166270. cblue = Cbbtab[cb];
  166271. y = GETJSAMPLE(*inptr00);
  166272. outptr0[RGB_RED] = range_limit[y + cred];
  166273. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166274. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166275. y = GETJSAMPLE(*inptr01);
  166276. outptr1[RGB_RED] = range_limit[y + cred];
  166277. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166278. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166279. }
  166280. }
  166281. /*
  166282. * Module initialization routine for merged upsampling/color conversion.
  166283. *
  166284. * NB: this is called under the conditions determined by use_merged_upsample()
  166285. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  166286. * of this module; no safety checks are made here.
  166287. */
  166288. GLOBAL(void)
  166289. jinit_merged_upsampler (j_decompress_ptr cinfo)
  166290. {
  166291. my_upsample_ptr upsample;
  166292. upsample = (my_upsample_ptr)
  166293. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166294. SIZEOF(my_upsampler));
  166295. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  166296. upsample->pub.start_pass = start_pass_merged_upsample;
  166297. upsample->pub.need_context_rows = FALSE;
  166298. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  166299. if (cinfo->max_v_samp_factor == 2) {
  166300. upsample->pub.upsample = merged_2v_upsample;
  166301. upsample->upmethod = h2v2_merged_upsample;
  166302. /* Allocate a spare row buffer */
  166303. upsample->spare_row = (JSAMPROW)
  166304. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166305. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  166306. } else {
  166307. upsample->pub.upsample = merged_1v_upsample;
  166308. upsample->upmethod = h2v1_merged_upsample;
  166309. /* No spare row needed */
  166310. upsample->spare_row = NULL;
  166311. }
  166312. build_ycc_rgb_table2(cinfo);
  166313. }
  166314. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  166315. /********* End of inlined file: jdmerge.c *********/
  166316. #undef ASSIGN_STATE
  166317. /********* Start of inlined file: jdphuff.c *********/
  166318. #define JPEG_INTERNALS
  166319. #ifdef D_PROGRESSIVE_SUPPORTED
  166320. /*
  166321. * Expanded entropy decoder object for progressive Huffman decoding.
  166322. *
  166323. * The savable_state subrecord contains fields that change within an MCU,
  166324. * but must not be updated permanently until we complete the MCU.
  166325. */
  166326. typedef struct {
  166327. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  166328. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166329. } savable_state3;
  166330. /* This macro is to work around compilers with missing or broken
  166331. * structure assignment. You'll need to fix this code if you have
  166332. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166333. */
  166334. #ifndef NO_STRUCT_ASSIGN
  166335. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166336. #else
  166337. #if MAX_COMPS_IN_SCAN == 4
  166338. #define ASSIGN_STATE(dest,src) \
  166339. ((dest).EOBRUN = (src).EOBRUN, \
  166340. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  166341. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  166342. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  166343. (dest).last_dc_val[3] = (src).last_dc_val[3])
  166344. #endif
  166345. #endif
  166346. typedef struct {
  166347. struct jpeg_entropy_decoder pub; /* public fields */
  166348. /* These fields are loaded into local variables at start of each MCU.
  166349. * In case of suspension, we exit WITHOUT updating them.
  166350. */
  166351. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  166352. savable_state3 saved; /* Other state at start of MCU */
  166353. /* These fields are NOT loaded into local working state. */
  166354. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166355. /* Pointers to derived tables (these workspaces have image lifespan) */
  166356. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166357. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  166358. } phuff_entropy_decoder;
  166359. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  166360. /* Forward declarations */
  166361. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  166362. JBLOCKROW *MCU_data));
  166363. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  166364. JBLOCKROW *MCU_data));
  166365. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  166366. JBLOCKROW *MCU_data));
  166367. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  166368. JBLOCKROW *MCU_data));
  166369. /*
  166370. * Initialize for a Huffman-compressed scan.
  166371. */
  166372. METHODDEF(void)
  166373. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  166374. {
  166375. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166376. boolean is_DC_band, bad;
  166377. int ci, coefi, tbl;
  166378. int *coef_bit_ptr;
  166379. jpeg_component_info * compptr;
  166380. is_DC_band = (cinfo->Ss == 0);
  166381. /* Validate scan parameters */
  166382. bad = FALSE;
  166383. if (is_DC_band) {
  166384. if (cinfo->Se != 0)
  166385. bad = TRUE;
  166386. } else {
  166387. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  166388. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  166389. bad = TRUE;
  166390. /* AC scans may have only one component */
  166391. if (cinfo->comps_in_scan != 1)
  166392. bad = TRUE;
  166393. }
  166394. if (cinfo->Ah != 0) {
  166395. /* Successive approximation refinement scan: must have Al = Ah-1. */
  166396. if (cinfo->Al != cinfo->Ah-1)
  166397. bad = TRUE;
  166398. }
  166399. if (cinfo->Al > 13) /* need not check for < 0 */
  166400. bad = TRUE;
  166401. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  166402. * but the spec doesn't say so, and we try to be liberal about what we
  166403. * accept. Note: large Al values could result in out-of-range DC
  166404. * coefficients during early scans, leading to bizarre displays due to
  166405. * overflows in the IDCT math. But we won't crash.
  166406. */
  166407. if (bad)
  166408. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  166409. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  166410. /* Update progression status, and verify that scan order is legal.
  166411. * Note that inter-scan inconsistencies are treated as warnings
  166412. * not fatal errors ... not clear if this is right way to behave.
  166413. */
  166414. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166415. int cindex = cinfo->cur_comp_info[ci]->component_index;
  166416. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  166417. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  166418. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  166419. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  166420. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  166421. if (cinfo->Ah != expected)
  166422. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  166423. coef_bit_ptr[coefi] = cinfo->Al;
  166424. }
  166425. }
  166426. /* Select MCU decoding routine */
  166427. if (cinfo->Ah == 0) {
  166428. if (is_DC_band)
  166429. entropy->pub.decode_mcu = decode_mcu_DC_first;
  166430. else
  166431. entropy->pub.decode_mcu = decode_mcu_AC_first;
  166432. } else {
  166433. if (is_DC_band)
  166434. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  166435. else
  166436. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  166437. }
  166438. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166439. compptr = cinfo->cur_comp_info[ci];
  166440. /* Make sure requested tables are present, and compute derived tables.
  166441. * We may build same derived table more than once, but it's not expensive.
  166442. */
  166443. if (is_DC_band) {
  166444. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  166445. tbl = compptr->dc_tbl_no;
  166446. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  166447. & entropy->derived_tbls[tbl]);
  166448. }
  166449. } else {
  166450. tbl = compptr->ac_tbl_no;
  166451. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  166452. & entropy->derived_tbls[tbl]);
  166453. /* remember the single active table */
  166454. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  166455. }
  166456. /* Initialize DC predictions to 0 */
  166457. entropy->saved.last_dc_val[ci] = 0;
  166458. }
  166459. /* Initialize bitread state variables */
  166460. entropy->bitstate.bits_left = 0;
  166461. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  166462. entropy->pub.insufficient_data = FALSE;
  166463. /* Initialize private state variables */
  166464. entropy->saved.EOBRUN = 0;
  166465. /* Initialize restart counter */
  166466. entropy->restarts_to_go = cinfo->restart_interval;
  166467. }
  166468. /*
  166469. * Check for a restart marker & resynchronize decoder.
  166470. * Returns FALSE if must suspend.
  166471. */
  166472. LOCAL(boolean)
  166473. process_restartp (j_decompress_ptr cinfo)
  166474. {
  166475. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166476. int ci;
  166477. /* Throw away any unused bits remaining in bit buffer; */
  166478. /* include any full bytes in next_marker's count of discarded bytes */
  166479. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  166480. entropy->bitstate.bits_left = 0;
  166481. /* Advance past the RSTn marker */
  166482. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  166483. return FALSE;
  166484. /* Re-initialize DC predictions to 0 */
  166485. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  166486. entropy->saved.last_dc_val[ci] = 0;
  166487. /* Re-init EOB run count, too */
  166488. entropy->saved.EOBRUN = 0;
  166489. /* Reset restart counter */
  166490. entropy->restarts_to_go = cinfo->restart_interval;
  166491. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  166492. * against a marker. In that case we will end up treating the next data
  166493. * segment as empty, and we can avoid producing bogus output pixels by
  166494. * leaving the flag set.
  166495. */
  166496. if (cinfo->unread_marker == 0)
  166497. entropy->pub.insufficient_data = FALSE;
  166498. return TRUE;
  166499. }
  166500. /*
  166501. * Huffman MCU decoding.
  166502. * Each of these routines decodes and returns one MCU's worth of
  166503. * Huffman-compressed coefficients.
  166504. * The coefficients are reordered from zigzag order into natural array order,
  166505. * but are not dequantized.
  166506. *
  166507. * The i'th block of the MCU is stored into the block pointed to by
  166508. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  166509. *
  166510. * We return FALSE if data source requested suspension. In that case no
  166511. * changes have been made to permanent state. (Exception: some output
  166512. * coefficients may already have been assigned. This is harmless for
  166513. * spectral selection, since we'll just re-assign them on the next call.
  166514. * Successive approximation AC refinement has to be more careful, however.)
  166515. */
  166516. /*
  166517. * MCU decoding for DC initial scan (either spectral selection,
  166518. * or first pass of successive approximation).
  166519. */
  166520. METHODDEF(boolean)
  166521. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166522. {
  166523. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166524. int Al = cinfo->Al;
  166525. register int s, r;
  166526. int blkn, ci;
  166527. JBLOCKROW block;
  166528. BITREAD_STATE_VARS;
  166529. savable_state3 state;
  166530. d_derived_tbl * tbl;
  166531. jpeg_component_info * compptr;
  166532. /* Process restart marker if needed; may have to suspend */
  166533. if (cinfo->restart_interval) {
  166534. if (entropy->restarts_to_go == 0)
  166535. if (! process_restartp(cinfo))
  166536. return FALSE;
  166537. }
  166538. /* If we've run out of data, just leave the MCU set to zeroes.
  166539. * This way, we return uniform gray for the remainder of the segment.
  166540. */
  166541. if (! entropy->pub.insufficient_data) {
  166542. /* Load up working state */
  166543. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166544. ASSIGN_STATE(state, entropy->saved);
  166545. /* Outer loop handles each block in the MCU */
  166546. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166547. block = MCU_data[blkn];
  166548. ci = cinfo->MCU_membership[blkn];
  166549. compptr = cinfo->cur_comp_info[ci];
  166550. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  166551. /* Decode a single block's worth of coefficients */
  166552. /* Section F.2.2.1: decode the DC coefficient difference */
  166553. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  166554. if (s) {
  166555. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166556. r = GET_BITS(s);
  166557. s = HUFF_EXTEND(r, s);
  166558. }
  166559. /* Convert DC difference to actual value, update last_dc_val */
  166560. s += state.last_dc_val[ci];
  166561. state.last_dc_val[ci] = s;
  166562. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  166563. (*block)[0] = (JCOEF) (s << Al);
  166564. }
  166565. /* Completed MCU, so update state */
  166566. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166567. ASSIGN_STATE(entropy->saved, state);
  166568. }
  166569. /* Account for restart interval (no-op if not using restarts) */
  166570. entropy->restarts_to_go--;
  166571. return TRUE;
  166572. }
  166573. /*
  166574. * MCU decoding for AC initial scan (either spectral selection,
  166575. * or first pass of successive approximation).
  166576. */
  166577. METHODDEF(boolean)
  166578. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166579. {
  166580. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166581. int Se = cinfo->Se;
  166582. int Al = cinfo->Al;
  166583. register int s, k, r;
  166584. unsigned int EOBRUN;
  166585. JBLOCKROW block;
  166586. BITREAD_STATE_VARS;
  166587. d_derived_tbl * tbl;
  166588. /* Process restart marker if needed; may have to suspend */
  166589. if (cinfo->restart_interval) {
  166590. if (entropy->restarts_to_go == 0)
  166591. if (! process_restartp(cinfo))
  166592. return FALSE;
  166593. }
  166594. /* If we've run out of data, just leave the MCU set to zeroes.
  166595. * This way, we return uniform gray for the remainder of the segment.
  166596. */
  166597. if (! entropy->pub.insufficient_data) {
  166598. /* Load up working state.
  166599. * We can avoid loading/saving bitread state if in an EOB run.
  166600. */
  166601. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  166602. /* There is always only one block per MCU */
  166603. if (EOBRUN > 0) /* if it's a band of zeroes... */
  166604. EOBRUN--; /* ...process it now (we do nothing) */
  166605. else {
  166606. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166607. block = MCU_data[0];
  166608. tbl = entropy->ac_derived_tbl;
  166609. for (k = cinfo->Ss; k <= Se; k++) {
  166610. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  166611. r = s >> 4;
  166612. s &= 15;
  166613. if (s) {
  166614. k += r;
  166615. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166616. r = GET_BITS(s);
  166617. s = HUFF_EXTEND(r, s);
  166618. /* Scale and output coefficient in natural (dezigzagged) order */
  166619. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  166620. } else {
  166621. if (r == 15) { /* ZRL */
  166622. k += 15; /* skip 15 zeroes in band */
  166623. } else { /* EOBr, run length is 2^r + appended bits */
  166624. EOBRUN = 1 << r;
  166625. if (r) { /* EOBr, r > 0 */
  166626. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  166627. r = GET_BITS(r);
  166628. EOBRUN += r;
  166629. }
  166630. EOBRUN--; /* this band is processed at this moment */
  166631. break; /* force end-of-band */
  166632. }
  166633. }
  166634. }
  166635. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166636. }
  166637. /* Completed MCU, so update state */
  166638. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  166639. }
  166640. /* Account for restart interval (no-op if not using restarts) */
  166641. entropy->restarts_to_go--;
  166642. return TRUE;
  166643. }
  166644. /*
  166645. * MCU decoding for DC successive approximation refinement scan.
  166646. * Note: we assume such scans can be multi-component, although the spec
  166647. * is not very clear on the point.
  166648. */
  166649. METHODDEF(boolean)
  166650. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166651. {
  166652. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166653. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  166654. int blkn;
  166655. JBLOCKROW block;
  166656. BITREAD_STATE_VARS;
  166657. /* Process restart marker if needed; may have to suspend */
  166658. if (cinfo->restart_interval) {
  166659. if (entropy->restarts_to_go == 0)
  166660. if (! process_restartp(cinfo))
  166661. return FALSE;
  166662. }
  166663. /* Not worth the cycles to check insufficient_data here,
  166664. * since we will not change the data anyway if we read zeroes.
  166665. */
  166666. /* Load up working state */
  166667. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166668. /* Outer loop handles each block in the MCU */
  166669. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166670. block = MCU_data[blkn];
  166671. /* Encoded data is simply the next bit of the two's-complement DC value */
  166672. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  166673. if (GET_BITS(1))
  166674. (*block)[0] |= p1;
  166675. /* Note: since we use |=, repeating the assignment later is safe */
  166676. }
  166677. /* Completed MCU, so update state */
  166678. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166679. /* Account for restart interval (no-op if not using restarts) */
  166680. entropy->restarts_to_go--;
  166681. return TRUE;
  166682. }
  166683. /*
  166684. * MCU decoding for AC successive approximation refinement scan.
  166685. */
  166686. METHODDEF(boolean)
  166687. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166688. {
  166689. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166690. int Se = cinfo->Se;
  166691. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  166692. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  166693. register int s, k, r;
  166694. unsigned int EOBRUN;
  166695. JBLOCKROW block;
  166696. JCOEFPTR thiscoef;
  166697. BITREAD_STATE_VARS;
  166698. d_derived_tbl * tbl;
  166699. int num_newnz;
  166700. int newnz_pos[DCTSIZE2];
  166701. /* Process restart marker if needed; may have to suspend */
  166702. if (cinfo->restart_interval) {
  166703. if (entropy->restarts_to_go == 0)
  166704. if (! process_restartp(cinfo))
  166705. return FALSE;
  166706. }
  166707. /* If we've run out of data, don't modify the MCU.
  166708. */
  166709. if (! entropy->pub.insufficient_data) {
  166710. /* Load up working state */
  166711. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166712. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  166713. /* There is always only one block per MCU */
  166714. block = MCU_data[0];
  166715. tbl = entropy->ac_derived_tbl;
  166716. /* If we are forced to suspend, we must undo the assignments to any newly
  166717. * nonzero coefficients in the block, because otherwise we'd get confused
  166718. * next time about which coefficients were already nonzero.
  166719. * But we need not undo addition of bits to already-nonzero coefficients;
  166720. * instead, we can test the current bit to see if we already did it.
  166721. */
  166722. num_newnz = 0;
  166723. /* initialize coefficient loop counter to start of band */
  166724. k = cinfo->Ss;
  166725. if (EOBRUN == 0) {
  166726. for (; k <= Se; k++) {
  166727. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  166728. r = s >> 4;
  166729. s &= 15;
  166730. if (s) {
  166731. if (s != 1) /* size of new coef should always be 1 */
  166732. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  166733. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166734. if (GET_BITS(1))
  166735. s = p1; /* newly nonzero coef is positive */
  166736. else
  166737. s = m1; /* newly nonzero coef is negative */
  166738. } else {
  166739. if (r != 15) {
  166740. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  166741. if (r) {
  166742. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  166743. r = GET_BITS(r);
  166744. EOBRUN += r;
  166745. }
  166746. break; /* rest of block is handled by EOB logic */
  166747. }
  166748. /* note s = 0 for processing ZRL */
  166749. }
  166750. /* Advance over already-nonzero coefs and r still-zero coefs,
  166751. * appending correction bits to the nonzeroes. A correction bit is 1
  166752. * if the absolute value of the coefficient must be increased.
  166753. */
  166754. do {
  166755. thiscoef = *block + jpeg_natural_order[k];
  166756. if (*thiscoef != 0) {
  166757. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166758. if (GET_BITS(1)) {
  166759. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  166760. if (*thiscoef >= 0)
  166761. *thiscoef += p1;
  166762. else
  166763. *thiscoef += m1;
  166764. }
  166765. }
  166766. } else {
  166767. if (--r < 0)
  166768. break; /* reached target zero coefficient */
  166769. }
  166770. k++;
  166771. } while (k <= Se);
  166772. if (s) {
  166773. int pos = jpeg_natural_order[k];
  166774. /* Output newly nonzero coefficient */
  166775. (*block)[pos] = (JCOEF) s;
  166776. /* Remember its position in case we have to suspend */
  166777. newnz_pos[num_newnz++] = pos;
  166778. }
  166779. }
  166780. }
  166781. if (EOBRUN > 0) {
  166782. /* Scan any remaining coefficient positions after the end-of-band
  166783. * (the last newly nonzero coefficient, if any). Append a correction
  166784. * bit to each already-nonzero coefficient. A correction bit is 1
  166785. * if the absolute value of the coefficient must be increased.
  166786. */
  166787. for (; k <= Se; k++) {
  166788. thiscoef = *block + jpeg_natural_order[k];
  166789. if (*thiscoef != 0) {
  166790. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166791. if (GET_BITS(1)) {
  166792. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  166793. if (*thiscoef >= 0)
  166794. *thiscoef += p1;
  166795. else
  166796. *thiscoef += m1;
  166797. }
  166798. }
  166799. }
  166800. }
  166801. /* Count one block completed in EOB run */
  166802. EOBRUN--;
  166803. }
  166804. /* Completed MCU, so update state */
  166805. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166806. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  166807. }
  166808. /* Account for restart interval (no-op if not using restarts) */
  166809. entropy->restarts_to_go--;
  166810. return TRUE;
  166811. undoit:
  166812. /* Re-zero any output coefficients that we made newly nonzero */
  166813. while (num_newnz > 0)
  166814. (*block)[newnz_pos[--num_newnz]] = 0;
  166815. return FALSE;
  166816. }
  166817. /*
  166818. * Module initialization routine for progressive Huffman entropy decoding.
  166819. */
  166820. GLOBAL(void)
  166821. jinit_phuff_decoder (j_decompress_ptr cinfo)
  166822. {
  166823. phuff_entropy_ptr2 entropy;
  166824. int *coef_bit_ptr;
  166825. int ci, i;
  166826. entropy = (phuff_entropy_ptr2)
  166827. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166828. SIZEOF(phuff_entropy_decoder));
  166829. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166830. entropy->pub.start_pass = start_pass_phuff_decoder;
  166831. /* Mark derived tables unallocated */
  166832. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166833. entropy->derived_tbls[i] = NULL;
  166834. }
  166835. /* Create progression status table */
  166836. cinfo->coef_bits = (int (*)[DCTSIZE2])
  166837. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166838. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  166839. coef_bit_ptr = & cinfo->coef_bits[0][0];
  166840. for (ci = 0; ci < cinfo->num_components; ci++)
  166841. for (i = 0; i < DCTSIZE2; i++)
  166842. *coef_bit_ptr++ = -1;
  166843. }
  166844. #endif /* D_PROGRESSIVE_SUPPORTED */
  166845. /********* End of inlined file: jdphuff.c *********/
  166846. /********* Start of inlined file: jdpostct.c *********/
  166847. #define JPEG_INTERNALS
  166848. /* Private buffer controller object */
  166849. typedef struct {
  166850. struct jpeg_d_post_controller pub; /* public fields */
  166851. /* Color quantization source buffer: this holds output data from
  166852. * the upsample/color conversion step to be passed to the quantizer.
  166853. * For two-pass color quantization, we need a full-image buffer;
  166854. * for one-pass operation, a strip buffer is sufficient.
  166855. */
  166856. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  166857. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  166858. JDIMENSION strip_height; /* buffer size in rows */
  166859. /* for two-pass mode only: */
  166860. JDIMENSION starting_row; /* row # of first row in current strip */
  166861. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  166862. } my_post_controller;
  166863. typedef my_post_controller * my_post_ptr;
  166864. /* Forward declarations */
  166865. METHODDEF(void) post_process_1pass
  166866. JPP((j_decompress_ptr cinfo,
  166867. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166868. JDIMENSION in_row_groups_avail,
  166869. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166870. JDIMENSION out_rows_avail));
  166871. #ifdef QUANT_2PASS_SUPPORTED
  166872. METHODDEF(void) post_process_prepass
  166873. JPP((j_decompress_ptr cinfo,
  166874. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166875. JDIMENSION in_row_groups_avail,
  166876. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166877. JDIMENSION out_rows_avail));
  166878. METHODDEF(void) post_process_2pass
  166879. JPP((j_decompress_ptr cinfo,
  166880. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166881. JDIMENSION in_row_groups_avail,
  166882. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166883. JDIMENSION out_rows_avail));
  166884. #endif
  166885. /*
  166886. * Initialize for a processing pass.
  166887. */
  166888. METHODDEF(void)
  166889. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166890. {
  166891. my_post_ptr post = (my_post_ptr) cinfo->post;
  166892. switch (pass_mode) {
  166893. case JBUF_PASS_THRU:
  166894. if (cinfo->quantize_colors) {
  166895. /* Single-pass processing with color quantization. */
  166896. post->pub.post_process_data = post_process_1pass;
  166897. /* We could be doing buffered-image output before starting a 2-pass
  166898. * color quantization; in that case, jinit_d_post_controller did not
  166899. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  166900. */
  166901. if (post->buffer == NULL) {
  166902. post->buffer = (*cinfo->mem->access_virt_sarray)
  166903. ((j_common_ptr) cinfo, post->whole_image,
  166904. (JDIMENSION) 0, post->strip_height, TRUE);
  166905. }
  166906. } else {
  166907. /* For single-pass processing without color quantization,
  166908. * I have no work to do; just call the upsampler directly.
  166909. */
  166910. post->pub.post_process_data = cinfo->upsample->upsample;
  166911. }
  166912. break;
  166913. #ifdef QUANT_2PASS_SUPPORTED
  166914. case JBUF_SAVE_AND_PASS:
  166915. /* First pass of 2-pass quantization */
  166916. if (post->whole_image == NULL)
  166917. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166918. post->pub.post_process_data = post_process_prepass;
  166919. break;
  166920. case JBUF_CRANK_DEST:
  166921. /* Second pass of 2-pass quantization */
  166922. if (post->whole_image == NULL)
  166923. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166924. post->pub.post_process_data = post_process_2pass;
  166925. break;
  166926. #endif /* QUANT_2PASS_SUPPORTED */
  166927. default:
  166928. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166929. break;
  166930. }
  166931. post->starting_row = post->next_row = 0;
  166932. }
  166933. /*
  166934. * Process some data in the one-pass (strip buffer) case.
  166935. * This is used for color precision reduction as well as one-pass quantization.
  166936. */
  166937. METHODDEF(void)
  166938. post_process_1pass (j_decompress_ptr cinfo,
  166939. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166940. JDIMENSION in_row_groups_avail,
  166941. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166942. JDIMENSION out_rows_avail)
  166943. {
  166944. my_post_ptr post = (my_post_ptr) cinfo->post;
  166945. JDIMENSION num_rows, max_rows;
  166946. /* Fill the buffer, but not more than what we can dump out in one go. */
  166947. /* Note we rely on the upsampler to detect bottom of image. */
  166948. max_rows = out_rows_avail - *out_row_ctr;
  166949. if (max_rows > post->strip_height)
  166950. max_rows = post->strip_height;
  166951. num_rows = 0;
  166952. (*cinfo->upsample->upsample) (cinfo,
  166953. input_buf, in_row_group_ctr, in_row_groups_avail,
  166954. post->buffer, &num_rows, max_rows);
  166955. /* Quantize and emit data. */
  166956. (*cinfo->cquantize->color_quantize) (cinfo,
  166957. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  166958. *out_row_ctr += num_rows;
  166959. }
  166960. #ifdef QUANT_2PASS_SUPPORTED
  166961. /*
  166962. * Process some data in the first pass of 2-pass quantization.
  166963. */
  166964. METHODDEF(void)
  166965. post_process_prepass (j_decompress_ptr cinfo,
  166966. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166967. JDIMENSION in_row_groups_avail,
  166968. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166969. JDIMENSION out_rows_avail)
  166970. {
  166971. my_post_ptr post = (my_post_ptr) cinfo->post;
  166972. JDIMENSION old_next_row, num_rows;
  166973. /* Reposition virtual buffer if at start of strip. */
  166974. if (post->next_row == 0) {
  166975. post->buffer = (*cinfo->mem->access_virt_sarray)
  166976. ((j_common_ptr) cinfo, post->whole_image,
  166977. post->starting_row, post->strip_height, TRUE);
  166978. }
  166979. /* Upsample some data (up to a strip height's worth). */
  166980. old_next_row = post->next_row;
  166981. (*cinfo->upsample->upsample) (cinfo,
  166982. input_buf, in_row_group_ctr, in_row_groups_avail,
  166983. post->buffer, &post->next_row, post->strip_height);
  166984. /* Allow quantizer to scan new data. No data is emitted, */
  166985. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  166986. if (post->next_row > old_next_row) {
  166987. num_rows = post->next_row - old_next_row;
  166988. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  166989. (JSAMPARRAY) NULL, (int) num_rows);
  166990. *out_row_ctr += num_rows;
  166991. }
  166992. /* Advance if we filled the strip. */
  166993. if (post->next_row >= post->strip_height) {
  166994. post->starting_row += post->strip_height;
  166995. post->next_row = 0;
  166996. }
  166997. }
  166998. /*
  166999. * Process some data in the second pass of 2-pass quantization.
  167000. */
  167001. METHODDEF(void)
  167002. post_process_2pass (j_decompress_ptr cinfo,
  167003. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167004. JDIMENSION in_row_groups_avail,
  167005. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167006. JDIMENSION out_rows_avail)
  167007. {
  167008. my_post_ptr post = (my_post_ptr) cinfo->post;
  167009. JDIMENSION num_rows, max_rows;
  167010. /* Reposition virtual buffer if at start of strip. */
  167011. if (post->next_row == 0) {
  167012. post->buffer = (*cinfo->mem->access_virt_sarray)
  167013. ((j_common_ptr) cinfo, post->whole_image,
  167014. post->starting_row, post->strip_height, FALSE);
  167015. }
  167016. /* Determine number of rows to emit. */
  167017. num_rows = post->strip_height - post->next_row; /* available in strip */
  167018. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  167019. if (num_rows > max_rows)
  167020. num_rows = max_rows;
  167021. /* We have to check bottom of image here, can't depend on upsampler. */
  167022. max_rows = cinfo->output_height - post->starting_row;
  167023. if (num_rows > max_rows)
  167024. num_rows = max_rows;
  167025. /* Quantize and emit data. */
  167026. (*cinfo->cquantize->color_quantize) (cinfo,
  167027. post->buffer + post->next_row, output_buf + *out_row_ctr,
  167028. (int) num_rows);
  167029. *out_row_ctr += num_rows;
  167030. /* Advance if we filled the strip. */
  167031. post->next_row += num_rows;
  167032. if (post->next_row >= post->strip_height) {
  167033. post->starting_row += post->strip_height;
  167034. post->next_row = 0;
  167035. }
  167036. }
  167037. #endif /* QUANT_2PASS_SUPPORTED */
  167038. /*
  167039. * Initialize postprocessing controller.
  167040. */
  167041. GLOBAL(void)
  167042. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167043. {
  167044. my_post_ptr post;
  167045. post = (my_post_ptr)
  167046. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167047. SIZEOF(my_post_controller));
  167048. cinfo->post = (struct jpeg_d_post_controller *) post;
  167049. post->pub.start_pass = start_pass_dpost;
  167050. post->whole_image = NULL; /* flag for no virtual arrays */
  167051. post->buffer = NULL; /* flag for no strip buffer */
  167052. /* Create the quantization buffer, if needed */
  167053. if (cinfo->quantize_colors) {
  167054. /* The buffer strip height is max_v_samp_factor, which is typically
  167055. * an efficient number of rows for upsampling to return.
  167056. * (In the presence of output rescaling, we might want to be smarter?)
  167057. */
  167058. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  167059. if (need_full_buffer) {
  167060. /* Two-pass color quantization: need full-image storage. */
  167061. /* We round up the number of rows to a multiple of the strip height. */
  167062. #ifdef QUANT_2PASS_SUPPORTED
  167063. post->whole_image = (*cinfo->mem->request_virt_sarray)
  167064. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  167065. cinfo->output_width * cinfo->out_color_components,
  167066. (JDIMENSION) jround_up((long) cinfo->output_height,
  167067. (long) post->strip_height),
  167068. post->strip_height);
  167069. #else
  167070. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167071. #endif /* QUANT_2PASS_SUPPORTED */
  167072. } else {
  167073. /* One-pass color quantization: just make a strip buffer. */
  167074. post->buffer = (*cinfo->mem->alloc_sarray)
  167075. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167076. cinfo->output_width * cinfo->out_color_components,
  167077. post->strip_height);
  167078. }
  167079. }
  167080. }
  167081. /********* End of inlined file: jdpostct.c *********/
  167082. #undef FIX
  167083. /********* Start of inlined file: jdsample.c *********/
  167084. #define JPEG_INTERNALS
  167085. /* Pointer to routine to upsample a single component */
  167086. typedef JMETHOD(void, upsample1_ptr,
  167087. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167088. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  167089. /* Private subobject */
  167090. typedef struct {
  167091. struct jpeg_upsampler pub; /* public fields */
  167092. /* Color conversion buffer. When using separate upsampling and color
  167093. * conversion steps, this buffer holds one upsampled row group until it
  167094. * has been color converted and output.
  167095. * Note: we do not allocate any storage for component(s) which are full-size,
  167096. * ie do not need rescaling. The corresponding entry of color_buf[] is
  167097. * simply set to point to the input data array, thereby avoiding copying.
  167098. */
  167099. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167100. /* Per-component upsampling method pointers */
  167101. upsample1_ptr methods[MAX_COMPONENTS];
  167102. int next_row_out; /* counts rows emitted from color_buf */
  167103. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167104. /* Height of an input row group for each component. */
  167105. int rowgroup_height[MAX_COMPONENTS];
  167106. /* These arrays save pixel expansion factors so that int_expand need not
  167107. * recompute them each time. They are unused for other upsampling methods.
  167108. */
  167109. UINT8 h_expand[MAX_COMPONENTS];
  167110. UINT8 v_expand[MAX_COMPONENTS];
  167111. } my_upsampler2;
  167112. typedef my_upsampler2 * my_upsample_ptr2;
  167113. /*
  167114. * Initialize for an upsampling pass.
  167115. */
  167116. METHODDEF(void)
  167117. start_pass_upsample (j_decompress_ptr cinfo)
  167118. {
  167119. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167120. /* Mark the conversion buffer empty */
  167121. upsample->next_row_out = cinfo->max_v_samp_factor;
  167122. /* Initialize total-height counter for detecting bottom of image */
  167123. upsample->rows_to_go = cinfo->output_height;
  167124. }
  167125. /*
  167126. * Control routine to do upsampling (and color conversion).
  167127. *
  167128. * In this version we upsample each component independently.
  167129. * We upsample one row group into the conversion buffer, then apply
  167130. * color conversion a row at a time.
  167131. */
  167132. METHODDEF(void)
  167133. sep_upsample (j_decompress_ptr cinfo,
  167134. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167135. JDIMENSION in_row_groups_avail,
  167136. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167137. JDIMENSION out_rows_avail)
  167138. {
  167139. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167140. int ci;
  167141. jpeg_component_info * compptr;
  167142. JDIMENSION num_rows;
  167143. /* Fill the conversion buffer, if it's empty */
  167144. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  167145. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167146. ci++, compptr++) {
  167147. /* Invoke per-component upsample method. Notice we pass a POINTER
  167148. * to color_buf[ci], so that fullsize_upsample can change it.
  167149. */
  167150. (*upsample->methods[ci]) (cinfo, compptr,
  167151. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  167152. upsample->color_buf + ci);
  167153. }
  167154. upsample->next_row_out = 0;
  167155. }
  167156. /* Color-convert and emit rows */
  167157. /* How many we have in the buffer: */
  167158. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  167159. /* Not more than the distance to the end of the image. Need this test
  167160. * in case the image height is not a multiple of max_v_samp_factor:
  167161. */
  167162. if (num_rows > upsample->rows_to_go)
  167163. num_rows = upsample->rows_to_go;
  167164. /* And not more than what the client can accept: */
  167165. out_rows_avail -= *out_row_ctr;
  167166. if (num_rows > out_rows_avail)
  167167. num_rows = out_rows_avail;
  167168. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  167169. (JDIMENSION) upsample->next_row_out,
  167170. output_buf + *out_row_ctr,
  167171. (int) num_rows);
  167172. /* Adjust counts */
  167173. *out_row_ctr += num_rows;
  167174. upsample->rows_to_go -= num_rows;
  167175. upsample->next_row_out += num_rows;
  167176. /* When the buffer is emptied, declare this input row group consumed */
  167177. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  167178. (*in_row_group_ctr)++;
  167179. }
  167180. /*
  167181. * These are the routines invoked by sep_upsample to upsample pixel values
  167182. * of a single component. One row group is processed per call.
  167183. */
  167184. /*
  167185. * For full-size components, we just make color_buf[ci] point at the
  167186. * input buffer, and thus avoid copying any data. Note that this is
  167187. * safe only because sep_upsample doesn't declare the input row group
  167188. * "consumed" until we are done color converting and emitting it.
  167189. */
  167190. METHODDEF(void)
  167191. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167192. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167193. {
  167194. *output_data_ptr = input_data;
  167195. }
  167196. /*
  167197. * This is a no-op version used for "uninteresting" components.
  167198. * These components will not be referenced by color conversion.
  167199. */
  167200. METHODDEF(void)
  167201. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167202. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167203. {
  167204. *output_data_ptr = NULL; /* safety check */
  167205. }
  167206. /*
  167207. * This version handles any integral sampling ratios.
  167208. * This is not used for typical JPEG files, so it need not be fast.
  167209. * Nor, for that matter, is it particularly accurate: the algorithm is
  167210. * simple replication of the input pixel onto the corresponding output
  167211. * pixels. The hi-falutin sampling literature refers to this as a
  167212. * "box filter". A box filter tends to introduce visible artifacts,
  167213. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  167214. * you would be well advised to improve this code.
  167215. */
  167216. METHODDEF(void)
  167217. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167218. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167219. {
  167220. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167221. JSAMPARRAY output_data = *output_data_ptr;
  167222. register JSAMPROW inptr, outptr;
  167223. register JSAMPLE invalue;
  167224. register int h;
  167225. JSAMPROW outend;
  167226. int h_expand, v_expand;
  167227. int inrow, outrow;
  167228. h_expand = upsample->h_expand[compptr->component_index];
  167229. v_expand = upsample->v_expand[compptr->component_index];
  167230. inrow = outrow = 0;
  167231. while (outrow < cinfo->max_v_samp_factor) {
  167232. /* Generate one output row with proper horizontal expansion */
  167233. inptr = input_data[inrow];
  167234. outptr = output_data[outrow];
  167235. outend = outptr + cinfo->output_width;
  167236. while (outptr < outend) {
  167237. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167238. for (h = h_expand; h > 0; h--) {
  167239. *outptr++ = invalue;
  167240. }
  167241. }
  167242. /* Generate any additional output rows by duplicating the first one */
  167243. if (v_expand > 1) {
  167244. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167245. v_expand-1, cinfo->output_width);
  167246. }
  167247. inrow++;
  167248. outrow += v_expand;
  167249. }
  167250. }
  167251. /*
  167252. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  167253. * It's still a box filter.
  167254. */
  167255. METHODDEF(void)
  167256. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167257. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167258. {
  167259. JSAMPARRAY output_data = *output_data_ptr;
  167260. register JSAMPROW inptr, outptr;
  167261. register JSAMPLE invalue;
  167262. JSAMPROW outend;
  167263. int inrow;
  167264. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167265. inptr = input_data[inrow];
  167266. outptr = output_data[inrow];
  167267. outend = outptr + cinfo->output_width;
  167268. while (outptr < outend) {
  167269. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167270. *outptr++ = invalue;
  167271. *outptr++ = invalue;
  167272. }
  167273. }
  167274. }
  167275. /*
  167276. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  167277. * It's still a box filter.
  167278. */
  167279. METHODDEF(void)
  167280. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167281. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167282. {
  167283. JSAMPARRAY output_data = *output_data_ptr;
  167284. register JSAMPROW inptr, outptr;
  167285. register JSAMPLE invalue;
  167286. JSAMPROW outend;
  167287. int inrow, outrow;
  167288. inrow = outrow = 0;
  167289. while (outrow < cinfo->max_v_samp_factor) {
  167290. inptr = input_data[inrow];
  167291. outptr = output_data[outrow];
  167292. outend = outptr + cinfo->output_width;
  167293. while (outptr < outend) {
  167294. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167295. *outptr++ = invalue;
  167296. *outptr++ = invalue;
  167297. }
  167298. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167299. 1, cinfo->output_width);
  167300. inrow++;
  167301. outrow += 2;
  167302. }
  167303. }
  167304. /*
  167305. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  167306. *
  167307. * The upsampling algorithm is linear interpolation between pixel centers,
  167308. * also known as a "triangle filter". This is a good compromise between
  167309. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  167310. * of the way between input pixel centers.
  167311. *
  167312. * A note about the "bias" calculations: when rounding fractional values to
  167313. * integer, we do not want to always round 0.5 up to the next integer.
  167314. * If we did that, we'd introduce a noticeable bias towards larger values.
  167315. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167316. * alternate pixel locations (a simple ordered dither pattern).
  167317. */
  167318. METHODDEF(void)
  167319. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167320. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167321. {
  167322. JSAMPARRAY output_data = *output_data_ptr;
  167323. register JSAMPROW inptr, outptr;
  167324. register int invalue;
  167325. register JDIMENSION colctr;
  167326. int inrow;
  167327. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167328. inptr = input_data[inrow];
  167329. outptr = output_data[inrow];
  167330. /* Special case for first column */
  167331. invalue = GETJSAMPLE(*inptr++);
  167332. *outptr++ = (JSAMPLE) invalue;
  167333. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  167334. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  167335. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  167336. invalue = GETJSAMPLE(*inptr++) * 3;
  167337. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  167338. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  167339. }
  167340. /* Special case for last column */
  167341. invalue = GETJSAMPLE(*inptr);
  167342. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  167343. *outptr++ = (JSAMPLE) invalue;
  167344. }
  167345. }
  167346. /*
  167347. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  167348. * Again a triangle filter; see comments for h2v1 case, above.
  167349. *
  167350. * It is OK for us to reference the adjacent input rows because we demanded
  167351. * context from the main buffer controller (see initialization code).
  167352. */
  167353. METHODDEF(void)
  167354. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167355. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167356. {
  167357. JSAMPARRAY output_data = *output_data_ptr;
  167358. register JSAMPROW inptr0, inptr1, outptr;
  167359. #if BITS_IN_JSAMPLE == 8
  167360. register int thiscolsum, lastcolsum, nextcolsum;
  167361. #else
  167362. register INT32 thiscolsum, lastcolsum, nextcolsum;
  167363. #endif
  167364. register JDIMENSION colctr;
  167365. int inrow, outrow, v;
  167366. inrow = outrow = 0;
  167367. while (outrow < cinfo->max_v_samp_factor) {
  167368. for (v = 0; v < 2; v++) {
  167369. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  167370. inptr0 = input_data[inrow];
  167371. if (v == 0) /* next nearest is row above */
  167372. inptr1 = input_data[inrow-1];
  167373. else /* next nearest is row below */
  167374. inptr1 = input_data[inrow+1];
  167375. outptr = output_data[outrow++];
  167376. /* Special case for first column */
  167377. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167378. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167379. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  167380. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  167381. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  167382. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  167383. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  167384. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  167385. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167386. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  167387. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  167388. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  167389. }
  167390. /* Special case for last column */
  167391. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  167392. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  167393. }
  167394. inrow++;
  167395. }
  167396. }
  167397. /*
  167398. * Module initialization routine for upsampling.
  167399. */
  167400. GLOBAL(void)
  167401. jinit_upsampler (j_decompress_ptr cinfo)
  167402. {
  167403. my_upsample_ptr2 upsample;
  167404. int ci;
  167405. jpeg_component_info * compptr;
  167406. boolean need_buffer, do_fancy;
  167407. int h_in_group, v_in_group, h_out_group, v_out_group;
  167408. upsample = (my_upsample_ptr2)
  167409. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167410. SIZEOF(my_upsampler2));
  167411. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167412. upsample->pub.start_pass = start_pass_upsample;
  167413. upsample->pub.upsample = sep_upsample;
  167414. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  167415. if (cinfo->CCIR601_sampling) /* this isn't supported */
  167416. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167417. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  167418. * so don't ask for it.
  167419. */
  167420. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  167421. /* Verify we can handle the sampling factors, select per-component methods,
  167422. * and create storage as needed.
  167423. */
  167424. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167425. ci++, compptr++) {
  167426. /* Compute size of an "input group" after IDCT scaling. This many samples
  167427. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  167428. */
  167429. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  167430. cinfo->min_DCT_scaled_size;
  167431. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167432. cinfo->min_DCT_scaled_size;
  167433. h_out_group = cinfo->max_h_samp_factor;
  167434. v_out_group = cinfo->max_v_samp_factor;
  167435. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  167436. need_buffer = TRUE;
  167437. if (! compptr->component_needed) {
  167438. /* Don't bother to upsample an uninteresting component. */
  167439. upsample->methods[ci] = noop_upsample;
  167440. need_buffer = FALSE;
  167441. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  167442. /* Fullsize components can be processed without any work. */
  167443. upsample->methods[ci] = fullsize_upsample;
  167444. need_buffer = FALSE;
  167445. } else if (h_in_group * 2 == h_out_group &&
  167446. v_in_group == v_out_group) {
  167447. /* Special cases for 2h1v upsampling */
  167448. if (do_fancy && compptr->downsampled_width > 2)
  167449. upsample->methods[ci] = h2v1_fancy_upsample;
  167450. else
  167451. upsample->methods[ci] = h2v1_upsample;
  167452. } else if (h_in_group * 2 == h_out_group &&
  167453. v_in_group * 2 == v_out_group) {
  167454. /* Special cases for 2h2v upsampling */
  167455. if (do_fancy && compptr->downsampled_width > 2) {
  167456. upsample->methods[ci] = h2v2_fancy_upsample;
  167457. upsample->pub.need_context_rows = TRUE;
  167458. } else
  167459. upsample->methods[ci] = h2v2_upsample;
  167460. } else if ((h_out_group % h_in_group) == 0 &&
  167461. (v_out_group % v_in_group) == 0) {
  167462. /* Generic integral-factors upsampling method */
  167463. upsample->methods[ci] = int_upsample;
  167464. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  167465. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  167466. } else
  167467. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167468. if (need_buffer) {
  167469. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  167470. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167471. (JDIMENSION) jround_up((long) cinfo->output_width,
  167472. (long) cinfo->max_h_samp_factor),
  167473. (JDIMENSION) cinfo->max_v_samp_factor);
  167474. }
  167475. }
  167476. }
  167477. /********* End of inlined file: jdsample.c *********/
  167478. /********* Start of inlined file: jdtrans.c *********/
  167479. #define JPEG_INTERNALS
  167480. /* Forward declarations */
  167481. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  167482. /*
  167483. * Read the coefficient arrays from a JPEG file.
  167484. * jpeg_read_header must be completed before calling this.
  167485. *
  167486. * The entire image is read into a set of virtual coefficient-block arrays,
  167487. * one per component. The return value is a pointer to the array of
  167488. * virtual-array descriptors. These can be manipulated directly via the
  167489. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  167490. * To release the memory occupied by the virtual arrays, call
  167491. * jpeg_finish_decompress() when done with the data.
  167492. *
  167493. * An alternative usage is to simply obtain access to the coefficient arrays
  167494. * during a buffered-image-mode decompression operation. This is allowed
  167495. * after any jpeg_finish_output() call. The arrays can be accessed until
  167496. * jpeg_finish_decompress() is called. (Note that any call to the library
  167497. * may reposition the arrays, so don't rely on access_virt_barray() results
  167498. * to stay valid across library calls.)
  167499. *
  167500. * Returns NULL if suspended. This case need be checked only if
  167501. * a suspending data source is used.
  167502. */
  167503. GLOBAL(jvirt_barray_ptr *)
  167504. jpeg_read_coefficients (j_decompress_ptr cinfo)
  167505. {
  167506. if (cinfo->global_state == DSTATE_READY) {
  167507. /* First call: initialize active modules */
  167508. transdecode_master_selection(cinfo);
  167509. cinfo->global_state = DSTATE_RDCOEFS;
  167510. }
  167511. if (cinfo->global_state == DSTATE_RDCOEFS) {
  167512. /* Absorb whole file into the coef buffer */
  167513. for (;;) {
  167514. int retcode;
  167515. /* Call progress monitor hook if present */
  167516. if (cinfo->progress != NULL)
  167517. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167518. /* Absorb some more input */
  167519. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167520. if (retcode == JPEG_SUSPENDED)
  167521. return NULL;
  167522. if (retcode == JPEG_REACHED_EOI)
  167523. break;
  167524. /* Advance progress counter if appropriate */
  167525. if (cinfo->progress != NULL &&
  167526. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167527. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167528. /* startup underestimated number of scans; ratchet up one scan */
  167529. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167530. }
  167531. }
  167532. }
  167533. /* Set state so that jpeg_finish_decompress does the right thing */
  167534. cinfo->global_state = DSTATE_STOPPING;
  167535. }
  167536. /* At this point we should be in state DSTATE_STOPPING if being used
  167537. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  167538. * to the coefficients during a full buffered-image-mode decompression.
  167539. */
  167540. if ((cinfo->global_state == DSTATE_STOPPING ||
  167541. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  167542. return cinfo->coef->coef_arrays;
  167543. }
  167544. /* Oops, improper usage */
  167545. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167546. return NULL; /* keep compiler happy */
  167547. }
  167548. /*
  167549. * Master selection of decompression modules for transcoding.
  167550. * This substitutes for jdmaster.c's initialization of the full decompressor.
  167551. */
  167552. LOCAL(void)
  167553. transdecode_master_selection (j_decompress_ptr cinfo)
  167554. {
  167555. /* This is effectively a buffered-image operation. */
  167556. cinfo->buffered_image = TRUE;
  167557. /* Entropy decoding: either Huffman or arithmetic coding. */
  167558. if (cinfo->arith_code) {
  167559. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167560. } else {
  167561. if (cinfo->progressive_mode) {
  167562. #ifdef D_PROGRESSIVE_SUPPORTED
  167563. jinit_phuff_decoder(cinfo);
  167564. #else
  167565. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167566. #endif
  167567. } else
  167568. jinit_huff_decoder(cinfo);
  167569. }
  167570. /* Always get a full-image coefficient buffer. */
  167571. jinit_d_coef_controller(cinfo, TRUE);
  167572. /* We can now tell the memory manager to allocate virtual arrays. */
  167573. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167574. /* Initialize input side of decompressor to consume first scan. */
  167575. (*cinfo->inputctl->start_input_pass) (cinfo);
  167576. /* Initialize progress monitoring. */
  167577. if (cinfo->progress != NULL) {
  167578. int nscans;
  167579. /* Estimate number of scans to set pass_limit. */
  167580. if (cinfo->progressive_mode) {
  167581. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  167582. nscans = 2 + 3 * cinfo->num_components;
  167583. } else if (cinfo->inputctl->has_multiple_scans) {
  167584. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  167585. nscans = cinfo->num_components;
  167586. } else {
  167587. nscans = 1;
  167588. }
  167589. cinfo->progress->pass_counter = 0L;
  167590. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  167591. cinfo->progress->completed_passes = 0;
  167592. cinfo->progress->total_passes = 1;
  167593. }
  167594. }
  167595. /********* End of inlined file: jdtrans.c *********/
  167596. /********* Start of inlined file: jfdctflt.c *********/
  167597. #define JPEG_INTERNALS
  167598. #ifdef DCT_FLOAT_SUPPORTED
  167599. /*
  167600. * This module is specialized to the case DCTSIZE = 8.
  167601. */
  167602. #if DCTSIZE != 8
  167603. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167604. #endif
  167605. /*
  167606. * Perform the forward DCT on one block of samples.
  167607. */
  167608. GLOBAL(void)
  167609. jpeg_fdct_float (FAST_FLOAT * data)
  167610. {
  167611. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167612. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  167613. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  167614. FAST_FLOAT *dataptr;
  167615. int ctr;
  167616. /* Pass 1: process rows. */
  167617. dataptr = data;
  167618. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167619. tmp0 = dataptr[0] + dataptr[7];
  167620. tmp7 = dataptr[0] - dataptr[7];
  167621. tmp1 = dataptr[1] + dataptr[6];
  167622. tmp6 = dataptr[1] - dataptr[6];
  167623. tmp2 = dataptr[2] + dataptr[5];
  167624. tmp5 = dataptr[2] - dataptr[5];
  167625. tmp3 = dataptr[3] + dataptr[4];
  167626. tmp4 = dataptr[3] - dataptr[4];
  167627. /* Even part */
  167628. tmp10 = tmp0 + tmp3; /* phase 2 */
  167629. tmp13 = tmp0 - tmp3;
  167630. tmp11 = tmp1 + tmp2;
  167631. tmp12 = tmp1 - tmp2;
  167632. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  167633. dataptr[4] = tmp10 - tmp11;
  167634. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  167635. dataptr[2] = tmp13 + z1; /* phase 5 */
  167636. dataptr[6] = tmp13 - z1;
  167637. /* Odd part */
  167638. tmp10 = tmp4 + tmp5; /* phase 2 */
  167639. tmp11 = tmp5 + tmp6;
  167640. tmp12 = tmp6 + tmp7;
  167641. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  167642. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  167643. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  167644. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  167645. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  167646. z11 = tmp7 + z3; /* phase 5 */
  167647. z13 = tmp7 - z3;
  167648. dataptr[5] = z13 + z2; /* phase 6 */
  167649. dataptr[3] = z13 - z2;
  167650. dataptr[1] = z11 + z4;
  167651. dataptr[7] = z11 - z4;
  167652. dataptr += DCTSIZE; /* advance pointer to next row */
  167653. }
  167654. /* Pass 2: process columns. */
  167655. dataptr = data;
  167656. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167657. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  167658. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  167659. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  167660. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  167661. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  167662. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  167663. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  167664. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  167665. /* Even part */
  167666. tmp10 = tmp0 + tmp3; /* phase 2 */
  167667. tmp13 = tmp0 - tmp3;
  167668. tmp11 = tmp1 + tmp2;
  167669. tmp12 = tmp1 - tmp2;
  167670. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  167671. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  167672. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  167673. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  167674. dataptr[DCTSIZE*6] = tmp13 - z1;
  167675. /* Odd part */
  167676. tmp10 = tmp4 + tmp5; /* phase 2 */
  167677. tmp11 = tmp5 + tmp6;
  167678. tmp12 = tmp6 + tmp7;
  167679. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  167680. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  167681. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  167682. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  167683. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  167684. z11 = tmp7 + z3; /* phase 5 */
  167685. z13 = tmp7 - z3;
  167686. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  167687. dataptr[DCTSIZE*3] = z13 - z2;
  167688. dataptr[DCTSIZE*1] = z11 + z4;
  167689. dataptr[DCTSIZE*7] = z11 - z4;
  167690. dataptr++; /* advance pointer to next column */
  167691. }
  167692. }
  167693. #endif /* DCT_FLOAT_SUPPORTED */
  167694. /********* End of inlined file: jfdctflt.c *********/
  167695. /********* Start of inlined file: jfdctint.c *********/
  167696. #define JPEG_INTERNALS
  167697. #ifdef DCT_ISLOW_SUPPORTED
  167698. /*
  167699. * This module is specialized to the case DCTSIZE = 8.
  167700. */
  167701. #if DCTSIZE != 8
  167702. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167703. #endif
  167704. /*
  167705. * The poop on this scaling stuff is as follows:
  167706. *
  167707. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  167708. * larger than the true DCT outputs. The final outputs are therefore
  167709. * a factor of N larger than desired; since N=8 this can be cured by
  167710. * a simple right shift at the end of the algorithm. The advantage of
  167711. * this arrangement is that we save two multiplications per 1-D DCT,
  167712. * because the y0 and y4 outputs need not be divided by sqrt(N).
  167713. * In the IJG code, this factor of 8 is removed by the quantization step
  167714. * (in jcdctmgr.c), NOT in this module.
  167715. *
  167716. * We have to do addition and subtraction of the integer inputs, which
  167717. * is no problem, and multiplication by fractional constants, which is
  167718. * a problem to do in integer arithmetic. We multiply all the constants
  167719. * by CONST_SCALE and convert them to integer constants (thus retaining
  167720. * CONST_BITS bits of precision in the constants). After doing a
  167721. * multiplication we have to divide the product by CONST_SCALE, with proper
  167722. * rounding, to produce the correct output. This division can be done
  167723. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  167724. * as long as possible so that partial sums can be added together with
  167725. * full fractional precision.
  167726. *
  167727. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  167728. * they are represented to better-than-integral precision. These outputs
  167729. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  167730. * with the recommended scaling. (For 12-bit sample data, the intermediate
  167731. * array is INT32 anyway.)
  167732. *
  167733. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  167734. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  167735. * shows that the values given below are the most effective.
  167736. */
  167737. #if BITS_IN_JSAMPLE == 8
  167738. #define CONST_BITS 13
  167739. #define PASS1_BITS 2
  167740. #else
  167741. #define CONST_BITS 13
  167742. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  167743. #endif
  167744. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  167745. * causing a lot of useless floating-point operations at run time.
  167746. * To get around this we use the following pre-calculated constants.
  167747. * If you change CONST_BITS you may want to add appropriate values.
  167748. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  167749. */
  167750. #if CONST_BITS == 13
  167751. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  167752. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  167753. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  167754. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  167755. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  167756. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  167757. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  167758. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  167759. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  167760. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  167761. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  167762. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  167763. #else
  167764. #define FIX_0_298631336 FIX(0.298631336)
  167765. #define FIX_0_390180644 FIX(0.390180644)
  167766. #define FIX_0_541196100 FIX(0.541196100)
  167767. #define FIX_0_765366865 FIX(0.765366865)
  167768. #define FIX_0_899976223 FIX(0.899976223)
  167769. #define FIX_1_175875602 FIX(1.175875602)
  167770. #define FIX_1_501321110 FIX(1.501321110)
  167771. #define FIX_1_847759065 FIX(1.847759065)
  167772. #define FIX_1_961570560 FIX(1.961570560)
  167773. #define FIX_2_053119869 FIX(2.053119869)
  167774. #define FIX_2_562915447 FIX(2.562915447)
  167775. #define FIX_3_072711026 FIX(3.072711026)
  167776. #endif
  167777. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  167778. * For 8-bit samples with the recommended scaling, all the variable
  167779. * and constant values involved are no more than 16 bits wide, so a
  167780. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  167781. * For 12-bit samples, a full 32-bit multiplication will be needed.
  167782. */
  167783. #if BITS_IN_JSAMPLE == 8
  167784. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  167785. #else
  167786. #define MULTIPLY(var,const) ((var) * (const))
  167787. #endif
  167788. /*
  167789. * Perform the forward DCT on one block of samples.
  167790. */
  167791. GLOBAL(void)
  167792. jpeg_fdct_islow (DCTELEM * data)
  167793. {
  167794. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167795. INT32 tmp10, tmp11, tmp12, tmp13;
  167796. INT32 z1, z2, z3, z4, z5;
  167797. DCTELEM *dataptr;
  167798. int ctr;
  167799. SHIFT_TEMPS
  167800. /* Pass 1: process rows. */
  167801. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  167802. /* furthermore, we scale the results by 2**PASS1_BITS. */
  167803. dataptr = data;
  167804. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167805. tmp0 = dataptr[0] + dataptr[7];
  167806. tmp7 = dataptr[0] - dataptr[7];
  167807. tmp1 = dataptr[1] + dataptr[6];
  167808. tmp6 = dataptr[1] - dataptr[6];
  167809. tmp2 = dataptr[2] + dataptr[5];
  167810. tmp5 = dataptr[2] - dataptr[5];
  167811. tmp3 = dataptr[3] + dataptr[4];
  167812. tmp4 = dataptr[3] - dataptr[4];
  167813. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  167814. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  167815. */
  167816. tmp10 = tmp0 + tmp3;
  167817. tmp13 = tmp0 - tmp3;
  167818. tmp11 = tmp1 + tmp2;
  167819. tmp12 = tmp1 - tmp2;
  167820. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  167821. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  167822. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  167823. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  167824. CONST_BITS-PASS1_BITS);
  167825. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  167826. CONST_BITS-PASS1_BITS);
  167827. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  167828. * cK represents cos(K*pi/16).
  167829. * i0..i3 in the paper are tmp4..tmp7 here.
  167830. */
  167831. z1 = tmp4 + tmp7;
  167832. z2 = tmp5 + tmp6;
  167833. z3 = tmp4 + tmp6;
  167834. z4 = tmp5 + tmp7;
  167835. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  167836. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  167837. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  167838. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  167839. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  167840. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  167841. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  167842. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  167843. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  167844. z3 += z5;
  167845. z4 += z5;
  167846. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  167847. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  167848. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  167849. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  167850. dataptr += DCTSIZE; /* advance pointer to next row */
  167851. }
  167852. /* Pass 2: process columns.
  167853. * We remove the PASS1_BITS scaling, but leave the results scaled up
  167854. * by an overall factor of 8.
  167855. */
  167856. dataptr = data;
  167857. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167858. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  167859. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  167860. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  167861. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  167862. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  167863. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  167864. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  167865. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  167866. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  167867. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  167868. */
  167869. tmp10 = tmp0 + tmp3;
  167870. tmp13 = tmp0 - tmp3;
  167871. tmp11 = tmp1 + tmp2;
  167872. tmp12 = tmp1 - tmp2;
  167873. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  167874. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  167875. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  167876. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  167877. CONST_BITS+PASS1_BITS);
  167878. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  167879. CONST_BITS+PASS1_BITS);
  167880. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  167881. * cK represents cos(K*pi/16).
  167882. * i0..i3 in the paper are tmp4..tmp7 here.
  167883. */
  167884. z1 = tmp4 + tmp7;
  167885. z2 = tmp5 + tmp6;
  167886. z3 = tmp4 + tmp6;
  167887. z4 = tmp5 + tmp7;
  167888. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  167889. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  167890. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  167891. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  167892. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  167893. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  167894. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  167895. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  167896. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  167897. z3 += z5;
  167898. z4 += z5;
  167899. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  167900. CONST_BITS+PASS1_BITS);
  167901. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  167902. CONST_BITS+PASS1_BITS);
  167903. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  167904. CONST_BITS+PASS1_BITS);
  167905. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  167906. CONST_BITS+PASS1_BITS);
  167907. dataptr++; /* advance pointer to next column */
  167908. }
  167909. }
  167910. #endif /* DCT_ISLOW_SUPPORTED */
  167911. /********* End of inlined file: jfdctint.c *********/
  167912. #undef CONST_BITS
  167913. #undef MULTIPLY
  167914. #undef FIX_0_541196100
  167915. /********* Start of inlined file: jfdctfst.c *********/
  167916. #define JPEG_INTERNALS
  167917. #ifdef DCT_IFAST_SUPPORTED
  167918. /*
  167919. * This module is specialized to the case DCTSIZE = 8.
  167920. */
  167921. #if DCTSIZE != 8
  167922. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167923. #endif
  167924. /* Scaling decisions are generally the same as in the LL&M algorithm;
  167925. * see jfdctint.c for more details. However, we choose to descale
  167926. * (right shift) multiplication products as soon as they are formed,
  167927. * rather than carrying additional fractional bits into subsequent additions.
  167928. * This compromises accuracy slightly, but it lets us save a few shifts.
  167929. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  167930. * everywhere except in the multiplications proper; this saves a good deal
  167931. * of work on 16-bit-int machines.
  167932. *
  167933. * Again to save a few shifts, the intermediate results between pass 1 and
  167934. * pass 2 are not upscaled, but are represented only to integral precision.
  167935. *
  167936. * A final compromise is to represent the multiplicative constants to only
  167937. * 8 fractional bits, rather than 13. This saves some shifting work on some
  167938. * machines, and may also reduce the cost of multiplication (since there
  167939. * are fewer one-bits in the constants).
  167940. */
  167941. #define CONST_BITS 8
  167942. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  167943. * causing a lot of useless floating-point operations at run time.
  167944. * To get around this we use the following pre-calculated constants.
  167945. * If you change CONST_BITS you may want to add appropriate values.
  167946. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  167947. */
  167948. #if CONST_BITS == 8
  167949. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  167950. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  167951. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  167952. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  167953. #else
  167954. #define FIX_0_382683433 FIX(0.382683433)
  167955. #define FIX_0_541196100 FIX(0.541196100)
  167956. #define FIX_0_707106781 FIX(0.707106781)
  167957. #define FIX_1_306562965 FIX(1.306562965)
  167958. #endif
  167959. /* We can gain a little more speed, with a further compromise in accuracy,
  167960. * by omitting the addition in a descaling shift. This yields an incorrectly
  167961. * rounded result half the time...
  167962. */
  167963. #ifndef USE_ACCURATE_ROUNDING
  167964. #undef DESCALE
  167965. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  167966. #endif
  167967. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  167968. * descale to yield a DCTELEM result.
  167969. */
  167970. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  167971. /*
  167972. * Perform the forward DCT on one block of samples.
  167973. */
  167974. GLOBAL(void)
  167975. jpeg_fdct_ifast (DCTELEM * data)
  167976. {
  167977. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167978. DCTELEM tmp10, tmp11, tmp12, tmp13;
  167979. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  167980. DCTELEM *dataptr;
  167981. int ctr;
  167982. SHIFT_TEMPS
  167983. /* Pass 1: process rows. */
  167984. dataptr = data;
  167985. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167986. tmp0 = dataptr[0] + dataptr[7];
  167987. tmp7 = dataptr[0] - dataptr[7];
  167988. tmp1 = dataptr[1] + dataptr[6];
  167989. tmp6 = dataptr[1] - dataptr[6];
  167990. tmp2 = dataptr[2] + dataptr[5];
  167991. tmp5 = dataptr[2] - dataptr[5];
  167992. tmp3 = dataptr[3] + dataptr[4];
  167993. tmp4 = dataptr[3] - dataptr[4];
  167994. /* Even part */
  167995. tmp10 = tmp0 + tmp3; /* phase 2 */
  167996. tmp13 = tmp0 - tmp3;
  167997. tmp11 = tmp1 + tmp2;
  167998. tmp12 = tmp1 - tmp2;
  167999. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168000. dataptr[4] = tmp10 - tmp11;
  168001. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168002. dataptr[2] = tmp13 + z1; /* phase 5 */
  168003. dataptr[6] = tmp13 - z1;
  168004. /* Odd part */
  168005. tmp10 = tmp4 + tmp5; /* phase 2 */
  168006. tmp11 = tmp5 + tmp6;
  168007. tmp12 = tmp6 + tmp7;
  168008. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168009. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168010. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168011. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168012. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168013. z11 = tmp7 + z3; /* phase 5 */
  168014. z13 = tmp7 - z3;
  168015. dataptr[5] = z13 + z2; /* phase 6 */
  168016. dataptr[3] = z13 - z2;
  168017. dataptr[1] = z11 + z4;
  168018. dataptr[7] = z11 - z4;
  168019. dataptr += DCTSIZE; /* advance pointer to next row */
  168020. }
  168021. /* Pass 2: process columns. */
  168022. dataptr = data;
  168023. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168024. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168025. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168026. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168027. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168028. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168029. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168030. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168031. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168032. /* Even part */
  168033. tmp10 = tmp0 + tmp3; /* phase 2 */
  168034. tmp13 = tmp0 - tmp3;
  168035. tmp11 = tmp1 + tmp2;
  168036. tmp12 = tmp1 - tmp2;
  168037. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168038. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168039. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168040. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168041. dataptr[DCTSIZE*6] = tmp13 - z1;
  168042. /* Odd part */
  168043. tmp10 = tmp4 + tmp5; /* phase 2 */
  168044. tmp11 = tmp5 + tmp6;
  168045. tmp12 = tmp6 + tmp7;
  168046. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168047. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168048. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168049. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168050. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168051. z11 = tmp7 + z3; /* phase 5 */
  168052. z13 = tmp7 - z3;
  168053. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168054. dataptr[DCTSIZE*3] = z13 - z2;
  168055. dataptr[DCTSIZE*1] = z11 + z4;
  168056. dataptr[DCTSIZE*7] = z11 - z4;
  168057. dataptr++; /* advance pointer to next column */
  168058. }
  168059. }
  168060. #endif /* DCT_IFAST_SUPPORTED */
  168061. /********* End of inlined file: jfdctfst.c *********/
  168062. #undef FIX_0_541196100
  168063. /********* Start of inlined file: jidctflt.c *********/
  168064. #define JPEG_INTERNALS
  168065. #ifdef DCT_FLOAT_SUPPORTED
  168066. /*
  168067. * This module is specialized to the case DCTSIZE = 8.
  168068. */
  168069. #if DCTSIZE != 8
  168070. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168071. #endif
  168072. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168073. * entry; produce a float result.
  168074. */
  168075. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  168076. /*
  168077. * Perform dequantization and inverse DCT on one block of coefficients.
  168078. */
  168079. GLOBAL(void)
  168080. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168081. JCOEFPTR coef_block,
  168082. JSAMPARRAY output_buf, JDIMENSION output_col)
  168083. {
  168084. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168085. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168086. FAST_FLOAT z5, z10, z11, z12, z13;
  168087. JCOEFPTR inptr;
  168088. FLOAT_MULT_TYPE * quantptr;
  168089. FAST_FLOAT * wsptr;
  168090. JSAMPROW outptr;
  168091. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168092. int ctr;
  168093. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  168094. SHIFT_TEMPS
  168095. /* Pass 1: process columns from input, store into work array. */
  168096. inptr = coef_block;
  168097. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168098. wsptr = workspace;
  168099. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168100. /* Due to quantization, we will usually find that many of the input
  168101. * coefficients are zero, especially the AC terms. We can exploit this
  168102. * by short-circuiting the IDCT calculation for any column in which all
  168103. * the AC terms are zero. In that case each output is equal to the
  168104. * DC coefficient (with scale factor as needed).
  168105. * With typical images and quantization tables, half or more of the
  168106. * column DCT calculations can be simplified this way.
  168107. */
  168108. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168109. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168110. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168111. inptr[DCTSIZE*7] == 0) {
  168112. /* AC terms all zero */
  168113. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168114. wsptr[DCTSIZE*0] = dcval;
  168115. wsptr[DCTSIZE*1] = dcval;
  168116. wsptr[DCTSIZE*2] = dcval;
  168117. wsptr[DCTSIZE*3] = dcval;
  168118. wsptr[DCTSIZE*4] = dcval;
  168119. wsptr[DCTSIZE*5] = dcval;
  168120. wsptr[DCTSIZE*6] = dcval;
  168121. wsptr[DCTSIZE*7] = dcval;
  168122. inptr++; /* advance pointers to next column */
  168123. quantptr++;
  168124. wsptr++;
  168125. continue;
  168126. }
  168127. /* Even part */
  168128. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168129. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168130. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168131. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168132. tmp10 = tmp0 + tmp2; /* phase 3 */
  168133. tmp11 = tmp0 - tmp2;
  168134. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168135. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  168136. tmp0 = tmp10 + tmp13; /* phase 2 */
  168137. tmp3 = tmp10 - tmp13;
  168138. tmp1 = tmp11 + tmp12;
  168139. tmp2 = tmp11 - tmp12;
  168140. /* Odd part */
  168141. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168142. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168143. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168144. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168145. z13 = tmp6 + tmp5; /* phase 6 */
  168146. z10 = tmp6 - tmp5;
  168147. z11 = tmp4 + tmp7;
  168148. z12 = tmp4 - tmp7;
  168149. tmp7 = z11 + z13; /* phase 5 */
  168150. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  168151. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168152. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168153. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168154. tmp6 = tmp12 - tmp7; /* phase 2 */
  168155. tmp5 = tmp11 - tmp6;
  168156. tmp4 = tmp10 + tmp5;
  168157. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  168158. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  168159. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  168160. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  168161. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  168162. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  168163. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  168164. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  168165. inptr++; /* advance pointers to next column */
  168166. quantptr++;
  168167. wsptr++;
  168168. }
  168169. /* Pass 2: process rows from work array, store into output array. */
  168170. /* Note that we must descale the results by a factor of 8 == 2**3. */
  168171. wsptr = workspace;
  168172. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168173. outptr = output_buf[ctr] + output_col;
  168174. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168175. * However, the column calculation has created many nonzero AC terms, so
  168176. * the simplification applies less often (typically 5% to 10% of the time).
  168177. * And testing floats for zero is relatively expensive, so we don't bother.
  168178. */
  168179. /* Even part */
  168180. tmp10 = wsptr[0] + wsptr[4];
  168181. tmp11 = wsptr[0] - wsptr[4];
  168182. tmp13 = wsptr[2] + wsptr[6];
  168183. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  168184. tmp0 = tmp10 + tmp13;
  168185. tmp3 = tmp10 - tmp13;
  168186. tmp1 = tmp11 + tmp12;
  168187. tmp2 = tmp11 - tmp12;
  168188. /* Odd part */
  168189. z13 = wsptr[5] + wsptr[3];
  168190. z10 = wsptr[5] - wsptr[3];
  168191. z11 = wsptr[1] + wsptr[7];
  168192. z12 = wsptr[1] - wsptr[7];
  168193. tmp7 = z11 + z13;
  168194. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  168195. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168196. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168197. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168198. tmp6 = tmp12 - tmp7;
  168199. tmp5 = tmp11 - tmp6;
  168200. tmp4 = tmp10 + tmp5;
  168201. /* Final output stage: scale down by a factor of 8 and range-limit */
  168202. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  168203. & RANGE_MASK];
  168204. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  168205. & RANGE_MASK];
  168206. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  168207. & RANGE_MASK];
  168208. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  168209. & RANGE_MASK];
  168210. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  168211. & RANGE_MASK];
  168212. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  168213. & RANGE_MASK];
  168214. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  168215. & RANGE_MASK];
  168216. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  168217. & RANGE_MASK];
  168218. wsptr += DCTSIZE; /* advance pointer to next row */
  168219. }
  168220. }
  168221. #endif /* DCT_FLOAT_SUPPORTED */
  168222. /********* End of inlined file: jidctflt.c *********/
  168223. #undef CONST_BITS
  168224. #undef FIX_1_847759065
  168225. #undef MULTIPLY
  168226. #undef DEQUANTIZE
  168227. #undef DESCALE
  168228. /********* Start of inlined file: jidctfst.c *********/
  168229. #define JPEG_INTERNALS
  168230. #ifdef DCT_IFAST_SUPPORTED
  168231. /*
  168232. * This module is specialized to the case DCTSIZE = 8.
  168233. */
  168234. #if DCTSIZE != 8
  168235. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168236. #endif
  168237. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168238. * see jidctint.c for more details. However, we choose to descale
  168239. * (right shift) multiplication products as soon as they are formed,
  168240. * rather than carrying additional fractional bits into subsequent additions.
  168241. * This compromises accuracy slightly, but it lets us save a few shifts.
  168242. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168243. * everywhere except in the multiplications proper; this saves a good deal
  168244. * of work on 16-bit-int machines.
  168245. *
  168246. * The dequantized coefficients are not integers because the AA&N scaling
  168247. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  168248. * so that the first and second IDCT rounds have the same input scaling.
  168249. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  168250. * avoid a descaling shift; this compromises accuracy rather drastically
  168251. * for small quantization table entries, but it saves a lot of shifts.
  168252. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  168253. * so we use a much larger scaling factor to preserve accuracy.
  168254. *
  168255. * A final compromise is to represent the multiplicative constants to only
  168256. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168257. * machines, and may also reduce the cost of multiplication (since there
  168258. * are fewer one-bits in the constants).
  168259. */
  168260. #if BITS_IN_JSAMPLE == 8
  168261. #define CONST_BITS 8
  168262. #define PASS1_BITS 2
  168263. #else
  168264. #define CONST_BITS 8
  168265. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168266. #endif
  168267. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168268. * causing a lot of useless floating-point operations at run time.
  168269. * To get around this we use the following pre-calculated constants.
  168270. * If you change CONST_BITS you may want to add appropriate values.
  168271. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168272. */
  168273. #if CONST_BITS == 8
  168274. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  168275. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  168276. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  168277. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  168278. #else
  168279. #define FIX_1_082392200 FIX(1.082392200)
  168280. #define FIX_1_414213562 FIX(1.414213562)
  168281. #define FIX_1_847759065 FIX(1.847759065)
  168282. #define FIX_2_613125930 FIX(2.613125930)
  168283. #endif
  168284. /* We can gain a little more speed, with a further compromise in accuracy,
  168285. * by omitting the addition in a descaling shift. This yields an incorrectly
  168286. * rounded result half the time...
  168287. */
  168288. #ifndef USE_ACCURATE_ROUNDING
  168289. #undef DESCALE
  168290. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168291. #endif
  168292. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168293. * descale to yield a DCTELEM result.
  168294. */
  168295. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  168296. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168297. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  168298. * multiplication will do. For 12-bit data, the multiplier table is
  168299. * declared INT32, so a 32-bit multiply will be used.
  168300. */
  168301. #if BITS_IN_JSAMPLE == 8
  168302. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  168303. #else
  168304. #define DEQUANTIZE(coef,quantval) \
  168305. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  168306. #endif
  168307. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  168308. * We assume that int right shift is unsigned if INT32 right shift is.
  168309. */
  168310. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  168311. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  168312. #if BITS_IN_JSAMPLE == 8
  168313. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  168314. #else
  168315. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  168316. #endif
  168317. #define IRIGHT_SHIFT(x,shft) \
  168318. ((ishift_temp = (x)) < 0 ? \
  168319. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  168320. (ishift_temp >> (shft)))
  168321. #else
  168322. #define ISHIFT_TEMPS
  168323. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  168324. #endif
  168325. #ifdef USE_ACCURATE_ROUNDING
  168326. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  168327. #else
  168328. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  168329. #endif
  168330. /*
  168331. * Perform dequantization and inverse DCT on one block of coefficients.
  168332. */
  168333. GLOBAL(void)
  168334. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168335. JCOEFPTR coef_block,
  168336. JSAMPARRAY output_buf, JDIMENSION output_col)
  168337. {
  168338. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168339. DCTELEM tmp10, tmp11, tmp12, tmp13;
  168340. DCTELEM z5, z10, z11, z12, z13;
  168341. JCOEFPTR inptr;
  168342. IFAST_MULT_TYPE * quantptr;
  168343. int * wsptr;
  168344. JSAMPROW outptr;
  168345. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168346. int ctr;
  168347. int workspace[DCTSIZE2]; /* buffers data between passes */
  168348. SHIFT_TEMPS /* for DESCALE */
  168349. ISHIFT_TEMPS /* for IDESCALE */
  168350. /* Pass 1: process columns from input, store into work array. */
  168351. inptr = coef_block;
  168352. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  168353. wsptr = workspace;
  168354. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168355. /* Due to quantization, we will usually find that many of the input
  168356. * coefficients are zero, especially the AC terms. We can exploit this
  168357. * by short-circuiting the IDCT calculation for any column in which all
  168358. * the AC terms are zero. In that case each output is equal to the
  168359. * DC coefficient (with scale factor as needed).
  168360. * With typical images and quantization tables, half or more of the
  168361. * column DCT calculations can be simplified this way.
  168362. */
  168363. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168364. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168365. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168366. inptr[DCTSIZE*7] == 0) {
  168367. /* AC terms all zero */
  168368. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168369. wsptr[DCTSIZE*0] = dcval;
  168370. wsptr[DCTSIZE*1] = dcval;
  168371. wsptr[DCTSIZE*2] = dcval;
  168372. wsptr[DCTSIZE*3] = dcval;
  168373. wsptr[DCTSIZE*4] = dcval;
  168374. wsptr[DCTSIZE*5] = dcval;
  168375. wsptr[DCTSIZE*6] = dcval;
  168376. wsptr[DCTSIZE*7] = dcval;
  168377. inptr++; /* advance pointers to next column */
  168378. quantptr++;
  168379. wsptr++;
  168380. continue;
  168381. }
  168382. /* Even part */
  168383. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168384. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168385. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168386. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168387. tmp10 = tmp0 + tmp2; /* phase 3 */
  168388. tmp11 = tmp0 - tmp2;
  168389. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168390. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  168391. tmp0 = tmp10 + tmp13; /* phase 2 */
  168392. tmp3 = tmp10 - tmp13;
  168393. tmp1 = tmp11 + tmp12;
  168394. tmp2 = tmp11 - tmp12;
  168395. /* Odd part */
  168396. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168397. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168398. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168399. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168400. z13 = tmp6 + tmp5; /* phase 6 */
  168401. z10 = tmp6 - tmp5;
  168402. z11 = tmp4 + tmp7;
  168403. z12 = tmp4 - tmp7;
  168404. tmp7 = z11 + z13; /* phase 5 */
  168405. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  168406. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  168407. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  168408. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  168409. tmp6 = tmp12 - tmp7; /* phase 2 */
  168410. tmp5 = tmp11 - tmp6;
  168411. tmp4 = tmp10 + tmp5;
  168412. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  168413. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  168414. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  168415. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  168416. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  168417. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  168418. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  168419. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  168420. inptr++; /* advance pointers to next column */
  168421. quantptr++;
  168422. wsptr++;
  168423. }
  168424. /* Pass 2: process rows from work array, store into output array. */
  168425. /* Note that we must descale the results by a factor of 8 == 2**3, */
  168426. /* and also undo the PASS1_BITS scaling. */
  168427. wsptr = workspace;
  168428. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168429. outptr = output_buf[ctr] + output_col;
  168430. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168431. * However, the column calculation has created many nonzero AC terms, so
  168432. * the simplification applies less often (typically 5% to 10% of the time).
  168433. * On machines with very fast multiplication, it's possible that the
  168434. * test takes more time than it's worth. In that case this section
  168435. * may be commented out.
  168436. */
  168437. #ifndef NO_ZERO_ROW_TEST
  168438. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  168439. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168440. /* AC terms all zero */
  168441. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  168442. & RANGE_MASK];
  168443. outptr[0] = dcval;
  168444. outptr[1] = dcval;
  168445. outptr[2] = dcval;
  168446. outptr[3] = dcval;
  168447. outptr[4] = dcval;
  168448. outptr[5] = dcval;
  168449. outptr[6] = dcval;
  168450. outptr[7] = dcval;
  168451. wsptr += DCTSIZE; /* advance pointer to next row */
  168452. continue;
  168453. }
  168454. #endif
  168455. /* Even part */
  168456. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  168457. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  168458. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  168459. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  168460. - tmp13;
  168461. tmp0 = tmp10 + tmp13;
  168462. tmp3 = tmp10 - tmp13;
  168463. tmp1 = tmp11 + tmp12;
  168464. tmp2 = tmp11 - tmp12;
  168465. /* Odd part */
  168466. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  168467. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  168468. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  168469. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  168470. tmp7 = z11 + z13; /* phase 5 */
  168471. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  168472. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  168473. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  168474. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  168475. tmp6 = tmp12 - tmp7; /* phase 2 */
  168476. tmp5 = tmp11 - tmp6;
  168477. tmp4 = tmp10 + tmp5;
  168478. /* Final output stage: scale down by a factor of 8 and range-limit */
  168479. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  168480. & RANGE_MASK];
  168481. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  168482. & RANGE_MASK];
  168483. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  168484. & RANGE_MASK];
  168485. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  168486. & RANGE_MASK];
  168487. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  168488. & RANGE_MASK];
  168489. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  168490. & RANGE_MASK];
  168491. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  168492. & RANGE_MASK];
  168493. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  168494. & RANGE_MASK];
  168495. wsptr += DCTSIZE; /* advance pointer to next row */
  168496. }
  168497. }
  168498. #endif /* DCT_IFAST_SUPPORTED */
  168499. /********* End of inlined file: jidctfst.c *********/
  168500. #undef CONST_BITS
  168501. #undef FIX_1_847759065
  168502. #undef MULTIPLY
  168503. #undef DEQUANTIZE
  168504. /********* Start of inlined file: jidctint.c *********/
  168505. #define JPEG_INTERNALS
  168506. #ifdef DCT_ISLOW_SUPPORTED
  168507. /*
  168508. * This module is specialized to the case DCTSIZE = 8.
  168509. */
  168510. #if DCTSIZE != 8
  168511. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168512. #endif
  168513. /*
  168514. * The poop on this scaling stuff is as follows:
  168515. *
  168516. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  168517. * larger than the true IDCT outputs. The final outputs are therefore
  168518. * a factor of N larger than desired; since N=8 this can be cured by
  168519. * a simple right shift at the end of the algorithm. The advantage of
  168520. * this arrangement is that we save two multiplications per 1-D IDCT,
  168521. * because the y0 and y4 inputs need not be divided by sqrt(N).
  168522. *
  168523. * We have to do addition and subtraction of the integer inputs, which
  168524. * is no problem, and multiplication by fractional constants, which is
  168525. * a problem to do in integer arithmetic. We multiply all the constants
  168526. * by CONST_SCALE and convert them to integer constants (thus retaining
  168527. * CONST_BITS bits of precision in the constants). After doing a
  168528. * multiplication we have to divide the product by CONST_SCALE, with proper
  168529. * rounding, to produce the correct output. This division can be done
  168530. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  168531. * as long as possible so that partial sums can be added together with
  168532. * full fractional precision.
  168533. *
  168534. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  168535. * they are represented to better-than-integral precision. These outputs
  168536. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  168537. * with the recommended scaling. (To scale up 12-bit sample data further, an
  168538. * intermediate INT32 array would be needed.)
  168539. *
  168540. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  168541. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  168542. * shows that the values given below are the most effective.
  168543. */
  168544. #if BITS_IN_JSAMPLE == 8
  168545. #define CONST_BITS 13
  168546. #define PASS1_BITS 2
  168547. #else
  168548. #define CONST_BITS 13
  168549. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168550. #endif
  168551. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168552. * causing a lot of useless floating-point operations at run time.
  168553. * To get around this we use the following pre-calculated constants.
  168554. * If you change CONST_BITS you may want to add appropriate values.
  168555. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168556. */
  168557. #if CONST_BITS == 13
  168558. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  168559. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  168560. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  168561. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168562. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168563. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  168564. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  168565. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168566. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  168567. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  168568. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168569. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  168570. #else
  168571. #define FIX_0_298631336 FIX(0.298631336)
  168572. #define FIX_0_390180644 FIX(0.390180644)
  168573. #define FIX_0_541196100 FIX(0.541196100)
  168574. #define FIX_0_765366865 FIX(0.765366865)
  168575. #define FIX_0_899976223 FIX(0.899976223)
  168576. #define FIX_1_175875602 FIX(1.175875602)
  168577. #define FIX_1_501321110 FIX(1.501321110)
  168578. #define FIX_1_847759065 FIX(1.847759065)
  168579. #define FIX_1_961570560 FIX(1.961570560)
  168580. #define FIX_2_053119869 FIX(2.053119869)
  168581. #define FIX_2_562915447 FIX(2.562915447)
  168582. #define FIX_3_072711026 FIX(3.072711026)
  168583. #endif
  168584. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168585. * For 8-bit samples with the recommended scaling, all the variable
  168586. * and constant values involved are no more than 16 bits wide, so a
  168587. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168588. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168589. */
  168590. #if BITS_IN_JSAMPLE == 8
  168591. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168592. #else
  168593. #define MULTIPLY(var,const) ((var) * (const))
  168594. #endif
  168595. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168596. * entry; produce an int result. In this module, both inputs and result
  168597. * are 16 bits or less, so either int or short multiply will work.
  168598. */
  168599. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  168600. /*
  168601. * Perform dequantization and inverse DCT on one block of coefficients.
  168602. */
  168603. GLOBAL(void)
  168604. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168605. JCOEFPTR coef_block,
  168606. JSAMPARRAY output_buf, JDIMENSION output_col)
  168607. {
  168608. INT32 tmp0, tmp1, tmp2, tmp3;
  168609. INT32 tmp10, tmp11, tmp12, tmp13;
  168610. INT32 z1, z2, z3, z4, z5;
  168611. JCOEFPTR inptr;
  168612. ISLOW_MULT_TYPE * quantptr;
  168613. int * wsptr;
  168614. JSAMPROW outptr;
  168615. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168616. int ctr;
  168617. int workspace[DCTSIZE2]; /* buffers data between passes */
  168618. SHIFT_TEMPS
  168619. /* Pass 1: process columns from input, store into work array. */
  168620. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  168621. /* furthermore, we scale the results by 2**PASS1_BITS. */
  168622. inptr = coef_block;
  168623. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168624. wsptr = workspace;
  168625. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168626. /* Due to quantization, we will usually find that many of the input
  168627. * coefficients are zero, especially the AC terms. We can exploit this
  168628. * by short-circuiting the IDCT calculation for any column in which all
  168629. * the AC terms are zero. In that case each output is equal to the
  168630. * DC coefficient (with scale factor as needed).
  168631. * With typical images and quantization tables, half or more of the
  168632. * column DCT calculations can be simplified this way.
  168633. */
  168634. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168635. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168636. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168637. inptr[DCTSIZE*7] == 0) {
  168638. /* AC terms all zero */
  168639. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  168640. wsptr[DCTSIZE*0] = dcval;
  168641. wsptr[DCTSIZE*1] = dcval;
  168642. wsptr[DCTSIZE*2] = dcval;
  168643. wsptr[DCTSIZE*3] = dcval;
  168644. wsptr[DCTSIZE*4] = dcval;
  168645. wsptr[DCTSIZE*5] = dcval;
  168646. wsptr[DCTSIZE*6] = dcval;
  168647. wsptr[DCTSIZE*7] = dcval;
  168648. inptr++; /* advance pointers to next column */
  168649. quantptr++;
  168650. wsptr++;
  168651. continue;
  168652. }
  168653. /* Even part: reverse the even part of the forward DCT. */
  168654. /* The rotator is sqrt(2)*c(-6). */
  168655. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168656. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168657. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  168658. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  168659. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  168660. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168661. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168662. tmp0 = (z2 + z3) << CONST_BITS;
  168663. tmp1 = (z2 - z3) << CONST_BITS;
  168664. tmp10 = tmp0 + tmp3;
  168665. tmp13 = tmp0 - tmp3;
  168666. tmp11 = tmp1 + tmp2;
  168667. tmp12 = tmp1 - tmp2;
  168668. /* Odd part per figure 8; the matrix is unitary and hence its
  168669. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  168670. */
  168671. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168672. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168673. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168674. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168675. z1 = tmp0 + tmp3;
  168676. z2 = tmp1 + tmp2;
  168677. z3 = tmp0 + tmp2;
  168678. z4 = tmp1 + tmp3;
  168679. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168680. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168681. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168682. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168683. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168684. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168685. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168686. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168687. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168688. z3 += z5;
  168689. z4 += z5;
  168690. tmp0 += z1 + z3;
  168691. tmp1 += z2 + z4;
  168692. tmp2 += z2 + z3;
  168693. tmp3 += z1 + z4;
  168694. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  168695. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  168696. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  168697. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  168698. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  168699. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  168700. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  168701. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  168702. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  168703. inptr++; /* advance pointers to next column */
  168704. quantptr++;
  168705. wsptr++;
  168706. }
  168707. /* Pass 2: process rows from work array, store into output array. */
  168708. /* Note that we must descale the results by a factor of 8 == 2**3, */
  168709. /* and also undo the PASS1_BITS scaling. */
  168710. wsptr = workspace;
  168711. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168712. outptr = output_buf[ctr] + output_col;
  168713. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168714. * However, the column calculation has created many nonzero AC terms, so
  168715. * the simplification applies less often (typically 5% to 10% of the time).
  168716. * On machines with very fast multiplication, it's possible that the
  168717. * test takes more time than it's worth. In that case this section
  168718. * may be commented out.
  168719. */
  168720. #ifndef NO_ZERO_ROW_TEST
  168721. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  168722. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168723. /* AC terms all zero */
  168724. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  168725. & RANGE_MASK];
  168726. outptr[0] = dcval;
  168727. outptr[1] = dcval;
  168728. outptr[2] = dcval;
  168729. outptr[3] = dcval;
  168730. outptr[4] = dcval;
  168731. outptr[5] = dcval;
  168732. outptr[6] = dcval;
  168733. outptr[7] = dcval;
  168734. wsptr += DCTSIZE; /* advance pointer to next row */
  168735. continue;
  168736. }
  168737. #endif
  168738. /* Even part: reverse the even part of the forward DCT. */
  168739. /* The rotator is sqrt(2)*c(-6). */
  168740. z2 = (INT32) wsptr[2];
  168741. z3 = (INT32) wsptr[6];
  168742. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  168743. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  168744. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  168745. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  168746. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  168747. tmp10 = tmp0 + tmp3;
  168748. tmp13 = tmp0 - tmp3;
  168749. tmp11 = tmp1 + tmp2;
  168750. tmp12 = tmp1 - tmp2;
  168751. /* Odd part per figure 8; the matrix is unitary and hence its
  168752. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  168753. */
  168754. tmp0 = (INT32) wsptr[7];
  168755. tmp1 = (INT32) wsptr[5];
  168756. tmp2 = (INT32) wsptr[3];
  168757. tmp3 = (INT32) wsptr[1];
  168758. z1 = tmp0 + tmp3;
  168759. z2 = tmp1 + tmp2;
  168760. z3 = tmp0 + tmp2;
  168761. z4 = tmp1 + tmp3;
  168762. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168763. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168764. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168765. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168766. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168767. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168768. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168769. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168770. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168771. z3 += z5;
  168772. z4 += z5;
  168773. tmp0 += z1 + z3;
  168774. tmp1 += z2 + z4;
  168775. tmp2 += z2 + z3;
  168776. tmp3 += z1 + z4;
  168777. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  168778. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  168779. CONST_BITS+PASS1_BITS+3)
  168780. & RANGE_MASK];
  168781. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  168782. CONST_BITS+PASS1_BITS+3)
  168783. & RANGE_MASK];
  168784. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  168785. CONST_BITS+PASS1_BITS+3)
  168786. & RANGE_MASK];
  168787. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  168788. CONST_BITS+PASS1_BITS+3)
  168789. & RANGE_MASK];
  168790. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  168791. CONST_BITS+PASS1_BITS+3)
  168792. & RANGE_MASK];
  168793. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  168794. CONST_BITS+PASS1_BITS+3)
  168795. & RANGE_MASK];
  168796. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  168797. CONST_BITS+PASS1_BITS+3)
  168798. & RANGE_MASK];
  168799. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  168800. CONST_BITS+PASS1_BITS+3)
  168801. & RANGE_MASK];
  168802. wsptr += DCTSIZE; /* advance pointer to next row */
  168803. }
  168804. }
  168805. #endif /* DCT_ISLOW_SUPPORTED */
  168806. /********* End of inlined file: jidctint.c *********/
  168807. /********* Start of inlined file: jidctred.c *********/
  168808. #define JPEG_INTERNALS
  168809. #ifdef IDCT_SCALING_SUPPORTED
  168810. /*
  168811. * This module is specialized to the case DCTSIZE = 8.
  168812. */
  168813. #if DCTSIZE != 8
  168814. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168815. #endif
  168816. /* Scaling is the same as in jidctint.c. */
  168817. #if BITS_IN_JSAMPLE == 8
  168818. #define CONST_BITS 13
  168819. #define PASS1_BITS 2
  168820. #else
  168821. #define CONST_BITS 13
  168822. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168823. #endif
  168824. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168825. * causing a lot of useless floating-point operations at run time.
  168826. * To get around this we use the following pre-calculated constants.
  168827. * If you change CONST_BITS you may want to add appropriate values.
  168828. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168829. */
  168830. #if CONST_BITS == 13
  168831. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  168832. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  168833. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  168834. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  168835. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168836. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  168837. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168838. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  168839. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  168840. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  168841. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168842. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  168843. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168844. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  168845. #else
  168846. #define FIX_0_211164243 FIX(0.211164243)
  168847. #define FIX_0_509795579 FIX(0.509795579)
  168848. #define FIX_0_601344887 FIX(0.601344887)
  168849. #define FIX_0_720959822 FIX(0.720959822)
  168850. #define FIX_0_765366865 FIX(0.765366865)
  168851. #define FIX_0_850430095 FIX(0.850430095)
  168852. #define FIX_0_899976223 FIX(0.899976223)
  168853. #define FIX_1_061594337 FIX(1.061594337)
  168854. #define FIX_1_272758580 FIX(1.272758580)
  168855. #define FIX_1_451774981 FIX(1.451774981)
  168856. #define FIX_1_847759065 FIX(1.847759065)
  168857. #define FIX_2_172734803 FIX(2.172734803)
  168858. #define FIX_2_562915447 FIX(2.562915447)
  168859. #define FIX_3_624509785 FIX(3.624509785)
  168860. #endif
  168861. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168862. * For 8-bit samples with the recommended scaling, all the variable
  168863. * and constant values involved are no more than 16 bits wide, so a
  168864. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168865. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168866. */
  168867. #if BITS_IN_JSAMPLE == 8
  168868. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168869. #else
  168870. #define MULTIPLY(var,const) ((var) * (const))
  168871. #endif
  168872. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168873. * entry; produce an int result. In this module, both inputs and result
  168874. * are 16 bits or less, so either int or short multiply will work.
  168875. */
  168876. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  168877. /*
  168878. * Perform dequantization and inverse DCT on one block of coefficients,
  168879. * producing a reduced-size 4x4 output block.
  168880. */
  168881. GLOBAL(void)
  168882. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168883. JCOEFPTR coef_block,
  168884. JSAMPARRAY output_buf, JDIMENSION output_col)
  168885. {
  168886. INT32 tmp0, tmp2, tmp10, tmp12;
  168887. INT32 z1, z2, z3, z4;
  168888. JCOEFPTR inptr;
  168889. ISLOW_MULT_TYPE * quantptr;
  168890. int * wsptr;
  168891. JSAMPROW outptr;
  168892. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168893. int ctr;
  168894. int workspace[DCTSIZE*4]; /* buffers data between passes */
  168895. SHIFT_TEMPS
  168896. /* Pass 1: process columns from input, store into work array. */
  168897. inptr = coef_block;
  168898. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168899. wsptr = workspace;
  168900. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  168901. /* Don't bother to process column 4, because second pass won't use it */
  168902. if (ctr == DCTSIZE-4)
  168903. continue;
  168904. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168905. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  168906. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  168907. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  168908. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  168909. wsptr[DCTSIZE*0] = dcval;
  168910. wsptr[DCTSIZE*1] = dcval;
  168911. wsptr[DCTSIZE*2] = dcval;
  168912. wsptr[DCTSIZE*3] = dcval;
  168913. continue;
  168914. }
  168915. /* Even part */
  168916. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168917. tmp0 <<= (CONST_BITS+1);
  168918. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168919. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168920. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  168921. tmp10 = tmp0 + tmp2;
  168922. tmp12 = tmp0 - tmp2;
  168923. /* Odd part */
  168924. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168925. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168926. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168927. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168928. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  168929. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  168930. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  168931. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  168932. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  168933. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  168934. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  168935. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  168936. /* Final output stage */
  168937. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  168938. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  168939. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  168940. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  168941. }
  168942. /* Pass 2: process 4 rows from work array, store into output array. */
  168943. wsptr = workspace;
  168944. for (ctr = 0; ctr < 4; ctr++) {
  168945. outptr = output_buf[ctr] + output_col;
  168946. /* It's not clear whether a zero row test is worthwhile here ... */
  168947. #ifndef NO_ZERO_ROW_TEST
  168948. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  168949. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168950. /* AC terms all zero */
  168951. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  168952. & RANGE_MASK];
  168953. outptr[0] = dcval;
  168954. outptr[1] = dcval;
  168955. outptr[2] = dcval;
  168956. outptr[3] = dcval;
  168957. wsptr += DCTSIZE; /* advance pointer to next row */
  168958. continue;
  168959. }
  168960. #endif
  168961. /* Even part */
  168962. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  168963. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  168964. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  168965. tmp10 = tmp0 + tmp2;
  168966. tmp12 = tmp0 - tmp2;
  168967. /* Odd part */
  168968. z1 = (INT32) wsptr[7];
  168969. z2 = (INT32) wsptr[5];
  168970. z3 = (INT32) wsptr[3];
  168971. z4 = (INT32) wsptr[1];
  168972. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  168973. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  168974. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  168975. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  168976. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  168977. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  168978. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  168979. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  168980. /* Final output stage */
  168981. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  168982. CONST_BITS+PASS1_BITS+3+1)
  168983. & RANGE_MASK];
  168984. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  168985. CONST_BITS+PASS1_BITS+3+1)
  168986. & RANGE_MASK];
  168987. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  168988. CONST_BITS+PASS1_BITS+3+1)
  168989. & RANGE_MASK];
  168990. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  168991. CONST_BITS+PASS1_BITS+3+1)
  168992. & RANGE_MASK];
  168993. wsptr += DCTSIZE; /* advance pointer to next row */
  168994. }
  168995. }
  168996. /*
  168997. * Perform dequantization and inverse DCT on one block of coefficients,
  168998. * producing a reduced-size 2x2 output block.
  168999. */
  169000. GLOBAL(void)
  169001. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169002. JCOEFPTR coef_block,
  169003. JSAMPARRAY output_buf, JDIMENSION output_col)
  169004. {
  169005. INT32 tmp0, tmp10, z1;
  169006. JCOEFPTR inptr;
  169007. ISLOW_MULT_TYPE * quantptr;
  169008. int * wsptr;
  169009. JSAMPROW outptr;
  169010. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169011. int ctr;
  169012. int workspace[DCTSIZE*2]; /* buffers data between passes */
  169013. SHIFT_TEMPS
  169014. /* Pass 1: process columns from input, store into work array. */
  169015. inptr = coef_block;
  169016. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169017. wsptr = workspace;
  169018. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169019. /* Don't bother to process columns 2,4,6 */
  169020. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  169021. continue;
  169022. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  169023. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  169024. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  169025. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169026. wsptr[DCTSIZE*0] = dcval;
  169027. wsptr[DCTSIZE*1] = dcval;
  169028. continue;
  169029. }
  169030. /* Even part */
  169031. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169032. tmp10 = z1 << (CONST_BITS+2);
  169033. /* Odd part */
  169034. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169035. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  169036. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169037. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  169038. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169039. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  169040. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169041. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169042. /* Final output stage */
  169043. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  169044. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  169045. }
  169046. /* Pass 2: process 2 rows from work array, store into output array. */
  169047. wsptr = workspace;
  169048. for (ctr = 0; ctr < 2; ctr++) {
  169049. outptr = output_buf[ctr] + output_col;
  169050. /* It's not clear whether a zero row test is worthwhile here ... */
  169051. #ifndef NO_ZERO_ROW_TEST
  169052. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  169053. /* AC terms all zero */
  169054. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169055. & RANGE_MASK];
  169056. outptr[0] = dcval;
  169057. outptr[1] = dcval;
  169058. wsptr += DCTSIZE; /* advance pointer to next row */
  169059. continue;
  169060. }
  169061. #endif
  169062. /* Even part */
  169063. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  169064. /* Odd part */
  169065. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  169066. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  169067. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  169068. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169069. /* Final output stage */
  169070. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  169071. CONST_BITS+PASS1_BITS+3+2)
  169072. & RANGE_MASK];
  169073. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  169074. CONST_BITS+PASS1_BITS+3+2)
  169075. & RANGE_MASK];
  169076. wsptr += DCTSIZE; /* advance pointer to next row */
  169077. }
  169078. }
  169079. /*
  169080. * Perform dequantization and inverse DCT on one block of coefficients,
  169081. * producing a reduced-size 1x1 output block.
  169082. */
  169083. GLOBAL(void)
  169084. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169085. JCOEFPTR coef_block,
  169086. JSAMPARRAY output_buf, JDIMENSION output_col)
  169087. {
  169088. int dcval;
  169089. ISLOW_MULT_TYPE * quantptr;
  169090. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169091. SHIFT_TEMPS
  169092. /* We hardly need an inverse DCT routine for this: just take the
  169093. * average pixel value, which is one-eighth of the DC coefficient.
  169094. */
  169095. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169096. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  169097. dcval = (int) DESCALE((INT32) dcval, 3);
  169098. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  169099. }
  169100. #endif /* IDCT_SCALING_SUPPORTED */
  169101. /********* End of inlined file: jidctred.c *********/
  169102. /********* Start of inlined file: jmemmgr.c *********/
  169103. #define JPEG_INTERNALS
  169104. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  169105. /********* Start of inlined file: jmemsys.h *********/
  169106. #ifndef __jmemsys_h__
  169107. #define __jmemsys_h__
  169108. /* Short forms of external names for systems with brain-damaged linkers. */
  169109. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169110. #define jpeg_get_small jGetSmall
  169111. #define jpeg_free_small jFreeSmall
  169112. #define jpeg_get_large jGetLarge
  169113. #define jpeg_free_large jFreeLarge
  169114. #define jpeg_mem_available jMemAvail
  169115. #define jpeg_open_backing_store jOpenBackStore
  169116. #define jpeg_mem_init jMemInit
  169117. #define jpeg_mem_term jMemTerm
  169118. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169119. /*
  169120. * These two functions are used to allocate and release small chunks of
  169121. * memory. (Typically the total amount requested through jpeg_get_small is
  169122. * no more than 20K or so; this will be requested in chunks of a few K each.)
  169123. * Behavior should be the same as for the standard library functions malloc
  169124. * and free; in particular, jpeg_get_small must return NULL on failure.
  169125. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  169126. * size of the object being freed, just in case it's needed.
  169127. * On an 80x86 machine using small-data memory model, these manage near heap.
  169128. */
  169129. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  169130. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  169131. size_t sizeofobject));
  169132. /*
  169133. * These two functions are used to allocate and release large chunks of
  169134. * memory (up to the total free space designated by jpeg_mem_available).
  169135. * The interface is the same as above, except that on an 80x86 machine,
  169136. * far pointers are used. On most other machines these are identical to
  169137. * the jpeg_get/free_small routines; but we keep them separate anyway,
  169138. * in case a different allocation strategy is desirable for large chunks.
  169139. */
  169140. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  169141. size_t sizeofobject));
  169142. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  169143. size_t sizeofobject));
  169144. /*
  169145. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  169146. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  169147. * matter, but that case should never come into play). This macro is needed
  169148. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  169149. * On those machines, we expect that jconfig.h will provide a proper value.
  169150. * On machines with 32-bit flat address spaces, any large constant may be used.
  169151. *
  169152. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  169153. * size_t and will be a multiple of sizeof(align_type).
  169154. */
  169155. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  169156. #define MAX_ALLOC_CHUNK 1000000000L
  169157. #endif
  169158. /*
  169159. * This routine computes the total space still available for allocation by
  169160. * jpeg_get_large. If more space than this is needed, backing store will be
  169161. * used. NOTE: any memory already allocated must not be counted.
  169162. *
  169163. * There is a minimum space requirement, corresponding to the minimum
  169164. * feasible buffer sizes; jmemmgr.c will request that much space even if
  169165. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  169166. * all working storage in memory, is also passed in case it is useful.
  169167. * Finally, the total space already allocated is passed. If no better
  169168. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  169169. * is often a suitable calculation.
  169170. *
  169171. * It is OK for jpeg_mem_available to underestimate the space available
  169172. * (that'll just lead to more backing-store access than is really necessary).
  169173. * However, an overestimate will lead to failure. Hence it's wise to subtract
  169174. * a slop factor from the true available space. 5% should be enough.
  169175. *
  169176. * On machines with lots of virtual memory, any large constant may be returned.
  169177. * Conversely, zero may be returned to always use the minimum amount of memory.
  169178. */
  169179. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  169180. long min_bytes_needed,
  169181. long max_bytes_needed,
  169182. long already_allocated));
  169183. /*
  169184. * This structure holds whatever state is needed to access a single
  169185. * backing-store object. The read/write/close method pointers are called
  169186. * by jmemmgr.c to manipulate the backing-store object; all other fields
  169187. * are private to the system-dependent backing store routines.
  169188. */
  169189. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  169190. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  169191. typedef unsigned short XMSH; /* type of extended-memory handles */
  169192. typedef unsigned short EMSH; /* type of expanded-memory handles */
  169193. typedef union {
  169194. short file_handle; /* DOS file handle if it's a temp file */
  169195. XMSH xms_handle; /* handle if it's a chunk of XMS */
  169196. EMSH ems_handle; /* handle if it's a chunk of EMS */
  169197. } handle_union;
  169198. #endif /* USE_MSDOS_MEMMGR */
  169199. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  169200. #include <Files.h>
  169201. #endif /* USE_MAC_MEMMGR */
  169202. //typedef struct backing_store_struct * backing_store_ptr;
  169203. typedef struct backing_store_struct {
  169204. /* Methods for reading/writing/closing this backing-store object */
  169205. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  169206. struct backing_store_struct *info,
  169207. void FAR * buffer_address,
  169208. long file_offset, long byte_count));
  169209. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  169210. struct backing_store_struct *info,
  169211. void FAR * buffer_address,
  169212. long file_offset, long byte_count));
  169213. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  169214. struct backing_store_struct *info));
  169215. /* Private fields for system-dependent backing-store management */
  169216. #ifdef USE_MSDOS_MEMMGR
  169217. /* For the MS-DOS manager (jmemdos.c), we need: */
  169218. handle_union handle; /* reference to backing-store storage object */
  169219. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169220. #else
  169221. #ifdef USE_MAC_MEMMGR
  169222. /* For the Mac manager (jmemmac.c), we need: */
  169223. short temp_file; /* file reference number to temp file */
  169224. FSSpec tempSpec; /* the FSSpec for the temp file */
  169225. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169226. #else
  169227. /* For a typical implementation with temp files, we need: */
  169228. FILE * temp_file; /* stdio reference to temp file */
  169229. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  169230. #endif
  169231. #endif
  169232. } backing_store_info;
  169233. /*
  169234. * Initial opening of a backing-store object. This must fill in the
  169235. * read/write/close pointers in the object. The read/write routines
  169236. * may take an error exit if the specified maximum file size is exceeded.
  169237. * (If jpeg_mem_available always returns a large value, this routine can
  169238. * just take an error exit.)
  169239. */
  169240. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  169241. struct backing_store_struct *info,
  169242. long total_bytes_needed));
  169243. /*
  169244. * These routines take care of any system-dependent initialization and
  169245. * cleanup required. jpeg_mem_init will be called before anything is
  169246. * allocated (and, therefore, nothing in cinfo is of use except the error
  169247. * manager pointer). It should return a suitable default value for
  169248. * max_memory_to_use; this may subsequently be overridden by the surrounding
  169249. * application. (Note that max_memory_to_use is only important if
  169250. * jpeg_mem_available chooses to consult it ... no one else will.)
  169251. * jpeg_mem_term may assume that all requested memory has been freed and that
  169252. * all opened backing-store objects have been closed.
  169253. */
  169254. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  169255. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  169256. #endif
  169257. /********* End of inlined file: jmemsys.h *********/
  169258. /* import the system-dependent declarations */
  169259. #ifndef NO_GETENV
  169260. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  169261. extern char * getenv JPP((const char * name));
  169262. #endif
  169263. #endif
  169264. /*
  169265. * Some important notes:
  169266. * The allocation routines provided here must never return NULL.
  169267. * They should exit to error_exit if unsuccessful.
  169268. *
  169269. * It's not a good idea to try to merge the sarray and barray routines,
  169270. * even though they are textually almost the same, because samples are
  169271. * usually stored as bytes while coefficients are shorts or ints. Thus,
  169272. * in machines where byte pointers have a different representation from
  169273. * word pointers, the resulting machine code could not be the same.
  169274. */
  169275. /*
  169276. * Many machines require storage alignment: longs must start on 4-byte
  169277. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  169278. * always returns pointers that are multiples of the worst-case alignment
  169279. * requirement, and we had better do so too.
  169280. * There isn't any really portable way to determine the worst-case alignment
  169281. * requirement. This module assumes that the alignment requirement is
  169282. * multiples of sizeof(ALIGN_TYPE).
  169283. * By default, we define ALIGN_TYPE as double. This is necessary on some
  169284. * workstations (where doubles really do need 8-byte alignment) and will work
  169285. * fine on nearly everything. If your machine has lesser alignment needs,
  169286. * you can save a few bytes by making ALIGN_TYPE smaller.
  169287. * The only place I know of where this will NOT work is certain Macintosh
  169288. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  169289. * Doing 10-byte alignment is counterproductive because longwords won't be
  169290. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  169291. * such a compiler.
  169292. */
  169293. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  169294. #define ALIGN_TYPE double
  169295. #endif
  169296. /*
  169297. * We allocate objects from "pools", where each pool is gotten with a single
  169298. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  169299. * overhead within a pool, except for alignment padding. Each pool has a
  169300. * header with a link to the next pool of the same class.
  169301. * Small and large pool headers are identical except that the latter's
  169302. * link pointer must be FAR on 80x86 machines.
  169303. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  169304. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  169305. * of the alignment requirement of ALIGN_TYPE.
  169306. */
  169307. typedef union small_pool_struct * small_pool_ptr;
  169308. typedef union small_pool_struct {
  169309. struct {
  169310. small_pool_ptr next; /* next in list of pools */
  169311. size_t bytes_used; /* how many bytes already used within pool */
  169312. size_t bytes_left; /* bytes still available in this pool */
  169313. } hdr;
  169314. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  169315. } small_pool_hdr;
  169316. typedef union large_pool_struct FAR * large_pool_ptr;
  169317. typedef union large_pool_struct {
  169318. struct {
  169319. large_pool_ptr next; /* next in list of pools */
  169320. size_t bytes_used; /* how many bytes already used within pool */
  169321. size_t bytes_left; /* bytes still available in this pool */
  169322. } hdr;
  169323. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  169324. } large_pool_hdr;
  169325. /*
  169326. * Here is the full definition of a memory manager object.
  169327. */
  169328. typedef struct {
  169329. struct jpeg_memory_mgr pub; /* public fields */
  169330. /* Each pool identifier (lifetime class) names a linked list of pools. */
  169331. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  169332. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  169333. /* Since we only have one lifetime class of virtual arrays, only one
  169334. * linked list is necessary (for each datatype). Note that the virtual
  169335. * array control blocks being linked together are actually stored somewhere
  169336. * in the small-pool list.
  169337. */
  169338. jvirt_sarray_ptr virt_sarray_list;
  169339. jvirt_barray_ptr virt_barray_list;
  169340. /* This counts total space obtained from jpeg_get_small/large */
  169341. long total_space_allocated;
  169342. /* alloc_sarray and alloc_barray set this value for use by virtual
  169343. * array routines.
  169344. */
  169345. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  169346. } my_memory_mgr;
  169347. typedef my_memory_mgr * my_mem_ptr;
  169348. /*
  169349. * The control blocks for virtual arrays.
  169350. * Note that these blocks are allocated in the "small" pool area.
  169351. * System-dependent info for the associated backing store (if any) is hidden
  169352. * inside the backing_store_info struct.
  169353. */
  169354. struct jvirt_sarray_control {
  169355. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  169356. JDIMENSION rows_in_array; /* total virtual array height */
  169357. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  169358. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  169359. JDIMENSION rows_in_mem; /* height of memory buffer */
  169360. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  169361. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  169362. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  169363. boolean pre_zero; /* pre-zero mode requested? */
  169364. boolean dirty; /* do current buffer contents need written? */
  169365. boolean b_s_open; /* is backing-store data valid? */
  169366. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  169367. backing_store_info b_s_info; /* System-dependent control info */
  169368. };
  169369. struct jvirt_barray_control {
  169370. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  169371. JDIMENSION rows_in_array; /* total virtual array height */
  169372. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  169373. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  169374. JDIMENSION rows_in_mem; /* height of memory buffer */
  169375. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  169376. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  169377. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  169378. boolean pre_zero; /* pre-zero mode requested? */
  169379. boolean dirty; /* do current buffer contents need written? */
  169380. boolean b_s_open; /* is backing-store data valid? */
  169381. jvirt_barray_ptr next; /* link to next virtual barray control block */
  169382. backing_store_info b_s_info; /* System-dependent control info */
  169383. };
  169384. #ifdef MEM_STATS /* optional extra stuff for statistics */
  169385. LOCAL(void)
  169386. print_mem_stats (j_common_ptr cinfo, int pool_id)
  169387. {
  169388. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169389. small_pool_ptr shdr_ptr;
  169390. large_pool_ptr lhdr_ptr;
  169391. /* Since this is only a debugging stub, we can cheat a little by using
  169392. * fprintf directly rather than going through the trace message code.
  169393. * This is helpful because message parm array can't handle longs.
  169394. */
  169395. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  169396. pool_id, mem->total_space_allocated);
  169397. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  169398. lhdr_ptr = lhdr_ptr->hdr.next) {
  169399. fprintf(stderr, " Large chunk used %ld\n",
  169400. (long) lhdr_ptr->hdr.bytes_used);
  169401. }
  169402. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  169403. shdr_ptr = shdr_ptr->hdr.next) {
  169404. fprintf(stderr, " Small chunk used %ld free %ld\n",
  169405. (long) shdr_ptr->hdr.bytes_used,
  169406. (long) shdr_ptr->hdr.bytes_left);
  169407. }
  169408. }
  169409. #endif /* MEM_STATS */
  169410. LOCAL(void)
  169411. out_of_memory (j_common_ptr cinfo, int which)
  169412. /* Report an out-of-memory error and stop execution */
  169413. /* If we compiled MEM_STATS support, report alloc requests before dying */
  169414. {
  169415. #ifdef MEM_STATS
  169416. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  169417. #endif
  169418. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  169419. }
  169420. /*
  169421. * Allocation of "small" objects.
  169422. *
  169423. * For these, we use pooled storage. When a new pool must be created,
  169424. * we try to get enough space for the current request plus a "slop" factor,
  169425. * where the slop will be the amount of leftover space in the new pool.
  169426. * The speed vs. space tradeoff is largely determined by the slop values.
  169427. * A different slop value is provided for each pool class (lifetime),
  169428. * and we also distinguish the first pool of a class from later ones.
  169429. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  169430. * machines, but may be too small if longs are 64 bits or more.
  169431. */
  169432. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  169433. {
  169434. 1600, /* first PERMANENT pool */
  169435. 16000 /* first IMAGE pool */
  169436. };
  169437. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  169438. {
  169439. 0, /* additional PERMANENT pools */
  169440. 5000 /* additional IMAGE pools */
  169441. };
  169442. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  169443. METHODDEF(void *)
  169444. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  169445. /* Allocate a "small" object */
  169446. {
  169447. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169448. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  169449. char * data_ptr;
  169450. size_t odd_bytes, min_request, slop;
  169451. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  169452. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  169453. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  169454. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  169455. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  169456. if (odd_bytes > 0)
  169457. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  169458. /* See if space is available in any existing pool */
  169459. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  169460. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169461. prev_hdr_ptr = NULL;
  169462. hdr_ptr = mem->small_list[pool_id];
  169463. while (hdr_ptr != NULL) {
  169464. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  169465. break; /* found pool with enough space */
  169466. prev_hdr_ptr = hdr_ptr;
  169467. hdr_ptr = hdr_ptr->hdr.next;
  169468. }
  169469. /* Time to make a new pool? */
  169470. if (hdr_ptr == NULL) {
  169471. /* min_request is what we need now, slop is what will be leftover */
  169472. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  169473. if (prev_hdr_ptr == NULL) /* first pool in class? */
  169474. slop = first_pool_slop[pool_id];
  169475. else
  169476. slop = extra_pool_slop[pool_id];
  169477. /* Don't ask for more than MAX_ALLOC_CHUNK */
  169478. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  169479. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  169480. /* Try to get space, if fail reduce slop and try again */
  169481. for (;;) {
  169482. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  169483. if (hdr_ptr != NULL)
  169484. break;
  169485. slop /= 2;
  169486. if (slop < MIN_SLOP) /* give up when it gets real small */
  169487. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  169488. }
  169489. mem->total_space_allocated += min_request + slop;
  169490. /* Success, initialize the new pool header and add to end of list */
  169491. hdr_ptr->hdr.next = NULL;
  169492. hdr_ptr->hdr.bytes_used = 0;
  169493. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  169494. if (prev_hdr_ptr == NULL) /* first pool in class? */
  169495. mem->small_list[pool_id] = hdr_ptr;
  169496. else
  169497. prev_hdr_ptr->hdr.next = hdr_ptr;
  169498. }
  169499. /* OK, allocate the object from the current pool */
  169500. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  169501. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  169502. hdr_ptr->hdr.bytes_used += sizeofobject;
  169503. hdr_ptr->hdr.bytes_left -= sizeofobject;
  169504. return (void *) data_ptr;
  169505. }
  169506. /*
  169507. * Allocation of "large" objects.
  169508. *
  169509. * The external semantics of these are the same as "small" objects,
  169510. * except that FAR pointers are used on 80x86. However the pool
  169511. * management heuristics are quite different. We assume that each
  169512. * request is large enough that it may as well be passed directly to
  169513. * jpeg_get_large; the pool management just links everything together
  169514. * so that we can free it all on demand.
  169515. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  169516. * structures. The routines that create these structures (see below)
  169517. * deliberately bunch rows together to ensure a large request size.
  169518. */
  169519. METHODDEF(void FAR *)
  169520. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  169521. /* Allocate a "large" object */
  169522. {
  169523. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169524. large_pool_ptr hdr_ptr;
  169525. size_t odd_bytes;
  169526. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  169527. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  169528. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  169529. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  169530. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  169531. if (odd_bytes > 0)
  169532. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  169533. /* Always make a new pool */
  169534. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  169535. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169536. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  169537. SIZEOF(large_pool_hdr));
  169538. if (hdr_ptr == NULL)
  169539. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  169540. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  169541. /* Success, initialize the new pool header and add to list */
  169542. hdr_ptr->hdr.next = mem->large_list[pool_id];
  169543. /* We maintain space counts in each pool header for statistical purposes,
  169544. * even though they are not needed for allocation.
  169545. */
  169546. hdr_ptr->hdr.bytes_used = sizeofobject;
  169547. hdr_ptr->hdr.bytes_left = 0;
  169548. mem->large_list[pool_id] = hdr_ptr;
  169549. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  169550. }
  169551. /*
  169552. * Creation of 2-D sample arrays.
  169553. * The pointers are in near heap, the samples themselves in FAR heap.
  169554. *
  169555. * To minimize allocation overhead and to allow I/O of large contiguous
  169556. * blocks, we allocate the sample rows in groups of as many rows as possible
  169557. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  169558. * NB: the virtual array control routines, later in this file, know about
  169559. * this chunking of rows. The rowsperchunk value is left in the mem manager
  169560. * object so that it can be saved away if this sarray is the workspace for
  169561. * a virtual array.
  169562. */
  169563. METHODDEF(JSAMPARRAY)
  169564. alloc_sarray (j_common_ptr cinfo, int pool_id,
  169565. JDIMENSION samplesperrow, JDIMENSION numrows)
  169566. /* Allocate a 2-D sample array */
  169567. {
  169568. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169569. JSAMPARRAY result;
  169570. JSAMPROW workspace;
  169571. JDIMENSION rowsperchunk, currow, i;
  169572. long ltemp;
  169573. /* Calculate max # of rows allowed in one allocation chunk */
  169574. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  169575. ((long) samplesperrow * SIZEOF(JSAMPLE));
  169576. if (ltemp <= 0)
  169577. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169578. if (ltemp < (long) numrows)
  169579. rowsperchunk = (JDIMENSION) ltemp;
  169580. else
  169581. rowsperchunk = numrows;
  169582. mem->last_rowsperchunk = rowsperchunk;
  169583. /* Get space for row pointers (small object) */
  169584. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  169585. (size_t) (numrows * SIZEOF(JSAMPROW)));
  169586. /* Get the rows themselves (large objects) */
  169587. currow = 0;
  169588. while (currow < numrows) {
  169589. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  169590. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  169591. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  169592. * SIZEOF(JSAMPLE)));
  169593. for (i = rowsperchunk; i > 0; i--) {
  169594. result[currow++] = workspace;
  169595. workspace += samplesperrow;
  169596. }
  169597. }
  169598. return result;
  169599. }
  169600. /*
  169601. * Creation of 2-D coefficient-block arrays.
  169602. * This is essentially the same as the code for sample arrays, above.
  169603. */
  169604. METHODDEF(JBLOCKARRAY)
  169605. alloc_barray (j_common_ptr cinfo, int pool_id,
  169606. JDIMENSION blocksperrow, JDIMENSION numrows)
  169607. /* Allocate a 2-D coefficient-block array */
  169608. {
  169609. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169610. JBLOCKARRAY result;
  169611. JBLOCKROW workspace;
  169612. JDIMENSION rowsperchunk, currow, i;
  169613. long ltemp;
  169614. /* Calculate max # of rows allowed in one allocation chunk */
  169615. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  169616. ((long) blocksperrow * SIZEOF(JBLOCK));
  169617. if (ltemp <= 0)
  169618. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169619. if (ltemp < (long) numrows)
  169620. rowsperchunk = (JDIMENSION) ltemp;
  169621. else
  169622. rowsperchunk = numrows;
  169623. mem->last_rowsperchunk = rowsperchunk;
  169624. /* Get space for row pointers (small object) */
  169625. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  169626. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  169627. /* Get the rows themselves (large objects) */
  169628. currow = 0;
  169629. while (currow < numrows) {
  169630. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  169631. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  169632. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  169633. * SIZEOF(JBLOCK)));
  169634. for (i = rowsperchunk; i > 0; i--) {
  169635. result[currow++] = workspace;
  169636. workspace += blocksperrow;
  169637. }
  169638. }
  169639. return result;
  169640. }
  169641. /*
  169642. * About virtual array management:
  169643. *
  169644. * The above "normal" array routines are only used to allocate strip buffers
  169645. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  169646. * are handled as "virtual" arrays. The array is still accessed a strip at a
  169647. * time, but the memory manager must save the whole array for repeated
  169648. * accesses. The intended implementation is that there is a strip buffer in
  169649. * memory (as high as is possible given the desired memory limit), plus a
  169650. * backing file that holds the rest of the array.
  169651. *
  169652. * The request_virt_array routines are told the total size of the image and
  169653. * the maximum number of rows that will be accessed at once. The in-memory
  169654. * buffer must be at least as large as the maxaccess value.
  169655. *
  169656. * The request routines create control blocks but not the in-memory buffers.
  169657. * That is postponed until realize_virt_arrays is called. At that time the
  169658. * total amount of space needed is known (approximately, anyway), so free
  169659. * memory can be divided up fairly.
  169660. *
  169661. * The access_virt_array routines are responsible for making a specific strip
  169662. * area accessible (after reading or writing the backing file, if necessary).
  169663. * Note that the access routines are told whether the caller intends to modify
  169664. * the accessed strip; during a read-only pass this saves having to rewrite
  169665. * data to disk. The access routines are also responsible for pre-zeroing
  169666. * any newly accessed rows, if pre-zeroing was requested.
  169667. *
  169668. * In current usage, the access requests are usually for nonoverlapping
  169669. * strips; that is, successive access start_row numbers differ by exactly
  169670. * num_rows = maxaccess. This means we can get good performance with simple
  169671. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  169672. * of the access height; then there will never be accesses across bufferload
  169673. * boundaries. The code will still work with overlapping access requests,
  169674. * but it doesn't handle bufferload overlaps very efficiently.
  169675. */
  169676. METHODDEF(jvirt_sarray_ptr)
  169677. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  169678. JDIMENSION samplesperrow, JDIMENSION numrows,
  169679. JDIMENSION maxaccess)
  169680. /* Request a virtual 2-D sample array */
  169681. {
  169682. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169683. jvirt_sarray_ptr result;
  169684. /* Only IMAGE-lifetime virtual arrays are currently supported */
  169685. if (pool_id != JPOOL_IMAGE)
  169686. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169687. /* get control block */
  169688. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  169689. SIZEOF(struct jvirt_sarray_control));
  169690. result->mem_buffer = NULL; /* marks array not yet realized */
  169691. result->rows_in_array = numrows;
  169692. result->samplesperrow = samplesperrow;
  169693. result->maxaccess = maxaccess;
  169694. result->pre_zero = pre_zero;
  169695. result->b_s_open = FALSE; /* no associated backing-store object */
  169696. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  169697. mem->virt_sarray_list = result;
  169698. return result;
  169699. }
  169700. METHODDEF(jvirt_barray_ptr)
  169701. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  169702. JDIMENSION blocksperrow, JDIMENSION numrows,
  169703. JDIMENSION maxaccess)
  169704. /* Request a virtual 2-D coefficient-block array */
  169705. {
  169706. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169707. jvirt_barray_ptr result;
  169708. /* Only IMAGE-lifetime virtual arrays are currently supported */
  169709. if (pool_id != JPOOL_IMAGE)
  169710. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169711. /* get control block */
  169712. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  169713. SIZEOF(struct jvirt_barray_control));
  169714. result->mem_buffer = NULL; /* marks array not yet realized */
  169715. result->rows_in_array = numrows;
  169716. result->blocksperrow = blocksperrow;
  169717. result->maxaccess = maxaccess;
  169718. result->pre_zero = pre_zero;
  169719. result->b_s_open = FALSE; /* no associated backing-store object */
  169720. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  169721. mem->virt_barray_list = result;
  169722. return result;
  169723. }
  169724. METHODDEF(void)
  169725. realize_virt_arrays (j_common_ptr cinfo)
  169726. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  169727. {
  169728. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169729. long space_per_minheight, maximum_space, avail_mem;
  169730. long minheights, max_minheights;
  169731. jvirt_sarray_ptr sptr;
  169732. jvirt_barray_ptr bptr;
  169733. /* Compute the minimum space needed (maxaccess rows in each buffer)
  169734. * and the maximum space needed (full image height in each buffer).
  169735. * These may be of use to the system-dependent jpeg_mem_available routine.
  169736. */
  169737. space_per_minheight = 0;
  169738. maximum_space = 0;
  169739. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  169740. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  169741. space_per_minheight += (long) sptr->maxaccess *
  169742. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  169743. maximum_space += (long) sptr->rows_in_array *
  169744. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  169745. }
  169746. }
  169747. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  169748. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  169749. space_per_minheight += (long) bptr->maxaccess *
  169750. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  169751. maximum_space += (long) bptr->rows_in_array *
  169752. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  169753. }
  169754. }
  169755. if (space_per_minheight <= 0)
  169756. return; /* no unrealized arrays, no work */
  169757. /* Determine amount of memory to actually use; this is system-dependent. */
  169758. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  169759. mem->total_space_allocated);
  169760. /* If the maximum space needed is available, make all the buffers full
  169761. * height; otherwise parcel it out with the same number of minheights
  169762. * in each buffer.
  169763. */
  169764. if (avail_mem >= maximum_space)
  169765. max_minheights = 1000000000L;
  169766. else {
  169767. max_minheights = avail_mem / space_per_minheight;
  169768. /* If there doesn't seem to be enough space, try to get the minimum
  169769. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  169770. */
  169771. if (max_minheights <= 0)
  169772. max_minheights = 1;
  169773. }
  169774. /* Allocate the in-memory buffers and initialize backing store as needed. */
  169775. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  169776. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  169777. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  169778. if (minheights <= max_minheights) {
  169779. /* This buffer fits in memory */
  169780. sptr->rows_in_mem = sptr->rows_in_array;
  169781. } else {
  169782. /* It doesn't fit in memory, create backing store. */
  169783. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  169784. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  169785. (long) sptr->rows_in_array *
  169786. (long) sptr->samplesperrow *
  169787. (long) SIZEOF(JSAMPLE));
  169788. sptr->b_s_open = TRUE;
  169789. }
  169790. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  169791. sptr->samplesperrow, sptr->rows_in_mem);
  169792. sptr->rowsperchunk = mem->last_rowsperchunk;
  169793. sptr->cur_start_row = 0;
  169794. sptr->first_undef_row = 0;
  169795. sptr->dirty = FALSE;
  169796. }
  169797. }
  169798. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  169799. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  169800. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  169801. if (minheights <= max_minheights) {
  169802. /* This buffer fits in memory */
  169803. bptr->rows_in_mem = bptr->rows_in_array;
  169804. } else {
  169805. /* It doesn't fit in memory, create backing store. */
  169806. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  169807. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  169808. (long) bptr->rows_in_array *
  169809. (long) bptr->blocksperrow *
  169810. (long) SIZEOF(JBLOCK));
  169811. bptr->b_s_open = TRUE;
  169812. }
  169813. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  169814. bptr->blocksperrow, bptr->rows_in_mem);
  169815. bptr->rowsperchunk = mem->last_rowsperchunk;
  169816. bptr->cur_start_row = 0;
  169817. bptr->first_undef_row = 0;
  169818. bptr->dirty = FALSE;
  169819. }
  169820. }
  169821. }
  169822. LOCAL(void)
  169823. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  169824. /* Do backing store read or write of a virtual sample array */
  169825. {
  169826. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  169827. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  169828. file_offset = ptr->cur_start_row * bytesperrow;
  169829. /* Loop to read or write each allocation chunk in mem_buffer */
  169830. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  169831. /* One chunk, but check for short chunk at end of buffer */
  169832. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  169833. /* Transfer no more than is currently defined */
  169834. thisrow = (long) ptr->cur_start_row + i;
  169835. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  169836. /* Transfer no more than fits in file */
  169837. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  169838. if (rows <= 0) /* this chunk might be past end of file! */
  169839. break;
  169840. byte_count = rows * bytesperrow;
  169841. if (writing)
  169842. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  169843. (void FAR *) ptr->mem_buffer[i],
  169844. file_offset, byte_count);
  169845. else
  169846. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  169847. (void FAR *) ptr->mem_buffer[i],
  169848. file_offset, byte_count);
  169849. file_offset += byte_count;
  169850. }
  169851. }
  169852. LOCAL(void)
  169853. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  169854. /* Do backing store read or write of a virtual coefficient-block array */
  169855. {
  169856. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  169857. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  169858. file_offset = ptr->cur_start_row * bytesperrow;
  169859. /* Loop to read or write each allocation chunk in mem_buffer */
  169860. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  169861. /* One chunk, but check for short chunk at end of buffer */
  169862. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  169863. /* Transfer no more than is currently defined */
  169864. thisrow = (long) ptr->cur_start_row + i;
  169865. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  169866. /* Transfer no more than fits in file */
  169867. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  169868. if (rows <= 0) /* this chunk might be past end of file! */
  169869. break;
  169870. byte_count = rows * bytesperrow;
  169871. if (writing)
  169872. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  169873. (void FAR *) ptr->mem_buffer[i],
  169874. file_offset, byte_count);
  169875. else
  169876. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  169877. (void FAR *) ptr->mem_buffer[i],
  169878. file_offset, byte_count);
  169879. file_offset += byte_count;
  169880. }
  169881. }
  169882. METHODDEF(JSAMPARRAY)
  169883. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  169884. JDIMENSION start_row, JDIMENSION num_rows,
  169885. boolean writable)
  169886. /* Access the part of a virtual sample array starting at start_row */
  169887. /* and extending for num_rows rows. writable is true if */
  169888. /* caller intends to modify the accessed area. */
  169889. {
  169890. JDIMENSION end_row = start_row + num_rows;
  169891. JDIMENSION undef_row;
  169892. /* debugging check */
  169893. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  169894. ptr->mem_buffer == NULL)
  169895. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169896. /* Make the desired part of the virtual array accessible */
  169897. if (start_row < ptr->cur_start_row ||
  169898. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  169899. if (! ptr->b_s_open)
  169900. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  169901. /* Flush old buffer contents if necessary */
  169902. if (ptr->dirty) {
  169903. do_sarray_io(cinfo, ptr, TRUE);
  169904. ptr->dirty = FALSE;
  169905. }
  169906. /* Decide what part of virtual array to access.
  169907. * Algorithm: if target address > current window, assume forward scan,
  169908. * load starting at target address. If target address < current window,
  169909. * assume backward scan, load so that target area is top of window.
  169910. * Note that when switching from forward write to forward read, will have
  169911. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  169912. */
  169913. if (start_row > ptr->cur_start_row) {
  169914. ptr->cur_start_row = start_row;
  169915. } else {
  169916. /* use long arithmetic here to avoid overflow & unsigned problems */
  169917. long ltemp;
  169918. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  169919. if (ltemp < 0)
  169920. ltemp = 0; /* don't fall off front end of file */
  169921. ptr->cur_start_row = (JDIMENSION) ltemp;
  169922. }
  169923. /* Read in the selected part of the array.
  169924. * During the initial write pass, we will do no actual read
  169925. * because the selected part is all undefined.
  169926. */
  169927. do_sarray_io(cinfo, ptr, FALSE);
  169928. }
  169929. /* Ensure the accessed part of the array is defined; prezero if needed.
  169930. * To improve locality of access, we only prezero the part of the array
  169931. * that the caller is about to access, not the entire in-memory array.
  169932. */
  169933. if (ptr->first_undef_row < end_row) {
  169934. if (ptr->first_undef_row < start_row) {
  169935. if (writable) /* writer skipped over a section of array */
  169936. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169937. undef_row = start_row; /* but reader is allowed to read ahead */
  169938. } else {
  169939. undef_row = ptr->first_undef_row;
  169940. }
  169941. if (writable)
  169942. ptr->first_undef_row = end_row;
  169943. if (ptr->pre_zero) {
  169944. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  169945. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  169946. end_row -= ptr->cur_start_row;
  169947. while (undef_row < end_row) {
  169948. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  169949. undef_row++;
  169950. }
  169951. } else {
  169952. if (! writable) /* reader looking at undefined data */
  169953. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169954. }
  169955. }
  169956. /* Flag the buffer dirty if caller will write in it */
  169957. if (writable)
  169958. ptr->dirty = TRUE;
  169959. /* Return address of proper part of the buffer */
  169960. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  169961. }
  169962. METHODDEF(JBLOCKARRAY)
  169963. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  169964. JDIMENSION start_row, JDIMENSION num_rows,
  169965. boolean writable)
  169966. /* Access the part of a virtual block array starting at start_row */
  169967. /* and extending for num_rows rows. writable is true if */
  169968. /* caller intends to modify the accessed area. */
  169969. {
  169970. JDIMENSION end_row = start_row + num_rows;
  169971. JDIMENSION undef_row;
  169972. /* debugging check */
  169973. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  169974. ptr->mem_buffer == NULL)
  169975. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169976. /* Make the desired part of the virtual array accessible */
  169977. if (start_row < ptr->cur_start_row ||
  169978. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  169979. if (! ptr->b_s_open)
  169980. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  169981. /* Flush old buffer contents if necessary */
  169982. if (ptr->dirty) {
  169983. do_barray_io(cinfo, ptr, TRUE);
  169984. ptr->dirty = FALSE;
  169985. }
  169986. /* Decide what part of virtual array to access.
  169987. * Algorithm: if target address > current window, assume forward scan,
  169988. * load starting at target address. If target address < current window,
  169989. * assume backward scan, load so that target area is top of window.
  169990. * Note that when switching from forward write to forward read, will have
  169991. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  169992. */
  169993. if (start_row > ptr->cur_start_row) {
  169994. ptr->cur_start_row = start_row;
  169995. } else {
  169996. /* use long arithmetic here to avoid overflow & unsigned problems */
  169997. long ltemp;
  169998. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  169999. if (ltemp < 0)
  170000. ltemp = 0; /* don't fall off front end of file */
  170001. ptr->cur_start_row = (JDIMENSION) ltemp;
  170002. }
  170003. /* Read in the selected part of the array.
  170004. * During the initial write pass, we will do no actual read
  170005. * because the selected part is all undefined.
  170006. */
  170007. do_barray_io(cinfo, ptr, FALSE);
  170008. }
  170009. /* Ensure the accessed part of the array is defined; prezero if needed.
  170010. * To improve locality of access, we only prezero the part of the array
  170011. * that the caller is about to access, not the entire in-memory array.
  170012. */
  170013. if (ptr->first_undef_row < end_row) {
  170014. if (ptr->first_undef_row < start_row) {
  170015. if (writable) /* writer skipped over a section of array */
  170016. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170017. undef_row = start_row; /* but reader is allowed to read ahead */
  170018. } else {
  170019. undef_row = ptr->first_undef_row;
  170020. }
  170021. if (writable)
  170022. ptr->first_undef_row = end_row;
  170023. if (ptr->pre_zero) {
  170024. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  170025. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170026. end_row -= ptr->cur_start_row;
  170027. while (undef_row < end_row) {
  170028. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170029. undef_row++;
  170030. }
  170031. } else {
  170032. if (! writable) /* reader looking at undefined data */
  170033. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170034. }
  170035. }
  170036. /* Flag the buffer dirty if caller will write in it */
  170037. if (writable)
  170038. ptr->dirty = TRUE;
  170039. /* Return address of proper part of the buffer */
  170040. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170041. }
  170042. /*
  170043. * Release all objects belonging to a specified pool.
  170044. */
  170045. METHODDEF(void)
  170046. free_pool (j_common_ptr cinfo, int pool_id)
  170047. {
  170048. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170049. small_pool_ptr shdr_ptr;
  170050. large_pool_ptr lhdr_ptr;
  170051. size_t space_freed;
  170052. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170053. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170054. #ifdef MEM_STATS
  170055. if (cinfo->err->trace_level > 1)
  170056. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  170057. #endif
  170058. /* If freeing IMAGE pool, close any virtual arrays first */
  170059. if (pool_id == JPOOL_IMAGE) {
  170060. jvirt_sarray_ptr sptr;
  170061. jvirt_barray_ptr bptr;
  170062. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170063. if (sptr->b_s_open) { /* there may be no backing store */
  170064. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  170065. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  170066. }
  170067. }
  170068. mem->virt_sarray_list = NULL;
  170069. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170070. if (bptr->b_s_open) { /* there may be no backing store */
  170071. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  170072. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  170073. }
  170074. }
  170075. mem->virt_barray_list = NULL;
  170076. }
  170077. /* Release large objects */
  170078. lhdr_ptr = mem->large_list[pool_id];
  170079. mem->large_list[pool_id] = NULL;
  170080. while (lhdr_ptr != NULL) {
  170081. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  170082. space_freed = lhdr_ptr->hdr.bytes_used +
  170083. lhdr_ptr->hdr.bytes_left +
  170084. SIZEOF(large_pool_hdr);
  170085. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  170086. mem->total_space_allocated -= space_freed;
  170087. lhdr_ptr = next_lhdr_ptr;
  170088. }
  170089. /* Release small objects */
  170090. shdr_ptr = mem->small_list[pool_id];
  170091. mem->small_list[pool_id] = NULL;
  170092. while (shdr_ptr != NULL) {
  170093. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  170094. space_freed = shdr_ptr->hdr.bytes_used +
  170095. shdr_ptr->hdr.bytes_left +
  170096. SIZEOF(small_pool_hdr);
  170097. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  170098. mem->total_space_allocated -= space_freed;
  170099. shdr_ptr = next_shdr_ptr;
  170100. }
  170101. }
  170102. /*
  170103. * Close up shop entirely.
  170104. * Note that this cannot be called unless cinfo->mem is non-NULL.
  170105. */
  170106. METHODDEF(void)
  170107. self_destruct (j_common_ptr cinfo)
  170108. {
  170109. int pool;
  170110. /* Close all backing store, release all memory.
  170111. * Releasing pools in reverse order might help avoid fragmentation
  170112. * with some (brain-damaged) malloc libraries.
  170113. */
  170114. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170115. free_pool(cinfo, pool);
  170116. }
  170117. /* Release the memory manager control block too. */
  170118. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  170119. cinfo->mem = NULL; /* ensures I will be called only once */
  170120. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170121. }
  170122. /*
  170123. * Memory manager initialization.
  170124. * When this is called, only the error manager pointer is valid in cinfo!
  170125. */
  170126. GLOBAL(void)
  170127. jinit_memory_mgr (j_common_ptr cinfo)
  170128. {
  170129. my_mem_ptr mem;
  170130. long max_to_use;
  170131. int pool;
  170132. size_t test_mac;
  170133. cinfo->mem = NULL; /* for safety if init fails */
  170134. /* Check for configuration errors.
  170135. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  170136. * doesn't reflect any real hardware alignment requirement.
  170137. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  170138. * in common if and only if X is a power of 2, ie has only one one-bit.
  170139. * Some compilers may give an "unreachable code" warning here; ignore it.
  170140. */
  170141. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  170142. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  170143. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  170144. * a multiple of SIZEOF(ALIGN_TYPE).
  170145. * Again, an "unreachable code" warning may be ignored here.
  170146. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  170147. */
  170148. test_mac = (size_t) MAX_ALLOC_CHUNK;
  170149. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  170150. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  170151. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  170152. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  170153. /* Attempt to allocate memory manager's control block */
  170154. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  170155. if (mem == NULL) {
  170156. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170157. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  170158. }
  170159. /* OK, fill in the method pointers */
  170160. mem->pub.alloc_small = alloc_small;
  170161. mem->pub.alloc_large = alloc_large;
  170162. mem->pub.alloc_sarray = alloc_sarray;
  170163. mem->pub.alloc_barray = alloc_barray;
  170164. mem->pub.request_virt_sarray = request_virt_sarray;
  170165. mem->pub.request_virt_barray = request_virt_barray;
  170166. mem->pub.realize_virt_arrays = realize_virt_arrays;
  170167. mem->pub.access_virt_sarray = access_virt_sarray;
  170168. mem->pub.access_virt_barray = access_virt_barray;
  170169. mem->pub.free_pool = free_pool;
  170170. mem->pub.self_destruct = self_destruct;
  170171. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  170172. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  170173. /* Initialize working state */
  170174. mem->pub.max_memory_to_use = max_to_use;
  170175. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170176. mem->small_list[pool] = NULL;
  170177. mem->large_list[pool] = NULL;
  170178. }
  170179. mem->virt_sarray_list = NULL;
  170180. mem->virt_barray_list = NULL;
  170181. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  170182. /* Declare ourselves open for business */
  170183. cinfo->mem = & mem->pub;
  170184. /* Check for an environment variable JPEGMEM; if found, override the
  170185. * default max_memory setting from jpeg_mem_init. Note that the
  170186. * surrounding application may again override this value.
  170187. * If your system doesn't support getenv(), define NO_GETENV to disable
  170188. * this feature.
  170189. */
  170190. #ifndef NO_GETENV
  170191. { char * memenv;
  170192. if ((memenv = getenv("JPEGMEM")) != NULL) {
  170193. char ch = 'x';
  170194. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  170195. if (ch == 'm' || ch == 'M')
  170196. max_to_use *= 1000L;
  170197. mem->pub.max_memory_to_use = max_to_use * 1000L;
  170198. }
  170199. }
  170200. }
  170201. #endif
  170202. }
  170203. /********* End of inlined file: jmemmgr.c *********/
  170204. /********* Start of inlined file: jmemnobs.c *********/
  170205. #define JPEG_INTERNALS
  170206. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  170207. extern void * malloc JPP((size_t size));
  170208. extern void free JPP((void *ptr));
  170209. #endif
  170210. /*
  170211. * Memory allocation and freeing are controlled by the regular library
  170212. * routines malloc() and free().
  170213. */
  170214. GLOBAL(void *)
  170215. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  170216. {
  170217. return (void *) malloc(sizeofobject);
  170218. }
  170219. GLOBAL(void)
  170220. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  170221. {
  170222. free(object);
  170223. }
  170224. /*
  170225. * "Large" objects are treated the same as "small" ones.
  170226. * NB: although we include FAR keywords in the routine declarations,
  170227. * this file won't actually work in 80x86 small/medium model; at least,
  170228. * you probably won't be able to process useful-size images in only 64KB.
  170229. */
  170230. GLOBAL(void FAR *)
  170231. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  170232. {
  170233. return (void FAR *) malloc(sizeofobject);
  170234. }
  170235. GLOBAL(void)
  170236. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  170237. {
  170238. free(object);
  170239. }
  170240. /*
  170241. * This routine computes the total memory space available for allocation.
  170242. * Here we always say, "we got all you want bud!"
  170243. */
  170244. GLOBAL(long)
  170245. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  170246. long max_bytes_needed, long already_allocated)
  170247. {
  170248. return max_bytes_needed;
  170249. }
  170250. /*
  170251. * Backing store (temporary file) management.
  170252. * Since jpeg_mem_available always promised the moon,
  170253. * this should never be called and we can just error out.
  170254. */
  170255. GLOBAL(void)
  170256. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  170257. long total_bytes_needed)
  170258. {
  170259. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  170260. }
  170261. /*
  170262. * These routines take care of any system-dependent initialization and
  170263. * cleanup required. Here, there isn't any.
  170264. */
  170265. GLOBAL(long)
  170266. jpeg_mem_init (j_common_ptr cinfo)
  170267. {
  170268. return 0; /* just set max_memory_to_use to 0 */
  170269. }
  170270. GLOBAL(void)
  170271. jpeg_mem_term (j_common_ptr cinfo)
  170272. {
  170273. /* no work */
  170274. }
  170275. /********* End of inlined file: jmemnobs.c *********/
  170276. /********* Start of inlined file: jquant1.c *********/
  170277. #define JPEG_INTERNALS
  170278. #ifdef QUANT_1PASS_SUPPORTED
  170279. /*
  170280. * The main purpose of 1-pass quantization is to provide a fast, if not very
  170281. * high quality, colormapped output capability. A 2-pass quantizer usually
  170282. * gives better visual quality; however, for quantized grayscale output this
  170283. * quantizer is perfectly adequate. Dithering is highly recommended with this
  170284. * quantizer, though you can turn it off if you really want to.
  170285. *
  170286. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  170287. * image. We use a map consisting of all combinations of Ncolors[i] color
  170288. * values for the i'th component. The Ncolors[] values are chosen so that
  170289. * their product, the total number of colors, is no more than that requested.
  170290. * (In most cases, the product will be somewhat less.)
  170291. *
  170292. * Since the colormap is orthogonal, the representative value for each color
  170293. * component can be determined without considering the other components;
  170294. * then these indexes can be combined into a colormap index by a standard
  170295. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  170296. * can be precalculated and stored in the lookup table colorindex[].
  170297. * colorindex[i][j] maps pixel value j in component i to the nearest
  170298. * representative value (grid plane) for that component; this index is
  170299. * multiplied by the array stride for component i, so that the
  170300. * index of the colormap entry closest to a given pixel value is just
  170301. * sum( colorindex[component-number][pixel-component-value] )
  170302. * Aside from being fast, this scheme allows for variable spacing between
  170303. * representative values with no additional lookup cost.
  170304. *
  170305. * If gamma correction has been applied in color conversion, it might be wise
  170306. * to adjust the color grid spacing so that the representative colors are
  170307. * equidistant in linear space. At this writing, gamma correction is not
  170308. * implemented by jdcolor, so nothing is done here.
  170309. */
  170310. /* Declarations for ordered dithering.
  170311. *
  170312. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  170313. * dithering is described in many references, for instance Dale Schumacher's
  170314. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  170315. * In place of Schumacher's comparisons against a "threshold" value, we add a
  170316. * "dither" value to the input pixel and then round the result to the nearest
  170317. * output value. The dither value is equivalent to (0.5 - threshold) times
  170318. * the distance between output values. For ordered dithering, we assume that
  170319. * the output colors are equally spaced; if not, results will probably be
  170320. * worse, since the dither may be too much or too little at a given point.
  170321. *
  170322. * The normal calculation would be to form pixel value + dither, range-limit
  170323. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  170324. * We can skip the separate range-limiting step by extending the colorindex
  170325. * table in both directions.
  170326. */
  170327. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  170328. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  170329. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  170330. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  170331. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  170332. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  170333. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  170334. /* Bayer's order-4 dither array. Generated by the code given in
  170335. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  170336. * The values in this array must range from 0 to ODITHER_CELLS-1.
  170337. */
  170338. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  170339. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  170340. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  170341. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  170342. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  170343. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  170344. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  170345. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  170346. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  170347. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  170348. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  170349. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  170350. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  170351. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  170352. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  170353. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  170354. };
  170355. /* Declarations for Floyd-Steinberg dithering.
  170356. *
  170357. * Errors are accumulated into the array fserrors[], at a resolution of
  170358. * 1/16th of a pixel count. The error at a given pixel is propagated
  170359. * to its not-yet-processed neighbors using the standard F-S fractions,
  170360. * ... (here) 7/16
  170361. * 3/16 5/16 1/16
  170362. * We work left-to-right on even rows, right-to-left on odd rows.
  170363. *
  170364. * We can get away with a single array (holding one row's worth of errors)
  170365. * by using it to store the current row's errors at pixel columns not yet
  170366. * processed, but the next row's errors at columns already processed. We
  170367. * need only a few extra variables to hold the errors immediately around the
  170368. * current column. (If we are lucky, those variables are in registers, but
  170369. * even if not, they're probably cheaper to access than array elements are.)
  170370. *
  170371. * The fserrors[] array is indexed [component#][position].
  170372. * We provide (#columns + 2) entries per component; the extra entry at each
  170373. * end saves us from special-casing the first and last pixels.
  170374. *
  170375. * Note: on a wide image, we might not have enough room in a PC's near data
  170376. * segment to hold the error array; so it is allocated with alloc_large.
  170377. */
  170378. #if BITS_IN_JSAMPLE == 8
  170379. typedef INT16 FSERROR; /* 16 bits should be enough */
  170380. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  170381. #else
  170382. typedef INT32 FSERROR; /* may need more than 16 bits */
  170383. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  170384. #endif
  170385. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  170386. /* Private subobject */
  170387. #define MAX_Q_COMPS 4 /* max components I can handle */
  170388. typedef struct {
  170389. struct jpeg_color_quantizer pub; /* public fields */
  170390. /* Initially allocated colormap is saved here */
  170391. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  170392. int sv_actual; /* number of entries in use */
  170393. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  170394. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  170395. * premultiplied as described above. Since colormap indexes must fit into
  170396. * JSAMPLEs, the entries of this array will too.
  170397. */
  170398. boolean is_padded; /* is the colorindex padded for odither? */
  170399. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  170400. /* Variables for ordered dithering */
  170401. int row_index; /* cur row's vertical index in dither matrix */
  170402. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  170403. /* Variables for Floyd-Steinberg dithering */
  170404. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  170405. boolean on_odd_row; /* flag to remember which row we are on */
  170406. } my_cquantizer;
  170407. typedef my_cquantizer * my_cquantize_ptr;
  170408. /*
  170409. * Policy-making subroutines for create_colormap and create_colorindex.
  170410. * These routines determine the colormap to be used. The rest of the module
  170411. * only assumes that the colormap is orthogonal.
  170412. *
  170413. * * select_ncolors decides how to divvy up the available colors
  170414. * among the components.
  170415. * * output_value defines the set of representative values for a component.
  170416. * * largest_input_value defines the mapping from input values to
  170417. * representative values for a component.
  170418. * Note that the latter two routines may impose different policies for
  170419. * different components, though this is not currently done.
  170420. */
  170421. LOCAL(int)
  170422. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  170423. /* Determine allocation of desired colors to components, */
  170424. /* and fill in Ncolors[] array to indicate choice. */
  170425. /* Return value is total number of colors (product of Ncolors[] values). */
  170426. {
  170427. int nc = cinfo->out_color_components; /* number of color components */
  170428. int max_colors = cinfo->desired_number_of_colors;
  170429. int total_colors, iroot, i, j;
  170430. boolean changed;
  170431. long temp;
  170432. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  170433. /* We can allocate at least the nc'th root of max_colors per component. */
  170434. /* Compute floor(nc'th root of max_colors). */
  170435. iroot = 1;
  170436. do {
  170437. iroot++;
  170438. temp = iroot; /* set temp = iroot ** nc */
  170439. for (i = 1; i < nc; i++)
  170440. temp *= iroot;
  170441. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  170442. iroot--; /* now iroot = floor(root) */
  170443. /* Must have at least 2 color values per component */
  170444. if (iroot < 2)
  170445. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  170446. /* Initialize to iroot color values for each component */
  170447. total_colors = 1;
  170448. for (i = 0; i < nc; i++) {
  170449. Ncolors[i] = iroot;
  170450. total_colors *= iroot;
  170451. }
  170452. /* We may be able to increment the count for one or more components without
  170453. * exceeding max_colors, though we know not all can be incremented.
  170454. * Sometimes, the first component can be incremented more than once!
  170455. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  170456. * In RGB colorspace, try to increment G first, then R, then B.
  170457. */
  170458. do {
  170459. changed = FALSE;
  170460. for (i = 0; i < nc; i++) {
  170461. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  170462. /* calculate new total_colors if Ncolors[j] is incremented */
  170463. temp = total_colors / Ncolors[j];
  170464. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  170465. if (temp > (long) max_colors)
  170466. break; /* won't fit, done with this pass */
  170467. Ncolors[j]++; /* OK, apply the increment */
  170468. total_colors = (int) temp;
  170469. changed = TRUE;
  170470. }
  170471. } while (changed);
  170472. return total_colors;
  170473. }
  170474. LOCAL(int)
  170475. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  170476. /* Return j'th output value, where j will range from 0 to maxj */
  170477. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  170478. {
  170479. /* We always provide values 0 and MAXJSAMPLE for each component;
  170480. * any additional values are equally spaced between these limits.
  170481. * (Forcing the upper and lower values to the limits ensures that
  170482. * dithering can't produce a color outside the selected gamut.)
  170483. */
  170484. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  170485. }
  170486. LOCAL(int)
  170487. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  170488. /* Return largest input value that should map to j'th output value */
  170489. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  170490. {
  170491. /* Breakpoints are halfway between values returned by output_value */
  170492. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  170493. }
  170494. /*
  170495. * Create the colormap.
  170496. */
  170497. LOCAL(void)
  170498. create_colormap (j_decompress_ptr cinfo)
  170499. {
  170500. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170501. JSAMPARRAY colormap; /* Created colormap */
  170502. int total_colors; /* Number of distinct output colors */
  170503. int i,j,k, nci, blksize, blkdist, ptr, val;
  170504. /* Select number of colors for each component */
  170505. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  170506. /* Report selected color counts */
  170507. if (cinfo->out_color_components == 3)
  170508. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  170509. total_colors, cquantize->Ncolors[0],
  170510. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  170511. else
  170512. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  170513. /* Allocate and fill in the colormap. */
  170514. /* The colors are ordered in the map in standard row-major order, */
  170515. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  170516. colormap = (*cinfo->mem->alloc_sarray)
  170517. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170518. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  170519. /* blksize is number of adjacent repeated entries for a component */
  170520. /* blkdist is distance between groups of identical entries for a component */
  170521. blkdist = total_colors;
  170522. for (i = 0; i < cinfo->out_color_components; i++) {
  170523. /* fill in colormap entries for i'th color component */
  170524. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170525. blksize = blkdist / nci;
  170526. for (j = 0; j < nci; j++) {
  170527. /* Compute j'th output value (out of nci) for component */
  170528. val = output_value(cinfo, i, j, nci-1);
  170529. /* Fill in all colormap entries that have this value of this component */
  170530. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  170531. /* fill in blksize entries beginning at ptr */
  170532. for (k = 0; k < blksize; k++)
  170533. colormap[i][ptr+k] = (JSAMPLE) val;
  170534. }
  170535. }
  170536. blkdist = blksize; /* blksize of this color is blkdist of next */
  170537. }
  170538. /* Save the colormap in private storage,
  170539. * where it will survive color quantization mode changes.
  170540. */
  170541. cquantize->sv_colormap = colormap;
  170542. cquantize->sv_actual = total_colors;
  170543. }
  170544. /*
  170545. * Create the color index table.
  170546. */
  170547. LOCAL(void)
  170548. create_colorindex (j_decompress_ptr cinfo)
  170549. {
  170550. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170551. JSAMPROW indexptr;
  170552. int i,j,k, nci, blksize, val, pad;
  170553. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  170554. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  170555. * This is not necessary in the other dithering modes. However, we
  170556. * flag whether it was done in case user changes dithering mode.
  170557. */
  170558. if (cinfo->dither_mode == JDITHER_ORDERED) {
  170559. pad = MAXJSAMPLE*2;
  170560. cquantize->is_padded = TRUE;
  170561. } else {
  170562. pad = 0;
  170563. cquantize->is_padded = FALSE;
  170564. }
  170565. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  170566. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170567. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  170568. (JDIMENSION) cinfo->out_color_components);
  170569. /* blksize is number of adjacent repeated entries for a component */
  170570. blksize = cquantize->sv_actual;
  170571. for (i = 0; i < cinfo->out_color_components; i++) {
  170572. /* fill in colorindex entries for i'th color component */
  170573. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170574. blksize = blksize / nci;
  170575. /* adjust colorindex pointers to provide padding at negative indexes. */
  170576. if (pad)
  170577. cquantize->colorindex[i] += MAXJSAMPLE;
  170578. /* in loop, val = index of current output value, */
  170579. /* and k = largest j that maps to current val */
  170580. indexptr = cquantize->colorindex[i];
  170581. val = 0;
  170582. k = largest_input_value(cinfo, i, 0, nci-1);
  170583. for (j = 0; j <= MAXJSAMPLE; j++) {
  170584. while (j > k) /* advance val if past boundary */
  170585. k = largest_input_value(cinfo, i, ++val, nci-1);
  170586. /* premultiply so that no multiplication needed in main processing */
  170587. indexptr[j] = (JSAMPLE) (val * blksize);
  170588. }
  170589. /* Pad at both ends if necessary */
  170590. if (pad)
  170591. for (j = 1; j <= MAXJSAMPLE; j++) {
  170592. indexptr[-j] = indexptr[0];
  170593. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  170594. }
  170595. }
  170596. }
  170597. /*
  170598. * Create an ordered-dither array for a component having ncolors
  170599. * distinct output values.
  170600. */
  170601. LOCAL(ODITHER_MATRIX_PTR)
  170602. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  170603. {
  170604. ODITHER_MATRIX_PTR odither;
  170605. int j,k;
  170606. INT32 num,den;
  170607. odither = (ODITHER_MATRIX_PTR)
  170608. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170609. SIZEOF(ODITHER_MATRIX));
  170610. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  170611. * Hence the dither value for the matrix cell with fill order f
  170612. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  170613. * On 16-bit-int machine, be careful to avoid overflow.
  170614. */
  170615. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  170616. for (j = 0; j < ODITHER_SIZE; j++) {
  170617. for (k = 0; k < ODITHER_SIZE; k++) {
  170618. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  170619. * MAXJSAMPLE;
  170620. /* Ensure round towards zero despite C's lack of consistency
  170621. * about rounding negative values in integer division...
  170622. */
  170623. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  170624. }
  170625. }
  170626. return odither;
  170627. }
  170628. /*
  170629. * Create the ordered-dither tables.
  170630. * Components having the same number of representative colors may
  170631. * share a dither table.
  170632. */
  170633. LOCAL(void)
  170634. create_odither_tables (j_decompress_ptr cinfo)
  170635. {
  170636. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170637. ODITHER_MATRIX_PTR odither;
  170638. int i, j, nci;
  170639. for (i = 0; i < cinfo->out_color_components; i++) {
  170640. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170641. odither = NULL; /* search for matching prior component */
  170642. for (j = 0; j < i; j++) {
  170643. if (nci == cquantize->Ncolors[j]) {
  170644. odither = cquantize->odither[j];
  170645. break;
  170646. }
  170647. }
  170648. if (odither == NULL) /* need a new table? */
  170649. odither = make_odither_array(cinfo, nci);
  170650. cquantize->odither[i] = odither;
  170651. }
  170652. }
  170653. /*
  170654. * Map some rows of pixels to the output colormapped representation.
  170655. */
  170656. METHODDEF(void)
  170657. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170658. JSAMPARRAY output_buf, int num_rows)
  170659. /* General case, no dithering */
  170660. {
  170661. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170662. JSAMPARRAY colorindex = cquantize->colorindex;
  170663. register int pixcode, ci;
  170664. register JSAMPROW ptrin, ptrout;
  170665. int row;
  170666. JDIMENSION col;
  170667. JDIMENSION width = cinfo->output_width;
  170668. register int nc = cinfo->out_color_components;
  170669. for (row = 0; row < num_rows; row++) {
  170670. ptrin = input_buf[row];
  170671. ptrout = output_buf[row];
  170672. for (col = width; col > 0; col--) {
  170673. pixcode = 0;
  170674. for (ci = 0; ci < nc; ci++) {
  170675. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  170676. }
  170677. *ptrout++ = (JSAMPLE) pixcode;
  170678. }
  170679. }
  170680. }
  170681. METHODDEF(void)
  170682. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170683. JSAMPARRAY output_buf, int num_rows)
  170684. /* Fast path for out_color_components==3, no dithering */
  170685. {
  170686. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170687. register int pixcode;
  170688. register JSAMPROW ptrin, ptrout;
  170689. JSAMPROW colorindex0 = cquantize->colorindex[0];
  170690. JSAMPROW colorindex1 = cquantize->colorindex[1];
  170691. JSAMPROW colorindex2 = cquantize->colorindex[2];
  170692. int row;
  170693. JDIMENSION col;
  170694. JDIMENSION width = cinfo->output_width;
  170695. for (row = 0; row < num_rows; row++) {
  170696. ptrin = input_buf[row];
  170697. ptrout = output_buf[row];
  170698. for (col = width; col > 0; col--) {
  170699. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  170700. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  170701. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  170702. *ptrout++ = (JSAMPLE) pixcode;
  170703. }
  170704. }
  170705. }
  170706. METHODDEF(void)
  170707. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170708. JSAMPARRAY output_buf, int num_rows)
  170709. /* General case, with ordered dithering */
  170710. {
  170711. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170712. register JSAMPROW input_ptr;
  170713. register JSAMPROW output_ptr;
  170714. JSAMPROW colorindex_ci;
  170715. int * dither; /* points to active row of dither matrix */
  170716. int row_index, col_index; /* current indexes into dither matrix */
  170717. int nc = cinfo->out_color_components;
  170718. int ci;
  170719. int row;
  170720. JDIMENSION col;
  170721. JDIMENSION width = cinfo->output_width;
  170722. for (row = 0; row < num_rows; row++) {
  170723. /* Initialize output values to 0 so can process components separately */
  170724. jzero_far((void FAR *) output_buf[row],
  170725. (size_t) (width * SIZEOF(JSAMPLE)));
  170726. row_index = cquantize->row_index;
  170727. for (ci = 0; ci < nc; ci++) {
  170728. input_ptr = input_buf[row] + ci;
  170729. output_ptr = output_buf[row];
  170730. colorindex_ci = cquantize->colorindex[ci];
  170731. dither = cquantize->odither[ci][row_index];
  170732. col_index = 0;
  170733. for (col = width; col > 0; col--) {
  170734. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  170735. * select output value, accumulate into output code for this pixel.
  170736. * Range-limiting need not be done explicitly, as we have extended
  170737. * the colorindex table to produce the right answers for out-of-range
  170738. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  170739. * required amount of padding.
  170740. */
  170741. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  170742. input_ptr += nc;
  170743. output_ptr++;
  170744. col_index = (col_index + 1) & ODITHER_MASK;
  170745. }
  170746. }
  170747. /* Advance row index for next row */
  170748. row_index = (row_index + 1) & ODITHER_MASK;
  170749. cquantize->row_index = row_index;
  170750. }
  170751. }
  170752. METHODDEF(void)
  170753. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170754. JSAMPARRAY output_buf, int num_rows)
  170755. /* Fast path for out_color_components==3, with ordered dithering */
  170756. {
  170757. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170758. register int pixcode;
  170759. register JSAMPROW input_ptr;
  170760. register JSAMPROW output_ptr;
  170761. JSAMPROW colorindex0 = cquantize->colorindex[0];
  170762. JSAMPROW colorindex1 = cquantize->colorindex[1];
  170763. JSAMPROW colorindex2 = cquantize->colorindex[2];
  170764. int * dither0; /* points to active row of dither matrix */
  170765. int * dither1;
  170766. int * dither2;
  170767. int row_index, col_index; /* current indexes into dither matrix */
  170768. int row;
  170769. JDIMENSION col;
  170770. JDIMENSION width = cinfo->output_width;
  170771. for (row = 0; row < num_rows; row++) {
  170772. row_index = cquantize->row_index;
  170773. input_ptr = input_buf[row];
  170774. output_ptr = output_buf[row];
  170775. dither0 = cquantize->odither[0][row_index];
  170776. dither1 = cquantize->odither[1][row_index];
  170777. dither2 = cquantize->odither[2][row_index];
  170778. col_index = 0;
  170779. for (col = width; col > 0; col--) {
  170780. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  170781. dither0[col_index]]);
  170782. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  170783. dither1[col_index]]);
  170784. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  170785. dither2[col_index]]);
  170786. *output_ptr++ = (JSAMPLE) pixcode;
  170787. col_index = (col_index + 1) & ODITHER_MASK;
  170788. }
  170789. row_index = (row_index + 1) & ODITHER_MASK;
  170790. cquantize->row_index = row_index;
  170791. }
  170792. }
  170793. METHODDEF(void)
  170794. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170795. JSAMPARRAY output_buf, int num_rows)
  170796. /* General case, with Floyd-Steinberg dithering */
  170797. {
  170798. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170799. register LOCFSERROR cur; /* current error or pixel value */
  170800. LOCFSERROR belowerr; /* error for pixel below cur */
  170801. LOCFSERROR bpreverr; /* error for below/prev col */
  170802. LOCFSERROR bnexterr; /* error for below/next col */
  170803. LOCFSERROR delta;
  170804. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  170805. register JSAMPROW input_ptr;
  170806. register JSAMPROW output_ptr;
  170807. JSAMPROW colorindex_ci;
  170808. JSAMPROW colormap_ci;
  170809. int pixcode;
  170810. int nc = cinfo->out_color_components;
  170811. int dir; /* 1 for left-to-right, -1 for right-to-left */
  170812. int dirnc; /* dir * nc */
  170813. int ci;
  170814. int row;
  170815. JDIMENSION col;
  170816. JDIMENSION width = cinfo->output_width;
  170817. JSAMPLE *range_limit = cinfo->sample_range_limit;
  170818. SHIFT_TEMPS
  170819. for (row = 0; row < num_rows; row++) {
  170820. /* Initialize output values to 0 so can process components separately */
  170821. jzero_far((void FAR *) output_buf[row],
  170822. (size_t) (width * SIZEOF(JSAMPLE)));
  170823. for (ci = 0; ci < nc; ci++) {
  170824. input_ptr = input_buf[row] + ci;
  170825. output_ptr = output_buf[row];
  170826. if (cquantize->on_odd_row) {
  170827. /* work right to left in this row */
  170828. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  170829. output_ptr += width-1;
  170830. dir = -1;
  170831. dirnc = -nc;
  170832. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  170833. } else {
  170834. /* work left to right in this row */
  170835. dir = 1;
  170836. dirnc = nc;
  170837. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  170838. }
  170839. colorindex_ci = cquantize->colorindex[ci];
  170840. colormap_ci = cquantize->sv_colormap[ci];
  170841. /* Preset error values: no error propagated to first pixel from left */
  170842. cur = 0;
  170843. /* and no error propagated to row below yet */
  170844. belowerr = bpreverr = 0;
  170845. for (col = width; col > 0; col--) {
  170846. /* cur holds the error propagated from the previous pixel on the
  170847. * current line. Add the error propagated from the previous line
  170848. * to form the complete error correction term for this pixel, and
  170849. * round the error term (which is expressed * 16) to an integer.
  170850. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  170851. * for either sign of the error value.
  170852. * Note: errorptr points to *previous* column's array entry.
  170853. */
  170854. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  170855. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  170856. * The maximum error is +- MAXJSAMPLE; this sets the required size
  170857. * of the range_limit array.
  170858. */
  170859. cur += GETJSAMPLE(*input_ptr);
  170860. cur = GETJSAMPLE(range_limit[cur]);
  170861. /* Select output value, accumulate into output code for this pixel */
  170862. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  170863. *output_ptr += (JSAMPLE) pixcode;
  170864. /* Compute actual representation error at this pixel */
  170865. /* Note: we can do this even though we don't have the final */
  170866. /* pixel code, because the colormap is orthogonal. */
  170867. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  170868. /* Compute error fractions to be propagated to adjacent pixels.
  170869. * Add these into the running sums, and simultaneously shift the
  170870. * next-line error sums left by 1 column.
  170871. */
  170872. bnexterr = cur;
  170873. delta = cur * 2;
  170874. cur += delta; /* form error * 3 */
  170875. errorptr[0] = (FSERROR) (bpreverr + cur);
  170876. cur += delta; /* form error * 5 */
  170877. bpreverr = belowerr + cur;
  170878. belowerr = bnexterr;
  170879. cur += delta; /* form error * 7 */
  170880. /* At this point cur contains the 7/16 error value to be propagated
  170881. * to the next pixel on the current line, and all the errors for the
  170882. * next line have been shifted over. We are therefore ready to move on.
  170883. */
  170884. input_ptr += dirnc; /* advance input ptr to next column */
  170885. output_ptr += dir; /* advance output ptr to next column */
  170886. errorptr += dir; /* advance errorptr to current column */
  170887. }
  170888. /* Post-loop cleanup: we must unload the final error value into the
  170889. * final fserrors[] entry. Note we need not unload belowerr because
  170890. * it is for the dummy column before or after the actual array.
  170891. */
  170892. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  170893. }
  170894. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  170895. }
  170896. }
  170897. /*
  170898. * Allocate workspace for Floyd-Steinberg errors.
  170899. */
  170900. LOCAL(void)
  170901. alloc_fs_workspace (j_decompress_ptr cinfo)
  170902. {
  170903. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170904. size_t arraysize;
  170905. int i;
  170906. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  170907. for (i = 0; i < cinfo->out_color_components; i++) {
  170908. cquantize->fserrors[i] = (FSERRPTR)
  170909. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  170910. }
  170911. }
  170912. /*
  170913. * Initialize for one-pass color quantization.
  170914. */
  170915. METHODDEF(void)
  170916. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  170917. {
  170918. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170919. size_t arraysize;
  170920. int i;
  170921. /* Install my colormap. */
  170922. cinfo->colormap = cquantize->sv_colormap;
  170923. cinfo->actual_number_of_colors = cquantize->sv_actual;
  170924. /* Initialize for desired dithering mode. */
  170925. switch (cinfo->dither_mode) {
  170926. case JDITHER_NONE:
  170927. if (cinfo->out_color_components == 3)
  170928. cquantize->pub.color_quantize = color_quantize3;
  170929. else
  170930. cquantize->pub.color_quantize = color_quantize;
  170931. break;
  170932. case JDITHER_ORDERED:
  170933. if (cinfo->out_color_components == 3)
  170934. cquantize->pub.color_quantize = quantize3_ord_dither;
  170935. else
  170936. cquantize->pub.color_quantize = quantize_ord_dither;
  170937. cquantize->row_index = 0; /* initialize state for ordered dither */
  170938. /* If user changed to ordered dither from another mode,
  170939. * we must recreate the color index table with padding.
  170940. * This will cost extra space, but probably isn't very likely.
  170941. */
  170942. if (! cquantize->is_padded)
  170943. create_colorindex(cinfo);
  170944. /* Create ordered-dither tables if we didn't already. */
  170945. if (cquantize->odither[0] == NULL)
  170946. create_odither_tables(cinfo);
  170947. break;
  170948. case JDITHER_FS:
  170949. cquantize->pub.color_quantize = quantize_fs_dither;
  170950. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  170951. /* Allocate Floyd-Steinberg workspace if didn't already. */
  170952. if (cquantize->fserrors[0] == NULL)
  170953. alloc_fs_workspace(cinfo);
  170954. /* Initialize the propagated errors to zero. */
  170955. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  170956. for (i = 0; i < cinfo->out_color_components; i++)
  170957. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  170958. break;
  170959. default:
  170960. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170961. break;
  170962. }
  170963. }
  170964. /*
  170965. * Finish up at the end of the pass.
  170966. */
  170967. METHODDEF(void)
  170968. finish_pass_1_quant (j_decompress_ptr cinfo)
  170969. {
  170970. /* no work in 1-pass case */
  170971. }
  170972. /*
  170973. * Switch to a new external colormap between output passes.
  170974. * Shouldn't get to this module!
  170975. */
  170976. METHODDEF(void)
  170977. new_color_map_1_quant (j_decompress_ptr cinfo)
  170978. {
  170979. ERREXIT(cinfo, JERR_MODE_CHANGE);
  170980. }
  170981. /*
  170982. * Module initialization routine for 1-pass color quantization.
  170983. */
  170984. GLOBAL(void)
  170985. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  170986. {
  170987. my_cquantize_ptr cquantize;
  170988. cquantize = (my_cquantize_ptr)
  170989. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170990. SIZEOF(my_cquantizer));
  170991. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  170992. cquantize->pub.start_pass = start_pass_1_quant;
  170993. cquantize->pub.finish_pass = finish_pass_1_quant;
  170994. cquantize->pub.new_color_map = new_color_map_1_quant;
  170995. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  170996. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  170997. /* Make sure my internal arrays won't overflow */
  170998. if (cinfo->out_color_components > MAX_Q_COMPS)
  170999. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  171000. /* Make sure colormap indexes can be represented by JSAMPLEs */
  171001. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  171002. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  171003. /* Create the colormap and color index table. */
  171004. create_colormap(cinfo);
  171005. create_colorindex(cinfo);
  171006. /* Allocate Floyd-Steinberg workspace now if requested.
  171007. * We do this now since it is FAR storage and may affect the memory
  171008. * manager's space calculations. If the user changes to FS dither
  171009. * mode in a later pass, we will allocate the space then, and will
  171010. * possibly overrun the max_memory_to_use setting.
  171011. */
  171012. if (cinfo->dither_mode == JDITHER_FS)
  171013. alloc_fs_workspace(cinfo);
  171014. }
  171015. #endif /* QUANT_1PASS_SUPPORTED */
  171016. /********* End of inlined file: jquant1.c *********/
  171017. /********* Start of inlined file: jquant2.c *********/
  171018. #define JPEG_INTERNALS
  171019. #ifdef QUANT_2PASS_SUPPORTED
  171020. /*
  171021. * This module implements the well-known Heckbert paradigm for color
  171022. * quantization. Most of the ideas used here can be traced back to
  171023. * Heckbert's seminal paper
  171024. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  171025. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  171026. *
  171027. * In the first pass over the image, we accumulate a histogram showing the
  171028. * usage count of each possible color. To keep the histogram to a reasonable
  171029. * size, we reduce the precision of the input; typical practice is to retain
  171030. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  171031. * in the same histogram cell.
  171032. *
  171033. * Next, the color-selection step begins with a box representing the whole
  171034. * color space, and repeatedly splits the "largest" remaining box until we
  171035. * have as many boxes as desired colors. Then the mean color in each
  171036. * remaining box becomes one of the possible output colors.
  171037. *
  171038. * The second pass over the image maps each input pixel to the closest output
  171039. * color (optionally after applying a Floyd-Steinberg dithering correction).
  171040. * This mapping is logically trivial, but making it go fast enough requires
  171041. * considerable care.
  171042. *
  171043. * Heckbert-style quantizers vary a good deal in their policies for choosing
  171044. * the "largest" box and deciding where to cut it. The particular policies
  171045. * used here have proved out well in experimental comparisons, but better ones
  171046. * may yet be found.
  171047. *
  171048. * In earlier versions of the IJG code, this module quantized in YCbCr color
  171049. * space, processing the raw upsampled data without a color conversion step.
  171050. * This allowed the color conversion math to be done only once per colormap
  171051. * entry, not once per pixel. However, that optimization precluded other
  171052. * useful optimizations (such as merging color conversion with upsampling)
  171053. * and it also interfered with desired capabilities such as quantizing to an
  171054. * externally-supplied colormap. We have therefore abandoned that approach.
  171055. * The present code works in the post-conversion color space, typically RGB.
  171056. *
  171057. * To improve the visual quality of the results, we actually work in scaled
  171058. * RGB space, giving G distances more weight than R, and R in turn more than
  171059. * B. To do everything in integer math, we must use integer scale factors.
  171060. * The 2/3/1 scale factors used here correspond loosely to the relative
  171061. * weights of the colors in the NTSC grayscale equation.
  171062. * If you want to use this code to quantize a non-RGB color space, you'll
  171063. * probably need to change these scale factors.
  171064. */
  171065. #define R_SCALE 2 /* scale R distances by this much */
  171066. #define G_SCALE 3 /* scale G distances by this much */
  171067. #define B_SCALE 1 /* and B by this much */
  171068. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  171069. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  171070. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  171071. * you'll get compile errors until you extend this logic. In that case
  171072. * you'll probably want to tweak the histogram sizes too.
  171073. */
  171074. #if RGB_RED == 0
  171075. #define C0_SCALE R_SCALE
  171076. #endif
  171077. #if RGB_BLUE == 0
  171078. #define C0_SCALE B_SCALE
  171079. #endif
  171080. #if RGB_GREEN == 1
  171081. #define C1_SCALE G_SCALE
  171082. #endif
  171083. #if RGB_RED == 2
  171084. #define C2_SCALE R_SCALE
  171085. #endif
  171086. #if RGB_BLUE == 2
  171087. #define C2_SCALE B_SCALE
  171088. #endif
  171089. /*
  171090. * First we have the histogram data structure and routines for creating it.
  171091. *
  171092. * The number of bits of precision can be adjusted by changing these symbols.
  171093. * We recommend keeping 6 bits for G and 5 each for R and B.
  171094. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  171095. * better results; if you are short of memory, 5 bits all around will save
  171096. * some space but degrade the results.
  171097. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  171098. * (preferably unsigned long) for each cell. In practice this is overkill;
  171099. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  171100. * and clamping those that do overflow to the maximum value will give close-
  171101. * enough results. This reduces the recommended histogram size from 256Kb
  171102. * to 128Kb, which is a useful savings on PC-class machines.
  171103. * (In the second pass the histogram space is re-used for pixel mapping data;
  171104. * in that capacity, each cell must be able to store zero to the number of
  171105. * desired colors. 16 bits/cell is plenty for that too.)
  171106. * Since the JPEG code is intended to run in small memory model on 80x86
  171107. * machines, we can't just allocate the histogram in one chunk. Instead
  171108. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  171109. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  171110. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  171111. * on 80x86 machines, the pointer row is in near memory but the actual
  171112. * arrays are in far memory (same arrangement as we use for image arrays).
  171113. */
  171114. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  171115. /* These will do the right thing for either R,G,B or B,G,R color order,
  171116. * but you may not like the results for other color orders.
  171117. */
  171118. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  171119. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  171120. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  171121. /* Number of elements along histogram axes. */
  171122. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  171123. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  171124. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  171125. /* These are the amounts to shift an input value to get a histogram index. */
  171126. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  171127. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  171128. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  171129. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  171130. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  171131. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  171132. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  171133. typedef hist2d * hist3d; /* type for top-level pointer */
  171134. /* Declarations for Floyd-Steinberg dithering.
  171135. *
  171136. * Errors are accumulated into the array fserrors[], at a resolution of
  171137. * 1/16th of a pixel count. The error at a given pixel is propagated
  171138. * to its not-yet-processed neighbors using the standard F-S fractions,
  171139. * ... (here) 7/16
  171140. * 3/16 5/16 1/16
  171141. * We work left-to-right on even rows, right-to-left on odd rows.
  171142. *
  171143. * We can get away with a single array (holding one row's worth of errors)
  171144. * by using it to store the current row's errors at pixel columns not yet
  171145. * processed, but the next row's errors at columns already processed. We
  171146. * need only a few extra variables to hold the errors immediately around the
  171147. * current column. (If we are lucky, those variables are in registers, but
  171148. * even if not, they're probably cheaper to access than array elements are.)
  171149. *
  171150. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  171151. * each end saves us from special-casing the first and last pixels.
  171152. * Each entry is three values long, one value for each color component.
  171153. *
  171154. * Note: on a wide image, we might not have enough room in a PC's near data
  171155. * segment to hold the error array; so it is allocated with alloc_large.
  171156. */
  171157. #if BITS_IN_JSAMPLE == 8
  171158. typedef INT16 FSERROR; /* 16 bits should be enough */
  171159. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171160. #else
  171161. typedef INT32 FSERROR; /* may need more than 16 bits */
  171162. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171163. #endif
  171164. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171165. /* Private subobject */
  171166. typedef struct {
  171167. struct jpeg_color_quantizer pub; /* public fields */
  171168. /* Space for the eventually created colormap is stashed here */
  171169. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  171170. int desired; /* desired # of colors = size of colormap */
  171171. /* Variables for accumulating image statistics */
  171172. hist3d histogram; /* pointer to the histogram */
  171173. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  171174. /* Variables for Floyd-Steinberg dithering */
  171175. FSERRPTR fserrors; /* accumulated errors */
  171176. boolean on_odd_row; /* flag to remember which row we are on */
  171177. int * error_limiter; /* table for clamping the applied error */
  171178. } my_cquantizer2;
  171179. typedef my_cquantizer2 * my_cquantize_ptr2;
  171180. /*
  171181. * Prescan some rows of pixels.
  171182. * In this module the prescan simply updates the histogram, which has been
  171183. * initialized to zeroes by start_pass.
  171184. * An output_buf parameter is required by the method signature, but no data
  171185. * is actually output (in fact the buffer controller is probably passing a
  171186. * NULL pointer).
  171187. */
  171188. METHODDEF(void)
  171189. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171190. JSAMPARRAY output_buf, int num_rows)
  171191. {
  171192. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171193. register JSAMPROW ptr;
  171194. register histptr histp;
  171195. register hist3d histogram = cquantize->histogram;
  171196. int row;
  171197. JDIMENSION col;
  171198. JDIMENSION width = cinfo->output_width;
  171199. for (row = 0; row < num_rows; row++) {
  171200. ptr = input_buf[row];
  171201. for (col = width; col > 0; col--) {
  171202. /* get pixel value and index into the histogram */
  171203. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  171204. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  171205. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  171206. /* increment, check for overflow and undo increment if so. */
  171207. if (++(*histp) <= 0)
  171208. (*histp)--;
  171209. ptr += 3;
  171210. }
  171211. }
  171212. }
  171213. /*
  171214. * Next we have the really interesting routines: selection of a colormap
  171215. * given the completed histogram.
  171216. * These routines work with a list of "boxes", each representing a rectangular
  171217. * subset of the input color space (to histogram precision).
  171218. */
  171219. typedef struct {
  171220. /* The bounds of the box (inclusive); expressed as histogram indexes */
  171221. int c0min, c0max;
  171222. int c1min, c1max;
  171223. int c2min, c2max;
  171224. /* The volume (actually 2-norm) of the box */
  171225. INT32 volume;
  171226. /* The number of nonzero histogram cells within this box */
  171227. long colorcount;
  171228. } box;
  171229. typedef box * boxptr;
  171230. LOCAL(boxptr)
  171231. find_biggest_color_pop (boxptr boxlist, int numboxes)
  171232. /* Find the splittable box with the largest color population */
  171233. /* Returns NULL if no splittable boxes remain */
  171234. {
  171235. register boxptr boxp;
  171236. register int i;
  171237. register long maxc = 0;
  171238. boxptr which = NULL;
  171239. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171240. if (boxp->colorcount > maxc && boxp->volume > 0) {
  171241. which = boxp;
  171242. maxc = boxp->colorcount;
  171243. }
  171244. }
  171245. return which;
  171246. }
  171247. LOCAL(boxptr)
  171248. find_biggest_volume (boxptr boxlist, int numboxes)
  171249. /* Find the splittable box with the largest (scaled) volume */
  171250. /* Returns NULL if no splittable boxes remain */
  171251. {
  171252. register boxptr boxp;
  171253. register int i;
  171254. register INT32 maxv = 0;
  171255. boxptr which = NULL;
  171256. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171257. if (boxp->volume > maxv) {
  171258. which = boxp;
  171259. maxv = boxp->volume;
  171260. }
  171261. }
  171262. return which;
  171263. }
  171264. LOCAL(void)
  171265. update_box (j_decompress_ptr cinfo, boxptr boxp)
  171266. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  171267. /* and recompute its volume and population */
  171268. {
  171269. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171270. hist3d histogram = cquantize->histogram;
  171271. histptr histp;
  171272. int c0,c1,c2;
  171273. int c0min,c0max,c1min,c1max,c2min,c2max;
  171274. INT32 dist0,dist1,dist2;
  171275. long ccount;
  171276. c0min = boxp->c0min; c0max = boxp->c0max;
  171277. c1min = boxp->c1min; c1max = boxp->c1max;
  171278. c2min = boxp->c2min; c2max = boxp->c2max;
  171279. if (c0max > c0min)
  171280. for (c0 = c0min; c0 <= c0max; c0++)
  171281. for (c1 = c1min; c1 <= c1max; c1++) {
  171282. histp = & histogram[c0][c1][c2min];
  171283. for (c2 = c2min; c2 <= c2max; c2++)
  171284. if (*histp++ != 0) {
  171285. boxp->c0min = c0min = c0;
  171286. goto have_c0min;
  171287. }
  171288. }
  171289. have_c0min:
  171290. if (c0max > c0min)
  171291. for (c0 = c0max; c0 >= c0min; c0--)
  171292. for (c1 = c1min; c1 <= c1max; c1++) {
  171293. histp = & histogram[c0][c1][c2min];
  171294. for (c2 = c2min; c2 <= c2max; c2++)
  171295. if (*histp++ != 0) {
  171296. boxp->c0max = c0max = c0;
  171297. goto have_c0max;
  171298. }
  171299. }
  171300. have_c0max:
  171301. if (c1max > c1min)
  171302. for (c1 = c1min; c1 <= c1max; c1++)
  171303. for (c0 = c0min; c0 <= c0max; c0++) {
  171304. histp = & histogram[c0][c1][c2min];
  171305. for (c2 = c2min; c2 <= c2max; c2++)
  171306. if (*histp++ != 0) {
  171307. boxp->c1min = c1min = c1;
  171308. goto have_c1min;
  171309. }
  171310. }
  171311. have_c1min:
  171312. if (c1max > c1min)
  171313. for (c1 = c1max; c1 >= c1min; c1--)
  171314. for (c0 = c0min; c0 <= c0max; c0++) {
  171315. histp = & histogram[c0][c1][c2min];
  171316. for (c2 = c2min; c2 <= c2max; c2++)
  171317. if (*histp++ != 0) {
  171318. boxp->c1max = c1max = c1;
  171319. goto have_c1max;
  171320. }
  171321. }
  171322. have_c1max:
  171323. if (c2max > c2min)
  171324. for (c2 = c2min; c2 <= c2max; c2++)
  171325. for (c0 = c0min; c0 <= c0max; c0++) {
  171326. histp = & histogram[c0][c1min][c2];
  171327. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  171328. if (*histp != 0) {
  171329. boxp->c2min = c2min = c2;
  171330. goto have_c2min;
  171331. }
  171332. }
  171333. have_c2min:
  171334. if (c2max > c2min)
  171335. for (c2 = c2max; c2 >= c2min; c2--)
  171336. for (c0 = c0min; c0 <= c0max; c0++) {
  171337. histp = & histogram[c0][c1min][c2];
  171338. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  171339. if (*histp != 0) {
  171340. boxp->c2max = c2max = c2;
  171341. goto have_c2max;
  171342. }
  171343. }
  171344. have_c2max:
  171345. /* Update box volume.
  171346. * We use 2-norm rather than real volume here; this biases the method
  171347. * against making long narrow boxes, and it has the side benefit that
  171348. * a box is splittable iff norm > 0.
  171349. * Since the differences are expressed in histogram-cell units,
  171350. * we have to shift back to JSAMPLE units to get consistent distances;
  171351. * after which, we scale according to the selected distance scale factors.
  171352. */
  171353. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  171354. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  171355. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  171356. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  171357. /* Now scan remaining volume of box and compute population */
  171358. ccount = 0;
  171359. for (c0 = c0min; c0 <= c0max; c0++)
  171360. for (c1 = c1min; c1 <= c1max; c1++) {
  171361. histp = & histogram[c0][c1][c2min];
  171362. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  171363. if (*histp != 0) {
  171364. ccount++;
  171365. }
  171366. }
  171367. boxp->colorcount = ccount;
  171368. }
  171369. LOCAL(int)
  171370. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  171371. int desired_colors)
  171372. /* Repeatedly select and split the largest box until we have enough boxes */
  171373. {
  171374. int n,lb;
  171375. int c0,c1,c2,cmax;
  171376. register boxptr b1,b2;
  171377. while (numboxes < desired_colors) {
  171378. /* Select box to split.
  171379. * Current algorithm: by population for first half, then by volume.
  171380. */
  171381. if (numboxes*2 <= desired_colors) {
  171382. b1 = find_biggest_color_pop(boxlist, numboxes);
  171383. } else {
  171384. b1 = find_biggest_volume(boxlist, numboxes);
  171385. }
  171386. if (b1 == NULL) /* no splittable boxes left! */
  171387. break;
  171388. b2 = &boxlist[numboxes]; /* where new box will go */
  171389. /* Copy the color bounds to the new box. */
  171390. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  171391. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  171392. /* Choose which axis to split the box on.
  171393. * Current algorithm: longest scaled axis.
  171394. * See notes in update_box about scaling distances.
  171395. */
  171396. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  171397. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  171398. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  171399. /* We want to break any ties in favor of green, then red, blue last.
  171400. * This code does the right thing for R,G,B or B,G,R color orders only.
  171401. */
  171402. #if RGB_RED == 0
  171403. cmax = c1; n = 1;
  171404. if (c0 > cmax) { cmax = c0; n = 0; }
  171405. if (c2 > cmax) { n = 2; }
  171406. #else
  171407. cmax = c1; n = 1;
  171408. if (c2 > cmax) { cmax = c2; n = 2; }
  171409. if (c0 > cmax) { n = 0; }
  171410. #endif
  171411. /* Choose split point along selected axis, and update box bounds.
  171412. * Current algorithm: split at halfway point.
  171413. * (Since the box has been shrunk to minimum volume,
  171414. * any split will produce two nonempty subboxes.)
  171415. * Note that lb value is max for lower box, so must be < old max.
  171416. */
  171417. switch (n) {
  171418. case 0:
  171419. lb = (b1->c0max + b1->c0min) / 2;
  171420. b1->c0max = lb;
  171421. b2->c0min = lb+1;
  171422. break;
  171423. case 1:
  171424. lb = (b1->c1max + b1->c1min) / 2;
  171425. b1->c1max = lb;
  171426. b2->c1min = lb+1;
  171427. break;
  171428. case 2:
  171429. lb = (b1->c2max + b1->c2min) / 2;
  171430. b1->c2max = lb;
  171431. b2->c2min = lb+1;
  171432. break;
  171433. }
  171434. /* Update stats for boxes */
  171435. update_box(cinfo, b1);
  171436. update_box(cinfo, b2);
  171437. numboxes++;
  171438. }
  171439. return numboxes;
  171440. }
  171441. LOCAL(void)
  171442. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  171443. /* Compute representative color for a box, put it in colormap[icolor] */
  171444. {
  171445. /* Current algorithm: mean weighted by pixels (not colors) */
  171446. /* Note it is important to get the rounding correct! */
  171447. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171448. hist3d histogram = cquantize->histogram;
  171449. histptr histp;
  171450. int c0,c1,c2;
  171451. int c0min,c0max,c1min,c1max,c2min,c2max;
  171452. long count;
  171453. long total = 0;
  171454. long c0total = 0;
  171455. long c1total = 0;
  171456. long c2total = 0;
  171457. c0min = boxp->c0min; c0max = boxp->c0max;
  171458. c1min = boxp->c1min; c1max = boxp->c1max;
  171459. c2min = boxp->c2min; c2max = boxp->c2max;
  171460. for (c0 = c0min; c0 <= c0max; c0++)
  171461. for (c1 = c1min; c1 <= c1max; c1++) {
  171462. histp = & histogram[c0][c1][c2min];
  171463. for (c2 = c2min; c2 <= c2max; c2++) {
  171464. if ((count = *histp++) != 0) {
  171465. total += count;
  171466. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  171467. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  171468. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  171469. }
  171470. }
  171471. }
  171472. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  171473. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  171474. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  171475. }
  171476. LOCAL(void)
  171477. select_colors (j_decompress_ptr cinfo, int desired_colors)
  171478. /* Master routine for color selection */
  171479. {
  171480. boxptr boxlist;
  171481. int numboxes;
  171482. int i;
  171483. /* Allocate workspace for box list */
  171484. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  171485. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  171486. /* Initialize one box containing whole space */
  171487. numboxes = 1;
  171488. boxlist[0].c0min = 0;
  171489. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  171490. boxlist[0].c1min = 0;
  171491. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  171492. boxlist[0].c2min = 0;
  171493. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  171494. /* Shrink it to actually-used volume and set its statistics */
  171495. update_box(cinfo, & boxlist[0]);
  171496. /* Perform median-cut to produce final box list */
  171497. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  171498. /* Compute the representative color for each box, fill colormap */
  171499. for (i = 0; i < numboxes; i++)
  171500. compute_color(cinfo, & boxlist[i], i);
  171501. cinfo->actual_number_of_colors = numboxes;
  171502. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  171503. }
  171504. /*
  171505. * These routines are concerned with the time-critical task of mapping input
  171506. * colors to the nearest color in the selected colormap.
  171507. *
  171508. * We re-use the histogram space as an "inverse color map", essentially a
  171509. * cache for the results of nearest-color searches. All colors within a
  171510. * histogram cell will be mapped to the same colormap entry, namely the one
  171511. * closest to the cell's center. This may not be quite the closest entry to
  171512. * the actual input color, but it's almost as good. A zero in the cache
  171513. * indicates we haven't found the nearest color for that cell yet; the array
  171514. * is cleared to zeroes before starting the mapping pass. When we find the
  171515. * nearest color for a cell, its colormap index plus one is recorded in the
  171516. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  171517. * when they need to use an unfilled entry in the cache.
  171518. *
  171519. * Our method of efficiently finding nearest colors is based on the "locally
  171520. * sorted search" idea described by Heckbert and on the incremental distance
  171521. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  171522. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  171523. * the distances from a given colormap entry to each cell of the histogram can
  171524. * be computed quickly using an incremental method: the differences between
  171525. * distances to adjacent cells themselves differ by a constant. This allows a
  171526. * fairly fast implementation of the "brute force" approach of computing the
  171527. * distance from every colormap entry to every histogram cell. Unfortunately,
  171528. * it needs a work array to hold the best-distance-so-far for each histogram
  171529. * cell (because the inner loop has to be over cells, not colormap entries).
  171530. * The work array elements have to be INT32s, so the work array would need
  171531. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  171532. *
  171533. * To get around these problems, we apply Thomas' method to compute the
  171534. * nearest colors for only the cells within a small subbox of the histogram.
  171535. * The work array need be only as big as the subbox, so the memory usage
  171536. * problem is solved. Furthermore, we need not fill subboxes that are never
  171537. * referenced in pass2; many images use only part of the color gamut, so a
  171538. * fair amount of work is saved. An additional advantage of this
  171539. * approach is that we can apply Heckbert's locality criterion to quickly
  171540. * eliminate colormap entries that are far away from the subbox; typically
  171541. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  171542. * and we need not compute their distances to individual cells in the subbox.
  171543. * The speed of this approach is heavily influenced by the subbox size: too
  171544. * small means too much overhead, too big loses because Heckbert's criterion
  171545. * can't eliminate as many colormap entries. Empirically the best subbox
  171546. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  171547. *
  171548. * Thomas' article also describes a refined method which is asymptotically
  171549. * faster than the brute-force method, but it is also far more complex and
  171550. * cannot efficiently be applied to small subboxes. It is therefore not
  171551. * useful for programs intended to be portable to DOS machines. On machines
  171552. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  171553. * refined method might be faster than the present code --- but then again,
  171554. * it might not be any faster, and it's certainly more complicated.
  171555. */
  171556. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  171557. #define BOX_C0_LOG (HIST_C0_BITS-3)
  171558. #define BOX_C1_LOG (HIST_C1_BITS-3)
  171559. #define BOX_C2_LOG (HIST_C2_BITS-3)
  171560. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  171561. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  171562. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  171563. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  171564. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  171565. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  171566. /*
  171567. * The next three routines implement inverse colormap filling. They could
  171568. * all be folded into one big routine, but splitting them up this way saves
  171569. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  171570. * and may allow some compilers to produce better code by registerizing more
  171571. * inner-loop variables.
  171572. */
  171573. LOCAL(int)
  171574. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  171575. JSAMPLE colorlist[])
  171576. /* Locate the colormap entries close enough to an update box to be candidates
  171577. * for the nearest entry to some cell(s) in the update box. The update box
  171578. * is specified by the center coordinates of its first cell. The number of
  171579. * candidate colormap entries is returned, and their colormap indexes are
  171580. * placed in colorlist[].
  171581. * This routine uses Heckbert's "locally sorted search" criterion to select
  171582. * the colors that need further consideration.
  171583. */
  171584. {
  171585. int numcolors = cinfo->actual_number_of_colors;
  171586. int maxc0, maxc1, maxc2;
  171587. int centerc0, centerc1, centerc2;
  171588. int i, x, ncolors;
  171589. INT32 minmaxdist, min_dist, max_dist, tdist;
  171590. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  171591. /* Compute true coordinates of update box's upper corner and center.
  171592. * Actually we compute the coordinates of the center of the upper-corner
  171593. * histogram cell, which are the upper bounds of the volume we care about.
  171594. * Note that since ">>" rounds down, the "center" values may be closer to
  171595. * min than to max; hence comparisons to them must be "<=", not "<".
  171596. */
  171597. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  171598. centerc0 = (minc0 + maxc0) >> 1;
  171599. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  171600. centerc1 = (minc1 + maxc1) >> 1;
  171601. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  171602. centerc2 = (minc2 + maxc2) >> 1;
  171603. /* For each color in colormap, find:
  171604. * 1. its minimum squared-distance to any point in the update box
  171605. * (zero if color is within update box);
  171606. * 2. its maximum squared-distance to any point in the update box.
  171607. * Both of these can be found by considering only the corners of the box.
  171608. * We save the minimum distance for each color in mindist[];
  171609. * only the smallest maximum distance is of interest.
  171610. */
  171611. minmaxdist = 0x7FFFFFFFL;
  171612. for (i = 0; i < numcolors; i++) {
  171613. /* We compute the squared-c0-distance term, then add in the other two. */
  171614. x = GETJSAMPLE(cinfo->colormap[0][i]);
  171615. if (x < minc0) {
  171616. tdist = (x - minc0) * C0_SCALE;
  171617. min_dist = tdist*tdist;
  171618. tdist = (x - maxc0) * C0_SCALE;
  171619. max_dist = tdist*tdist;
  171620. } else if (x > maxc0) {
  171621. tdist = (x - maxc0) * C0_SCALE;
  171622. min_dist = tdist*tdist;
  171623. tdist = (x - minc0) * C0_SCALE;
  171624. max_dist = tdist*tdist;
  171625. } else {
  171626. /* within cell range so no contribution to min_dist */
  171627. min_dist = 0;
  171628. if (x <= centerc0) {
  171629. tdist = (x - maxc0) * C0_SCALE;
  171630. max_dist = tdist*tdist;
  171631. } else {
  171632. tdist = (x - minc0) * C0_SCALE;
  171633. max_dist = tdist*tdist;
  171634. }
  171635. }
  171636. x = GETJSAMPLE(cinfo->colormap[1][i]);
  171637. if (x < minc1) {
  171638. tdist = (x - minc1) * C1_SCALE;
  171639. min_dist += tdist*tdist;
  171640. tdist = (x - maxc1) * C1_SCALE;
  171641. max_dist += tdist*tdist;
  171642. } else if (x > maxc1) {
  171643. tdist = (x - maxc1) * C1_SCALE;
  171644. min_dist += tdist*tdist;
  171645. tdist = (x - minc1) * C1_SCALE;
  171646. max_dist += tdist*tdist;
  171647. } else {
  171648. /* within cell range so no contribution to min_dist */
  171649. if (x <= centerc1) {
  171650. tdist = (x - maxc1) * C1_SCALE;
  171651. max_dist += tdist*tdist;
  171652. } else {
  171653. tdist = (x - minc1) * C1_SCALE;
  171654. max_dist += tdist*tdist;
  171655. }
  171656. }
  171657. x = GETJSAMPLE(cinfo->colormap[2][i]);
  171658. if (x < minc2) {
  171659. tdist = (x - minc2) * C2_SCALE;
  171660. min_dist += tdist*tdist;
  171661. tdist = (x - maxc2) * C2_SCALE;
  171662. max_dist += tdist*tdist;
  171663. } else if (x > maxc2) {
  171664. tdist = (x - maxc2) * C2_SCALE;
  171665. min_dist += tdist*tdist;
  171666. tdist = (x - minc2) * C2_SCALE;
  171667. max_dist += tdist*tdist;
  171668. } else {
  171669. /* within cell range so no contribution to min_dist */
  171670. if (x <= centerc2) {
  171671. tdist = (x - maxc2) * C2_SCALE;
  171672. max_dist += tdist*tdist;
  171673. } else {
  171674. tdist = (x - minc2) * C2_SCALE;
  171675. max_dist += tdist*tdist;
  171676. }
  171677. }
  171678. mindist[i] = min_dist; /* save away the results */
  171679. if (max_dist < minmaxdist)
  171680. minmaxdist = max_dist;
  171681. }
  171682. /* Now we know that no cell in the update box is more than minmaxdist
  171683. * away from some colormap entry. Therefore, only colors that are
  171684. * within minmaxdist of some part of the box need be considered.
  171685. */
  171686. ncolors = 0;
  171687. for (i = 0; i < numcolors; i++) {
  171688. if (mindist[i] <= minmaxdist)
  171689. colorlist[ncolors++] = (JSAMPLE) i;
  171690. }
  171691. return ncolors;
  171692. }
  171693. LOCAL(void)
  171694. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  171695. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  171696. /* Find the closest colormap entry for each cell in the update box,
  171697. * given the list of candidate colors prepared by find_nearby_colors.
  171698. * Return the indexes of the closest entries in the bestcolor[] array.
  171699. * This routine uses Thomas' incremental distance calculation method to
  171700. * find the distance from a colormap entry to successive cells in the box.
  171701. */
  171702. {
  171703. int ic0, ic1, ic2;
  171704. int i, icolor;
  171705. register INT32 * bptr; /* pointer into bestdist[] array */
  171706. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  171707. INT32 dist0, dist1; /* initial distance values */
  171708. register INT32 dist2; /* current distance in inner loop */
  171709. INT32 xx0, xx1; /* distance increments */
  171710. register INT32 xx2;
  171711. INT32 inc0, inc1, inc2; /* initial values for increments */
  171712. /* This array holds the distance to the nearest-so-far color for each cell */
  171713. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  171714. /* Initialize best-distance for each cell of the update box */
  171715. bptr = bestdist;
  171716. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  171717. *bptr++ = 0x7FFFFFFFL;
  171718. /* For each color selected by find_nearby_colors,
  171719. * compute its distance to the center of each cell in the box.
  171720. * If that's less than best-so-far, update best distance and color number.
  171721. */
  171722. /* Nominal steps between cell centers ("x" in Thomas article) */
  171723. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  171724. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  171725. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  171726. for (i = 0; i < numcolors; i++) {
  171727. icolor = GETJSAMPLE(colorlist[i]);
  171728. /* Compute (square of) distance from minc0/c1/c2 to this color */
  171729. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  171730. dist0 = inc0*inc0;
  171731. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  171732. dist0 += inc1*inc1;
  171733. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  171734. dist0 += inc2*inc2;
  171735. /* Form the initial difference increments */
  171736. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  171737. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  171738. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  171739. /* Now loop over all cells in box, updating distance per Thomas method */
  171740. bptr = bestdist;
  171741. cptr = bestcolor;
  171742. xx0 = inc0;
  171743. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  171744. dist1 = dist0;
  171745. xx1 = inc1;
  171746. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  171747. dist2 = dist1;
  171748. xx2 = inc2;
  171749. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  171750. if (dist2 < *bptr) {
  171751. *bptr = dist2;
  171752. *cptr = (JSAMPLE) icolor;
  171753. }
  171754. dist2 += xx2;
  171755. xx2 += 2 * STEP_C2 * STEP_C2;
  171756. bptr++;
  171757. cptr++;
  171758. }
  171759. dist1 += xx1;
  171760. xx1 += 2 * STEP_C1 * STEP_C1;
  171761. }
  171762. dist0 += xx0;
  171763. xx0 += 2 * STEP_C0 * STEP_C0;
  171764. }
  171765. }
  171766. }
  171767. LOCAL(void)
  171768. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  171769. /* Fill the inverse-colormap entries in the update box that contains */
  171770. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  171771. /* we can fill as many others as we wish.) */
  171772. {
  171773. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171774. hist3d histogram = cquantize->histogram;
  171775. int minc0, minc1, minc2; /* lower left corner of update box */
  171776. int ic0, ic1, ic2;
  171777. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  171778. register histptr cachep; /* pointer into main cache array */
  171779. /* This array lists the candidate colormap indexes. */
  171780. JSAMPLE colorlist[MAXNUMCOLORS];
  171781. int numcolors; /* number of candidate colors */
  171782. /* This array holds the actually closest colormap index for each cell. */
  171783. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  171784. /* Convert cell coordinates to update box ID */
  171785. c0 >>= BOX_C0_LOG;
  171786. c1 >>= BOX_C1_LOG;
  171787. c2 >>= BOX_C2_LOG;
  171788. /* Compute true coordinates of update box's origin corner.
  171789. * Actually we compute the coordinates of the center of the corner
  171790. * histogram cell, which are the lower bounds of the volume we care about.
  171791. */
  171792. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  171793. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  171794. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  171795. /* Determine which colormap entries are close enough to be candidates
  171796. * for the nearest entry to some cell in the update box.
  171797. */
  171798. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  171799. /* Determine the actually nearest colors. */
  171800. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  171801. bestcolor);
  171802. /* Save the best color numbers (plus 1) in the main cache array */
  171803. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  171804. c1 <<= BOX_C1_LOG;
  171805. c2 <<= BOX_C2_LOG;
  171806. cptr = bestcolor;
  171807. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  171808. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  171809. cachep = & histogram[c0+ic0][c1+ic1][c2];
  171810. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  171811. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  171812. }
  171813. }
  171814. }
  171815. }
  171816. /*
  171817. * Map some rows of pixels to the output colormapped representation.
  171818. */
  171819. METHODDEF(void)
  171820. pass2_no_dither (j_decompress_ptr cinfo,
  171821. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  171822. /* This version performs no dithering */
  171823. {
  171824. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171825. hist3d histogram = cquantize->histogram;
  171826. register JSAMPROW inptr, outptr;
  171827. register histptr cachep;
  171828. register int c0, c1, c2;
  171829. int row;
  171830. JDIMENSION col;
  171831. JDIMENSION width = cinfo->output_width;
  171832. for (row = 0; row < num_rows; row++) {
  171833. inptr = input_buf[row];
  171834. outptr = output_buf[row];
  171835. for (col = width; col > 0; col--) {
  171836. /* get pixel value and index into the cache */
  171837. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  171838. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  171839. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  171840. cachep = & histogram[c0][c1][c2];
  171841. /* If we have not seen this color before, find nearest colormap entry */
  171842. /* and update the cache */
  171843. if (*cachep == 0)
  171844. fill_inverse_cmap(cinfo, c0,c1,c2);
  171845. /* Now emit the colormap index for this cell */
  171846. *outptr++ = (JSAMPLE) (*cachep - 1);
  171847. }
  171848. }
  171849. }
  171850. METHODDEF(void)
  171851. pass2_fs_dither (j_decompress_ptr cinfo,
  171852. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  171853. /* This version performs Floyd-Steinberg dithering */
  171854. {
  171855. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171856. hist3d histogram = cquantize->histogram;
  171857. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  171858. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  171859. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  171860. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  171861. JSAMPROW inptr; /* => current input pixel */
  171862. JSAMPROW outptr; /* => current output pixel */
  171863. histptr cachep;
  171864. int dir; /* +1 or -1 depending on direction */
  171865. int dir3; /* 3*dir, for advancing inptr & errorptr */
  171866. int row;
  171867. JDIMENSION col;
  171868. JDIMENSION width = cinfo->output_width;
  171869. JSAMPLE *range_limit = cinfo->sample_range_limit;
  171870. int *error_limit = cquantize->error_limiter;
  171871. JSAMPROW colormap0 = cinfo->colormap[0];
  171872. JSAMPROW colormap1 = cinfo->colormap[1];
  171873. JSAMPROW colormap2 = cinfo->colormap[2];
  171874. SHIFT_TEMPS
  171875. for (row = 0; row < num_rows; row++) {
  171876. inptr = input_buf[row];
  171877. outptr = output_buf[row];
  171878. if (cquantize->on_odd_row) {
  171879. /* work right to left in this row */
  171880. inptr += (width-1) * 3; /* so point to rightmost pixel */
  171881. outptr += width-1;
  171882. dir = -1;
  171883. dir3 = -3;
  171884. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  171885. cquantize->on_odd_row = FALSE; /* flip for next time */
  171886. } else {
  171887. /* work left to right in this row */
  171888. dir = 1;
  171889. dir3 = 3;
  171890. errorptr = cquantize->fserrors; /* => entry before first real column */
  171891. cquantize->on_odd_row = TRUE; /* flip for next time */
  171892. }
  171893. /* Preset error values: no error propagated to first pixel from left */
  171894. cur0 = cur1 = cur2 = 0;
  171895. /* and no error propagated to row below yet */
  171896. belowerr0 = belowerr1 = belowerr2 = 0;
  171897. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  171898. for (col = width; col > 0; col--) {
  171899. /* curN holds the error propagated from the previous pixel on the
  171900. * current line. Add the error propagated from the previous line
  171901. * to form the complete error correction term for this pixel, and
  171902. * round the error term (which is expressed * 16) to an integer.
  171903. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  171904. * for either sign of the error value.
  171905. * Note: errorptr points to *previous* column's array entry.
  171906. */
  171907. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  171908. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  171909. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  171910. /* Limit the error using transfer function set by init_error_limit.
  171911. * See comments with init_error_limit for rationale.
  171912. */
  171913. cur0 = error_limit[cur0];
  171914. cur1 = error_limit[cur1];
  171915. cur2 = error_limit[cur2];
  171916. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  171917. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  171918. * this sets the required size of the range_limit array.
  171919. */
  171920. cur0 += GETJSAMPLE(inptr[0]);
  171921. cur1 += GETJSAMPLE(inptr[1]);
  171922. cur2 += GETJSAMPLE(inptr[2]);
  171923. cur0 = GETJSAMPLE(range_limit[cur0]);
  171924. cur1 = GETJSAMPLE(range_limit[cur1]);
  171925. cur2 = GETJSAMPLE(range_limit[cur2]);
  171926. /* Index into the cache with adjusted pixel value */
  171927. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  171928. /* If we have not seen this color before, find nearest colormap */
  171929. /* entry and update the cache */
  171930. if (*cachep == 0)
  171931. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  171932. /* Now emit the colormap index for this cell */
  171933. { register int pixcode = *cachep - 1;
  171934. *outptr = (JSAMPLE) pixcode;
  171935. /* Compute representation error for this pixel */
  171936. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  171937. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  171938. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  171939. }
  171940. /* Compute error fractions to be propagated to adjacent pixels.
  171941. * Add these into the running sums, and simultaneously shift the
  171942. * next-line error sums left by 1 column.
  171943. */
  171944. { register LOCFSERROR bnexterr, delta;
  171945. bnexterr = cur0; /* Process component 0 */
  171946. delta = cur0 * 2;
  171947. cur0 += delta; /* form error * 3 */
  171948. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  171949. cur0 += delta; /* form error * 5 */
  171950. bpreverr0 = belowerr0 + cur0;
  171951. belowerr0 = bnexterr;
  171952. cur0 += delta; /* form error * 7 */
  171953. bnexterr = cur1; /* Process component 1 */
  171954. delta = cur1 * 2;
  171955. cur1 += delta; /* form error * 3 */
  171956. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  171957. cur1 += delta; /* form error * 5 */
  171958. bpreverr1 = belowerr1 + cur1;
  171959. belowerr1 = bnexterr;
  171960. cur1 += delta; /* form error * 7 */
  171961. bnexterr = cur2; /* Process component 2 */
  171962. delta = cur2 * 2;
  171963. cur2 += delta; /* form error * 3 */
  171964. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  171965. cur2 += delta; /* form error * 5 */
  171966. bpreverr2 = belowerr2 + cur2;
  171967. belowerr2 = bnexterr;
  171968. cur2 += delta; /* form error * 7 */
  171969. }
  171970. /* At this point curN contains the 7/16 error value to be propagated
  171971. * to the next pixel on the current line, and all the errors for the
  171972. * next line have been shifted over. We are therefore ready to move on.
  171973. */
  171974. inptr += dir3; /* Advance pixel pointers to next column */
  171975. outptr += dir;
  171976. errorptr += dir3; /* advance errorptr to current column */
  171977. }
  171978. /* Post-loop cleanup: we must unload the final error values into the
  171979. * final fserrors[] entry. Note we need not unload belowerrN because
  171980. * it is for the dummy column before or after the actual array.
  171981. */
  171982. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  171983. errorptr[1] = (FSERROR) bpreverr1;
  171984. errorptr[2] = (FSERROR) bpreverr2;
  171985. }
  171986. }
  171987. /*
  171988. * Initialize the error-limiting transfer function (lookup table).
  171989. * The raw F-S error computation can potentially compute error values of up to
  171990. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  171991. * much less, otherwise obviously wrong pixels will be created. (Typical
  171992. * effects include weird fringes at color-area boundaries, isolated bright
  171993. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  171994. * is to ensure that the "corners" of the color cube are allocated as output
  171995. * colors; then repeated errors in the same direction cannot cause cascading
  171996. * error buildup. However, that only prevents the error from getting
  171997. * completely out of hand; Aaron Giles reports that error limiting improves
  171998. * the results even with corner colors allocated.
  171999. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  172000. * well, but the smoother transfer function used below is even better. Thanks
  172001. * to Aaron Giles for this idea.
  172002. */
  172003. LOCAL(void)
  172004. init_error_limit (j_decompress_ptr cinfo)
  172005. /* Allocate and fill in the error_limiter table */
  172006. {
  172007. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172008. int * table;
  172009. int in, out;
  172010. table = (int *) (*cinfo->mem->alloc_small)
  172011. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  172012. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  172013. cquantize->error_limiter = table;
  172014. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  172015. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  172016. out = 0;
  172017. for (in = 0; in < STEPSIZE; in++, out++) {
  172018. table[in] = out; table[-in] = -out;
  172019. }
  172020. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  172021. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  172022. table[in] = out; table[-in] = -out;
  172023. }
  172024. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  172025. for (; in <= MAXJSAMPLE; in++) {
  172026. table[in] = out; table[-in] = -out;
  172027. }
  172028. #undef STEPSIZE
  172029. }
  172030. /*
  172031. * Finish up at the end of each pass.
  172032. */
  172033. METHODDEF(void)
  172034. finish_pass1 (j_decompress_ptr cinfo)
  172035. {
  172036. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172037. /* Select the representative colors and fill in cinfo->colormap */
  172038. cinfo->colormap = cquantize->sv_colormap;
  172039. select_colors(cinfo, cquantize->desired);
  172040. /* Force next pass to zero the color index table */
  172041. cquantize->needs_zeroed = TRUE;
  172042. }
  172043. METHODDEF(void)
  172044. finish_pass2 (j_decompress_ptr cinfo)
  172045. {
  172046. /* no work */
  172047. }
  172048. /*
  172049. * Initialize for each processing pass.
  172050. */
  172051. METHODDEF(void)
  172052. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172053. {
  172054. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172055. hist3d histogram = cquantize->histogram;
  172056. int i;
  172057. /* Only F-S dithering or no dithering is supported. */
  172058. /* If user asks for ordered dither, give him F-S. */
  172059. if (cinfo->dither_mode != JDITHER_NONE)
  172060. cinfo->dither_mode = JDITHER_FS;
  172061. if (is_pre_scan) {
  172062. /* Set up method pointers */
  172063. cquantize->pub.color_quantize = prescan_quantize;
  172064. cquantize->pub.finish_pass = finish_pass1;
  172065. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  172066. } else {
  172067. /* Set up method pointers */
  172068. if (cinfo->dither_mode == JDITHER_FS)
  172069. cquantize->pub.color_quantize = pass2_fs_dither;
  172070. else
  172071. cquantize->pub.color_quantize = pass2_no_dither;
  172072. cquantize->pub.finish_pass = finish_pass2;
  172073. /* Make sure color count is acceptable */
  172074. i = cinfo->actual_number_of_colors;
  172075. if (i < 1)
  172076. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  172077. if (i > MAXNUMCOLORS)
  172078. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172079. if (cinfo->dither_mode == JDITHER_FS) {
  172080. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  172081. (3 * SIZEOF(FSERROR)));
  172082. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  172083. if (cquantize->fserrors == NULL)
  172084. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172085. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172086. /* Initialize the propagated errors to zero. */
  172087. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  172088. /* Make the error-limit table if we didn't already. */
  172089. if (cquantize->error_limiter == NULL)
  172090. init_error_limit(cinfo);
  172091. cquantize->on_odd_row = FALSE;
  172092. }
  172093. }
  172094. /* Zero the histogram or inverse color map, if necessary */
  172095. if (cquantize->needs_zeroed) {
  172096. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172097. jzero_far((void FAR *) histogram[i],
  172098. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172099. }
  172100. cquantize->needs_zeroed = FALSE;
  172101. }
  172102. }
  172103. /*
  172104. * Switch to a new external colormap between output passes.
  172105. */
  172106. METHODDEF(void)
  172107. new_color_map_2_quant (j_decompress_ptr cinfo)
  172108. {
  172109. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172110. /* Reset the inverse color map */
  172111. cquantize->needs_zeroed = TRUE;
  172112. }
  172113. /*
  172114. * Module initialization routine for 2-pass color quantization.
  172115. */
  172116. GLOBAL(void)
  172117. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  172118. {
  172119. my_cquantize_ptr2 cquantize;
  172120. int i;
  172121. cquantize = (my_cquantize_ptr2)
  172122. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172123. SIZEOF(my_cquantizer2));
  172124. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172125. cquantize->pub.start_pass = start_pass_2_quant;
  172126. cquantize->pub.new_color_map = new_color_map_2_quant;
  172127. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  172128. cquantize->error_limiter = NULL;
  172129. /* Make sure jdmaster didn't give me a case I can't handle */
  172130. if (cinfo->out_color_components != 3)
  172131. ERREXIT(cinfo, JERR_NOTIMPL);
  172132. /* Allocate the histogram/inverse colormap storage */
  172133. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  172134. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  172135. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172136. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  172137. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172138. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172139. }
  172140. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  172141. /* Allocate storage for the completed colormap, if required.
  172142. * We do this now since it is FAR storage and may affect
  172143. * the memory manager's space calculations.
  172144. */
  172145. if (cinfo->enable_2pass_quant) {
  172146. /* Make sure color count is acceptable */
  172147. int desired = cinfo->desired_number_of_colors;
  172148. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  172149. if (desired < 8)
  172150. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  172151. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172152. if (desired > MAXNUMCOLORS)
  172153. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172154. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  172155. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  172156. cquantize->desired = desired;
  172157. } else
  172158. cquantize->sv_colormap = NULL;
  172159. /* Only F-S dithering or no dithering is supported. */
  172160. /* If user asks for ordered dither, give him F-S. */
  172161. if (cinfo->dither_mode != JDITHER_NONE)
  172162. cinfo->dither_mode = JDITHER_FS;
  172163. /* Allocate Floyd-Steinberg workspace if necessary.
  172164. * This isn't really needed until pass 2, but again it is FAR storage.
  172165. * Although we will cope with a later change in dither_mode,
  172166. * we do not promise to honor max_memory_to_use if dither_mode changes.
  172167. */
  172168. if (cinfo->dither_mode == JDITHER_FS) {
  172169. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172170. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172171. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  172172. /* Might as well create the error-limiting table too. */
  172173. init_error_limit(cinfo);
  172174. }
  172175. }
  172176. #endif /* QUANT_2PASS_SUPPORTED */
  172177. /********* End of inlined file: jquant2.c *********/
  172178. /********* Start of inlined file: jutils.c *********/
  172179. #define JPEG_INTERNALS
  172180. /*
  172181. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  172182. * of a DCT block read in natural order (left to right, top to bottom).
  172183. */
  172184. #if 0 /* This table is not actually needed in v6a */
  172185. const int jpeg_zigzag_order[DCTSIZE2] = {
  172186. 0, 1, 5, 6, 14, 15, 27, 28,
  172187. 2, 4, 7, 13, 16, 26, 29, 42,
  172188. 3, 8, 12, 17, 25, 30, 41, 43,
  172189. 9, 11, 18, 24, 31, 40, 44, 53,
  172190. 10, 19, 23, 32, 39, 45, 52, 54,
  172191. 20, 22, 33, 38, 46, 51, 55, 60,
  172192. 21, 34, 37, 47, 50, 56, 59, 61,
  172193. 35, 36, 48, 49, 57, 58, 62, 63
  172194. };
  172195. #endif
  172196. /*
  172197. * jpeg_natural_order[i] is the natural-order position of the i'th element
  172198. * of zigzag order.
  172199. *
  172200. * When reading corrupted data, the Huffman decoders could attempt
  172201. * to reference an entry beyond the end of this array (if the decoded
  172202. * zero run length reaches past the end of the block). To prevent
  172203. * wild stores without adding an inner-loop test, we put some extra
  172204. * "63"s after the real entries. This will cause the extra coefficient
  172205. * to be stored in location 63 of the block, not somewhere random.
  172206. * The worst case would be a run-length of 15, which means we need 16
  172207. * fake entries.
  172208. */
  172209. const int jpeg_natural_order[DCTSIZE2+16] = {
  172210. 0, 1, 8, 16, 9, 2, 3, 10,
  172211. 17, 24, 32, 25, 18, 11, 4, 5,
  172212. 12, 19, 26, 33, 40, 48, 41, 34,
  172213. 27, 20, 13, 6, 7, 14, 21, 28,
  172214. 35, 42, 49, 56, 57, 50, 43, 36,
  172215. 29, 22, 15, 23, 30, 37, 44, 51,
  172216. 58, 59, 52, 45, 38, 31, 39, 46,
  172217. 53, 60, 61, 54, 47, 55, 62, 63,
  172218. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  172219. 63, 63, 63, 63, 63, 63, 63, 63
  172220. };
  172221. /*
  172222. * Arithmetic utilities
  172223. */
  172224. GLOBAL(long)
  172225. jdiv_round_up (long a, long b)
  172226. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  172227. /* Assumes a >= 0, b > 0 */
  172228. {
  172229. return (a + b - 1L) / b;
  172230. }
  172231. GLOBAL(long)
  172232. jround_up (long a, long b)
  172233. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  172234. /* Assumes a >= 0, b > 0 */
  172235. {
  172236. a += b - 1L;
  172237. return a - (a % b);
  172238. }
  172239. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  172240. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  172241. * are FAR and we're assuming a small-pointer memory model. However, some
  172242. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  172243. * in the small-model libraries. These will be used if USE_FMEM is defined.
  172244. * Otherwise, the routines below do it the hard way. (The performance cost
  172245. * is not all that great, because these routines aren't very heavily used.)
  172246. */
  172247. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  172248. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  172249. #define FMEMZERO(target,size) MEMZERO(target,size)
  172250. #else /* 80x86 case, define if we can */
  172251. #ifdef USE_FMEM
  172252. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  172253. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  172254. #endif
  172255. #endif
  172256. GLOBAL(void)
  172257. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  172258. JSAMPARRAY output_array, int dest_row,
  172259. int num_rows, JDIMENSION num_cols)
  172260. /* Copy some rows of samples from one place to another.
  172261. * num_rows rows are copied from input_array[source_row++]
  172262. * to output_array[dest_row++]; these areas may overlap for duplication.
  172263. * The source and destination arrays must be at least as wide as num_cols.
  172264. */
  172265. {
  172266. register JSAMPROW inptr, outptr;
  172267. #ifdef FMEMCOPY
  172268. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  172269. #else
  172270. register JDIMENSION count;
  172271. #endif
  172272. register int row;
  172273. input_array += source_row;
  172274. output_array += dest_row;
  172275. for (row = num_rows; row > 0; row--) {
  172276. inptr = *input_array++;
  172277. outptr = *output_array++;
  172278. #ifdef FMEMCOPY
  172279. FMEMCOPY(outptr, inptr, count);
  172280. #else
  172281. for (count = num_cols; count > 0; count--)
  172282. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  172283. #endif
  172284. }
  172285. }
  172286. GLOBAL(void)
  172287. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  172288. JDIMENSION num_blocks)
  172289. /* Copy a row of coefficient blocks from one place to another. */
  172290. {
  172291. #ifdef FMEMCOPY
  172292. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  172293. #else
  172294. register JCOEFPTR inptr, outptr;
  172295. register long count;
  172296. inptr = (JCOEFPTR) input_row;
  172297. outptr = (JCOEFPTR) output_row;
  172298. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  172299. *outptr++ = *inptr++;
  172300. }
  172301. #endif
  172302. }
  172303. GLOBAL(void)
  172304. jzero_far (void FAR * target, size_t bytestozero)
  172305. /* Zero out a chunk of FAR memory. */
  172306. /* This might be sample-array data, block-array data, or alloc_large data. */
  172307. {
  172308. #ifdef FMEMZERO
  172309. FMEMZERO(target, bytestozero);
  172310. #else
  172311. register char FAR * ptr = (char FAR *) target;
  172312. register size_t count;
  172313. for (count = bytestozero; count > 0; count--) {
  172314. *ptr++ = 0;
  172315. }
  172316. #endif
  172317. }
  172318. /********* End of inlined file: jutils.c *********/
  172319. /********* Start of inlined file: transupp.c *********/
  172320. /* Although this file really shouldn't have access to the library internals,
  172321. * it's helpful to let it call jround_up() and jcopy_block_row().
  172322. */
  172323. #define JPEG_INTERNALS
  172324. /********* Start of inlined file: transupp.h *********/
  172325. /* If you happen not to want the image transform support, disable it here */
  172326. #ifndef TRANSFORMS_SUPPORTED
  172327. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  172328. #endif
  172329. /* Short forms of external names for systems with brain-damaged linkers. */
  172330. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172331. #define jtransform_request_workspace jTrRequest
  172332. #define jtransform_adjust_parameters jTrAdjust
  172333. #define jtransform_execute_transformation jTrExec
  172334. #define jcopy_markers_setup jCMrkSetup
  172335. #define jcopy_markers_execute jCMrkExec
  172336. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172337. /*
  172338. * Codes for supported types of image transformations.
  172339. */
  172340. typedef enum {
  172341. JXFORM_NONE, /* no transformation */
  172342. JXFORM_FLIP_H, /* horizontal flip */
  172343. JXFORM_FLIP_V, /* vertical flip */
  172344. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  172345. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  172346. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  172347. JXFORM_ROT_180, /* 180-degree rotation */
  172348. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  172349. } JXFORM_CODE;
  172350. /*
  172351. * Although rotating and flipping data expressed as DCT coefficients is not
  172352. * hard, there is an asymmetry in the JPEG format specification for images
  172353. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  172354. * image edges are padded out to the next iMCU boundary with junk data; but
  172355. * no padding is possible at the top and left edges. If we were to flip
  172356. * the whole image including the pad data, then pad garbage would become
  172357. * visible at the top and/or left, and real pixels would disappear into the
  172358. * pad margins --- perhaps permanently, since encoders & decoders may not
  172359. * bother to preserve DCT blocks that appear to be completely outside the
  172360. * nominal image area. So, we have to exclude any partial iMCUs from the
  172361. * basic transformation.
  172362. *
  172363. * Transpose is the only transformation that can handle partial iMCUs at the
  172364. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  172365. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  172366. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  172367. * The other transforms are defined as combinations of these basic transforms
  172368. * and process edge blocks in a way that preserves the equivalence.
  172369. *
  172370. * The "trim" option causes untransformable partial iMCUs to be dropped;
  172371. * this is not strictly lossless, but it usually gives the best-looking
  172372. * result for odd-size images. Note that when this option is active,
  172373. * the expected mathematical equivalences between the transforms may not hold.
  172374. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  172375. * followed by -rot 180 -trim trims both edges.)
  172376. *
  172377. * We also offer a "force to grayscale" option, which simply discards the
  172378. * chrominance channels of a YCbCr image. This is lossless in the sense that
  172379. * the luminance channel is preserved exactly. It's not the same kind of
  172380. * thing as the rotate/flip transformations, but it's convenient to handle it
  172381. * as part of this package, mainly because the transformation routines have to
  172382. * be aware of the option to know how many components to work on.
  172383. */
  172384. typedef struct {
  172385. /* Options: set by caller */
  172386. JXFORM_CODE transform; /* image transform operator */
  172387. boolean trim; /* if TRUE, trim partial MCUs as needed */
  172388. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  172389. /* Internal workspace: caller should not touch these */
  172390. int num_components; /* # of components in workspace */
  172391. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  172392. } jpeg_transform_info;
  172393. #if TRANSFORMS_SUPPORTED
  172394. /* Request any required workspace */
  172395. EXTERN(void) jtransform_request_workspace
  172396. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  172397. /* Adjust output image parameters */
  172398. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  172399. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172400. jvirt_barray_ptr *src_coef_arrays,
  172401. jpeg_transform_info *info));
  172402. /* Execute the actual transformation, if any */
  172403. EXTERN(void) jtransform_execute_transformation
  172404. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172405. jvirt_barray_ptr *src_coef_arrays,
  172406. jpeg_transform_info *info));
  172407. #endif /* TRANSFORMS_SUPPORTED */
  172408. /*
  172409. * Support for copying optional markers from source to destination file.
  172410. */
  172411. typedef enum {
  172412. JCOPYOPT_NONE, /* copy no optional markers */
  172413. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  172414. JCOPYOPT_ALL /* copy all optional markers */
  172415. } JCOPY_OPTION;
  172416. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  172417. /* Setup decompression object to save desired markers in memory */
  172418. EXTERN(void) jcopy_markers_setup
  172419. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  172420. /* Copy markers saved in the given source object to the destination object */
  172421. EXTERN(void) jcopy_markers_execute
  172422. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172423. JCOPY_OPTION option));
  172424. /********* End of inlined file: transupp.h *********/
  172425. /* My own external interface */
  172426. #if TRANSFORMS_SUPPORTED
  172427. /*
  172428. * Lossless image transformation routines. These routines work on DCT
  172429. * coefficient arrays and thus do not require any lossy decompression
  172430. * or recompression of the image.
  172431. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  172432. *
  172433. * Horizontal flipping is done in-place, using a single top-to-bottom
  172434. * pass through the virtual source array. It will thus be much the
  172435. * fastest option for images larger than main memory.
  172436. *
  172437. * The other routines require a set of destination virtual arrays, so they
  172438. * need twice as much memory as jpegtran normally does. The destination
  172439. * arrays are always written in normal scan order (top to bottom) because
  172440. * the virtual array manager expects this. The source arrays will be scanned
  172441. * in the corresponding order, which means multiple passes through the source
  172442. * arrays for most of the transforms. That could result in much thrashing
  172443. * if the image is larger than main memory.
  172444. *
  172445. * Some notes about the operating environment of the individual transform
  172446. * routines:
  172447. * 1. Both the source and destination virtual arrays are allocated from the
  172448. * source JPEG object, and therefore should be manipulated by calling the
  172449. * source's memory manager.
  172450. * 2. The destination's component count should be used. It may be smaller
  172451. * than the source's when forcing to grayscale.
  172452. * 3. Likewise the destination's sampling factors should be used. When
  172453. * forcing to grayscale the destination's sampling factors will be all 1,
  172454. * and we may as well take that as the effective iMCU size.
  172455. * 4. When "trim" is in effect, the destination's dimensions will be the
  172456. * trimmed values but the source's will be untrimmed.
  172457. * 5. All the routines assume that the source and destination buffers are
  172458. * padded out to a full iMCU boundary. This is true, although for the
  172459. * source buffer it is an undocumented property of jdcoefct.c.
  172460. * Notes 2,3,4 boil down to this: generally we should use the destination's
  172461. * dimensions and ignore the source's.
  172462. */
  172463. LOCAL(void)
  172464. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172465. jvirt_barray_ptr *src_coef_arrays)
  172466. /* Horizontal flip; done in-place, so no separate dest array is required */
  172467. {
  172468. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  172469. int ci, k, offset_y;
  172470. JBLOCKARRAY buffer;
  172471. JCOEFPTR ptr1, ptr2;
  172472. JCOEF temp1, temp2;
  172473. jpeg_component_info *compptr;
  172474. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  172475. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  172476. * mirroring by changing the signs of odd-numbered columns.
  172477. * Partial iMCUs at the right edge are left untouched.
  172478. */
  172479. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172480. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172481. compptr = dstinfo->comp_info + ci;
  172482. comp_width = MCU_cols * compptr->h_samp_factor;
  172483. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  172484. blk_y += compptr->v_samp_factor) {
  172485. buffer = (*srcinfo->mem->access_virt_barray)
  172486. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  172487. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172488. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172489. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  172490. ptr1 = buffer[offset_y][blk_x];
  172491. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  172492. /* this unrolled loop doesn't need to know which row it's on... */
  172493. for (k = 0; k < DCTSIZE2; k += 2) {
  172494. temp1 = *ptr1; /* swap even column */
  172495. temp2 = *ptr2;
  172496. *ptr1++ = temp2;
  172497. *ptr2++ = temp1;
  172498. temp1 = *ptr1; /* swap odd column with sign change */
  172499. temp2 = *ptr2;
  172500. *ptr1++ = -temp2;
  172501. *ptr2++ = -temp1;
  172502. }
  172503. }
  172504. }
  172505. }
  172506. }
  172507. }
  172508. LOCAL(void)
  172509. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172510. jvirt_barray_ptr *src_coef_arrays,
  172511. jvirt_barray_ptr *dst_coef_arrays)
  172512. /* Vertical flip */
  172513. {
  172514. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  172515. int ci, i, j, offset_y;
  172516. JBLOCKARRAY src_buffer, dst_buffer;
  172517. JBLOCKROW src_row_ptr, dst_row_ptr;
  172518. JCOEFPTR src_ptr, dst_ptr;
  172519. jpeg_component_info *compptr;
  172520. /* We output into a separate array because we can't touch different
  172521. * rows of the source virtual array simultaneously. Otherwise, this
  172522. * is a pretty straightforward analog of horizontal flip.
  172523. * Within a DCT block, vertical mirroring is done by changing the signs
  172524. * of odd-numbered rows.
  172525. * Partial iMCUs at the bottom edge are copied verbatim.
  172526. */
  172527. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172528. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172529. compptr = dstinfo->comp_info + ci;
  172530. comp_height = MCU_rows * compptr->v_samp_factor;
  172531. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172532. dst_blk_y += compptr->v_samp_factor) {
  172533. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172534. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172535. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172536. if (dst_blk_y < comp_height) {
  172537. /* Row is within the mirrorable area. */
  172538. src_buffer = (*srcinfo->mem->access_virt_barray)
  172539. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  172540. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  172541. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172542. } else {
  172543. /* Bottom-edge blocks will be copied verbatim. */
  172544. src_buffer = (*srcinfo->mem->access_virt_barray)
  172545. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  172546. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172547. }
  172548. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172549. if (dst_blk_y < comp_height) {
  172550. /* Row is within the mirrorable area. */
  172551. dst_row_ptr = dst_buffer[offset_y];
  172552. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  172553. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172554. dst_blk_x++) {
  172555. dst_ptr = dst_row_ptr[dst_blk_x];
  172556. src_ptr = src_row_ptr[dst_blk_x];
  172557. for (i = 0; i < DCTSIZE; i += 2) {
  172558. /* copy even row */
  172559. for (j = 0; j < DCTSIZE; j++)
  172560. *dst_ptr++ = *src_ptr++;
  172561. /* copy odd row with sign change */
  172562. for (j = 0; j < DCTSIZE; j++)
  172563. *dst_ptr++ = - *src_ptr++;
  172564. }
  172565. }
  172566. } else {
  172567. /* Just copy row verbatim. */
  172568. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  172569. compptr->width_in_blocks);
  172570. }
  172571. }
  172572. }
  172573. }
  172574. }
  172575. LOCAL(void)
  172576. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172577. jvirt_barray_ptr *src_coef_arrays,
  172578. jvirt_barray_ptr *dst_coef_arrays)
  172579. /* Transpose source into destination */
  172580. {
  172581. JDIMENSION dst_blk_x, dst_blk_y;
  172582. int ci, i, j, offset_x, offset_y;
  172583. JBLOCKARRAY src_buffer, dst_buffer;
  172584. JCOEFPTR src_ptr, dst_ptr;
  172585. jpeg_component_info *compptr;
  172586. /* Transposing pixels within a block just requires transposing the
  172587. * DCT coefficients.
  172588. * Partial iMCUs at the edges require no special treatment; we simply
  172589. * process all the available DCT blocks for every component.
  172590. */
  172591. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172592. compptr = dstinfo->comp_info + ci;
  172593. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172594. dst_blk_y += compptr->v_samp_factor) {
  172595. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172596. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172597. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172598. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172599. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172600. dst_blk_x += compptr->h_samp_factor) {
  172601. src_buffer = (*srcinfo->mem->access_virt_barray)
  172602. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172603. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172604. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172605. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172606. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172607. for (i = 0; i < DCTSIZE; i++)
  172608. for (j = 0; j < DCTSIZE; j++)
  172609. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172610. }
  172611. }
  172612. }
  172613. }
  172614. }
  172615. }
  172616. LOCAL(void)
  172617. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172618. jvirt_barray_ptr *src_coef_arrays,
  172619. jvirt_barray_ptr *dst_coef_arrays)
  172620. /* 90 degree rotation is equivalent to
  172621. * 1. Transposing the image;
  172622. * 2. Horizontal mirroring.
  172623. * These two steps are merged into a single processing routine.
  172624. */
  172625. {
  172626. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  172627. int ci, i, j, offset_x, offset_y;
  172628. JBLOCKARRAY src_buffer, dst_buffer;
  172629. JCOEFPTR src_ptr, dst_ptr;
  172630. jpeg_component_info *compptr;
  172631. /* Because of the horizontal mirror step, we can't process partial iMCUs
  172632. * at the (output) right edge properly. They just get transposed and
  172633. * not mirrored.
  172634. */
  172635. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172636. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172637. compptr = dstinfo->comp_info + ci;
  172638. comp_width = MCU_cols * compptr->h_samp_factor;
  172639. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172640. dst_blk_y += compptr->v_samp_factor) {
  172641. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172642. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172643. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172644. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172645. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172646. dst_blk_x += compptr->h_samp_factor) {
  172647. src_buffer = (*srcinfo->mem->access_virt_barray)
  172648. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172649. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172650. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172651. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172652. if (dst_blk_x < comp_width) {
  172653. /* Block is within the mirrorable area. */
  172654. dst_ptr = dst_buffer[offset_y]
  172655. [comp_width - dst_blk_x - offset_x - 1];
  172656. for (i = 0; i < DCTSIZE; i++) {
  172657. for (j = 0; j < DCTSIZE; j++)
  172658. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172659. i++;
  172660. for (j = 0; j < DCTSIZE; j++)
  172661. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172662. }
  172663. } else {
  172664. /* Edge blocks are transposed but not mirrored. */
  172665. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172666. for (i = 0; i < DCTSIZE; i++)
  172667. for (j = 0; j < DCTSIZE; j++)
  172668. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172669. }
  172670. }
  172671. }
  172672. }
  172673. }
  172674. }
  172675. }
  172676. LOCAL(void)
  172677. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172678. jvirt_barray_ptr *src_coef_arrays,
  172679. jvirt_barray_ptr *dst_coef_arrays)
  172680. /* 270 degree rotation is equivalent to
  172681. * 1. Horizontal mirroring;
  172682. * 2. Transposing the image.
  172683. * These two steps are merged into a single processing routine.
  172684. */
  172685. {
  172686. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  172687. int ci, i, j, offset_x, offset_y;
  172688. JBLOCKARRAY src_buffer, dst_buffer;
  172689. JCOEFPTR src_ptr, dst_ptr;
  172690. jpeg_component_info *compptr;
  172691. /* Because of the horizontal mirror step, we can't process partial iMCUs
  172692. * at the (output) bottom edge properly. They just get transposed and
  172693. * not mirrored.
  172694. */
  172695. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172696. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172697. compptr = dstinfo->comp_info + ci;
  172698. comp_height = MCU_rows * compptr->v_samp_factor;
  172699. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172700. dst_blk_y += compptr->v_samp_factor) {
  172701. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172702. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172703. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172704. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172705. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172706. dst_blk_x += compptr->h_samp_factor) {
  172707. src_buffer = (*srcinfo->mem->access_virt_barray)
  172708. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172709. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172710. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172711. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172712. if (dst_blk_y < comp_height) {
  172713. /* Block is within the mirrorable area. */
  172714. src_ptr = src_buffer[offset_x]
  172715. [comp_height - dst_blk_y - offset_y - 1];
  172716. for (i = 0; i < DCTSIZE; i++) {
  172717. for (j = 0; j < DCTSIZE; j++) {
  172718. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172719. j++;
  172720. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172721. }
  172722. }
  172723. } else {
  172724. /* Edge blocks are transposed but not mirrored. */
  172725. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172726. for (i = 0; i < DCTSIZE; i++)
  172727. for (j = 0; j < DCTSIZE; j++)
  172728. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172729. }
  172730. }
  172731. }
  172732. }
  172733. }
  172734. }
  172735. }
  172736. LOCAL(void)
  172737. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172738. jvirt_barray_ptr *src_coef_arrays,
  172739. jvirt_barray_ptr *dst_coef_arrays)
  172740. /* 180 degree rotation is equivalent to
  172741. * 1. Vertical mirroring;
  172742. * 2. Horizontal mirroring.
  172743. * These two steps are merged into a single processing routine.
  172744. */
  172745. {
  172746. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  172747. int ci, i, j, offset_y;
  172748. JBLOCKARRAY src_buffer, dst_buffer;
  172749. JBLOCKROW src_row_ptr, dst_row_ptr;
  172750. JCOEFPTR src_ptr, dst_ptr;
  172751. jpeg_component_info *compptr;
  172752. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172753. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172754. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172755. compptr = dstinfo->comp_info + ci;
  172756. comp_width = MCU_cols * compptr->h_samp_factor;
  172757. comp_height = MCU_rows * compptr->v_samp_factor;
  172758. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172759. dst_blk_y += compptr->v_samp_factor) {
  172760. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172761. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172762. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172763. if (dst_blk_y < comp_height) {
  172764. /* Row is within the vertically mirrorable area. */
  172765. src_buffer = (*srcinfo->mem->access_virt_barray)
  172766. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  172767. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  172768. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172769. } else {
  172770. /* Bottom-edge rows are only mirrored horizontally. */
  172771. src_buffer = (*srcinfo->mem->access_virt_barray)
  172772. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  172773. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172774. }
  172775. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172776. if (dst_blk_y < comp_height) {
  172777. /* Row is within the mirrorable area. */
  172778. dst_row_ptr = dst_buffer[offset_y];
  172779. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  172780. /* Process the blocks that can be mirrored both ways. */
  172781. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  172782. dst_ptr = dst_row_ptr[dst_blk_x];
  172783. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  172784. for (i = 0; i < DCTSIZE; i += 2) {
  172785. /* For even row, negate every odd column. */
  172786. for (j = 0; j < DCTSIZE; j += 2) {
  172787. *dst_ptr++ = *src_ptr++;
  172788. *dst_ptr++ = - *src_ptr++;
  172789. }
  172790. /* For odd row, negate every even column. */
  172791. for (j = 0; j < DCTSIZE; j += 2) {
  172792. *dst_ptr++ = - *src_ptr++;
  172793. *dst_ptr++ = *src_ptr++;
  172794. }
  172795. }
  172796. }
  172797. /* Any remaining right-edge blocks are only mirrored vertically. */
  172798. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  172799. dst_ptr = dst_row_ptr[dst_blk_x];
  172800. src_ptr = src_row_ptr[dst_blk_x];
  172801. for (i = 0; i < DCTSIZE; i += 2) {
  172802. for (j = 0; j < DCTSIZE; j++)
  172803. *dst_ptr++ = *src_ptr++;
  172804. for (j = 0; j < DCTSIZE; j++)
  172805. *dst_ptr++ = - *src_ptr++;
  172806. }
  172807. }
  172808. } else {
  172809. /* Remaining rows are just mirrored horizontally. */
  172810. dst_row_ptr = dst_buffer[offset_y];
  172811. src_row_ptr = src_buffer[offset_y];
  172812. /* Process the blocks that can be mirrored. */
  172813. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  172814. dst_ptr = dst_row_ptr[dst_blk_x];
  172815. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  172816. for (i = 0; i < DCTSIZE2; i += 2) {
  172817. *dst_ptr++ = *src_ptr++;
  172818. *dst_ptr++ = - *src_ptr++;
  172819. }
  172820. }
  172821. /* Any remaining right-edge blocks are only copied. */
  172822. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  172823. dst_ptr = dst_row_ptr[dst_blk_x];
  172824. src_ptr = src_row_ptr[dst_blk_x];
  172825. for (i = 0; i < DCTSIZE2; i++)
  172826. *dst_ptr++ = *src_ptr++;
  172827. }
  172828. }
  172829. }
  172830. }
  172831. }
  172832. }
  172833. LOCAL(void)
  172834. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172835. jvirt_barray_ptr *src_coef_arrays,
  172836. jvirt_barray_ptr *dst_coef_arrays)
  172837. /* Transverse transpose is equivalent to
  172838. * 1. 180 degree rotation;
  172839. * 2. Transposition;
  172840. * or
  172841. * 1. Horizontal mirroring;
  172842. * 2. Transposition;
  172843. * 3. Horizontal mirroring.
  172844. * These steps are merged into a single processing routine.
  172845. */
  172846. {
  172847. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  172848. int ci, i, j, offset_x, offset_y;
  172849. JBLOCKARRAY src_buffer, dst_buffer;
  172850. JCOEFPTR src_ptr, dst_ptr;
  172851. jpeg_component_info *compptr;
  172852. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172853. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172854. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172855. compptr = dstinfo->comp_info + ci;
  172856. comp_width = MCU_cols * compptr->h_samp_factor;
  172857. comp_height = MCU_rows * compptr->v_samp_factor;
  172858. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172859. dst_blk_y += compptr->v_samp_factor) {
  172860. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172861. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172862. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172863. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172864. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172865. dst_blk_x += compptr->h_samp_factor) {
  172866. src_buffer = (*srcinfo->mem->access_virt_barray)
  172867. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172868. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172869. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172870. if (dst_blk_y < comp_height) {
  172871. src_ptr = src_buffer[offset_x]
  172872. [comp_height - dst_blk_y - offset_y - 1];
  172873. if (dst_blk_x < comp_width) {
  172874. /* Block is within the mirrorable area. */
  172875. dst_ptr = dst_buffer[offset_y]
  172876. [comp_width - dst_blk_x - offset_x - 1];
  172877. for (i = 0; i < DCTSIZE; i++) {
  172878. for (j = 0; j < DCTSIZE; j++) {
  172879. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172880. j++;
  172881. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172882. }
  172883. i++;
  172884. for (j = 0; j < DCTSIZE; j++) {
  172885. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172886. j++;
  172887. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172888. }
  172889. }
  172890. } else {
  172891. /* Right-edge blocks are mirrored in y only */
  172892. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172893. for (i = 0; i < DCTSIZE; i++) {
  172894. for (j = 0; j < DCTSIZE; j++) {
  172895. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172896. j++;
  172897. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172898. }
  172899. }
  172900. }
  172901. } else {
  172902. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172903. if (dst_blk_x < comp_width) {
  172904. /* Bottom-edge blocks are mirrored in x only */
  172905. dst_ptr = dst_buffer[offset_y]
  172906. [comp_width - dst_blk_x - offset_x - 1];
  172907. for (i = 0; i < DCTSIZE; i++) {
  172908. for (j = 0; j < DCTSIZE; j++)
  172909. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172910. i++;
  172911. for (j = 0; j < DCTSIZE; j++)
  172912. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172913. }
  172914. } else {
  172915. /* At lower right corner, just transpose, no mirroring */
  172916. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172917. for (i = 0; i < DCTSIZE; i++)
  172918. for (j = 0; j < DCTSIZE; j++)
  172919. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172920. }
  172921. }
  172922. }
  172923. }
  172924. }
  172925. }
  172926. }
  172927. }
  172928. /* Request any required workspace.
  172929. *
  172930. * We allocate the workspace virtual arrays from the source decompression
  172931. * object, so that all the arrays (both the original data and the workspace)
  172932. * will be taken into account while making memory management decisions.
  172933. * Hence, this routine must be called after jpeg_read_header (which reads
  172934. * the image dimensions) and before jpeg_read_coefficients (which realizes
  172935. * the source's virtual arrays).
  172936. */
  172937. GLOBAL(void)
  172938. jtransform_request_workspace (j_decompress_ptr srcinfo,
  172939. jpeg_transform_info *info)
  172940. {
  172941. jvirt_barray_ptr *coef_arrays = NULL;
  172942. jpeg_component_info *compptr;
  172943. int ci;
  172944. if (info->force_grayscale &&
  172945. srcinfo->jpeg_color_space == JCS_YCbCr &&
  172946. srcinfo->num_components == 3) {
  172947. /* We'll only process the first component */
  172948. info->num_components = 1;
  172949. } else {
  172950. /* Process all the components */
  172951. info->num_components = srcinfo->num_components;
  172952. }
  172953. switch (info->transform) {
  172954. case JXFORM_NONE:
  172955. case JXFORM_FLIP_H:
  172956. /* Don't need a workspace array */
  172957. break;
  172958. case JXFORM_FLIP_V:
  172959. case JXFORM_ROT_180:
  172960. /* Need workspace arrays having same dimensions as source image.
  172961. * Note that we allocate arrays padded out to the next iMCU boundary,
  172962. * so that transform routines need not worry about missing edge blocks.
  172963. */
  172964. coef_arrays = (jvirt_barray_ptr *)
  172965. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  172966. SIZEOF(jvirt_barray_ptr) * info->num_components);
  172967. for (ci = 0; ci < info->num_components; ci++) {
  172968. compptr = srcinfo->comp_info + ci;
  172969. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  172970. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  172971. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  172972. (long) compptr->h_samp_factor),
  172973. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  172974. (long) compptr->v_samp_factor),
  172975. (JDIMENSION) compptr->v_samp_factor);
  172976. }
  172977. break;
  172978. case JXFORM_TRANSPOSE:
  172979. case JXFORM_TRANSVERSE:
  172980. case JXFORM_ROT_90:
  172981. case JXFORM_ROT_270:
  172982. /* Need workspace arrays having transposed dimensions.
  172983. * Note that we allocate arrays padded out to the next iMCU boundary,
  172984. * so that transform routines need not worry about missing edge blocks.
  172985. */
  172986. coef_arrays = (jvirt_barray_ptr *)
  172987. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  172988. SIZEOF(jvirt_barray_ptr) * info->num_components);
  172989. for (ci = 0; ci < info->num_components; ci++) {
  172990. compptr = srcinfo->comp_info + ci;
  172991. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  172992. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  172993. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  172994. (long) compptr->v_samp_factor),
  172995. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  172996. (long) compptr->h_samp_factor),
  172997. (JDIMENSION) compptr->h_samp_factor);
  172998. }
  172999. break;
  173000. }
  173001. info->workspace_coef_arrays = coef_arrays;
  173002. }
  173003. /* Transpose destination image parameters */
  173004. LOCAL(void)
  173005. transpose_critical_parameters (j_compress_ptr dstinfo)
  173006. {
  173007. int tblno, i, j, ci, itemp;
  173008. jpeg_component_info *compptr;
  173009. JQUANT_TBL *qtblptr;
  173010. JDIMENSION dtemp;
  173011. UINT16 qtemp;
  173012. /* Transpose basic image dimensions */
  173013. dtemp = dstinfo->image_width;
  173014. dstinfo->image_width = dstinfo->image_height;
  173015. dstinfo->image_height = dtemp;
  173016. /* Transpose sampling factors */
  173017. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173018. compptr = dstinfo->comp_info + ci;
  173019. itemp = compptr->h_samp_factor;
  173020. compptr->h_samp_factor = compptr->v_samp_factor;
  173021. compptr->v_samp_factor = itemp;
  173022. }
  173023. /* Transpose quantization tables */
  173024. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  173025. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  173026. if (qtblptr != NULL) {
  173027. for (i = 0; i < DCTSIZE; i++) {
  173028. for (j = 0; j < i; j++) {
  173029. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  173030. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  173031. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  173032. }
  173033. }
  173034. }
  173035. }
  173036. }
  173037. /* Trim off any partial iMCUs on the indicated destination edge */
  173038. LOCAL(void)
  173039. trim_right_edge (j_compress_ptr dstinfo)
  173040. {
  173041. int ci, max_h_samp_factor;
  173042. JDIMENSION MCU_cols;
  173043. /* We have to compute max_h_samp_factor ourselves,
  173044. * because it hasn't been set yet in the destination
  173045. * (and we don't want to use the source's value).
  173046. */
  173047. max_h_samp_factor = 1;
  173048. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173049. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  173050. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  173051. }
  173052. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  173053. if (MCU_cols > 0) /* can't trim to 0 pixels */
  173054. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  173055. }
  173056. LOCAL(void)
  173057. trim_bottom_edge (j_compress_ptr dstinfo)
  173058. {
  173059. int ci, max_v_samp_factor;
  173060. JDIMENSION MCU_rows;
  173061. /* We have to compute max_v_samp_factor ourselves,
  173062. * because it hasn't been set yet in the destination
  173063. * (and we don't want to use the source's value).
  173064. */
  173065. max_v_samp_factor = 1;
  173066. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173067. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  173068. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  173069. }
  173070. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  173071. if (MCU_rows > 0) /* can't trim to 0 pixels */
  173072. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  173073. }
  173074. /* Adjust output image parameters as needed.
  173075. *
  173076. * This must be called after jpeg_copy_critical_parameters()
  173077. * and before jpeg_write_coefficients().
  173078. *
  173079. * The return value is the set of virtual coefficient arrays to be written
  173080. * (either the ones allocated by jtransform_request_workspace, or the
  173081. * original source data arrays). The caller will need to pass this value
  173082. * to jpeg_write_coefficients().
  173083. */
  173084. GLOBAL(jvirt_barray_ptr *)
  173085. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  173086. j_compress_ptr dstinfo,
  173087. jvirt_barray_ptr *src_coef_arrays,
  173088. jpeg_transform_info *info)
  173089. {
  173090. /* If force-to-grayscale is requested, adjust destination parameters */
  173091. if (info->force_grayscale) {
  173092. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  173093. * properly. Among other things, the target h_samp_factor & v_samp_factor
  173094. * will get set to 1, which typically won't match the source.
  173095. * In fact we do this even if the source is already grayscale; that
  173096. * provides an easy way of coercing a grayscale JPEG with funny sampling
  173097. * factors to the customary 1,1. (Some decoders fail on other factors.)
  173098. */
  173099. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  173100. dstinfo->num_components == 3) ||
  173101. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  173102. dstinfo->num_components == 1)) {
  173103. /* We have to preserve the source's quantization table number. */
  173104. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  173105. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  173106. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  173107. } else {
  173108. /* Sorry, can't do it */
  173109. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  173110. }
  173111. }
  173112. /* Correct the destination's image dimensions etc if necessary */
  173113. switch (info->transform) {
  173114. case JXFORM_NONE:
  173115. /* Nothing to do */
  173116. break;
  173117. case JXFORM_FLIP_H:
  173118. if (info->trim)
  173119. trim_right_edge(dstinfo);
  173120. break;
  173121. case JXFORM_FLIP_V:
  173122. if (info->trim)
  173123. trim_bottom_edge(dstinfo);
  173124. break;
  173125. case JXFORM_TRANSPOSE:
  173126. transpose_critical_parameters(dstinfo);
  173127. /* transpose does NOT have to trim anything */
  173128. break;
  173129. case JXFORM_TRANSVERSE:
  173130. transpose_critical_parameters(dstinfo);
  173131. if (info->trim) {
  173132. trim_right_edge(dstinfo);
  173133. trim_bottom_edge(dstinfo);
  173134. }
  173135. break;
  173136. case JXFORM_ROT_90:
  173137. transpose_critical_parameters(dstinfo);
  173138. if (info->trim)
  173139. trim_right_edge(dstinfo);
  173140. break;
  173141. case JXFORM_ROT_180:
  173142. if (info->trim) {
  173143. trim_right_edge(dstinfo);
  173144. trim_bottom_edge(dstinfo);
  173145. }
  173146. break;
  173147. case JXFORM_ROT_270:
  173148. transpose_critical_parameters(dstinfo);
  173149. if (info->trim)
  173150. trim_bottom_edge(dstinfo);
  173151. break;
  173152. }
  173153. /* Return the appropriate output data set */
  173154. if (info->workspace_coef_arrays != NULL)
  173155. return info->workspace_coef_arrays;
  173156. return src_coef_arrays;
  173157. }
  173158. /* Execute the actual transformation, if any.
  173159. *
  173160. * This must be called *after* jpeg_write_coefficients, because it depends
  173161. * on jpeg_write_coefficients to have computed subsidiary values such as
  173162. * the per-component width and height fields in the destination object.
  173163. *
  173164. * Note that some transformations will modify the source data arrays!
  173165. */
  173166. GLOBAL(void)
  173167. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  173168. j_compress_ptr dstinfo,
  173169. jvirt_barray_ptr *src_coef_arrays,
  173170. jpeg_transform_info *info)
  173171. {
  173172. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  173173. switch (info->transform) {
  173174. case JXFORM_NONE:
  173175. break;
  173176. case JXFORM_FLIP_H:
  173177. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  173178. break;
  173179. case JXFORM_FLIP_V:
  173180. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173181. break;
  173182. case JXFORM_TRANSPOSE:
  173183. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173184. break;
  173185. case JXFORM_TRANSVERSE:
  173186. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173187. break;
  173188. case JXFORM_ROT_90:
  173189. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173190. break;
  173191. case JXFORM_ROT_180:
  173192. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173193. break;
  173194. case JXFORM_ROT_270:
  173195. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173196. break;
  173197. }
  173198. }
  173199. #endif /* TRANSFORMS_SUPPORTED */
  173200. /* Setup decompression object to save desired markers in memory.
  173201. * This must be called before jpeg_read_header() to have the desired effect.
  173202. */
  173203. GLOBAL(void)
  173204. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  173205. {
  173206. #ifdef SAVE_MARKERS_SUPPORTED
  173207. int m;
  173208. /* Save comments except under NONE option */
  173209. if (option != JCOPYOPT_NONE) {
  173210. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  173211. }
  173212. /* Save all types of APPn markers iff ALL option */
  173213. if (option == JCOPYOPT_ALL) {
  173214. for (m = 0; m < 16; m++)
  173215. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  173216. }
  173217. #endif /* SAVE_MARKERS_SUPPORTED */
  173218. }
  173219. /* Copy markers saved in the given source object to the destination object.
  173220. * This should be called just after jpeg_start_compress() or
  173221. * jpeg_write_coefficients().
  173222. * Note that those routines will have written the SOI, and also the
  173223. * JFIF APP0 or Adobe APP14 markers if selected.
  173224. */
  173225. GLOBAL(void)
  173226. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173227. JCOPY_OPTION option)
  173228. {
  173229. jpeg_saved_marker_ptr marker;
  173230. /* In the current implementation, we don't actually need to examine the
  173231. * option flag here; we just copy everything that got saved.
  173232. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  173233. * if the encoder library already wrote one.
  173234. */
  173235. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  173236. if (dstinfo->write_JFIF_header &&
  173237. marker->marker == JPEG_APP0 &&
  173238. marker->data_length >= 5 &&
  173239. GETJOCTET(marker->data[0]) == 0x4A &&
  173240. GETJOCTET(marker->data[1]) == 0x46 &&
  173241. GETJOCTET(marker->data[2]) == 0x49 &&
  173242. GETJOCTET(marker->data[3]) == 0x46 &&
  173243. GETJOCTET(marker->data[4]) == 0)
  173244. continue; /* reject duplicate JFIF */
  173245. if (dstinfo->write_Adobe_marker &&
  173246. marker->marker == JPEG_APP0+14 &&
  173247. marker->data_length >= 5 &&
  173248. GETJOCTET(marker->data[0]) == 0x41 &&
  173249. GETJOCTET(marker->data[1]) == 0x64 &&
  173250. GETJOCTET(marker->data[2]) == 0x6F &&
  173251. GETJOCTET(marker->data[3]) == 0x62 &&
  173252. GETJOCTET(marker->data[4]) == 0x65)
  173253. continue; /* reject duplicate Adobe */
  173254. #ifdef NEED_FAR_POINTERS
  173255. /* We could use jpeg_write_marker if the data weren't FAR... */
  173256. {
  173257. unsigned int i;
  173258. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  173259. for (i = 0; i < marker->data_length; i++)
  173260. jpeg_write_m_byte(dstinfo, marker->data[i]);
  173261. }
  173262. #else
  173263. jpeg_write_marker(dstinfo, marker->marker,
  173264. marker->data, marker->data_length);
  173265. #endif
  173266. }
  173267. }
  173268. /********* End of inlined file: transupp.c *********/
  173269. }
  173270. }
  173271. #if JUCE_MSVC
  173272. #pragma warning (pop)
  173273. #endif
  173274. BEGIN_JUCE_NAMESPACE
  173275. using namespace jpeglibNamespace;
  173276. struct JPEGDecodingFailure {};
  173277. static void fatalErrorHandler (j_common_ptr)
  173278. {
  173279. throw JPEGDecodingFailure();
  173280. }
  173281. static void silentErrorCallback1 (j_common_ptr) {}
  173282. static void silentErrorCallback2 (j_common_ptr, int) {}
  173283. static void silentErrorCallback3 (j_common_ptr, char*) {}
  173284. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  173285. {
  173286. zerostruct (err);
  173287. err.error_exit = fatalErrorHandler;
  173288. err.emit_message = silentErrorCallback2;
  173289. err.output_message = silentErrorCallback1;
  173290. err.format_message = silentErrorCallback3;
  173291. err.reset_error_mgr = silentErrorCallback1;
  173292. }
  173293. static void dummyCallback1 (j_decompress_ptr) throw()
  173294. {
  173295. }
  173296. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  173297. {
  173298. decompStruct->src->next_input_byte += num;
  173299. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  173300. decompStruct->src->bytes_in_buffer -= num;
  173301. }
  173302. static boolean jpegFill (j_decompress_ptr) throw()
  173303. {
  173304. return 0;
  173305. }
  173306. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  173307. {
  173308. MemoryBlock mb;
  173309. in.readIntoMemoryBlock (mb);
  173310. Image* image = 0;
  173311. if (mb.getSize() > 16)
  173312. {
  173313. struct jpeg_decompress_struct jpegDecompStruct;
  173314. struct jpeg_error_mgr jerr;
  173315. setupSilentErrorHandler (jerr);
  173316. jpegDecompStruct.err = &jerr;
  173317. jpeg_create_decompress (&jpegDecompStruct);
  173318. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  173319. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  173320. jpegDecompStruct.src->init_source = dummyCallback1;
  173321. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  173322. jpegDecompStruct.src->skip_input_data = jpegSkip;
  173323. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  173324. jpegDecompStruct.src->term_source = dummyCallback1;
  173325. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  173326. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  173327. try
  173328. {
  173329. jpeg_read_header (&jpegDecompStruct, TRUE);
  173330. jpeg_calc_output_dimensions (&jpegDecompStruct);
  173331. const int width = jpegDecompStruct.output_width;
  173332. const int height = jpegDecompStruct.output_height;
  173333. jpegDecompStruct.out_color_space = JCS_RGB;
  173334. JSAMPARRAY buffer
  173335. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  173336. JPOOL_IMAGE,
  173337. width * 3, 1);
  173338. if (jpeg_start_decompress (&jpegDecompStruct))
  173339. {
  173340. image = new Image (Image::RGB, width, height, false);
  173341. for (int y = 0; y < height; ++y)
  173342. {
  173343. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  173344. int stride, pixelStride;
  173345. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  173346. const uint8* src = *buffer;
  173347. uint8* dest = pixels;
  173348. for (int i = width; --i >= 0;)
  173349. {
  173350. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  173351. dest += pixelStride;
  173352. src += 3;
  173353. }
  173354. image->releasePixelDataReadWrite (pixels);
  173355. }
  173356. jpeg_finish_decompress (&jpegDecompStruct);
  173357. }
  173358. jpeg_destroy_decompress (&jpegDecompStruct);
  173359. }
  173360. catch (...)
  173361. {}
  173362. }
  173363. return image;
  173364. }
  173365. static const int bufferSize = 512;
  173366. struct JuceJpegDest : public jpeg_destination_mgr
  173367. {
  173368. OutputStream* output;
  173369. char* buffer;
  173370. };
  173371. static void jpegWriteInit (j_compress_ptr) throw()
  173372. {
  173373. }
  173374. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  173375. {
  173376. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  173377. const int numToWrite = bufferSize - dest->free_in_buffer;
  173378. dest->output->write (dest->buffer, numToWrite);
  173379. }
  173380. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  173381. {
  173382. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  173383. const int numToWrite = bufferSize;
  173384. dest->next_output_byte = (JOCTET*) dest->buffer;
  173385. dest->free_in_buffer = bufferSize;
  173386. return dest->output->write (dest->buffer, numToWrite);
  173387. }
  173388. bool juce_writeJPEGImageToStream (const Image& image,
  173389. OutputStream& out,
  173390. float quality) throw()
  173391. {
  173392. if (image.hasAlphaChannel())
  173393. {
  173394. // this method could fill the background in white and still save the image..
  173395. jassertfalse
  173396. return true;
  173397. }
  173398. struct jpeg_compress_struct jpegCompStruct;
  173399. struct jpeg_error_mgr jerr;
  173400. setupSilentErrorHandler (jerr);
  173401. jpegCompStruct.err = &jerr;
  173402. jpeg_create_compress (&jpegCompStruct);
  173403. JuceJpegDest dest;
  173404. jpegCompStruct.dest = &dest;
  173405. dest.output = &out;
  173406. dest.buffer = (char*) juce_malloc (bufferSize);
  173407. dest.next_output_byte = (JOCTET*) dest.buffer;
  173408. dest.free_in_buffer = bufferSize;
  173409. dest.init_destination = jpegWriteInit;
  173410. dest.empty_output_buffer = jpegWriteFlush;
  173411. dest.term_destination = jpegWriteTerminate;
  173412. jpegCompStruct.image_width = image.getWidth();
  173413. jpegCompStruct.image_height = image.getHeight();
  173414. jpegCompStruct.input_components = 3;
  173415. jpegCompStruct.in_color_space = JCS_RGB;
  173416. jpegCompStruct.write_JFIF_header = 1;
  173417. jpegCompStruct.X_density = 72;
  173418. jpegCompStruct.Y_density = 72;
  173419. jpeg_set_defaults (&jpegCompStruct);
  173420. jpegCompStruct.dct_method = JDCT_FLOAT;
  173421. jpegCompStruct.optimize_coding = 1;
  173422. // jpegCompStruct.smoothing_factor = 10;
  173423. if (quality < 0.0f)
  173424. quality = 6.0f;
  173425. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  173426. jpeg_start_compress (&jpegCompStruct, TRUE);
  173427. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  173428. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  173429. JPOOL_IMAGE,
  173430. strideBytes, 1);
  173431. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  173432. {
  173433. int stride, pixelStride;
  173434. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  173435. const uint8* src = pixels;
  173436. uint8* dst = *buffer;
  173437. for (int i = jpegCompStruct.image_width; --i >= 0;)
  173438. {
  173439. *dst++ = ((const PixelRGB*) src)->getRed();
  173440. *dst++ = ((const PixelRGB*) src)->getGreen();
  173441. *dst++ = ((const PixelRGB*) src)->getBlue();
  173442. src += pixelStride;
  173443. }
  173444. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  173445. image.releasePixelDataReadOnly (pixels);
  173446. }
  173447. jpeg_finish_compress (&jpegCompStruct);
  173448. jpeg_destroy_compress (&jpegCompStruct);
  173449. juce_free (dest.buffer);
  173450. out.flush();
  173451. return true;
  173452. }
  173453. END_JUCE_NAMESPACE
  173454. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  173455. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  173456. #ifdef _MSC_VER
  173457. #pragma warning (push)
  173458. #pragma warning (disable: 4390 4611)
  173459. #endif
  173460. namespace zlibNamespace
  173461. {
  173462. #undef OS_CODE
  173463. #undef fdopen
  173464. #undef OS_CODE
  173465. }
  173466. namespace pnglibNamespace
  173467. {
  173468. using namespace zlibNamespace;
  173469. using ::malloc;
  173470. using ::free;
  173471. extern "C"
  173472. {
  173473. using ::abs;
  173474. #define PNG_INTERNAL
  173475. #define NO_DUMMY_DECL
  173476. #define PNG_SETJMP_NOT_SUPPORTED
  173477. /********* Start of inlined file: png.h *********/
  173478. /* png.h - header file for PNG reference library
  173479. *
  173480. * libpng version 1.2.21 - October 4, 2007
  173481. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  173482. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  173483. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  173484. *
  173485. * Authors and maintainers:
  173486. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  173487. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  173488. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  173489. * See also "Contributing Authors", below.
  173490. *
  173491. * Note about libpng version numbers:
  173492. *
  173493. * Due to various miscommunications, unforeseen code incompatibilities
  173494. * and occasional factors outside the authors' control, version numbering
  173495. * on the library has not always been consistent and straightforward.
  173496. * The following table summarizes matters since version 0.89c, which was
  173497. * the first widely used release:
  173498. *
  173499. * source png.h png.h shared-lib
  173500. * version string int version
  173501. * ------- ------ ----- ----------
  173502. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  173503. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  173504. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  173505. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  173506. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  173507. * 0.97c 0.97 97 2.0.97
  173508. * 0.98 0.98 98 2.0.98
  173509. * 0.99 0.99 98 2.0.99
  173510. * 0.99a-m 0.99 99 2.0.99
  173511. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  173512. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  173513. * 1.0.1 png.h string is 10001 2.1.0
  173514. * 1.0.1a-e identical to the 10002 from here on, the shared library
  173515. * 1.0.2 source version) 10002 is 2.V where V is the source code
  173516. * 1.0.2a-b 10003 version, except as noted.
  173517. * 1.0.3 10003
  173518. * 1.0.3a-d 10004
  173519. * 1.0.4 10004
  173520. * 1.0.4a-f 10005
  173521. * 1.0.5 (+ 2 patches) 10005
  173522. * 1.0.5a-d 10006
  173523. * 1.0.5e-r 10100 (not source compatible)
  173524. * 1.0.5s-v 10006 (not binary compatible)
  173525. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  173526. * 1.0.6d-f 10007 (still binary incompatible)
  173527. * 1.0.6g 10007
  173528. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  173529. * 1.0.6i 10007 10.6i
  173530. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  173531. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  173532. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  173533. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  173534. * 1.0.7 1 10007 (still compatible)
  173535. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  173536. * 1.0.8rc1 1 10008 2.1.0.8rc1
  173537. * 1.0.8 1 10008 2.1.0.8
  173538. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  173539. * 1.0.9rc1 1 10009 2.1.0.9rc1
  173540. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  173541. * 1.0.9rc2 1 10009 2.1.0.9rc2
  173542. * 1.0.9 1 10009 2.1.0.9
  173543. * 1.0.10beta1 1 10010 2.1.0.10beta1
  173544. * 1.0.10rc1 1 10010 2.1.0.10rc1
  173545. * 1.0.10 1 10010 2.1.0.10
  173546. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  173547. * 1.0.11rc1 1 10011 2.1.0.11rc1
  173548. * 1.0.11 1 10011 2.1.0.11
  173549. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  173550. * 1.0.12rc1 2 10012 2.1.0.12rc1
  173551. * 1.0.12 2 10012 2.1.0.12
  173552. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  173553. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  173554. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  173555. * 1.2.0rc1 3 10200 3.1.2.0rc1
  173556. * 1.2.0 3 10200 3.1.2.0
  173557. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  173558. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  173559. * 1.2.1 3 10201 3.1.2.1
  173560. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  173561. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  173562. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  173563. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  173564. * 1.0.13 10 10013 10.so.0.1.0.13
  173565. * 1.2.2 12 10202 12.so.0.1.2.2
  173566. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  173567. * 1.2.3 12 10203 12.so.0.1.2.3
  173568. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  173569. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  173570. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  173571. * 1.0.14 10 10014 10.so.0.1.0.14
  173572. * 1.2.4 13 10204 12.so.0.1.2.4
  173573. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  173574. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  173575. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  173576. * 1.0.15 10 10015 10.so.0.1.0.15
  173577. * 1.2.5 13 10205 12.so.0.1.2.5
  173578. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  173579. * 1.0.16 10 10016 10.so.0.1.0.16
  173580. * 1.2.6 13 10206 12.so.0.1.2.6
  173581. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  173582. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  173583. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  173584. * 1.0.17 10 10017 10.so.0.1.0.17
  173585. * 1.2.7 13 10207 12.so.0.1.2.7
  173586. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  173587. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  173588. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  173589. * 1.0.18 10 10018 10.so.0.1.0.18
  173590. * 1.2.8 13 10208 12.so.0.1.2.8
  173591. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  173592. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  173593. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  173594. * 1.2.9 13 10209 12.so.0.9[.0]
  173595. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  173596. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  173597. * 1.2.10 13 10210 12.so.0.10[.0]
  173598. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  173599. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  173600. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  173601. * 1.0.19 10 10019 10.so.0.19[.0]
  173602. * 1.2.11 13 10211 12.so.0.11[.0]
  173603. * 1.0.20 10 10020 10.so.0.20[.0]
  173604. * 1.2.12 13 10212 12.so.0.12[.0]
  173605. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  173606. * 1.0.21 10 10021 10.so.0.21[.0]
  173607. * 1.2.13 13 10213 12.so.0.13[.0]
  173608. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  173609. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  173610. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  173611. * 1.0.22 10 10022 10.so.0.22[.0]
  173612. * 1.2.14 13 10214 12.so.0.14[.0]
  173613. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  173614. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  173615. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  173616. * 1.0.23 10 10023 10.so.0.23[.0]
  173617. * 1.2.15 13 10215 12.so.0.15[.0]
  173618. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  173619. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  173620. * 1.0.24 10 10024 10.so.0.24[.0]
  173621. * 1.2.16 13 10216 12.so.0.16[.0]
  173622. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  173623. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  173624. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  173625. * 1.0.25 10 10025 10.so.0.25[.0]
  173626. * 1.2.17 13 10217 12.so.0.17[.0]
  173627. * 1.0.26 10 10026 10.so.0.26[.0]
  173628. * 1.2.18 13 10218 12.so.0.18[.0]
  173629. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  173630. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  173631. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  173632. * 1.0.27 10 10027 10.so.0.27[.0]
  173633. * 1.2.19 13 10219 12.so.0.19[.0]
  173634. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  173635. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  173636. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  173637. * 1.0.28 10 10028 10.so.0.28[.0]
  173638. * 1.2.20 13 10220 12.so.0.20[.0]
  173639. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  173640. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  173641. * 1.0.29 10 10029 10.so.0.29[.0]
  173642. * 1.2.21 13 10221 12.so.0.21[.0]
  173643. *
  173644. * Henceforth the source version will match the shared-library major
  173645. * and minor numbers; the shared-library major version number will be
  173646. * used for changes in backward compatibility, as it is intended. The
  173647. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  173648. * for applications, is an unsigned integer of the form xyyzz corresponding
  173649. * to the source version x.y.z (leading zeros in y and z). Beta versions
  173650. * were given the previous public release number plus a letter, until
  173651. * version 1.0.6j; from then on they were given the upcoming public
  173652. * release number plus "betaNN" or "rcN".
  173653. *
  173654. * Binary incompatibility exists only when applications make direct access
  173655. * to the info_ptr or png_ptr members through png.h, and the compiled
  173656. * application is loaded with a different version of the library.
  173657. *
  173658. * DLLNUM will change each time there are forward or backward changes
  173659. * in binary compatibility (e.g., when a new feature is added).
  173660. *
  173661. * See libpng.txt or libpng.3 for more information. The PNG specification
  173662. * is available as a W3C Recommendation and as an ISO Specification,
  173663. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  173664. */
  173665. /*
  173666. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  173667. *
  173668. * If you modify libpng you may insert additional notices immediately following
  173669. * this sentence.
  173670. *
  173671. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  173672. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  173673. * distributed according to the same disclaimer and license as libpng-1.2.5
  173674. * with the following individual added to the list of Contributing Authors:
  173675. *
  173676. * Cosmin Truta
  173677. *
  173678. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  173679. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  173680. * distributed according to the same disclaimer and license as libpng-1.0.6
  173681. * with the following individuals added to the list of Contributing Authors:
  173682. *
  173683. * Simon-Pierre Cadieux
  173684. * Eric S. Raymond
  173685. * Gilles Vollant
  173686. *
  173687. * and with the following additions to the disclaimer:
  173688. *
  173689. * There is no warranty against interference with your enjoyment of the
  173690. * library or against infringement. There is no warranty that our
  173691. * efforts or the library will fulfill any of your particular purposes
  173692. * or needs. This library is provided with all faults, and the entire
  173693. * risk of satisfactory quality, performance, accuracy, and effort is with
  173694. * the user.
  173695. *
  173696. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  173697. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  173698. * distributed according to the same disclaimer and license as libpng-0.96,
  173699. * with the following individuals added to the list of Contributing Authors:
  173700. *
  173701. * Tom Lane
  173702. * Glenn Randers-Pehrson
  173703. * Willem van Schaik
  173704. *
  173705. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  173706. * Copyright (c) 1996, 1997 Andreas Dilger
  173707. * Distributed according to the same disclaimer and license as libpng-0.88,
  173708. * with the following individuals added to the list of Contributing Authors:
  173709. *
  173710. * John Bowler
  173711. * Kevin Bracey
  173712. * Sam Bushell
  173713. * Magnus Holmgren
  173714. * Greg Roelofs
  173715. * Tom Tanner
  173716. *
  173717. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  173718. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  173719. *
  173720. * For the purposes of this copyright and license, "Contributing Authors"
  173721. * is defined as the following set of individuals:
  173722. *
  173723. * Andreas Dilger
  173724. * Dave Martindale
  173725. * Guy Eric Schalnat
  173726. * Paul Schmidt
  173727. * Tim Wegner
  173728. *
  173729. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  173730. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  173731. * including, without limitation, the warranties of merchantability and of
  173732. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  173733. * assume no liability for direct, indirect, incidental, special, exemplary,
  173734. * or consequential damages, which may result from the use of the PNG
  173735. * Reference Library, even if advised of the possibility of such damage.
  173736. *
  173737. * Permission is hereby granted to use, copy, modify, and distribute this
  173738. * source code, or portions hereof, for any purpose, without fee, subject
  173739. * to the following restrictions:
  173740. *
  173741. * 1. The origin of this source code must not be misrepresented.
  173742. *
  173743. * 2. Altered versions must be plainly marked as such and
  173744. * must not be misrepresented as being the original source.
  173745. *
  173746. * 3. This Copyright notice may not be removed or altered from
  173747. * any source or altered source distribution.
  173748. *
  173749. * The Contributing Authors and Group 42, Inc. specifically permit, without
  173750. * fee, and encourage the use of this source code as a component to
  173751. * supporting the PNG file format in commercial products. If you use this
  173752. * source code in a product, acknowledgment is not required but would be
  173753. * appreciated.
  173754. */
  173755. /*
  173756. * A "png_get_copyright" function is available, for convenient use in "about"
  173757. * boxes and the like:
  173758. *
  173759. * printf("%s",png_get_copyright(NULL));
  173760. *
  173761. * Also, the PNG logo (in PNG format, of course) is supplied in the
  173762. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  173763. */
  173764. /*
  173765. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  173766. * certification mark of the Open Source Initiative.
  173767. */
  173768. /*
  173769. * The contributing authors would like to thank all those who helped
  173770. * with testing, bug fixes, and patience. This wouldn't have been
  173771. * possible without all of you.
  173772. *
  173773. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  173774. */
  173775. /*
  173776. * Y2K compliance in libpng:
  173777. * =========================
  173778. *
  173779. * October 4, 2007
  173780. *
  173781. * Since the PNG Development group is an ad-hoc body, we can't make
  173782. * an official declaration.
  173783. *
  173784. * This is your unofficial assurance that libpng from version 0.71 and
  173785. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  173786. * versions were also Y2K compliant.
  173787. *
  173788. * Libpng only has three year fields. One is a 2-byte unsigned integer
  173789. * that will hold years up to 65535. The other two hold the date in text
  173790. * format, and will hold years up to 9999.
  173791. *
  173792. * The integer is
  173793. * "png_uint_16 year" in png_time_struct.
  173794. *
  173795. * The strings are
  173796. * "png_charp time_buffer" in png_struct and
  173797. * "near_time_buffer", which is a local character string in png.c.
  173798. *
  173799. * There are seven time-related functions:
  173800. * png.c: png_convert_to_rfc_1123() in png.c
  173801. * (formerly png_convert_to_rfc_1152() in error)
  173802. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  173803. * png_convert_from_time_t() in pngwrite.c
  173804. * png_get_tIME() in pngget.c
  173805. * png_handle_tIME() in pngrutil.c, called in pngread.c
  173806. * png_set_tIME() in pngset.c
  173807. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  173808. *
  173809. * All handle dates properly in a Y2K environment. The
  173810. * png_convert_from_time_t() function calls gmtime() to convert from system
  173811. * clock time, which returns (year - 1900), which we properly convert to
  173812. * the full 4-digit year. There is a possibility that applications using
  173813. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  173814. * function, or that they are incorrectly passing only a 2-digit year
  173815. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  173816. * but this is not under our control. The libpng documentation has always
  173817. * stated that it works with 4-digit years, and the APIs have been
  173818. * documented as such.
  173819. *
  173820. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  173821. * integer to hold the year, and can hold years as large as 65535.
  173822. *
  173823. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  173824. * no date-related code.
  173825. *
  173826. * Glenn Randers-Pehrson
  173827. * libpng maintainer
  173828. * PNG Development Group
  173829. */
  173830. #ifndef PNG_H
  173831. #define PNG_H
  173832. /* This is not the place to learn how to use libpng. The file libpng.txt
  173833. * describes how to use libpng, and the file example.c summarizes it
  173834. * with some code on which to build. This file is useful for looking
  173835. * at the actual function definitions and structure components.
  173836. */
  173837. /* Version information for png.h - this should match the version in png.c */
  173838. #define PNG_LIBPNG_VER_STRING "1.2.21"
  173839. #define PNG_HEADER_VERSION_STRING \
  173840. " libpng version 1.2.21 - October 4, 2007\n"
  173841. #define PNG_LIBPNG_VER_SONUM 0
  173842. #define PNG_LIBPNG_VER_DLLNUM 13
  173843. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  173844. #define PNG_LIBPNG_VER_MAJOR 1
  173845. #define PNG_LIBPNG_VER_MINOR 2
  173846. #define PNG_LIBPNG_VER_RELEASE 21
  173847. /* This should match the numeric part of the final component of
  173848. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  173849. #define PNG_LIBPNG_VER_BUILD 0
  173850. /* Release Status */
  173851. #define PNG_LIBPNG_BUILD_ALPHA 1
  173852. #define PNG_LIBPNG_BUILD_BETA 2
  173853. #define PNG_LIBPNG_BUILD_RC 3
  173854. #define PNG_LIBPNG_BUILD_STABLE 4
  173855. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  173856. /* Release-Specific Flags */
  173857. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  173858. PNG_LIBPNG_BUILD_STABLE only */
  173859. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  173860. PNG_LIBPNG_BUILD_SPECIAL */
  173861. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  173862. PNG_LIBPNG_BUILD_PRIVATE */
  173863. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  173864. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  173865. * We must not include leading zeros.
  173866. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  173867. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  173868. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  173869. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  173870. #ifndef PNG_VERSION_INFO_ONLY
  173871. /* include the compression library's header */
  173872. #endif
  173873. /* include all user configurable info, including optional assembler routines */
  173874. /********* Start of inlined file: pngconf.h *********/
  173875. /* pngconf.h - machine configurable file for libpng
  173876. *
  173877. * libpng version 1.2.21 - October 4, 2007
  173878. * For conditions of distribution and use, see copyright notice in png.h
  173879. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  173880. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  173881. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  173882. */
  173883. /* Any machine specific code is near the front of this file, so if you
  173884. * are configuring libpng for a machine, you may want to read the section
  173885. * starting here down to where it starts to typedef png_color, png_text,
  173886. * and png_info.
  173887. */
  173888. #ifndef PNGCONF_H
  173889. #define PNGCONF_H
  173890. #define PNG_1_2_X
  173891. // These are some Juce config settings that should remove any unnecessary code bloat..
  173892. #define PNG_NO_STDIO 1
  173893. #define PNG_DEBUG 0
  173894. #define PNG_NO_WARNINGS 1
  173895. #define PNG_NO_ERROR_TEXT 1
  173896. #define PNG_NO_ERROR_NUMBERS 1
  173897. #define PNG_NO_USER_MEM 1
  173898. #define PNG_NO_READ_iCCP 1
  173899. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  173900. #define PNG_NO_READ_USER_CHUNKS 1
  173901. #define PNG_NO_READ_iTXt 1
  173902. #define PNG_NO_READ_sCAL 1
  173903. #define PNG_NO_READ_sPLT 1
  173904. #define png_error(a, b) png_err(a)
  173905. #define png_warning(a, b)
  173906. #define png_chunk_error(a, b) png_err(a)
  173907. #define png_chunk_warning(a, b)
  173908. /*
  173909. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  173910. * includes the resource compiler for Windows DLL configurations.
  173911. */
  173912. #ifdef PNG_USER_CONFIG
  173913. # ifndef PNG_USER_PRIVATEBUILD
  173914. # define PNG_USER_PRIVATEBUILD
  173915. # endif
  173916. #include "pngusr.h"
  173917. #endif
  173918. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  173919. #ifdef PNG_CONFIGURE_LIBPNG
  173920. #ifdef HAVE_CONFIG_H
  173921. #include "config.h"
  173922. #endif
  173923. #endif
  173924. /*
  173925. * Added at libpng-1.2.8
  173926. *
  173927. * If you create a private DLL you need to define in "pngusr.h" the followings:
  173928. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  173929. * the DLL was built>
  173930. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  173931. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  173932. * distinguish your DLL from those of the official release. These
  173933. * correspond to the trailing letters that come after the version
  173934. * number and must match your private DLL name>
  173935. * e.g. // private DLL "libpng13gx.dll"
  173936. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  173937. *
  173938. * The following macros are also at your disposal if you want to complete the
  173939. * DLL VERSIONINFO structure.
  173940. * - PNG_USER_VERSIONINFO_COMMENTS
  173941. * - PNG_USER_VERSIONINFO_COMPANYNAME
  173942. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  173943. */
  173944. #ifdef __STDC__
  173945. #ifdef SPECIALBUILD
  173946. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  173947. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  173948. #endif
  173949. #ifdef PRIVATEBUILD
  173950. # pragma message("PRIVATEBUILD is deprecated.\
  173951. Use PNG_USER_PRIVATEBUILD instead.")
  173952. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  173953. #endif
  173954. #endif /* __STDC__ */
  173955. #ifndef PNG_VERSION_INFO_ONLY
  173956. /* End of material added to libpng-1.2.8 */
  173957. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  173958. Restored at libpng-1.2.21 */
  173959. # define PNG_WARN_UNINITIALIZED_ROW 1
  173960. /* End of material added at libpng-1.2.19/1.2.21 */
  173961. /* This is the size of the compression buffer, and thus the size of
  173962. * an IDAT chunk. Make this whatever size you feel is best for your
  173963. * machine. One of these will be allocated per png_struct. When this
  173964. * is full, it writes the data to the disk, and does some other
  173965. * calculations. Making this an extremely small size will slow
  173966. * the library down, but you may want to experiment to determine
  173967. * where it becomes significant, if you are concerned with memory
  173968. * usage. Note that zlib allocates at least 32Kb also. For readers,
  173969. * this describes the size of the buffer available to read the data in.
  173970. * Unless this gets smaller than the size of a row (compressed),
  173971. * it should not make much difference how big this is.
  173972. */
  173973. #ifndef PNG_ZBUF_SIZE
  173974. # define PNG_ZBUF_SIZE 8192
  173975. #endif
  173976. /* Enable if you want a write-only libpng */
  173977. #ifndef PNG_NO_READ_SUPPORTED
  173978. # define PNG_READ_SUPPORTED
  173979. #endif
  173980. /* Enable if you want a read-only libpng */
  173981. #ifndef PNG_NO_WRITE_SUPPORTED
  173982. # define PNG_WRITE_SUPPORTED
  173983. #endif
  173984. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  173985. support PNGs that are embedded in MNG datastreams */
  173986. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  173987. # ifndef PNG_MNG_FEATURES_SUPPORTED
  173988. # define PNG_MNG_FEATURES_SUPPORTED
  173989. # endif
  173990. #endif
  173991. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  173992. # ifndef PNG_FLOATING_POINT_SUPPORTED
  173993. # define PNG_FLOATING_POINT_SUPPORTED
  173994. # endif
  173995. #endif
  173996. /* If you are running on a machine where you cannot allocate more
  173997. * than 64K of memory at once, uncomment this. While libpng will not
  173998. * normally need that much memory in a chunk (unless you load up a very
  173999. * large file), zlib needs to know how big of a chunk it can use, and
  174000. * libpng thus makes sure to check any memory allocation to verify it
  174001. * will fit into memory.
  174002. #define PNG_MAX_MALLOC_64K
  174003. */
  174004. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  174005. # define PNG_MAX_MALLOC_64K
  174006. #endif
  174007. /* Special munging to support doing things the 'cygwin' way:
  174008. * 'Normal' png-on-win32 defines/defaults:
  174009. * PNG_BUILD_DLL -- building dll
  174010. * PNG_USE_DLL -- building an application, linking to dll
  174011. * (no define) -- building static library, or building an
  174012. * application and linking to the static lib
  174013. * 'Cygwin' defines/defaults:
  174014. * PNG_BUILD_DLL -- (ignored) building the dll
  174015. * (no define) -- (ignored) building an application, linking to the dll
  174016. * PNG_STATIC -- (ignored) building the static lib, or building an
  174017. * application that links to the static lib.
  174018. * ALL_STATIC -- (ignored) building various static libs, or building an
  174019. * application that links to the static libs.
  174020. * Thus,
  174021. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  174022. * this bit of #ifdefs will define the 'correct' config variables based on
  174023. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  174024. * unnecessary.
  174025. *
  174026. * Also, the precedence order is:
  174027. * ALL_STATIC (since we can't #undef something outside our namespace)
  174028. * PNG_BUILD_DLL
  174029. * PNG_STATIC
  174030. * (nothing) == PNG_USE_DLL
  174031. *
  174032. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  174033. * of auto-import in binutils, we no longer need to worry about
  174034. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  174035. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  174036. * to __declspec() stuff. However, we DO need to worry about
  174037. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  174038. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  174039. */
  174040. #if defined(__CYGWIN__)
  174041. # if defined(ALL_STATIC)
  174042. # if defined(PNG_BUILD_DLL)
  174043. # undef PNG_BUILD_DLL
  174044. # endif
  174045. # if defined(PNG_USE_DLL)
  174046. # undef PNG_USE_DLL
  174047. # endif
  174048. # if defined(PNG_DLL)
  174049. # undef PNG_DLL
  174050. # endif
  174051. # if !defined(PNG_STATIC)
  174052. # define PNG_STATIC
  174053. # endif
  174054. # else
  174055. # if defined (PNG_BUILD_DLL)
  174056. # if defined(PNG_STATIC)
  174057. # undef PNG_STATIC
  174058. # endif
  174059. # if defined(PNG_USE_DLL)
  174060. # undef PNG_USE_DLL
  174061. # endif
  174062. # if !defined(PNG_DLL)
  174063. # define PNG_DLL
  174064. # endif
  174065. # else
  174066. # if defined(PNG_STATIC)
  174067. # if defined(PNG_USE_DLL)
  174068. # undef PNG_USE_DLL
  174069. # endif
  174070. # if defined(PNG_DLL)
  174071. # undef PNG_DLL
  174072. # endif
  174073. # else
  174074. # if !defined(PNG_USE_DLL)
  174075. # define PNG_USE_DLL
  174076. # endif
  174077. # if !defined(PNG_DLL)
  174078. # define PNG_DLL
  174079. # endif
  174080. # endif
  174081. # endif
  174082. # endif
  174083. #endif
  174084. /* This protects us against compilers that run on a windowing system
  174085. * and thus don't have or would rather us not use the stdio types:
  174086. * stdin, stdout, and stderr. The only one currently used is stderr
  174087. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  174088. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  174089. * will also prevent these, plus will prevent the entire set of stdio
  174090. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  174091. * unless (PNG_DEBUG > 0) has been #defined.
  174092. *
  174093. * #define PNG_NO_CONSOLE_IO
  174094. * #define PNG_NO_STDIO
  174095. */
  174096. #if defined(_WIN32_WCE)
  174097. # include <windows.h>
  174098. /* Console I/O functions are not supported on WindowsCE */
  174099. # define PNG_NO_CONSOLE_IO
  174100. # ifdef PNG_DEBUG
  174101. # undef PNG_DEBUG
  174102. # endif
  174103. #endif
  174104. #ifdef PNG_BUILD_DLL
  174105. # ifndef PNG_CONSOLE_IO_SUPPORTED
  174106. # ifndef PNG_NO_CONSOLE_IO
  174107. # define PNG_NO_CONSOLE_IO
  174108. # endif
  174109. # endif
  174110. #endif
  174111. # ifdef PNG_NO_STDIO
  174112. # ifndef PNG_NO_CONSOLE_IO
  174113. # define PNG_NO_CONSOLE_IO
  174114. # endif
  174115. # ifdef PNG_DEBUG
  174116. # if (PNG_DEBUG > 0)
  174117. # include <stdio.h>
  174118. # endif
  174119. # endif
  174120. # else
  174121. # if !defined(_WIN32_WCE)
  174122. /* "stdio.h" functions are not supported on WindowsCE */
  174123. # include <stdio.h>
  174124. # endif
  174125. # endif
  174126. /* This macro protects us against machines that don't have function
  174127. * prototypes (ie K&R style headers). If your compiler does not handle
  174128. * function prototypes, define this macro and use the included ansi2knr.
  174129. * I've always been able to use _NO_PROTO as the indicator, but you may
  174130. * need to drag the empty declaration out in front of here, or change the
  174131. * ifdef to suit your own needs.
  174132. */
  174133. #ifndef PNGARG
  174134. #ifdef OF /* zlib prototype munger */
  174135. # define PNGARG(arglist) OF(arglist)
  174136. #else
  174137. #ifdef _NO_PROTO
  174138. # define PNGARG(arglist) ()
  174139. # ifndef PNG_TYPECAST_NULL
  174140. # define PNG_TYPECAST_NULL
  174141. # endif
  174142. #else
  174143. # define PNGARG(arglist) arglist
  174144. #endif /* _NO_PROTO */
  174145. #endif /* OF */
  174146. #endif /* PNGARG */
  174147. /* Try to determine if we are compiling on a Mac. Note that testing for
  174148. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  174149. * on non-Mac platforms.
  174150. */
  174151. #ifndef MACOS
  174152. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  174153. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  174154. # define MACOS
  174155. # endif
  174156. #endif
  174157. /* enough people need this for various reasons to include it here */
  174158. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  174159. # include <sys/types.h>
  174160. #endif
  174161. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  174162. # define PNG_SETJMP_SUPPORTED
  174163. #endif
  174164. #ifdef PNG_SETJMP_SUPPORTED
  174165. /* This is an attempt to force a single setjmp behaviour on Linux. If
  174166. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  174167. */
  174168. # ifdef __linux__
  174169. # ifdef _BSD_SOURCE
  174170. # define PNG_SAVE_BSD_SOURCE
  174171. # undef _BSD_SOURCE
  174172. # endif
  174173. # ifdef _SETJMP_H
  174174. /* If you encounter a compiler error here, see the explanation
  174175. * near the end of INSTALL.
  174176. */
  174177. __png.h__ already includes setjmp.h;
  174178. __dont__ include it again.;
  174179. # endif
  174180. # endif /* __linux__ */
  174181. /* include setjmp.h for error handling */
  174182. # include <setjmp.h>
  174183. # ifdef __linux__
  174184. # ifdef PNG_SAVE_BSD_SOURCE
  174185. # define _BSD_SOURCE
  174186. # undef PNG_SAVE_BSD_SOURCE
  174187. # endif
  174188. # endif /* __linux__ */
  174189. #endif /* PNG_SETJMP_SUPPORTED */
  174190. #ifdef BSD
  174191. # include <strings.h>
  174192. #else
  174193. # include <string.h>
  174194. #endif
  174195. /* Other defines for things like memory and the like can go here. */
  174196. #ifdef PNG_INTERNAL
  174197. #include <stdlib.h>
  174198. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  174199. * aren't usually used outside the library (as far as I know), so it is
  174200. * debatable if they should be exported at all. In the future, when it is
  174201. * possible to have run-time registry of chunk-handling functions, some of
  174202. * these will be made available again.
  174203. #define PNG_EXTERN extern
  174204. */
  174205. #define PNG_EXTERN
  174206. /* Other defines specific to compilers can go here. Try to keep
  174207. * them inside an appropriate ifdef/endif pair for portability.
  174208. */
  174209. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  174210. # if defined(MACOS)
  174211. /* We need to check that <math.h> hasn't already been included earlier
  174212. * as it seems it doesn't agree with <fp.h>, yet we should really use
  174213. * <fp.h> if possible.
  174214. */
  174215. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  174216. # include <fp.h>
  174217. # endif
  174218. # else
  174219. # include <math.h>
  174220. # endif
  174221. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  174222. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  174223. * MATH=68881
  174224. */
  174225. # include <m68881.h>
  174226. # endif
  174227. #endif
  174228. /* Codewarrior on NT has linking problems without this. */
  174229. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  174230. # define PNG_ALWAYS_EXTERN
  174231. #endif
  174232. /* This provides the non-ANSI (far) memory allocation routines. */
  174233. #if defined(__TURBOC__) && defined(__MSDOS__)
  174234. # include <mem.h>
  174235. # include <alloc.h>
  174236. #endif
  174237. /* I have no idea why is this necessary... */
  174238. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  174239. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  174240. # include <malloc.h>
  174241. #endif
  174242. /* This controls how fine the dithering gets. As this allocates
  174243. * a largish chunk of memory (32K), those who are not as concerned
  174244. * with dithering quality can decrease some or all of these.
  174245. */
  174246. #ifndef PNG_DITHER_RED_BITS
  174247. # define PNG_DITHER_RED_BITS 5
  174248. #endif
  174249. #ifndef PNG_DITHER_GREEN_BITS
  174250. # define PNG_DITHER_GREEN_BITS 5
  174251. #endif
  174252. #ifndef PNG_DITHER_BLUE_BITS
  174253. # define PNG_DITHER_BLUE_BITS 5
  174254. #endif
  174255. /* This controls how fine the gamma correction becomes when you
  174256. * are only interested in 8 bits anyway. Increasing this value
  174257. * results in more memory being used, and more pow() functions
  174258. * being called to fill in the gamma tables. Don't set this value
  174259. * less then 8, and even that may not work (I haven't tested it).
  174260. */
  174261. #ifndef PNG_MAX_GAMMA_8
  174262. # define PNG_MAX_GAMMA_8 11
  174263. #endif
  174264. /* This controls how much a difference in gamma we can tolerate before
  174265. * we actually start doing gamma conversion.
  174266. */
  174267. #ifndef PNG_GAMMA_THRESHOLD
  174268. # define PNG_GAMMA_THRESHOLD 0.05
  174269. #endif
  174270. #endif /* PNG_INTERNAL */
  174271. /* The following uses const char * instead of char * for error
  174272. * and warning message functions, so some compilers won't complain.
  174273. * If you do not want to use const, define PNG_NO_CONST here.
  174274. */
  174275. #ifndef PNG_NO_CONST
  174276. # define PNG_CONST const
  174277. #else
  174278. # define PNG_CONST
  174279. #endif
  174280. /* The following defines give you the ability to remove code from the
  174281. * library that you will not be using. I wish I could figure out how to
  174282. * automate this, but I can't do that without making it seriously hard
  174283. * on the users. So if you are not using an ability, change the #define
  174284. * to and #undef, and that part of the library will not be compiled. If
  174285. * your linker can't find a function, you may want to make sure the
  174286. * ability is defined here. Some of these depend upon some others being
  174287. * defined. I haven't figured out all the interactions here, so you may
  174288. * have to experiment awhile to get everything to compile. If you are
  174289. * creating or using a shared library, you probably shouldn't touch this,
  174290. * as it will affect the size of the structures, and this will cause bad
  174291. * things to happen if the library and/or application ever change.
  174292. */
  174293. /* Any features you will not be using can be undef'ed here */
  174294. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  174295. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  174296. * on the compile line, then pick and choose which ones to define without
  174297. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  174298. * if you only want to have a png-compliant reader/writer but don't need
  174299. * any of the extra transformations. This saves about 80 kbytes in a
  174300. * typical installation of the library. (PNG_NO_* form added in version
  174301. * 1.0.1c, for consistency)
  174302. */
  174303. /* The size of the png_text structure changed in libpng-1.0.6 when
  174304. * iTXt support was added. iTXt support was turned off by default through
  174305. * libpng-1.2.x, to support old apps that malloc the png_text structure
  174306. * instead of calling png_set_text() and letting libpng malloc it. It
  174307. * was turned on by default in libpng-1.3.0.
  174308. */
  174309. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174310. # ifndef PNG_NO_iTXt_SUPPORTED
  174311. # define PNG_NO_iTXt_SUPPORTED
  174312. # endif
  174313. # ifndef PNG_NO_READ_iTXt
  174314. # define PNG_NO_READ_iTXt
  174315. # endif
  174316. # ifndef PNG_NO_WRITE_iTXt
  174317. # define PNG_NO_WRITE_iTXt
  174318. # endif
  174319. #endif
  174320. #if !defined(PNG_NO_iTXt_SUPPORTED)
  174321. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  174322. # define PNG_READ_iTXt
  174323. # endif
  174324. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  174325. # define PNG_WRITE_iTXt
  174326. # endif
  174327. #endif
  174328. /* The following support, added after version 1.0.0, can be turned off here en
  174329. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  174330. * with old applications that require the length of png_struct and png_info
  174331. * to remain unchanged.
  174332. */
  174333. #ifdef PNG_LEGACY_SUPPORTED
  174334. # define PNG_NO_FREE_ME
  174335. # define PNG_NO_READ_UNKNOWN_CHUNKS
  174336. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  174337. # define PNG_NO_READ_USER_CHUNKS
  174338. # define PNG_NO_READ_iCCP
  174339. # define PNG_NO_WRITE_iCCP
  174340. # define PNG_NO_READ_iTXt
  174341. # define PNG_NO_WRITE_iTXt
  174342. # define PNG_NO_READ_sCAL
  174343. # define PNG_NO_WRITE_sCAL
  174344. # define PNG_NO_READ_sPLT
  174345. # define PNG_NO_WRITE_sPLT
  174346. # define PNG_NO_INFO_IMAGE
  174347. # define PNG_NO_READ_RGB_TO_GRAY
  174348. # define PNG_NO_READ_USER_TRANSFORM
  174349. # define PNG_NO_WRITE_USER_TRANSFORM
  174350. # define PNG_NO_USER_MEM
  174351. # define PNG_NO_READ_EMPTY_PLTE
  174352. # define PNG_NO_MNG_FEATURES
  174353. # define PNG_NO_FIXED_POINT_SUPPORTED
  174354. #endif
  174355. /* Ignore attempt to turn off both floating and fixed point support */
  174356. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  174357. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  174358. # define PNG_FIXED_POINT_SUPPORTED
  174359. #endif
  174360. #ifndef PNG_NO_FREE_ME
  174361. # define PNG_FREE_ME_SUPPORTED
  174362. #endif
  174363. #if defined(PNG_READ_SUPPORTED)
  174364. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  174365. !defined(PNG_NO_READ_TRANSFORMS)
  174366. # define PNG_READ_TRANSFORMS_SUPPORTED
  174367. #endif
  174368. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  174369. # ifndef PNG_NO_READ_EXPAND
  174370. # define PNG_READ_EXPAND_SUPPORTED
  174371. # endif
  174372. # ifndef PNG_NO_READ_SHIFT
  174373. # define PNG_READ_SHIFT_SUPPORTED
  174374. # endif
  174375. # ifndef PNG_NO_READ_PACK
  174376. # define PNG_READ_PACK_SUPPORTED
  174377. # endif
  174378. # ifndef PNG_NO_READ_BGR
  174379. # define PNG_READ_BGR_SUPPORTED
  174380. # endif
  174381. # ifndef PNG_NO_READ_SWAP
  174382. # define PNG_READ_SWAP_SUPPORTED
  174383. # endif
  174384. # ifndef PNG_NO_READ_PACKSWAP
  174385. # define PNG_READ_PACKSWAP_SUPPORTED
  174386. # endif
  174387. # ifndef PNG_NO_READ_INVERT
  174388. # define PNG_READ_INVERT_SUPPORTED
  174389. # endif
  174390. # ifndef PNG_NO_READ_DITHER
  174391. # define PNG_READ_DITHER_SUPPORTED
  174392. # endif
  174393. # ifndef PNG_NO_READ_BACKGROUND
  174394. # define PNG_READ_BACKGROUND_SUPPORTED
  174395. # endif
  174396. # ifndef PNG_NO_READ_16_TO_8
  174397. # define PNG_READ_16_TO_8_SUPPORTED
  174398. # endif
  174399. # ifndef PNG_NO_READ_FILLER
  174400. # define PNG_READ_FILLER_SUPPORTED
  174401. # endif
  174402. # ifndef PNG_NO_READ_GAMMA
  174403. # define PNG_READ_GAMMA_SUPPORTED
  174404. # endif
  174405. # ifndef PNG_NO_READ_GRAY_TO_RGB
  174406. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  174407. # endif
  174408. # ifndef PNG_NO_READ_SWAP_ALPHA
  174409. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  174410. # endif
  174411. # ifndef PNG_NO_READ_INVERT_ALPHA
  174412. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  174413. # endif
  174414. # ifndef PNG_NO_READ_STRIP_ALPHA
  174415. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  174416. # endif
  174417. # ifndef PNG_NO_READ_USER_TRANSFORM
  174418. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  174419. # endif
  174420. # ifndef PNG_NO_READ_RGB_TO_GRAY
  174421. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  174422. # endif
  174423. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  174424. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  174425. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  174426. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  174427. #endif /* about interlacing capability! You'll */
  174428. /* still have interlacing unless you change the following line: */
  174429. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  174430. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  174431. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  174432. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  174433. # endif
  174434. #endif
  174435. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174436. /* Deprecated, will be removed from version 2.0.0.
  174437. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  174438. #ifndef PNG_NO_READ_EMPTY_PLTE
  174439. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  174440. #endif
  174441. #endif
  174442. #endif /* PNG_READ_SUPPORTED */
  174443. #if defined(PNG_WRITE_SUPPORTED)
  174444. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  174445. !defined(PNG_NO_WRITE_TRANSFORMS)
  174446. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  174447. #endif
  174448. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  174449. # ifndef PNG_NO_WRITE_SHIFT
  174450. # define PNG_WRITE_SHIFT_SUPPORTED
  174451. # endif
  174452. # ifndef PNG_NO_WRITE_PACK
  174453. # define PNG_WRITE_PACK_SUPPORTED
  174454. # endif
  174455. # ifndef PNG_NO_WRITE_BGR
  174456. # define PNG_WRITE_BGR_SUPPORTED
  174457. # endif
  174458. # ifndef PNG_NO_WRITE_SWAP
  174459. # define PNG_WRITE_SWAP_SUPPORTED
  174460. # endif
  174461. # ifndef PNG_NO_WRITE_PACKSWAP
  174462. # define PNG_WRITE_PACKSWAP_SUPPORTED
  174463. # endif
  174464. # ifndef PNG_NO_WRITE_INVERT
  174465. # define PNG_WRITE_INVERT_SUPPORTED
  174466. # endif
  174467. # ifndef PNG_NO_WRITE_FILLER
  174468. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  174469. # endif
  174470. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  174471. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  174472. # endif
  174473. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  174474. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  174475. # endif
  174476. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  174477. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  174478. # endif
  174479. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  174480. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  174481. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  174482. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  174483. encoders, but can cause trouble
  174484. if left undefined */
  174485. #endif
  174486. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  174487. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  174488. defined(PNG_FLOATING_POINT_SUPPORTED)
  174489. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  174490. #endif
  174491. #ifndef PNG_NO_WRITE_FLUSH
  174492. # define PNG_WRITE_FLUSH_SUPPORTED
  174493. #endif
  174494. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174495. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  174496. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  174497. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  174498. #endif
  174499. #endif
  174500. #endif /* PNG_WRITE_SUPPORTED */
  174501. #ifndef PNG_1_0_X
  174502. # ifndef PNG_NO_ERROR_NUMBERS
  174503. # define PNG_ERROR_NUMBERS_SUPPORTED
  174504. # endif
  174505. #endif /* PNG_1_0_X */
  174506. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  174507. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  174508. # ifndef PNG_NO_USER_TRANSFORM_PTR
  174509. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  174510. # endif
  174511. #endif
  174512. #ifndef PNG_NO_STDIO
  174513. # define PNG_TIME_RFC1123_SUPPORTED
  174514. #endif
  174515. /* This adds extra functions in pngget.c for accessing data from the
  174516. * info pointer (added in version 0.99)
  174517. * png_get_image_width()
  174518. * png_get_image_height()
  174519. * png_get_bit_depth()
  174520. * png_get_color_type()
  174521. * png_get_compression_type()
  174522. * png_get_filter_type()
  174523. * png_get_interlace_type()
  174524. * png_get_pixel_aspect_ratio()
  174525. * png_get_pixels_per_meter()
  174526. * png_get_x_offset_pixels()
  174527. * png_get_y_offset_pixels()
  174528. * png_get_x_offset_microns()
  174529. * png_get_y_offset_microns()
  174530. */
  174531. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  174532. # define PNG_EASY_ACCESS_SUPPORTED
  174533. #endif
  174534. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  174535. * and removed from version 1.2.20. The following will be removed
  174536. * from libpng-1.4.0
  174537. */
  174538. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  174539. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  174540. # define PNG_OPTIMIZED_CODE_SUPPORTED
  174541. # endif
  174542. #endif
  174543. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  174544. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  174545. # define PNG_ASSEMBLER_CODE_SUPPORTED
  174546. # endif
  174547. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  174548. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  174549. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174550. # define PNG_NO_MMX_CODE
  174551. # endif
  174552. # endif
  174553. # if defined(__APPLE__)
  174554. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174555. # define PNG_NO_MMX_CODE
  174556. # endif
  174557. # endif
  174558. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  174559. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174560. # define PNG_NO_MMX_CODE
  174561. # endif
  174562. # endif
  174563. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174564. # define PNG_MMX_CODE_SUPPORTED
  174565. # endif
  174566. #endif
  174567. /* end of obsolete code to be removed from libpng-1.4.0 */
  174568. #if !defined(PNG_1_0_X)
  174569. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  174570. # define PNG_USER_MEM_SUPPORTED
  174571. #endif
  174572. #endif /* PNG_1_0_X */
  174573. /* Added at libpng-1.2.6 */
  174574. #if !defined(PNG_1_0_X)
  174575. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  174576. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  174577. # define PNG_SET_USER_LIMITS_SUPPORTED
  174578. #endif
  174579. #endif
  174580. #endif /* PNG_1_0_X */
  174581. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  174582. * how large, set these limits to 0x7fffffffL
  174583. */
  174584. #ifndef PNG_USER_WIDTH_MAX
  174585. # define PNG_USER_WIDTH_MAX 1000000L
  174586. #endif
  174587. #ifndef PNG_USER_HEIGHT_MAX
  174588. # define PNG_USER_HEIGHT_MAX 1000000L
  174589. #endif
  174590. /* These are currently experimental features, define them if you want */
  174591. /* very little testing */
  174592. /*
  174593. #ifdef PNG_READ_SUPPORTED
  174594. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  174595. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  174596. # endif
  174597. #endif
  174598. */
  174599. /* This is only for PowerPC big-endian and 680x0 systems */
  174600. /* some testing */
  174601. /*
  174602. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  174603. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  174604. #endif
  174605. */
  174606. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  174607. /*
  174608. #define PNG_NO_POINTER_INDEXING
  174609. */
  174610. /* These functions are turned off by default, as they will be phased out. */
  174611. /*
  174612. #define PNG_USELESS_TESTS_SUPPORTED
  174613. #define PNG_CORRECT_PALETTE_SUPPORTED
  174614. */
  174615. /* Any chunks you are not interested in, you can undef here. The
  174616. * ones that allocate memory may be expecially important (hIST,
  174617. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  174618. * a bit smaller.
  174619. */
  174620. #if defined(PNG_READ_SUPPORTED) && \
  174621. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  174622. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  174623. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  174624. #endif
  174625. #if defined(PNG_WRITE_SUPPORTED) && \
  174626. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  174627. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  174628. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  174629. #endif
  174630. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  174631. #ifdef PNG_NO_READ_TEXT
  174632. # define PNG_NO_READ_iTXt
  174633. # define PNG_NO_READ_tEXt
  174634. # define PNG_NO_READ_zTXt
  174635. #endif
  174636. #ifndef PNG_NO_READ_bKGD
  174637. # define PNG_READ_bKGD_SUPPORTED
  174638. # define PNG_bKGD_SUPPORTED
  174639. #endif
  174640. #ifndef PNG_NO_READ_cHRM
  174641. # define PNG_READ_cHRM_SUPPORTED
  174642. # define PNG_cHRM_SUPPORTED
  174643. #endif
  174644. #ifndef PNG_NO_READ_gAMA
  174645. # define PNG_READ_gAMA_SUPPORTED
  174646. # define PNG_gAMA_SUPPORTED
  174647. #endif
  174648. #ifndef PNG_NO_READ_hIST
  174649. # define PNG_READ_hIST_SUPPORTED
  174650. # define PNG_hIST_SUPPORTED
  174651. #endif
  174652. #ifndef PNG_NO_READ_iCCP
  174653. # define PNG_READ_iCCP_SUPPORTED
  174654. # define PNG_iCCP_SUPPORTED
  174655. #endif
  174656. #ifndef PNG_NO_READ_iTXt
  174657. # ifndef PNG_READ_iTXt_SUPPORTED
  174658. # define PNG_READ_iTXt_SUPPORTED
  174659. # endif
  174660. # ifndef PNG_iTXt_SUPPORTED
  174661. # define PNG_iTXt_SUPPORTED
  174662. # endif
  174663. #endif
  174664. #ifndef PNG_NO_READ_oFFs
  174665. # define PNG_READ_oFFs_SUPPORTED
  174666. # define PNG_oFFs_SUPPORTED
  174667. #endif
  174668. #ifndef PNG_NO_READ_pCAL
  174669. # define PNG_READ_pCAL_SUPPORTED
  174670. # define PNG_pCAL_SUPPORTED
  174671. #endif
  174672. #ifndef PNG_NO_READ_sCAL
  174673. # define PNG_READ_sCAL_SUPPORTED
  174674. # define PNG_sCAL_SUPPORTED
  174675. #endif
  174676. #ifndef PNG_NO_READ_pHYs
  174677. # define PNG_READ_pHYs_SUPPORTED
  174678. # define PNG_pHYs_SUPPORTED
  174679. #endif
  174680. #ifndef PNG_NO_READ_sBIT
  174681. # define PNG_READ_sBIT_SUPPORTED
  174682. # define PNG_sBIT_SUPPORTED
  174683. #endif
  174684. #ifndef PNG_NO_READ_sPLT
  174685. # define PNG_READ_sPLT_SUPPORTED
  174686. # define PNG_sPLT_SUPPORTED
  174687. #endif
  174688. #ifndef PNG_NO_READ_sRGB
  174689. # define PNG_READ_sRGB_SUPPORTED
  174690. # define PNG_sRGB_SUPPORTED
  174691. #endif
  174692. #ifndef PNG_NO_READ_tEXt
  174693. # define PNG_READ_tEXt_SUPPORTED
  174694. # define PNG_tEXt_SUPPORTED
  174695. #endif
  174696. #ifndef PNG_NO_READ_tIME
  174697. # define PNG_READ_tIME_SUPPORTED
  174698. # define PNG_tIME_SUPPORTED
  174699. #endif
  174700. #ifndef PNG_NO_READ_tRNS
  174701. # define PNG_READ_tRNS_SUPPORTED
  174702. # define PNG_tRNS_SUPPORTED
  174703. #endif
  174704. #ifndef PNG_NO_READ_zTXt
  174705. # define PNG_READ_zTXt_SUPPORTED
  174706. # define PNG_zTXt_SUPPORTED
  174707. #endif
  174708. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  174709. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  174710. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  174711. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  174712. # endif
  174713. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  174714. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174715. # endif
  174716. #endif
  174717. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  174718. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  174719. # define PNG_READ_USER_CHUNKS_SUPPORTED
  174720. # define PNG_USER_CHUNKS_SUPPORTED
  174721. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  174722. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  174723. # endif
  174724. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  174725. # undef PNG_NO_HANDLE_AS_UNKNOWN
  174726. # endif
  174727. #endif
  174728. #ifndef PNG_NO_READ_OPT_PLTE
  174729. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  174730. #endif /* optional PLTE chunk in RGB and RGBA images */
  174731. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  174732. defined(PNG_READ_zTXt_SUPPORTED)
  174733. # define PNG_READ_TEXT_SUPPORTED
  174734. # define PNG_TEXT_SUPPORTED
  174735. #endif
  174736. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  174737. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  174738. #ifdef PNG_NO_WRITE_TEXT
  174739. # define PNG_NO_WRITE_iTXt
  174740. # define PNG_NO_WRITE_tEXt
  174741. # define PNG_NO_WRITE_zTXt
  174742. #endif
  174743. #ifndef PNG_NO_WRITE_bKGD
  174744. # define PNG_WRITE_bKGD_SUPPORTED
  174745. # ifndef PNG_bKGD_SUPPORTED
  174746. # define PNG_bKGD_SUPPORTED
  174747. # endif
  174748. #endif
  174749. #ifndef PNG_NO_WRITE_cHRM
  174750. # define PNG_WRITE_cHRM_SUPPORTED
  174751. # ifndef PNG_cHRM_SUPPORTED
  174752. # define PNG_cHRM_SUPPORTED
  174753. # endif
  174754. #endif
  174755. #ifndef PNG_NO_WRITE_gAMA
  174756. # define PNG_WRITE_gAMA_SUPPORTED
  174757. # ifndef PNG_gAMA_SUPPORTED
  174758. # define PNG_gAMA_SUPPORTED
  174759. # endif
  174760. #endif
  174761. #ifndef PNG_NO_WRITE_hIST
  174762. # define PNG_WRITE_hIST_SUPPORTED
  174763. # ifndef PNG_hIST_SUPPORTED
  174764. # define PNG_hIST_SUPPORTED
  174765. # endif
  174766. #endif
  174767. #ifndef PNG_NO_WRITE_iCCP
  174768. # define PNG_WRITE_iCCP_SUPPORTED
  174769. # ifndef PNG_iCCP_SUPPORTED
  174770. # define PNG_iCCP_SUPPORTED
  174771. # endif
  174772. #endif
  174773. #ifndef PNG_NO_WRITE_iTXt
  174774. # ifndef PNG_WRITE_iTXt_SUPPORTED
  174775. # define PNG_WRITE_iTXt_SUPPORTED
  174776. # endif
  174777. # ifndef PNG_iTXt_SUPPORTED
  174778. # define PNG_iTXt_SUPPORTED
  174779. # endif
  174780. #endif
  174781. #ifndef PNG_NO_WRITE_oFFs
  174782. # define PNG_WRITE_oFFs_SUPPORTED
  174783. # ifndef PNG_oFFs_SUPPORTED
  174784. # define PNG_oFFs_SUPPORTED
  174785. # endif
  174786. #endif
  174787. #ifndef PNG_NO_WRITE_pCAL
  174788. # define PNG_WRITE_pCAL_SUPPORTED
  174789. # ifndef PNG_pCAL_SUPPORTED
  174790. # define PNG_pCAL_SUPPORTED
  174791. # endif
  174792. #endif
  174793. #ifndef PNG_NO_WRITE_sCAL
  174794. # define PNG_WRITE_sCAL_SUPPORTED
  174795. # ifndef PNG_sCAL_SUPPORTED
  174796. # define PNG_sCAL_SUPPORTED
  174797. # endif
  174798. #endif
  174799. #ifndef PNG_NO_WRITE_pHYs
  174800. # define PNG_WRITE_pHYs_SUPPORTED
  174801. # ifndef PNG_pHYs_SUPPORTED
  174802. # define PNG_pHYs_SUPPORTED
  174803. # endif
  174804. #endif
  174805. #ifndef PNG_NO_WRITE_sBIT
  174806. # define PNG_WRITE_sBIT_SUPPORTED
  174807. # ifndef PNG_sBIT_SUPPORTED
  174808. # define PNG_sBIT_SUPPORTED
  174809. # endif
  174810. #endif
  174811. #ifndef PNG_NO_WRITE_sPLT
  174812. # define PNG_WRITE_sPLT_SUPPORTED
  174813. # ifndef PNG_sPLT_SUPPORTED
  174814. # define PNG_sPLT_SUPPORTED
  174815. # endif
  174816. #endif
  174817. #ifndef PNG_NO_WRITE_sRGB
  174818. # define PNG_WRITE_sRGB_SUPPORTED
  174819. # ifndef PNG_sRGB_SUPPORTED
  174820. # define PNG_sRGB_SUPPORTED
  174821. # endif
  174822. #endif
  174823. #ifndef PNG_NO_WRITE_tEXt
  174824. # define PNG_WRITE_tEXt_SUPPORTED
  174825. # ifndef PNG_tEXt_SUPPORTED
  174826. # define PNG_tEXt_SUPPORTED
  174827. # endif
  174828. #endif
  174829. #ifndef PNG_NO_WRITE_tIME
  174830. # define PNG_WRITE_tIME_SUPPORTED
  174831. # ifndef PNG_tIME_SUPPORTED
  174832. # define PNG_tIME_SUPPORTED
  174833. # endif
  174834. #endif
  174835. #ifndef PNG_NO_WRITE_tRNS
  174836. # define PNG_WRITE_tRNS_SUPPORTED
  174837. # ifndef PNG_tRNS_SUPPORTED
  174838. # define PNG_tRNS_SUPPORTED
  174839. # endif
  174840. #endif
  174841. #ifndef PNG_NO_WRITE_zTXt
  174842. # define PNG_WRITE_zTXt_SUPPORTED
  174843. # ifndef PNG_zTXt_SUPPORTED
  174844. # define PNG_zTXt_SUPPORTED
  174845. # endif
  174846. #endif
  174847. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  174848. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  174849. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  174850. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  174851. # endif
  174852. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  174853. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174854. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174855. # endif
  174856. # endif
  174857. #endif
  174858. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  174859. defined(PNG_WRITE_zTXt_SUPPORTED)
  174860. # define PNG_WRITE_TEXT_SUPPORTED
  174861. # ifndef PNG_TEXT_SUPPORTED
  174862. # define PNG_TEXT_SUPPORTED
  174863. # endif
  174864. #endif
  174865. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  174866. /* Turn this off to disable png_read_png() and
  174867. * png_write_png() and leave the row_pointers member
  174868. * out of the info structure.
  174869. */
  174870. #ifndef PNG_NO_INFO_IMAGE
  174871. # define PNG_INFO_IMAGE_SUPPORTED
  174872. #endif
  174873. /* need the time information for reading tIME chunks */
  174874. #if defined(PNG_tIME_SUPPORTED)
  174875. # if !defined(_WIN32_WCE)
  174876. /* "time.h" functions are not supported on WindowsCE */
  174877. # include <time.h>
  174878. # endif
  174879. #endif
  174880. /* Some typedefs to get us started. These should be safe on most of the
  174881. * common platforms. The typedefs should be at least as large as the
  174882. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  174883. * don't have to be exactly that size. Some compilers dislike passing
  174884. * unsigned shorts as function parameters, so you may be better off using
  174885. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  174886. * want to have unsigned int for png_uint_32 instead of unsigned long.
  174887. */
  174888. typedef unsigned long png_uint_32;
  174889. typedef long png_int_32;
  174890. typedef unsigned short png_uint_16;
  174891. typedef short png_int_16;
  174892. typedef unsigned char png_byte;
  174893. /* This is usually size_t. It is typedef'ed just in case you need it to
  174894. change (I'm not sure if you will or not, so I thought I'd be safe) */
  174895. #ifdef PNG_SIZE_T
  174896. typedef PNG_SIZE_T png_size_t;
  174897. # define png_sizeof(x) png_convert_size(sizeof (x))
  174898. #else
  174899. typedef size_t png_size_t;
  174900. # define png_sizeof(x) sizeof (x)
  174901. #endif
  174902. /* The following is needed for medium model support. It cannot be in the
  174903. * PNG_INTERNAL section. Needs modification for other compilers besides
  174904. * MSC. Model independent support declares all arrays and pointers to be
  174905. * large using the far keyword. The zlib version used must also support
  174906. * model independent data. As of version zlib 1.0.4, the necessary changes
  174907. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  174908. * changes that are needed. (Tim Wegner)
  174909. */
  174910. /* Separate compiler dependencies (problem here is that zlib.h always
  174911. defines FAR. (SJT) */
  174912. #ifdef __BORLANDC__
  174913. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  174914. # define LDATA 1
  174915. # else
  174916. # define LDATA 0
  174917. # endif
  174918. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  174919. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  174920. # define PNG_MAX_MALLOC_64K
  174921. # if (LDATA != 1)
  174922. # ifndef FAR
  174923. # define FAR __far
  174924. # endif
  174925. # define USE_FAR_KEYWORD
  174926. # endif /* LDATA != 1 */
  174927. /* Possibly useful for moving data out of default segment.
  174928. * Uncomment it if you want. Could also define FARDATA as
  174929. * const if your compiler supports it. (SJT)
  174930. # define FARDATA FAR
  174931. */
  174932. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  174933. #endif /* __BORLANDC__ */
  174934. /* Suggest testing for specific compiler first before testing for
  174935. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  174936. * making reliance oncertain keywords suspect. (SJT)
  174937. */
  174938. /* MSC Medium model */
  174939. #if defined(FAR)
  174940. # if defined(M_I86MM)
  174941. # define USE_FAR_KEYWORD
  174942. # define FARDATA FAR
  174943. # include <dos.h>
  174944. # endif
  174945. #endif
  174946. /* SJT: default case */
  174947. #ifndef FAR
  174948. # define FAR
  174949. #endif
  174950. /* At this point FAR is always defined */
  174951. #ifndef FARDATA
  174952. # define FARDATA
  174953. #endif
  174954. /* Typedef for floating-point numbers that are converted
  174955. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  174956. typedef png_int_32 png_fixed_point;
  174957. /* Add typedefs for pointers */
  174958. typedef void FAR * png_voidp;
  174959. typedef png_byte FAR * png_bytep;
  174960. typedef png_uint_32 FAR * png_uint_32p;
  174961. typedef png_int_32 FAR * png_int_32p;
  174962. typedef png_uint_16 FAR * png_uint_16p;
  174963. typedef png_int_16 FAR * png_int_16p;
  174964. typedef PNG_CONST char FAR * png_const_charp;
  174965. typedef char FAR * png_charp;
  174966. typedef png_fixed_point FAR * png_fixed_point_p;
  174967. #ifndef PNG_NO_STDIO
  174968. #if defined(_WIN32_WCE)
  174969. typedef HANDLE png_FILE_p;
  174970. #else
  174971. typedef FILE * png_FILE_p;
  174972. #endif
  174973. #endif
  174974. #ifdef PNG_FLOATING_POINT_SUPPORTED
  174975. typedef double FAR * png_doublep;
  174976. #endif
  174977. /* Pointers to pointers; i.e. arrays */
  174978. typedef png_byte FAR * FAR * png_bytepp;
  174979. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  174980. typedef png_int_32 FAR * FAR * png_int_32pp;
  174981. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  174982. typedef png_int_16 FAR * FAR * png_int_16pp;
  174983. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  174984. typedef char FAR * FAR * png_charpp;
  174985. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  174986. #ifdef PNG_FLOATING_POINT_SUPPORTED
  174987. typedef double FAR * FAR * png_doublepp;
  174988. #endif
  174989. /* Pointers to pointers to pointers; i.e., pointer to array */
  174990. typedef char FAR * FAR * FAR * png_charppp;
  174991. #if 0
  174992. /* SPC - Is this stuff deprecated? */
  174993. /* It'll be removed as of libpng-1.3.0 - GR-P */
  174994. /* libpng typedefs for types in zlib. If zlib changes
  174995. * or another compression library is used, then change these.
  174996. * Eliminates need to change all the source files.
  174997. */
  174998. typedef charf * png_zcharp;
  174999. typedef charf * FAR * png_zcharpp;
  175000. typedef z_stream FAR * png_zstreamp;
  175001. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  175002. /*
  175003. * Define PNG_BUILD_DLL if the module being built is a Windows
  175004. * LIBPNG DLL.
  175005. *
  175006. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  175007. * It is equivalent to Microsoft predefined macro _DLL that is
  175008. * automatically defined when you compile using the share
  175009. * version of the CRT (C Run-Time library)
  175010. *
  175011. * The cygwin mods make this behavior a little different:
  175012. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  175013. * Define PNG_STATIC if you are building a static library for use with cygwin,
  175014. * -or- if you are building an application that you want to link to the
  175015. * static library.
  175016. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  175017. * the other flags is defined.
  175018. */
  175019. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  175020. # define PNG_DLL
  175021. #endif
  175022. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  175023. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  175024. * command-line override
  175025. */
  175026. #if defined(__CYGWIN__)
  175027. # if !defined(PNG_STATIC)
  175028. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175029. # undef PNG_USE_GLOBAL_ARRAYS
  175030. # endif
  175031. # if !defined(PNG_USE_LOCAL_ARRAYS)
  175032. # define PNG_USE_LOCAL_ARRAYS
  175033. # endif
  175034. # else
  175035. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  175036. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175037. # undef PNG_USE_GLOBAL_ARRAYS
  175038. # endif
  175039. # endif
  175040. # endif
  175041. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175042. # define PNG_USE_LOCAL_ARRAYS
  175043. # endif
  175044. #endif
  175045. /* Do not use global arrays (helps with building DLL's)
  175046. * They are no longer used in libpng itself, since version 1.0.5c,
  175047. * but might be required for some pre-1.0.5c applications.
  175048. */
  175049. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175050. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  175051. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  175052. # define PNG_USE_LOCAL_ARRAYS
  175053. # else
  175054. # define PNG_USE_GLOBAL_ARRAYS
  175055. # endif
  175056. #endif
  175057. #if defined(__CYGWIN__)
  175058. # undef PNGAPI
  175059. # define PNGAPI __cdecl
  175060. # undef PNG_IMPEXP
  175061. # define PNG_IMPEXP
  175062. #endif
  175063. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  175064. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  175065. * Don't ignore those warnings; you must also reset the default calling
  175066. * convention in your compiler to match your PNGAPI, and you must build
  175067. * zlib and your applications the same way you build libpng.
  175068. */
  175069. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  175070. # ifndef PNG_NO_MODULEDEF
  175071. # define PNG_NO_MODULEDEF
  175072. # endif
  175073. #endif
  175074. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  175075. # define PNG_IMPEXP
  175076. #endif
  175077. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  175078. (( defined(_Windows) || defined(_WINDOWS) || \
  175079. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  175080. # ifndef PNGAPI
  175081. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  175082. # define PNGAPI __cdecl
  175083. # else
  175084. # define PNGAPI _cdecl
  175085. # endif
  175086. # endif
  175087. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  175088. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  175089. # define PNG_IMPEXP
  175090. # endif
  175091. # if !defined(PNG_IMPEXP)
  175092. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175093. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  175094. /* Borland/Microsoft */
  175095. # if defined(_MSC_VER) || defined(__BORLANDC__)
  175096. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  175097. # define PNG_EXPORT PNG_EXPORT_TYPE1
  175098. # else
  175099. # define PNG_EXPORT PNG_EXPORT_TYPE2
  175100. # if defined(PNG_BUILD_DLL)
  175101. # define PNG_IMPEXP __export
  175102. # else
  175103. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  175104. VC++ */
  175105. # endif /* Exists in Borland C++ for
  175106. C++ classes (== huge) */
  175107. # endif
  175108. # endif
  175109. # if !defined(PNG_IMPEXP)
  175110. # if defined(PNG_BUILD_DLL)
  175111. # define PNG_IMPEXP __declspec(dllexport)
  175112. # else
  175113. # define PNG_IMPEXP __declspec(dllimport)
  175114. # endif
  175115. # endif
  175116. # endif /* PNG_IMPEXP */
  175117. #else /* !(DLL || non-cygwin WINDOWS) */
  175118. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  175119. # ifndef PNGAPI
  175120. # define PNGAPI _System
  175121. # endif
  175122. # else
  175123. # if 0 /* ... other platforms, with other meanings */
  175124. # endif
  175125. # endif
  175126. #endif
  175127. #ifndef PNGAPI
  175128. # define PNGAPI
  175129. #endif
  175130. #ifndef PNG_IMPEXP
  175131. # define PNG_IMPEXP
  175132. #endif
  175133. #ifdef PNG_BUILDSYMS
  175134. # ifndef PNG_EXPORT
  175135. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  175136. # endif
  175137. # ifdef PNG_USE_GLOBAL_ARRAYS
  175138. # ifndef PNG_EXPORT_VAR
  175139. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  175140. # endif
  175141. # endif
  175142. #endif
  175143. #ifndef PNG_EXPORT
  175144. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175145. #endif
  175146. #ifdef PNG_USE_GLOBAL_ARRAYS
  175147. # ifndef PNG_EXPORT_VAR
  175148. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  175149. # endif
  175150. #endif
  175151. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  175152. * functions that are passed far data must be model independent.
  175153. */
  175154. #ifndef PNG_ABORT
  175155. # define PNG_ABORT() abort()
  175156. #endif
  175157. #ifdef PNG_SETJMP_SUPPORTED
  175158. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  175159. #else
  175160. # define png_jmpbuf(png_ptr) \
  175161. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  175162. #endif
  175163. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  175164. /* use this to make far-to-near assignments */
  175165. # define CHECK 1
  175166. # define NOCHECK 0
  175167. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  175168. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  175169. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  175170. # define png_strcpy _fstrcpy
  175171. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  175172. # define png_strlen _fstrlen
  175173. # define png_memcmp _fmemcmp /* SJT: added */
  175174. # define png_memcpy _fmemcpy
  175175. # define png_memset _fmemset
  175176. #else /* use the usual functions */
  175177. # define CVT_PTR(ptr) (ptr)
  175178. # define CVT_PTR_NOCHECK(ptr) (ptr)
  175179. # ifndef PNG_NO_SNPRINTF
  175180. # ifdef _MSC_VER
  175181. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  175182. # define png_snprintf2 _snprintf
  175183. # define png_snprintf6 _snprintf
  175184. # else
  175185. # define png_snprintf snprintf /* Added to v 1.2.19 */
  175186. # define png_snprintf2 snprintf
  175187. # define png_snprintf6 snprintf
  175188. # endif
  175189. # else
  175190. /* You don't have or don't want to use snprintf(). Caution: Using
  175191. * sprintf instead of snprintf exposes your application to accidental
  175192. * or malevolent buffer overflows. If you don't have snprintf()
  175193. * as a general rule you should provide one (you can get one from
  175194. * Portable OpenSSH). */
  175195. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  175196. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  175197. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  175198. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  175199. # endif
  175200. # define png_strcpy strcpy
  175201. # define png_strncpy strncpy /* Added to v 1.2.6 */
  175202. # define png_strlen strlen
  175203. # define png_memcmp memcmp /* SJT: added */
  175204. # define png_memcpy memcpy
  175205. # define png_memset memset
  175206. #endif
  175207. /* End of memory model independent support */
  175208. /* Just a little check that someone hasn't tried to define something
  175209. * contradictory.
  175210. */
  175211. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  175212. # undef PNG_ZBUF_SIZE
  175213. # define PNG_ZBUF_SIZE 65536L
  175214. #endif
  175215. /* Added at libpng-1.2.8 */
  175216. #endif /* PNG_VERSION_INFO_ONLY */
  175217. #endif /* PNGCONF_H */
  175218. /********* End of inlined file: pngconf.h *********/
  175219. #ifdef _MSC_VER
  175220. #pragma warning (disable: 4996 4100)
  175221. #endif
  175222. /*
  175223. * Added at libpng-1.2.8 */
  175224. /* Ref MSDN: Private as priority over Special
  175225. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  175226. * procedures. If this value is given, the StringFileInfo block must
  175227. * contain a PrivateBuild string.
  175228. *
  175229. * VS_FF_SPECIALBUILD File *was* built by the original company using
  175230. * standard release procedures but is a variation of the standard
  175231. * file of the same version number. If this value is given, the
  175232. * StringFileInfo block must contain a SpecialBuild string.
  175233. */
  175234. #if defined(PNG_USER_PRIVATEBUILD)
  175235. # define PNG_LIBPNG_BUILD_TYPE \
  175236. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  175237. #else
  175238. # if defined(PNG_LIBPNG_SPECIALBUILD)
  175239. # define PNG_LIBPNG_BUILD_TYPE \
  175240. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  175241. # else
  175242. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  175243. # endif
  175244. #endif
  175245. #ifndef PNG_VERSION_INFO_ONLY
  175246. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  175247. #ifdef __cplusplus
  175248. extern "C" {
  175249. #endif /* __cplusplus */
  175250. /* This file is arranged in several sections. The first section contains
  175251. * structure and type definitions. The second section contains the external
  175252. * library functions, while the third has the internal library functions,
  175253. * which applications aren't expected to use directly.
  175254. */
  175255. #ifndef PNG_NO_TYPECAST_NULL
  175256. #define int_p_NULL (int *)NULL
  175257. #define png_bytep_NULL (png_bytep)NULL
  175258. #define png_bytepp_NULL (png_bytepp)NULL
  175259. #define png_doublep_NULL (png_doublep)NULL
  175260. #define png_error_ptr_NULL (png_error_ptr)NULL
  175261. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  175262. #define png_free_ptr_NULL (png_free_ptr)NULL
  175263. #define png_infopp_NULL (png_infopp)NULL
  175264. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  175265. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  175266. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  175267. #define png_structp_NULL (png_structp)NULL
  175268. #define png_uint_16p_NULL (png_uint_16p)NULL
  175269. #define png_voidp_NULL (png_voidp)NULL
  175270. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  175271. #else
  175272. #define int_p_NULL NULL
  175273. #define png_bytep_NULL NULL
  175274. #define png_bytepp_NULL NULL
  175275. #define png_doublep_NULL NULL
  175276. #define png_error_ptr_NULL NULL
  175277. #define png_flush_ptr_NULL NULL
  175278. #define png_free_ptr_NULL NULL
  175279. #define png_infopp_NULL NULL
  175280. #define png_malloc_ptr_NULL NULL
  175281. #define png_read_status_ptr_NULL NULL
  175282. #define png_rw_ptr_NULL NULL
  175283. #define png_structp_NULL NULL
  175284. #define png_uint_16p_NULL NULL
  175285. #define png_voidp_NULL NULL
  175286. #define png_write_status_ptr_NULL NULL
  175287. #endif
  175288. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  175289. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  175290. /* Version information for C files, stored in png.c. This had better match
  175291. * the version above.
  175292. */
  175293. #ifdef PNG_USE_GLOBAL_ARRAYS
  175294. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  175295. /* need room for 99.99.99beta99z */
  175296. #else
  175297. #define png_libpng_ver png_get_header_ver(NULL)
  175298. #endif
  175299. #ifdef PNG_USE_GLOBAL_ARRAYS
  175300. /* This was removed in version 1.0.5c */
  175301. /* Structures to facilitate easy interlacing. See png.c for more details */
  175302. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  175303. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  175304. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  175305. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  175306. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  175307. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  175308. /* This isn't currently used. If you need it, see png.c for more details.
  175309. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  175310. */
  175311. #endif
  175312. #endif /* PNG_NO_EXTERN */
  175313. /* Three color definitions. The order of the red, green, and blue, (and the
  175314. * exact size) is not important, although the size of the fields need to
  175315. * be png_byte or png_uint_16 (as defined below).
  175316. */
  175317. typedef struct png_color_struct
  175318. {
  175319. png_byte red;
  175320. png_byte green;
  175321. png_byte blue;
  175322. } png_color;
  175323. typedef png_color FAR * png_colorp;
  175324. typedef png_color FAR * FAR * png_colorpp;
  175325. typedef struct png_color_16_struct
  175326. {
  175327. png_byte index; /* used for palette files */
  175328. png_uint_16 red; /* for use in red green blue files */
  175329. png_uint_16 green;
  175330. png_uint_16 blue;
  175331. png_uint_16 gray; /* for use in grayscale files */
  175332. } png_color_16;
  175333. typedef png_color_16 FAR * png_color_16p;
  175334. typedef png_color_16 FAR * FAR * png_color_16pp;
  175335. typedef struct png_color_8_struct
  175336. {
  175337. png_byte red; /* for use in red green blue files */
  175338. png_byte green;
  175339. png_byte blue;
  175340. png_byte gray; /* for use in grayscale files */
  175341. png_byte alpha; /* for alpha channel files */
  175342. } png_color_8;
  175343. typedef png_color_8 FAR * png_color_8p;
  175344. typedef png_color_8 FAR * FAR * png_color_8pp;
  175345. /*
  175346. * The following two structures are used for the in-core representation
  175347. * of sPLT chunks.
  175348. */
  175349. typedef struct png_sPLT_entry_struct
  175350. {
  175351. png_uint_16 red;
  175352. png_uint_16 green;
  175353. png_uint_16 blue;
  175354. png_uint_16 alpha;
  175355. png_uint_16 frequency;
  175356. } png_sPLT_entry;
  175357. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  175358. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  175359. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  175360. * occupy the LSB of their respective members, and the MSB of each member
  175361. * is zero-filled. The frequency member always occupies the full 16 bits.
  175362. */
  175363. typedef struct png_sPLT_struct
  175364. {
  175365. png_charp name; /* palette name */
  175366. png_byte depth; /* depth of palette samples */
  175367. png_sPLT_entryp entries; /* palette entries */
  175368. png_int_32 nentries; /* number of palette entries */
  175369. } png_sPLT_t;
  175370. typedef png_sPLT_t FAR * png_sPLT_tp;
  175371. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  175372. #ifdef PNG_TEXT_SUPPORTED
  175373. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  175374. * and whether that contents is compressed or not. The "key" field
  175375. * points to a regular zero-terminated C string. The "text", "lang", and
  175376. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  175377. * However, the * structure returned by png_get_text() will always contain
  175378. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  175379. * so they can be safely used in printf() and other string-handling functions.
  175380. */
  175381. typedef struct png_text_struct
  175382. {
  175383. int compression; /* compression value:
  175384. -1: tEXt, none
  175385. 0: zTXt, deflate
  175386. 1: iTXt, none
  175387. 2: iTXt, deflate */
  175388. png_charp key; /* keyword, 1-79 character description of "text" */
  175389. png_charp text; /* comment, may be an empty string (ie "")
  175390. or a NULL pointer */
  175391. png_size_t text_length; /* length of the text string */
  175392. #ifdef PNG_iTXt_SUPPORTED
  175393. png_size_t itxt_length; /* length of the itxt string */
  175394. png_charp lang; /* language code, 0-79 characters
  175395. or a NULL pointer */
  175396. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  175397. chars or a NULL pointer */
  175398. #endif
  175399. } png_text;
  175400. typedef png_text FAR * png_textp;
  175401. typedef png_text FAR * FAR * png_textpp;
  175402. #endif
  175403. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  175404. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  175405. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  175406. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  175407. #define PNG_TEXT_COMPRESSION_NONE -1
  175408. #define PNG_TEXT_COMPRESSION_zTXt 0
  175409. #define PNG_ITXT_COMPRESSION_NONE 1
  175410. #define PNG_ITXT_COMPRESSION_zTXt 2
  175411. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  175412. /* png_time is a way to hold the time in an machine independent way.
  175413. * Two conversions are provided, both from time_t and struct tm. There
  175414. * is no portable way to convert to either of these structures, as far
  175415. * as I know. If you know of a portable way, send it to me. As a side
  175416. * note - PNG has always been Year 2000 compliant!
  175417. */
  175418. typedef struct png_time_struct
  175419. {
  175420. png_uint_16 year; /* full year, as in, 1995 */
  175421. png_byte month; /* month of year, 1 - 12 */
  175422. png_byte day; /* day of month, 1 - 31 */
  175423. png_byte hour; /* hour of day, 0 - 23 */
  175424. png_byte minute; /* minute of hour, 0 - 59 */
  175425. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  175426. } png_time;
  175427. typedef png_time FAR * png_timep;
  175428. typedef png_time FAR * FAR * png_timepp;
  175429. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175430. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  175431. * no specific support. The idea is that we can use this to queue
  175432. * up private chunks for output even though the library doesn't actually
  175433. * know about their semantics.
  175434. */
  175435. typedef struct png_unknown_chunk_t
  175436. {
  175437. png_byte name[5];
  175438. png_byte *data;
  175439. png_size_t size;
  175440. /* libpng-using applications should NOT directly modify this byte. */
  175441. png_byte location; /* mode of operation at read time */
  175442. }
  175443. png_unknown_chunk;
  175444. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  175445. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  175446. #endif
  175447. /* png_info is a structure that holds the information in a PNG file so
  175448. * that the application can find out the characteristics of the image.
  175449. * If you are reading the file, this structure will tell you what is
  175450. * in the PNG file. If you are writing the file, fill in the information
  175451. * you want to put into the PNG file, then call png_write_info().
  175452. * The names chosen should be very close to the PNG specification, so
  175453. * consult that document for information about the meaning of each field.
  175454. *
  175455. * With libpng < 0.95, it was only possible to directly set and read the
  175456. * the values in the png_info_struct, which meant that the contents and
  175457. * order of the values had to remain fixed. With libpng 0.95 and later,
  175458. * however, there are now functions that abstract the contents of
  175459. * png_info_struct from the application, so this makes it easier to use
  175460. * libpng with dynamic libraries, and even makes it possible to use
  175461. * libraries that don't have all of the libpng ancillary chunk-handing
  175462. * functionality.
  175463. *
  175464. * In any case, the order of the parameters in png_info_struct should NOT
  175465. * be changed for as long as possible to keep compatibility with applications
  175466. * that use the old direct-access method with png_info_struct.
  175467. *
  175468. * The following members may have allocated storage attached that should be
  175469. * cleaned up before the structure is discarded: palette, trans, text,
  175470. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  175471. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  175472. * are automatically freed when the info structure is deallocated, if they were
  175473. * allocated internally by libpng. This behavior can be changed by means
  175474. * of the png_data_freer() function.
  175475. *
  175476. * More allocation details: all the chunk-reading functions that
  175477. * change these members go through the corresponding png_set_*
  175478. * functions. A function to clear these members is available: see
  175479. * png_free_data(). The png_set_* functions do not depend on being
  175480. * able to point info structure members to any of the storage they are
  175481. * passed (they make their own copies), EXCEPT that the png_set_text
  175482. * functions use the same storage passed to them in the text_ptr or
  175483. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  175484. * functions do not make their own copies.
  175485. */
  175486. typedef struct png_info_struct
  175487. {
  175488. /* the following are necessary for every PNG file */
  175489. png_uint_32 width; /* width of image in pixels (from IHDR) */
  175490. png_uint_32 height; /* height of image in pixels (from IHDR) */
  175491. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  175492. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  175493. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  175494. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  175495. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  175496. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  175497. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  175498. /* The following three should have been named *_method not *_type */
  175499. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  175500. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  175501. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  175502. /* The following is informational only on read, and not used on writes. */
  175503. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  175504. png_byte pixel_depth; /* number of bits per pixel */
  175505. png_byte spare_byte; /* to align the data, and for future use */
  175506. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  175507. /* The rest of the data is optional. If you are reading, check the
  175508. * valid field to see if the information in these are valid. If you
  175509. * are writing, set the valid field to those chunks you want written,
  175510. * and initialize the appropriate fields below.
  175511. */
  175512. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  175513. /* The gAMA chunk describes the gamma characteristics of the system
  175514. * on which the image was created, normally in the range [1.0, 2.5].
  175515. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  175516. */
  175517. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  175518. #endif
  175519. #if defined(PNG_sRGB_SUPPORTED)
  175520. /* GR-P, 0.96a */
  175521. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  175522. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  175523. #endif
  175524. #if defined(PNG_TEXT_SUPPORTED)
  175525. /* The tEXt, and zTXt chunks contain human-readable textual data in
  175526. * uncompressed, compressed, and optionally compressed forms, respectively.
  175527. * The data in "text" is an array of pointers to uncompressed,
  175528. * null-terminated C strings. Each chunk has a keyword that describes the
  175529. * textual data contained in that chunk. Keywords are not required to be
  175530. * unique, and the text string may be empty. Any number of text chunks may
  175531. * be in an image.
  175532. */
  175533. int num_text; /* number of comments read/to write */
  175534. int max_text; /* current size of text array */
  175535. png_textp text; /* array of comments read/to write */
  175536. #endif /* PNG_TEXT_SUPPORTED */
  175537. #if defined(PNG_tIME_SUPPORTED)
  175538. /* The tIME chunk holds the last time the displayed image data was
  175539. * modified. See the png_time struct for the contents of this struct.
  175540. */
  175541. png_time mod_time;
  175542. #endif
  175543. #if defined(PNG_sBIT_SUPPORTED)
  175544. /* The sBIT chunk specifies the number of significant high-order bits
  175545. * in the pixel data. Values are in the range [1, bit_depth], and are
  175546. * only specified for the channels in the pixel data. The contents of
  175547. * the low-order bits is not specified. Data is valid if
  175548. * (valid & PNG_INFO_sBIT) is non-zero.
  175549. */
  175550. png_color_8 sig_bit; /* significant bits in color channels */
  175551. #endif
  175552. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  175553. defined(PNG_READ_BACKGROUND_SUPPORTED)
  175554. /* The tRNS chunk supplies transparency data for paletted images and
  175555. * other image types that don't need a full alpha channel. There are
  175556. * "num_trans" transparency values for a paletted image, stored in the
  175557. * same order as the palette colors, starting from index 0. Values
  175558. * for the data are in the range [0, 255], ranging from fully transparent
  175559. * to fully opaque, respectively. For non-paletted images, there is a
  175560. * single color specified that should be treated as fully transparent.
  175561. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  175562. */
  175563. png_bytep trans; /* transparent values for paletted image */
  175564. png_color_16 trans_values; /* transparent color for non-palette image */
  175565. #endif
  175566. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175567. /* The bKGD chunk gives the suggested image background color if the
  175568. * display program does not have its own background color and the image
  175569. * is needs to composited onto a background before display. The colors
  175570. * in "background" are normally in the same color space/depth as the
  175571. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  175572. */
  175573. png_color_16 background;
  175574. #endif
  175575. #if defined(PNG_oFFs_SUPPORTED)
  175576. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  175577. * and downwards from the top-left corner of the display, page, or other
  175578. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  175579. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  175580. */
  175581. png_int_32 x_offset; /* x offset on page */
  175582. png_int_32 y_offset; /* y offset on page */
  175583. png_byte offset_unit_type; /* offset units type */
  175584. #endif
  175585. #if defined(PNG_pHYs_SUPPORTED)
  175586. /* The pHYs chunk gives the physical pixel density of the image for
  175587. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  175588. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  175589. */
  175590. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  175591. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  175592. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  175593. #endif
  175594. #if defined(PNG_hIST_SUPPORTED)
  175595. /* The hIST chunk contains the relative frequency or importance of the
  175596. * various palette entries, so that a viewer can intelligently select a
  175597. * reduced-color palette, if required. Data is an array of "num_palette"
  175598. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  175599. * is non-zero.
  175600. */
  175601. png_uint_16p hist;
  175602. #endif
  175603. #ifdef PNG_cHRM_SUPPORTED
  175604. /* The cHRM chunk describes the CIE color characteristics of the monitor
  175605. * on which the PNG was created. This data allows the viewer to do gamut
  175606. * mapping of the input image to ensure that the viewer sees the same
  175607. * colors in the image as the creator. Values are in the range
  175608. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  175609. */
  175610. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175611. float x_white;
  175612. float y_white;
  175613. float x_red;
  175614. float y_red;
  175615. float x_green;
  175616. float y_green;
  175617. float x_blue;
  175618. float y_blue;
  175619. #endif
  175620. #endif
  175621. #if defined(PNG_pCAL_SUPPORTED)
  175622. /* The pCAL chunk describes a transformation between the stored pixel
  175623. * values and original physical data values used to create the image.
  175624. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  175625. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  175626. * (possibly non-linear) transformation function given by "pcal_type"
  175627. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  175628. * defines below, and the PNG-Group's PNG extensions document for a
  175629. * complete description of the transformations and how they should be
  175630. * implemented, and for a description of the ASCII parameter strings.
  175631. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  175632. */
  175633. png_charp pcal_purpose; /* pCAL chunk description string */
  175634. png_int_32 pcal_X0; /* minimum value */
  175635. png_int_32 pcal_X1; /* maximum value */
  175636. png_charp pcal_units; /* Latin-1 string giving physical units */
  175637. png_charpp pcal_params; /* ASCII strings containing parameter values */
  175638. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  175639. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  175640. #endif
  175641. /* New members added in libpng-1.0.6 */
  175642. #ifdef PNG_FREE_ME_SUPPORTED
  175643. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  175644. #endif
  175645. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175646. /* storage for unknown chunks that the library doesn't recognize. */
  175647. png_unknown_chunkp unknown_chunks;
  175648. png_size_t unknown_chunks_num;
  175649. #endif
  175650. #if defined(PNG_iCCP_SUPPORTED)
  175651. /* iCCP chunk data. */
  175652. png_charp iccp_name; /* profile name */
  175653. png_charp iccp_profile; /* International Color Consortium profile data */
  175654. /* Note to maintainer: should be png_bytep */
  175655. png_uint_32 iccp_proflen; /* ICC profile data length */
  175656. png_byte iccp_compression; /* Always zero */
  175657. #endif
  175658. #if defined(PNG_sPLT_SUPPORTED)
  175659. /* data on sPLT chunks (there may be more than one). */
  175660. png_sPLT_tp splt_palettes;
  175661. png_uint_32 splt_palettes_num;
  175662. #endif
  175663. #if defined(PNG_sCAL_SUPPORTED)
  175664. /* The sCAL chunk describes the actual physical dimensions of the
  175665. * subject matter of the graphic. The chunk contains a unit specification
  175666. * a byte value, and two ASCII strings representing floating-point
  175667. * values. The values are width and height corresponsing to one pixel
  175668. * in the image. This external representation is converted to double
  175669. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  175670. */
  175671. png_byte scal_unit; /* unit of physical scale */
  175672. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175673. double scal_pixel_width; /* width of one pixel */
  175674. double scal_pixel_height; /* height of one pixel */
  175675. #endif
  175676. #ifdef PNG_FIXED_POINT_SUPPORTED
  175677. png_charp scal_s_width; /* string containing height */
  175678. png_charp scal_s_height; /* string containing width */
  175679. #endif
  175680. #endif
  175681. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  175682. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  175683. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  175684. png_bytepp row_pointers; /* the image bits */
  175685. #endif
  175686. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  175687. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  175688. #endif
  175689. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  175690. png_fixed_point int_x_white;
  175691. png_fixed_point int_y_white;
  175692. png_fixed_point int_x_red;
  175693. png_fixed_point int_y_red;
  175694. png_fixed_point int_x_green;
  175695. png_fixed_point int_y_green;
  175696. png_fixed_point int_x_blue;
  175697. png_fixed_point int_y_blue;
  175698. #endif
  175699. } png_info;
  175700. typedef png_info FAR * png_infop;
  175701. typedef png_info FAR * FAR * png_infopp;
  175702. /* Maximum positive integer used in PNG is (2^31)-1 */
  175703. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  175704. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  175705. #define PNG_SIZE_MAX ((png_size_t)(-1))
  175706. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175707. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  175708. #define PNG_MAX_UINT PNG_UINT_31_MAX
  175709. #endif
  175710. /* These describe the color_type field in png_info. */
  175711. /* color type masks */
  175712. #define PNG_COLOR_MASK_PALETTE 1
  175713. #define PNG_COLOR_MASK_COLOR 2
  175714. #define PNG_COLOR_MASK_ALPHA 4
  175715. /* color types. Note that not all combinations are legal */
  175716. #define PNG_COLOR_TYPE_GRAY 0
  175717. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  175718. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  175719. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  175720. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  175721. /* aliases */
  175722. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  175723. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  175724. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  175725. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  175726. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  175727. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  175728. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  175729. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  175730. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  175731. /* These are for the interlacing type. These values should NOT be changed. */
  175732. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  175733. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  175734. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  175735. /* These are for the oFFs chunk. These values should NOT be changed. */
  175736. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  175737. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  175738. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  175739. /* These are for the pCAL chunk. These values should NOT be changed. */
  175740. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  175741. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  175742. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  175743. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  175744. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  175745. /* These are for the sCAL chunk. These values should NOT be changed. */
  175746. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  175747. #define PNG_SCALE_METER 1 /* meters per pixel */
  175748. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  175749. #define PNG_SCALE_LAST 3 /* Not a valid value */
  175750. /* These are for the pHYs chunk. These values should NOT be changed. */
  175751. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  175752. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  175753. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  175754. /* These are for the sRGB chunk. These values should NOT be changed. */
  175755. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  175756. #define PNG_sRGB_INTENT_RELATIVE 1
  175757. #define PNG_sRGB_INTENT_SATURATION 2
  175758. #define PNG_sRGB_INTENT_ABSOLUTE 3
  175759. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  175760. /* This is for text chunks */
  175761. #define PNG_KEYWORD_MAX_LENGTH 79
  175762. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  175763. #define PNG_MAX_PALETTE_LENGTH 256
  175764. /* These determine if an ancillary chunk's data has been successfully read
  175765. * from the PNG header, or if the application has filled in the corresponding
  175766. * data in the info_struct to be written into the output file. The values
  175767. * of the PNG_INFO_<chunk> defines should NOT be changed.
  175768. */
  175769. #define PNG_INFO_gAMA 0x0001
  175770. #define PNG_INFO_sBIT 0x0002
  175771. #define PNG_INFO_cHRM 0x0004
  175772. #define PNG_INFO_PLTE 0x0008
  175773. #define PNG_INFO_tRNS 0x0010
  175774. #define PNG_INFO_bKGD 0x0020
  175775. #define PNG_INFO_hIST 0x0040
  175776. #define PNG_INFO_pHYs 0x0080
  175777. #define PNG_INFO_oFFs 0x0100
  175778. #define PNG_INFO_tIME 0x0200
  175779. #define PNG_INFO_pCAL 0x0400
  175780. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  175781. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  175782. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  175783. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  175784. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  175785. /* This is used for the transformation routines, as some of them
  175786. * change these values for the row. It also should enable using
  175787. * the routines for other purposes.
  175788. */
  175789. typedef struct png_row_info_struct
  175790. {
  175791. png_uint_32 width; /* width of row */
  175792. png_uint_32 rowbytes; /* number of bytes in row */
  175793. png_byte color_type; /* color type of row */
  175794. png_byte bit_depth; /* bit depth of row */
  175795. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  175796. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  175797. } png_row_info;
  175798. typedef png_row_info FAR * png_row_infop;
  175799. typedef png_row_info FAR * FAR * png_row_infopp;
  175800. /* These are the function types for the I/O functions and for the functions
  175801. * that allow the user to override the default I/O functions with his or her
  175802. * own. The png_error_ptr type should match that of user-supplied warning
  175803. * and error functions, while the png_rw_ptr type should match that of the
  175804. * user read/write data functions.
  175805. */
  175806. typedef struct png_struct_def png_struct;
  175807. typedef png_struct FAR * png_structp;
  175808. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  175809. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  175810. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  175811. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  175812. int));
  175813. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  175814. int));
  175815. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  175816. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  175817. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  175818. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  175819. png_uint_32, int));
  175820. #endif
  175821. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175822. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  175823. defined(PNG_LEGACY_SUPPORTED)
  175824. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  175825. png_row_infop, png_bytep));
  175826. #endif
  175827. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  175828. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  175829. #endif
  175830. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175831. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  175832. #endif
  175833. /* Transform masks for the high-level interface */
  175834. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  175835. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  175836. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  175837. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  175838. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  175839. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  175840. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  175841. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  175842. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  175843. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  175844. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  175845. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  175846. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  175847. /* Flags for MNG supported features */
  175848. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  175849. #define PNG_FLAG_MNG_FILTER_64 0x04
  175850. #define PNG_ALL_MNG_FEATURES 0x05
  175851. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  175852. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  175853. /* The structure that holds the information to read and write PNG files.
  175854. * The only people who need to care about what is inside of this are the
  175855. * people who will be modifying the library for their own special needs.
  175856. * It should NOT be accessed directly by an application, except to store
  175857. * the jmp_buf.
  175858. */
  175859. struct png_struct_def
  175860. {
  175861. #ifdef PNG_SETJMP_SUPPORTED
  175862. jmp_buf jmpbuf; /* used in png_error */
  175863. #endif
  175864. png_error_ptr error_fn; /* function for printing errors and aborting */
  175865. png_error_ptr warning_fn; /* function for printing warnings */
  175866. png_voidp error_ptr; /* user supplied struct for error functions */
  175867. png_rw_ptr write_data_fn; /* function for writing output data */
  175868. png_rw_ptr read_data_fn; /* function for reading input data */
  175869. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  175870. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  175871. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  175872. #endif
  175873. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175874. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  175875. #endif
  175876. /* These were added in libpng-1.0.2 */
  175877. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  175878. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175879. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175880. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  175881. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  175882. png_byte user_transform_channels; /* channels in user transformed pixels */
  175883. #endif
  175884. #endif
  175885. png_uint_32 mode; /* tells us where we are in the PNG file */
  175886. png_uint_32 flags; /* flags indicating various things to libpng */
  175887. png_uint_32 transformations; /* which transformations to perform */
  175888. z_stream zstream; /* pointer to decompression structure (below) */
  175889. png_bytep zbuf; /* buffer for zlib */
  175890. png_size_t zbuf_size; /* size of zbuf */
  175891. int zlib_level; /* holds zlib compression level */
  175892. int zlib_method; /* holds zlib compression method */
  175893. int zlib_window_bits; /* holds zlib compression window bits */
  175894. int zlib_mem_level; /* holds zlib compression memory level */
  175895. int zlib_strategy; /* holds zlib compression strategy */
  175896. png_uint_32 width; /* width of image in pixels */
  175897. png_uint_32 height; /* height of image in pixels */
  175898. png_uint_32 num_rows; /* number of rows in current pass */
  175899. png_uint_32 usr_width; /* width of row at start of write */
  175900. png_uint_32 rowbytes; /* size of row in bytes */
  175901. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  175902. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  175903. png_uint_32 row_number; /* current row in interlace pass */
  175904. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  175905. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  175906. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  175907. png_bytep up_row; /* buffer to save "up" row when filtering */
  175908. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  175909. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  175910. png_row_info row_info; /* used for transformation routines */
  175911. png_uint_32 idat_size; /* current IDAT size for read */
  175912. png_uint_32 crc; /* current chunk CRC value */
  175913. png_colorp palette; /* palette from the input file */
  175914. png_uint_16 num_palette; /* number of color entries in palette */
  175915. png_uint_16 num_trans; /* number of transparency values */
  175916. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  175917. png_byte compression; /* file compression type (always 0) */
  175918. png_byte filter; /* file filter type (always 0) */
  175919. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  175920. png_byte pass; /* current interlace pass (0 - 6) */
  175921. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  175922. png_byte color_type; /* color type of file */
  175923. png_byte bit_depth; /* bit depth of file */
  175924. png_byte usr_bit_depth; /* bit depth of users row */
  175925. png_byte pixel_depth; /* number of bits per pixel */
  175926. png_byte channels; /* number of channels in file */
  175927. png_byte usr_channels; /* channels at start of write */
  175928. png_byte sig_bytes; /* magic bytes read/written from start of file */
  175929. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  175930. #ifdef PNG_LEGACY_SUPPORTED
  175931. png_byte filler; /* filler byte for pixel expansion */
  175932. #else
  175933. png_uint_16 filler; /* filler bytes for pixel expansion */
  175934. #endif
  175935. #endif
  175936. #if defined(PNG_bKGD_SUPPORTED)
  175937. png_byte background_gamma_type;
  175938. # ifdef PNG_FLOATING_POINT_SUPPORTED
  175939. float background_gamma;
  175940. # endif
  175941. png_color_16 background; /* background color in screen gamma space */
  175942. #if defined(PNG_READ_GAMMA_SUPPORTED)
  175943. png_color_16 background_1; /* background normalized to gamma 1.0 */
  175944. #endif
  175945. #endif /* PNG_bKGD_SUPPORTED */
  175946. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  175947. png_flush_ptr output_flush_fn;/* Function for flushing output */
  175948. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  175949. png_uint_32 flush_rows; /* number of rows written since last flush */
  175950. #endif
  175951. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175952. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  175953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175954. float gamma; /* file gamma value */
  175955. float screen_gamma; /* screen gamma value (display_exponent) */
  175956. #endif
  175957. #endif
  175958. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175959. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  175960. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  175961. png_bytep gamma_to_1; /* converts from file to 1.0 */
  175962. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  175963. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  175964. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  175965. #endif
  175966. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  175967. png_color_8 sig_bit; /* significant bits in each available channel */
  175968. #endif
  175969. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  175970. png_color_8 shift; /* shift for significant bit tranformation */
  175971. #endif
  175972. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  175973. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175974. png_bytep trans; /* transparency values for paletted files */
  175975. png_color_16 trans_values; /* transparency values for non-paletted files */
  175976. #endif
  175977. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  175978. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  175979. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  175980. png_progressive_info_ptr info_fn; /* called after header data fully read */
  175981. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  175982. png_progressive_end_ptr end_fn; /* called after image is complete */
  175983. png_bytep save_buffer_ptr; /* current location in save_buffer */
  175984. png_bytep save_buffer; /* buffer for previously read data */
  175985. png_bytep current_buffer_ptr; /* current location in current_buffer */
  175986. png_bytep current_buffer; /* buffer for recently used data */
  175987. png_uint_32 push_length; /* size of current input chunk */
  175988. png_uint_32 skip_length; /* bytes to skip in input data */
  175989. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  175990. png_size_t save_buffer_max; /* total size of save_buffer */
  175991. png_size_t buffer_size; /* total amount of available input data */
  175992. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  175993. int process_mode; /* what push library is currently doing */
  175994. int cur_palette; /* current push library palette index */
  175995. # if defined(PNG_TEXT_SUPPORTED)
  175996. png_size_t current_text_size; /* current size of text input data */
  175997. png_size_t current_text_left; /* how much text left to read in input */
  175998. png_charp current_text; /* current text chunk buffer */
  175999. png_charp current_text_ptr; /* current location in current_text */
  176000. # endif /* PNG_TEXT_SUPPORTED */
  176001. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176002. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  176003. /* for the Borland special 64K segment handler */
  176004. png_bytepp offset_table_ptr;
  176005. png_bytep offset_table;
  176006. png_uint_16 offset_table_number;
  176007. png_uint_16 offset_table_count;
  176008. png_uint_16 offset_table_count_free;
  176009. #endif
  176010. #if defined(PNG_READ_DITHER_SUPPORTED)
  176011. png_bytep palette_lookup; /* lookup table for dithering */
  176012. png_bytep dither_index; /* index translation for palette files */
  176013. #endif
  176014. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  176015. png_uint_16p hist; /* histogram */
  176016. #endif
  176017. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  176018. png_byte heuristic_method; /* heuristic for row filter selection */
  176019. png_byte num_prev_filters; /* number of weights for previous rows */
  176020. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  176021. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  176022. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  176023. png_uint_16p filter_costs; /* relative filter calculation cost */
  176024. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  176025. #endif
  176026. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176027. png_charp time_buffer; /* String to hold RFC 1123 time text */
  176028. #endif
  176029. /* New members added in libpng-1.0.6 */
  176030. #ifdef PNG_FREE_ME_SUPPORTED
  176031. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176032. #endif
  176033. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176034. png_voidp user_chunk_ptr;
  176035. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  176036. #endif
  176037. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176038. int num_chunk_list;
  176039. png_bytep chunk_list;
  176040. #endif
  176041. /* New members added in libpng-1.0.3 */
  176042. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176043. png_byte rgb_to_gray_status;
  176044. /* These were changed from png_byte in libpng-1.0.6 */
  176045. png_uint_16 rgb_to_gray_red_coeff;
  176046. png_uint_16 rgb_to_gray_green_coeff;
  176047. png_uint_16 rgb_to_gray_blue_coeff;
  176048. #endif
  176049. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  176050. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  176051. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176052. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176053. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  176054. #ifdef PNG_1_0_X
  176055. png_byte mng_features_permitted;
  176056. #else
  176057. png_uint_32 mng_features_permitted;
  176058. #endif /* PNG_1_0_X */
  176059. #endif
  176060. /* New member added in libpng-1.0.7 */
  176061. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176062. png_fixed_point int_gamma;
  176063. #endif
  176064. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  176065. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  176066. png_byte filter_type;
  176067. #endif
  176068. #if defined(PNG_1_0_X)
  176069. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  176070. png_uint_32 row_buf_size;
  176071. #endif
  176072. /* New members added in libpng-1.2.0 */
  176073. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  176074. # if !defined(PNG_1_0_X)
  176075. # if defined(PNG_MMX_CODE_SUPPORTED)
  176076. png_byte mmx_bitdepth_threshold;
  176077. png_uint_32 mmx_rowbytes_threshold;
  176078. # endif
  176079. png_uint_32 asm_flags;
  176080. # endif
  176081. #endif
  176082. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  176083. #ifdef PNG_USER_MEM_SUPPORTED
  176084. png_voidp mem_ptr; /* user supplied struct for mem functions */
  176085. png_malloc_ptr malloc_fn; /* function for allocating memory */
  176086. png_free_ptr free_fn; /* function for freeing memory */
  176087. #endif
  176088. /* New member added in libpng-1.0.13 and 1.2.0 */
  176089. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  176090. #if defined(PNG_READ_DITHER_SUPPORTED)
  176091. /* The following three members were added at version 1.0.14 and 1.2.4 */
  176092. png_bytep dither_sort; /* working sort array */
  176093. png_bytep index_to_palette; /* where the original index currently is */
  176094. /* in the palette */
  176095. png_bytep palette_to_index; /* which original index points to this */
  176096. /* palette color */
  176097. #endif
  176098. /* New members added in libpng-1.0.16 and 1.2.6 */
  176099. png_byte compression_type;
  176100. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  176101. png_uint_32 user_width_max;
  176102. png_uint_32 user_height_max;
  176103. #endif
  176104. /* New member added in libpng-1.0.25 and 1.2.17 */
  176105. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176106. /* storage for unknown chunk that the library doesn't recognize. */
  176107. png_unknown_chunk unknown_chunk;
  176108. #endif
  176109. };
  176110. /* This triggers a compiler error in png.c, if png.c and png.h
  176111. * do not agree upon the version number.
  176112. */
  176113. typedef png_structp version_1_2_21;
  176114. typedef png_struct FAR * FAR * png_structpp;
  176115. /* Here are the function definitions most commonly used. This is not
  176116. * the place to find out how to use libpng. See libpng.txt for the
  176117. * full explanation, see example.c for the summary. This just provides
  176118. * a simple one line description of the use of each function.
  176119. */
  176120. /* Returns the version number of the library */
  176121. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  176122. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  176123. * Handling more than 8 bytes from the beginning of the file is an error.
  176124. */
  176125. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  176126. int num_bytes));
  176127. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  176128. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  176129. * signature, and non-zero otherwise. Having num_to_check == 0 or
  176130. * start > 7 will always fail (ie return non-zero).
  176131. */
  176132. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  176133. png_size_t num_to_check));
  176134. /* Simple signature checking function. This is the same as calling
  176135. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  176136. */
  176137. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  176138. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  176139. extern PNG_EXPORT(png_structp,png_create_read_struct)
  176140. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176141. png_error_ptr error_fn, png_error_ptr warn_fn));
  176142. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  176143. extern PNG_EXPORT(png_structp,png_create_write_struct)
  176144. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176145. png_error_ptr error_fn, png_error_ptr warn_fn));
  176146. #ifdef PNG_WRITE_SUPPORTED
  176147. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  176148. PNGARG((png_structp png_ptr));
  176149. #endif
  176150. #ifdef PNG_WRITE_SUPPORTED
  176151. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  176152. PNGARG((png_structp png_ptr, png_uint_32 size));
  176153. #endif
  176154. /* Reset the compression stream */
  176155. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  176156. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  176157. #ifdef PNG_USER_MEM_SUPPORTED
  176158. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  176159. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176160. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176161. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176162. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  176163. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176164. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176165. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176166. #endif
  176167. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  176168. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  176169. png_bytep chunk_name, png_bytep data, png_size_t length));
  176170. /* Write the start of a PNG chunk - length and chunk name. */
  176171. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  176172. png_bytep chunk_name, png_uint_32 length));
  176173. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  176174. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  176175. png_bytep data, png_size_t length));
  176176. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  176177. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  176178. /* Allocate and initialize the info structure */
  176179. extern PNG_EXPORT(png_infop,png_create_info_struct)
  176180. PNGARG((png_structp png_ptr));
  176181. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176182. /* Initialize the info structure (old interface - DEPRECATED) */
  176183. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  176184. #undef png_info_init
  176185. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  176186. png_sizeof(png_info));
  176187. #endif
  176188. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  176189. png_size_t png_info_struct_size));
  176190. /* Writes all the PNG information before the image. */
  176191. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  176192. png_infop info_ptr));
  176193. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  176194. png_infop info_ptr));
  176195. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176196. /* read the information before the actual image data. */
  176197. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  176198. png_infop info_ptr));
  176199. #endif
  176200. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176201. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  176202. PNGARG((png_structp png_ptr, png_timep ptime));
  176203. #endif
  176204. #if !defined(_WIN32_WCE)
  176205. /* "time.h" functions are not supported on WindowsCE */
  176206. #if defined(PNG_WRITE_tIME_SUPPORTED)
  176207. /* convert from a struct tm to png_time */
  176208. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  176209. struct tm FAR * ttime));
  176210. /* convert from time_t to png_time. Uses gmtime() */
  176211. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  176212. time_t ttime));
  176213. #endif /* PNG_WRITE_tIME_SUPPORTED */
  176214. #endif /* _WIN32_WCE */
  176215. #if defined(PNG_READ_EXPAND_SUPPORTED)
  176216. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  176217. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  176218. #if !defined(PNG_1_0_X)
  176219. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  176220. png_ptr));
  176221. #endif
  176222. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  176223. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  176224. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176225. /* Deprecated */
  176226. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  176227. #endif
  176228. #endif
  176229. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  176230. /* Use blue, green, red order for pixels. */
  176231. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  176232. #endif
  176233. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  176234. /* Expand the grayscale to 24-bit RGB if necessary. */
  176235. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  176236. #endif
  176237. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176238. /* Reduce RGB to grayscale. */
  176239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176240. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  176241. int error_action, double red, double green ));
  176242. #endif
  176243. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  176244. int error_action, png_fixed_point red, png_fixed_point green ));
  176245. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  176246. png_ptr));
  176247. #endif
  176248. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  176249. png_colorp palette));
  176250. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  176251. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  176252. #endif
  176253. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  176254. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  176255. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  176256. #endif
  176257. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  176258. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  176259. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  176260. #endif
  176261. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176262. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  176263. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  176264. png_uint_32 filler, int flags));
  176265. /* The values of the PNG_FILLER_ defines should NOT be changed */
  176266. #define PNG_FILLER_BEFORE 0
  176267. #define PNG_FILLER_AFTER 1
  176268. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  176269. #if !defined(PNG_1_0_X)
  176270. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  176271. png_uint_32 filler, int flags));
  176272. #endif
  176273. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  176274. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  176275. /* Swap bytes in 16-bit depth files. */
  176276. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  176277. #endif
  176278. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  176279. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  176280. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  176281. #endif
  176282. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  176283. /* Swap packing order of pixels in bytes. */
  176284. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  176285. #endif
  176286. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176287. /* Converts files to legal bit depths. */
  176288. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  176289. png_color_8p true_bits));
  176290. #endif
  176291. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  176292. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176293. /* Have the code handle the interlacing. Returns the number of passes. */
  176294. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  176295. #endif
  176296. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  176297. /* Invert monochrome files */
  176298. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  176299. #endif
  176300. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  176301. /* Handle alpha and tRNS by replacing with a background color. */
  176302. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176303. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  176304. png_color_16p background_color, int background_gamma_code,
  176305. int need_expand, double background_gamma));
  176306. #endif
  176307. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  176308. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  176309. #define PNG_BACKGROUND_GAMMA_FILE 2
  176310. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  176311. #endif
  176312. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  176313. /* strip the second byte of information from a 16-bit depth file. */
  176314. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  176315. #endif
  176316. #if defined(PNG_READ_DITHER_SUPPORTED)
  176317. /* Turn on dithering, and reduce the palette to the number of colors available. */
  176318. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  176319. png_colorp palette, int num_palette, int maximum_colors,
  176320. png_uint_16p histogram, int full_dither));
  176321. #endif
  176322. #if defined(PNG_READ_GAMMA_SUPPORTED)
  176323. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  176324. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176325. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  176326. double screen_gamma, double default_file_gamma));
  176327. #endif
  176328. #endif
  176329. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176330. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176331. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176332. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  176333. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  176334. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  176335. int empty_plte_permitted));
  176336. #endif
  176337. #endif
  176338. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  176339. /* Set how many lines between output flushes - 0 for no flushing */
  176340. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  176341. /* Flush the current PNG output buffer */
  176342. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  176343. #endif
  176344. /* optional update palette with requested transformations */
  176345. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  176346. /* optional call to update the users info structure */
  176347. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  176348. png_infop info_ptr));
  176349. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176350. /* read one or more rows of image data. */
  176351. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  176352. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  176353. #endif
  176354. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176355. /* read a row of data. */
  176356. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  176357. png_bytep row,
  176358. png_bytep display_row));
  176359. #endif
  176360. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176361. /* read the whole image into memory at once. */
  176362. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  176363. png_bytepp image));
  176364. #endif
  176365. /* write a row of image data */
  176366. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  176367. png_bytep row));
  176368. /* write a few rows of image data */
  176369. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  176370. png_bytepp row, png_uint_32 num_rows));
  176371. /* write the image data */
  176372. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  176373. png_bytepp image));
  176374. /* writes the end of the PNG file. */
  176375. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  176376. png_infop info_ptr));
  176377. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176378. /* read the end of the PNG file. */
  176379. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  176380. png_infop info_ptr));
  176381. #endif
  176382. /* free any memory associated with the png_info_struct */
  176383. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  176384. png_infopp info_ptr_ptr));
  176385. /* free any memory associated with the png_struct and the png_info_structs */
  176386. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  176387. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  176388. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  176389. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  176390. png_infop end_info_ptr));
  176391. /* free any memory associated with the png_struct and the png_info_structs */
  176392. extern PNG_EXPORT(void,png_destroy_write_struct)
  176393. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  176394. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  176395. extern void png_write_destroy PNGARG((png_structp png_ptr));
  176396. /* set the libpng method of handling chunk CRC errors */
  176397. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  176398. int crit_action, int ancil_action));
  176399. /* Values for png_set_crc_action() to say how to handle CRC errors in
  176400. * ancillary and critical chunks, and whether to use the data contained
  176401. * therein. Note that it is impossible to "discard" data in a critical
  176402. * chunk. For versions prior to 0.90, the action was always error/quit,
  176403. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  176404. * chunks is warn/discard. These values should NOT be changed.
  176405. *
  176406. * value action:critical action:ancillary
  176407. */
  176408. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  176409. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  176410. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  176411. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  176412. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  176413. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  176414. /* These functions give the user control over the scan-line filtering in
  176415. * libpng and the compression methods used by zlib. These functions are
  176416. * mainly useful for testing, as the defaults should work with most users.
  176417. * Those users who are tight on memory or want faster performance at the
  176418. * expense of compression can modify them. See the compression library
  176419. * header file (zlib.h) for an explination of the compression functions.
  176420. */
  176421. /* set the filtering method(s) used by libpng. Currently, the only valid
  176422. * value for "method" is 0.
  176423. */
  176424. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  176425. int filters));
  176426. /* Flags for png_set_filter() to say which filters to use. The flags
  176427. * are chosen so that they don't conflict with real filter types
  176428. * below, in case they are supplied instead of the #defined constants.
  176429. * These values should NOT be changed.
  176430. */
  176431. #define PNG_NO_FILTERS 0x00
  176432. #define PNG_FILTER_NONE 0x08
  176433. #define PNG_FILTER_SUB 0x10
  176434. #define PNG_FILTER_UP 0x20
  176435. #define PNG_FILTER_AVG 0x40
  176436. #define PNG_FILTER_PAETH 0x80
  176437. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  176438. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  176439. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  176440. * These defines should NOT be changed.
  176441. */
  176442. #define PNG_FILTER_VALUE_NONE 0
  176443. #define PNG_FILTER_VALUE_SUB 1
  176444. #define PNG_FILTER_VALUE_UP 2
  176445. #define PNG_FILTER_VALUE_AVG 3
  176446. #define PNG_FILTER_VALUE_PAETH 4
  176447. #define PNG_FILTER_VALUE_LAST 5
  176448. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  176449. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  176450. * defines, either the default (minimum-sum-of-absolute-differences), or
  176451. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  176452. *
  176453. * Weights are factors >= 1.0, indicating how important it is to keep the
  176454. * filter type consistent between rows. Larger numbers mean the current
  176455. * filter is that many times as likely to be the same as the "num_weights"
  176456. * previous filters. This is cumulative for each previous row with a weight.
  176457. * There needs to be "num_weights" values in "filter_weights", or it can be
  176458. * NULL if the weights aren't being specified. Weights have no influence on
  176459. * the selection of the first row filter. Well chosen weights can (in theory)
  176460. * improve the compression for a given image.
  176461. *
  176462. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  176463. * filter type. Higher costs indicate more decoding expense, and are
  176464. * therefore less likely to be selected over a filter with lower computational
  176465. * costs. There needs to be a value in "filter_costs" for each valid filter
  176466. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  176467. * setting the costs. Costs try to improve the speed of decompression without
  176468. * unduly increasing the compressed image size.
  176469. *
  176470. * A negative weight or cost indicates the default value is to be used, and
  176471. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  176472. * The default values for both weights and costs are currently 1.0, but may
  176473. * change if good general weighting/cost heuristics can be found. If both
  176474. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  176475. * to the UNWEIGHTED method, but with added encoding time/computation.
  176476. */
  176477. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176478. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  176479. int heuristic_method, int num_weights, png_doublep filter_weights,
  176480. png_doublep filter_costs));
  176481. #endif
  176482. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  176483. /* Heuristic used for row filter selection. These defines should NOT be
  176484. * changed.
  176485. */
  176486. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  176487. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  176488. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  176489. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  176490. /* Set the library compression level. Currently, valid values range from
  176491. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  176492. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  176493. * shown that zlib compression levels 3-6 usually perform as well as level 9
  176494. * for PNG images, and do considerably fewer caclulations. In the future,
  176495. * these values may not correspond directly to the zlib compression levels.
  176496. */
  176497. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  176498. int level));
  176499. extern PNG_EXPORT(void,png_set_compression_mem_level)
  176500. PNGARG((png_structp png_ptr, int mem_level));
  176501. extern PNG_EXPORT(void,png_set_compression_strategy)
  176502. PNGARG((png_structp png_ptr, int strategy));
  176503. extern PNG_EXPORT(void,png_set_compression_window_bits)
  176504. PNGARG((png_structp png_ptr, int window_bits));
  176505. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  176506. int method));
  176507. /* These next functions are called for input/output, memory, and error
  176508. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  176509. * and call standard C I/O routines such as fread(), fwrite(), and
  176510. * fprintf(). These functions can be made to use other I/O routines
  176511. * at run time for those applications that need to handle I/O in a
  176512. * different manner by calling png_set_???_fn(). See libpng.txt for
  176513. * more information.
  176514. */
  176515. #if !defined(PNG_NO_STDIO)
  176516. /* Initialize the input/output for the PNG file to the default functions. */
  176517. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  176518. #endif
  176519. /* Replace the (error and abort), and warning functions with user
  176520. * supplied functions. If no messages are to be printed you must still
  176521. * write and use replacement functions. The replacement error_fn should
  176522. * still do a longjmp to the last setjmp location if you are using this
  176523. * method of error handling. If error_fn or warning_fn is NULL, the
  176524. * default function will be used.
  176525. */
  176526. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  176527. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  176528. /* Return the user pointer associated with the error functions */
  176529. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  176530. /* Replace the default data output functions with a user supplied one(s).
  176531. * If buffered output is not used, then output_flush_fn can be set to NULL.
  176532. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  176533. * output_flush_fn will be ignored (and thus can be NULL).
  176534. */
  176535. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  176536. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  176537. /* Replace the default data input function with a user supplied one. */
  176538. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  176539. png_voidp io_ptr, png_rw_ptr read_data_fn));
  176540. /* Return the user pointer associated with the I/O functions */
  176541. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  176542. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  176543. png_read_status_ptr read_row_fn));
  176544. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  176545. png_write_status_ptr write_row_fn));
  176546. #ifdef PNG_USER_MEM_SUPPORTED
  176547. /* Replace the default memory allocation functions with user supplied one(s). */
  176548. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  176549. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176550. /* Return the user pointer associated with the memory functions */
  176551. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  176552. #endif
  176553. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176554. defined(PNG_LEGACY_SUPPORTED)
  176555. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  176556. png_ptr, png_user_transform_ptr read_user_transform_fn));
  176557. #endif
  176558. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176559. defined(PNG_LEGACY_SUPPORTED)
  176560. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  176561. png_ptr, png_user_transform_ptr write_user_transform_fn));
  176562. #endif
  176563. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176564. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176565. defined(PNG_LEGACY_SUPPORTED)
  176566. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  176567. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  176568. int user_transform_channels));
  176569. /* Return the user pointer associated with the user transform functions */
  176570. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  176571. PNGARG((png_structp png_ptr));
  176572. #endif
  176573. #ifdef PNG_USER_CHUNKS_SUPPORTED
  176574. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  176575. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  176576. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  176577. png_ptr));
  176578. #endif
  176579. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176580. /* Sets the function callbacks for the push reader, and a pointer to a
  176581. * user-defined structure available to the callback functions.
  176582. */
  176583. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  176584. png_voidp progressive_ptr,
  176585. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  176586. png_progressive_end_ptr end_fn));
  176587. /* returns the user pointer associated with the push read functions */
  176588. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  176589. PNGARG((png_structp png_ptr));
  176590. /* function to be called when data becomes available */
  176591. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  176592. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  176593. /* function that combines rows. Not very much different than the
  176594. * png_combine_row() call. Is this even used?????
  176595. */
  176596. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  176597. png_bytep old_row, png_bytep new_row));
  176598. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176599. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  176600. png_uint_32 size));
  176601. #if defined(PNG_1_0_X)
  176602. # define png_malloc_warn png_malloc
  176603. #else
  176604. /* Added at libpng version 1.2.4 */
  176605. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  176606. png_uint_32 size));
  176607. #endif
  176608. /* frees a pointer allocated by png_malloc() */
  176609. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  176610. #if defined(PNG_1_0_X)
  176611. /* Function to allocate memory for zlib. */
  176612. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  176613. uInt size));
  176614. /* Function to free memory for zlib */
  176615. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  176616. #endif
  176617. /* Free data that was allocated internally */
  176618. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  176619. png_infop info_ptr, png_uint_32 free_me, int num));
  176620. #ifdef PNG_FREE_ME_SUPPORTED
  176621. /* Reassign responsibility for freeing existing data, whether allocated
  176622. * by libpng or by the application */
  176623. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  176624. png_infop info_ptr, int freer, png_uint_32 mask));
  176625. #endif
  176626. /* assignments for png_data_freer */
  176627. #define PNG_DESTROY_WILL_FREE_DATA 1
  176628. #define PNG_SET_WILL_FREE_DATA 1
  176629. #define PNG_USER_WILL_FREE_DATA 2
  176630. /* Flags for png_ptr->free_me and info_ptr->free_me */
  176631. #define PNG_FREE_HIST 0x0008
  176632. #define PNG_FREE_ICCP 0x0010
  176633. #define PNG_FREE_SPLT 0x0020
  176634. #define PNG_FREE_ROWS 0x0040
  176635. #define PNG_FREE_PCAL 0x0080
  176636. #define PNG_FREE_SCAL 0x0100
  176637. #define PNG_FREE_UNKN 0x0200
  176638. #define PNG_FREE_LIST 0x0400
  176639. #define PNG_FREE_PLTE 0x1000
  176640. #define PNG_FREE_TRNS 0x2000
  176641. #define PNG_FREE_TEXT 0x4000
  176642. #define PNG_FREE_ALL 0x7fff
  176643. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  176644. #ifdef PNG_USER_MEM_SUPPORTED
  176645. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  176646. png_uint_32 size));
  176647. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  176648. png_voidp ptr));
  176649. #endif
  176650. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  176651. png_voidp s1, png_voidp s2, png_uint_32 size));
  176652. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  176653. png_voidp s1, int value, png_uint_32 size));
  176654. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  176655. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  176656. int check));
  176657. #endif /* USE_FAR_KEYWORD */
  176658. #ifndef PNG_NO_ERROR_TEXT
  176659. /* Fatal error in PNG image of libpng - can't continue */
  176660. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  176661. png_const_charp error_message));
  176662. /* The same, but the chunk name is prepended to the error string. */
  176663. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  176664. png_const_charp error_message));
  176665. #else
  176666. /* Fatal error in PNG image of libpng - can't continue */
  176667. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  176668. #endif
  176669. #ifndef PNG_NO_WARNINGS
  176670. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  176671. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  176672. png_const_charp warning_message));
  176673. #ifdef PNG_READ_SUPPORTED
  176674. /* Non-fatal error in libpng, chunk name is prepended to message. */
  176675. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  176676. png_const_charp warning_message));
  176677. #endif /* PNG_READ_SUPPORTED */
  176678. #endif /* PNG_NO_WARNINGS */
  176679. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  176680. * Similarly, the png_get_<chunk> calls are used to read values from the
  176681. * png_info_struct, either storing the parameters in the passed variables, or
  176682. * setting pointers into the png_info_struct where the data is stored. The
  176683. * png_get_<chunk> functions return a non-zero value if the data was available
  176684. * in info_ptr, or return zero and do not change any of the parameters if the
  176685. * data was not available.
  176686. *
  176687. * These functions should be used instead of directly accessing png_info
  176688. * to avoid problems with future changes in the size and internal layout of
  176689. * png_info_struct.
  176690. */
  176691. /* Returns "flag" if chunk data is valid in info_ptr. */
  176692. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  176693. png_infop info_ptr, png_uint_32 flag));
  176694. /* Returns number of bytes needed to hold a transformed row. */
  176695. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  176696. png_infop info_ptr));
  176697. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176698. /* Returns row_pointers, which is an array of pointers to scanlines that was
  176699. returned from png_read_png(). */
  176700. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  176701. png_infop info_ptr));
  176702. /* Set row_pointers, which is an array of pointers to scanlines for use
  176703. by png_write_png(). */
  176704. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  176705. png_infop info_ptr, png_bytepp row_pointers));
  176706. #endif
  176707. /* Returns number of color channels in image. */
  176708. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  176709. png_infop info_ptr));
  176710. #ifdef PNG_EASY_ACCESS_SUPPORTED
  176711. /* Returns image width in pixels. */
  176712. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  176713. png_ptr, png_infop info_ptr));
  176714. /* Returns image height in pixels. */
  176715. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  176716. png_ptr, png_infop info_ptr));
  176717. /* Returns image bit_depth. */
  176718. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  176719. png_ptr, png_infop info_ptr));
  176720. /* Returns image color_type. */
  176721. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  176722. png_ptr, png_infop info_ptr));
  176723. /* Returns image filter_type. */
  176724. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  176725. png_ptr, png_infop info_ptr));
  176726. /* Returns image interlace_type. */
  176727. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  176728. png_ptr, png_infop info_ptr));
  176729. /* Returns image compression_type. */
  176730. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  176731. png_ptr, png_infop info_ptr));
  176732. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  176733. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  176734. png_ptr, png_infop info_ptr));
  176735. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  176736. png_ptr, png_infop info_ptr));
  176737. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  176738. png_ptr, png_infop info_ptr));
  176739. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  176740. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176741. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  176742. png_ptr, png_infop info_ptr));
  176743. #endif
  176744. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  176745. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  176746. png_ptr, png_infop info_ptr));
  176747. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  176748. png_ptr, png_infop info_ptr));
  176749. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  176750. png_ptr, png_infop info_ptr));
  176751. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  176752. png_ptr, png_infop info_ptr));
  176753. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  176754. /* Returns pointer to signature string read from PNG header */
  176755. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  176756. png_infop info_ptr));
  176757. #if defined(PNG_bKGD_SUPPORTED)
  176758. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  176759. png_infop info_ptr, png_color_16p *background));
  176760. #endif
  176761. #if defined(PNG_bKGD_SUPPORTED)
  176762. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  176763. png_infop info_ptr, png_color_16p background));
  176764. #endif
  176765. #if defined(PNG_cHRM_SUPPORTED)
  176766. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176767. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  176768. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  176769. double *red_y, double *green_x, double *green_y, double *blue_x,
  176770. double *blue_y));
  176771. #endif
  176772. #ifdef PNG_FIXED_POINT_SUPPORTED
  176773. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  176774. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  176775. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  176776. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  176777. *int_blue_x, png_fixed_point *int_blue_y));
  176778. #endif
  176779. #endif
  176780. #if defined(PNG_cHRM_SUPPORTED)
  176781. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176782. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  176783. png_infop info_ptr, double white_x, double white_y, double red_x,
  176784. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  176785. #endif
  176786. #ifdef PNG_FIXED_POINT_SUPPORTED
  176787. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  176788. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  176789. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  176790. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  176791. png_fixed_point int_blue_y));
  176792. #endif
  176793. #endif
  176794. #if defined(PNG_gAMA_SUPPORTED)
  176795. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176796. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  176797. png_infop info_ptr, double *file_gamma));
  176798. #endif
  176799. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  176800. png_infop info_ptr, png_fixed_point *int_file_gamma));
  176801. #endif
  176802. #if defined(PNG_gAMA_SUPPORTED)
  176803. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176804. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  176805. png_infop info_ptr, double file_gamma));
  176806. #endif
  176807. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  176808. png_infop info_ptr, png_fixed_point int_file_gamma));
  176809. #endif
  176810. #if defined(PNG_hIST_SUPPORTED)
  176811. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  176812. png_infop info_ptr, png_uint_16p *hist));
  176813. #endif
  176814. #if defined(PNG_hIST_SUPPORTED)
  176815. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  176816. png_infop info_ptr, png_uint_16p hist));
  176817. #endif
  176818. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  176819. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  176820. int *bit_depth, int *color_type, int *interlace_method,
  176821. int *compression_method, int *filter_method));
  176822. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  176823. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  176824. int color_type, int interlace_method, int compression_method,
  176825. int filter_method));
  176826. #if defined(PNG_oFFs_SUPPORTED)
  176827. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  176828. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  176829. int *unit_type));
  176830. #endif
  176831. #if defined(PNG_oFFs_SUPPORTED)
  176832. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  176833. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  176834. int unit_type));
  176835. #endif
  176836. #if defined(PNG_pCAL_SUPPORTED)
  176837. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  176838. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  176839. int *type, int *nparams, png_charp *units, png_charpp *params));
  176840. #endif
  176841. #if defined(PNG_pCAL_SUPPORTED)
  176842. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  176843. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  176844. int type, int nparams, png_charp units, png_charpp params));
  176845. #endif
  176846. #if defined(PNG_pHYs_SUPPORTED)
  176847. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  176848. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  176849. #endif
  176850. #if defined(PNG_pHYs_SUPPORTED)
  176851. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  176852. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  176853. #endif
  176854. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  176855. png_infop info_ptr, png_colorp *palette, int *num_palette));
  176856. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  176857. png_infop info_ptr, png_colorp palette, int num_palette));
  176858. #if defined(PNG_sBIT_SUPPORTED)
  176859. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  176860. png_infop info_ptr, png_color_8p *sig_bit));
  176861. #endif
  176862. #if defined(PNG_sBIT_SUPPORTED)
  176863. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  176864. png_infop info_ptr, png_color_8p sig_bit));
  176865. #endif
  176866. #if defined(PNG_sRGB_SUPPORTED)
  176867. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  176868. png_infop info_ptr, int *intent));
  176869. #endif
  176870. #if defined(PNG_sRGB_SUPPORTED)
  176871. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  176872. png_infop info_ptr, int intent));
  176873. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  176874. png_infop info_ptr, int intent));
  176875. #endif
  176876. #if defined(PNG_iCCP_SUPPORTED)
  176877. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  176878. png_infop info_ptr, png_charpp name, int *compression_type,
  176879. png_charpp profile, png_uint_32 *proflen));
  176880. /* Note to maintainer: profile should be png_bytepp */
  176881. #endif
  176882. #if defined(PNG_iCCP_SUPPORTED)
  176883. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  176884. png_infop info_ptr, png_charp name, int compression_type,
  176885. png_charp profile, png_uint_32 proflen));
  176886. /* Note to maintainer: profile should be png_bytep */
  176887. #endif
  176888. #if defined(PNG_sPLT_SUPPORTED)
  176889. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  176890. png_infop info_ptr, png_sPLT_tpp entries));
  176891. #endif
  176892. #if defined(PNG_sPLT_SUPPORTED)
  176893. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  176894. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  176895. #endif
  176896. #if defined(PNG_TEXT_SUPPORTED)
  176897. /* png_get_text also returns the number of text chunks in *num_text */
  176898. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  176899. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  176900. #endif
  176901. /*
  176902. * Note while png_set_text() will accept a structure whose text,
  176903. * language, and translated keywords are NULL pointers, the structure
  176904. * returned by png_get_text will always contain regular
  176905. * zero-terminated C strings. They might be empty strings but
  176906. * they will never be NULL pointers.
  176907. */
  176908. #if defined(PNG_TEXT_SUPPORTED)
  176909. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  176910. png_infop info_ptr, png_textp text_ptr, int num_text));
  176911. #endif
  176912. #if defined(PNG_tIME_SUPPORTED)
  176913. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  176914. png_infop info_ptr, png_timep *mod_time));
  176915. #endif
  176916. #if defined(PNG_tIME_SUPPORTED)
  176917. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  176918. png_infop info_ptr, png_timep mod_time));
  176919. #endif
  176920. #if defined(PNG_tRNS_SUPPORTED)
  176921. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  176922. png_infop info_ptr, png_bytep *trans, int *num_trans,
  176923. png_color_16p *trans_values));
  176924. #endif
  176925. #if defined(PNG_tRNS_SUPPORTED)
  176926. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  176927. png_infop info_ptr, png_bytep trans, int num_trans,
  176928. png_color_16p trans_values));
  176929. #endif
  176930. #if defined(PNG_tRNS_SUPPORTED)
  176931. #endif
  176932. #if defined(PNG_sCAL_SUPPORTED)
  176933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176934. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  176935. png_infop info_ptr, int *unit, double *width, double *height));
  176936. #else
  176937. #ifdef PNG_FIXED_POINT_SUPPORTED
  176938. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  176939. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  176940. #endif
  176941. #endif
  176942. #endif /* PNG_sCAL_SUPPORTED */
  176943. #if defined(PNG_sCAL_SUPPORTED)
  176944. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176945. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  176946. png_infop info_ptr, int unit, double width, double height));
  176947. #else
  176948. #ifdef PNG_FIXED_POINT_SUPPORTED
  176949. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  176950. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  176951. #endif
  176952. #endif
  176953. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  176954. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176955. /* provide a list of chunks and how they are to be handled, if the built-in
  176956. handling or default unknown chunk handling is not desired. Any chunks not
  176957. listed will be handled in the default manner. The IHDR and IEND chunks
  176958. must not be listed.
  176959. keep = 0: follow default behaviour
  176960. = 1: do not keep
  176961. = 2: keep only if safe-to-copy
  176962. = 3: keep even if unsafe-to-copy
  176963. */
  176964. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  176965. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  176966. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  176967. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  176968. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  176969. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  176970. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  176971. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  176972. #endif
  176973. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176974. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  176975. chunk_name));
  176976. #endif
  176977. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  176978. If you need to turn it off for a chunk that your application has freed,
  176979. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  176980. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  176981. png_infop info_ptr, int mask));
  176982. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176983. /* The "params" pointer is currently not used and is for future expansion. */
  176984. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  176985. png_infop info_ptr,
  176986. int transforms,
  176987. png_voidp params));
  176988. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  176989. png_infop info_ptr,
  176990. int transforms,
  176991. png_voidp params));
  176992. #endif
  176993. /* Define PNG_DEBUG at compile time for debugging information. Higher
  176994. * numbers for PNG_DEBUG mean more debugging information. This has
  176995. * only been added since version 0.95 so it is not implemented throughout
  176996. * libpng yet, but more support will be added as needed.
  176997. */
  176998. #ifdef PNG_DEBUG
  176999. #if (PNG_DEBUG > 0)
  177000. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  177001. #include <crtdbg.h>
  177002. #if (PNG_DEBUG > 1)
  177003. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  177004. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  177005. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  177006. #endif
  177007. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  177008. #ifndef PNG_DEBUG_FILE
  177009. #define PNG_DEBUG_FILE stderr
  177010. #endif /* PNG_DEBUG_FILE */
  177011. #if (PNG_DEBUG > 1)
  177012. #define png_debug(l,m) \
  177013. { \
  177014. int num_tabs=l; \
  177015. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177016. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  177017. }
  177018. #define png_debug1(l,m,p1) \
  177019. { \
  177020. int num_tabs=l; \
  177021. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177022. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  177023. }
  177024. #define png_debug2(l,m,p1,p2) \
  177025. { \
  177026. int num_tabs=l; \
  177027. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177028. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  177029. }
  177030. #endif /* (PNG_DEBUG > 1) */
  177031. #endif /* _MSC_VER */
  177032. #endif /* (PNG_DEBUG > 0) */
  177033. #endif /* PNG_DEBUG */
  177034. #ifndef png_debug
  177035. #define png_debug(l, m)
  177036. #endif
  177037. #ifndef png_debug1
  177038. #define png_debug1(l, m, p1)
  177039. #endif
  177040. #ifndef png_debug2
  177041. #define png_debug2(l, m, p1, p2)
  177042. #endif
  177043. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  177044. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  177045. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  177046. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  177047. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177048. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  177049. png_ptr, png_uint_32 mng_features_permitted));
  177050. #endif
  177051. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  177052. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  177053. #define PNG_HANDLE_CHUNK_NEVER 1
  177054. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  177055. #define PNG_HANDLE_CHUNK_ALWAYS 3
  177056. /* Added to version 1.2.0 */
  177057. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177058. #if defined(PNG_MMX_CODE_SUPPORTED)
  177059. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  177060. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  177061. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  177062. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  177063. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  177064. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  177065. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  177066. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  177067. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  177068. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  177069. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  177070. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  177071. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  177072. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  177073. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  177074. #define PNG_MMX_WRITE_FLAGS ( 0 )
  177075. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  177076. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  177077. | PNG_MMX_READ_FLAGS \
  177078. | PNG_MMX_WRITE_FLAGS )
  177079. #define PNG_SELECT_READ 1
  177080. #define PNG_SELECT_WRITE 2
  177081. #endif /* PNG_MMX_CODE_SUPPORTED */
  177082. #if !defined(PNG_1_0_X)
  177083. /* pngget.c */
  177084. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  177085. PNGARG((int flag_select, int *compilerID));
  177086. /* pngget.c */
  177087. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  177088. PNGARG((int flag_select));
  177089. /* pngget.c */
  177090. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  177091. PNGARG((png_structp png_ptr));
  177092. /* pngget.c */
  177093. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  177094. PNGARG((png_structp png_ptr));
  177095. /* pngget.c */
  177096. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  177097. PNGARG((png_structp png_ptr));
  177098. /* pngset.c */
  177099. extern PNG_EXPORT(void,png_set_asm_flags)
  177100. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  177101. /* pngset.c */
  177102. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  177103. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  177104. png_uint_32 mmx_rowbytes_threshold));
  177105. #endif /* PNG_1_0_X */
  177106. #if !defined(PNG_1_0_X)
  177107. /* png.c, pnggccrd.c, or pngvcrd.c */
  177108. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  177109. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  177110. /* Strip the prepended error numbers ("#nnn ") from error and warning
  177111. * messages before passing them to the error or warning handler. */
  177112. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  177113. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  177114. png_ptr, png_uint_32 strip_mode));
  177115. #endif
  177116. #endif /* PNG_1_0_X */
  177117. /* Added at libpng-1.2.6 */
  177118. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177119. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  177120. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  177121. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  177122. png_ptr));
  177123. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  177124. png_ptr));
  177125. #endif
  177126. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  177127. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  177128. /* With these routines we avoid an integer divide, which will be slower on
  177129. * most machines. However, it does take more operations than the corresponding
  177130. * divide method, so it may be slower on a few RISC systems. There are two
  177131. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  177132. *
  177133. * Note that the rounding factors are NOT supposed to be the same! 128 and
  177134. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  177135. * standard method.
  177136. *
  177137. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  177138. */
  177139. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  177140. # define png_composite(composite, fg, alpha, bg) \
  177141. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  177142. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  177143. (png_uint_16)(alpha)) + (png_uint_16)128); \
  177144. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  177145. # define png_composite_16(composite, fg, alpha, bg) \
  177146. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  177147. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  177148. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  177149. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  177150. #else /* standard method using integer division */
  177151. # define png_composite(composite, fg, alpha, bg) \
  177152. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  177153. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  177154. (png_uint_16)127) / 255)
  177155. # define png_composite_16(composite, fg, alpha, bg) \
  177156. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  177157. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  177158. (png_uint_32)32767) / (png_uint_32)65535L)
  177159. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  177160. /* Inline macros to do direct reads of bytes from the input buffer. These
  177161. * require that you are using an architecture that uses PNG byte ordering
  177162. * (MSB first) and supports unaligned data storage. I think that PowerPC
  177163. * in big-endian mode and 680x0 are the only ones that will support this.
  177164. * The x86 line of processors definitely do not. The png_get_int_32()
  177165. * routine also assumes we are using two's complement format for negative
  177166. * values, which is almost certainly true.
  177167. */
  177168. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  177169. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  177170. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  177171. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  177172. #else
  177173. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  177174. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  177175. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  177176. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  177177. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  177178. PNGARG((png_structp png_ptr, png_bytep buf));
  177179. /* No png_get_int_16 -- may be added if there's a real need for it. */
  177180. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  177181. */
  177182. extern PNG_EXPORT(void,png_save_uint_32)
  177183. PNGARG((png_bytep buf, png_uint_32 i));
  177184. extern PNG_EXPORT(void,png_save_int_32)
  177185. PNGARG((png_bytep buf, png_int_32 i));
  177186. /* Place a 16-bit number into a buffer in PNG byte order.
  177187. * The parameter is declared unsigned int, not png_uint_16,
  177188. * just to avoid potential problems on pre-ANSI C compilers.
  177189. */
  177190. extern PNG_EXPORT(void,png_save_uint_16)
  177191. PNGARG((png_bytep buf, unsigned int i));
  177192. /* No png_save_int_16 -- may be added if there's a real need for it. */
  177193. /* ************************************************************************* */
  177194. /* These next functions are used internally in the code. They generally
  177195. * shouldn't be used unless you are writing code to add or replace some
  177196. * functionality in libpng. More information about most functions can
  177197. * be found in the files where the functions are located.
  177198. */
  177199. /* Various modes of operation, that are visible to applications because
  177200. * they are used for unknown chunk location.
  177201. */
  177202. #define PNG_HAVE_IHDR 0x01
  177203. #define PNG_HAVE_PLTE 0x02
  177204. #define PNG_HAVE_IDAT 0x04
  177205. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  177206. #define PNG_HAVE_IEND 0x10
  177207. #if defined(PNG_INTERNAL)
  177208. /* More modes of operation. Note that after an init, mode is set to
  177209. * zero automatically when the structure is created.
  177210. */
  177211. #define PNG_HAVE_gAMA 0x20
  177212. #define PNG_HAVE_cHRM 0x40
  177213. #define PNG_HAVE_sRGB 0x80
  177214. #define PNG_HAVE_CHUNK_HEADER 0x100
  177215. #define PNG_WROTE_tIME 0x200
  177216. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  177217. #define PNG_BACKGROUND_IS_GRAY 0x800
  177218. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  177219. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  177220. /* flags for the transformations the PNG library does on the image data */
  177221. #define PNG_BGR 0x0001
  177222. #define PNG_INTERLACE 0x0002
  177223. #define PNG_PACK 0x0004
  177224. #define PNG_SHIFT 0x0008
  177225. #define PNG_SWAP_BYTES 0x0010
  177226. #define PNG_INVERT_MONO 0x0020
  177227. #define PNG_DITHER 0x0040
  177228. #define PNG_BACKGROUND 0x0080
  177229. #define PNG_BACKGROUND_EXPAND 0x0100
  177230. /* 0x0200 unused */
  177231. #define PNG_16_TO_8 0x0400
  177232. #define PNG_RGBA 0x0800
  177233. #define PNG_EXPAND 0x1000
  177234. #define PNG_GAMMA 0x2000
  177235. #define PNG_GRAY_TO_RGB 0x4000
  177236. #define PNG_FILLER 0x8000L
  177237. #define PNG_PACKSWAP 0x10000L
  177238. #define PNG_SWAP_ALPHA 0x20000L
  177239. #define PNG_STRIP_ALPHA 0x40000L
  177240. #define PNG_INVERT_ALPHA 0x80000L
  177241. #define PNG_USER_TRANSFORM 0x100000L
  177242. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  177243. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  177244. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  177245. /* 0x800000L Unused */
  177246. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  177247. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  177248. /* 0x4000000L unused */
  177249. /* 0x8000000L unused */
  177250. /* 0x10000000L unused */
  177251. /* 0x20000000L unused */
  177252. /* 0x40000000L unused */
  177253. /* flags for png_create_struct */
  177254. #define PNG_STRUCT_PNG 0x0001
  177255. #define PNG_STRUCT_INFO 0x0002
  177256. /* Scaling factor for filter heuristic weighting calculations */
  177257. #define PNG_WEIGHT_SHIFT 8
  177258. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  177259. #define PNG_COST_SHIFT 3
  177260. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  177261. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  177262. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  177263. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  177264. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  177265. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  177266. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  177267. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  177268. #define PNG_FLAG_ROW_INIT 0x0040
  177269. #define PNG_FLAG_FILLER_AFTER 0x0080
  177270. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  177271. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  177272. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  177273. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  177274. #define PNG_FLAG_FREE_PLTE 0x1000
  177275. #define PNG_FLAG_FREE_TRNS 0x2000
  177276. #define PNG_FLAG_FREE_HIST 0x4000
  177277. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  177278. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  177279. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  177280. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  177281. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  177282. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  177283. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  177284. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  177285. /* 0x800000L unused */
  177286. /* 0x1000000L unused */
  177287. /* 0x2000000L unused */
  177288. /* 0x4000000L unused */
  177289. /* 0x8000000L unused */
  177290. /* 0x10000000L unused */
  177291. /* 0x20000000L unused */
  177292. /* 0x40000000L unused */
  177293. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  177294. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  177295. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  177296. PNG_FLAG_CRC_CRITICAL_IGNORE)
  177297. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  177298. PNG_FLAG_CRC_CRITICAL_MASK)
  177299. /* save typing and make code easier to understand */
  177300. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  177301. abs((int)((c1).green) - (int)((c2).green)) + \
  177302. abs((int)((c1).blue) - (int)((c2).blue)))
  177303. /* Added to libpng-1.2.6 JB */
  177304. #define PNG_ROWBYTES(pixel_bits, width) \
  177305. ((pixel_bits) >= 8 ? \
  177306. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  177307. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  177308. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  177309. ideal-delta..ideal+delta. Each argument is evaluated twice.
  177310. "ideal" and "delta" should be constants, normally simple
  177311. integers, "value" a variable. Added to libpng-1.2.6 JB */
  177312. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  177313. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  177314. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177315. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177316. /* place to hold the signature string for a PNG file. */
  177317. #ifdef PNG_USE_GLOBAL_ARRAYS
  177318. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  177319. #else
  177320. #endif
  177321. #endif /* PNG_NO_EXTERN */
  177322. /* Constant strings for known chunk types. If you need to add a chunk,
  177323. * define the name here, and add an invocation of the macro in png.c and
  177324. * wherever it's needed.
  177325. */
  177326. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  177327. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  177328. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  177329. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  177330. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  177331. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  177332. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  177333. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  177334. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  177335. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  177336. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  177337. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  177338. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  177339. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  177340. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  177341. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  177342. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  177343. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  177344. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  177345. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  177346. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  177347. #ifdef PNG_USE_GLOBAL_ARRAYS
  177348. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  177349. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  177350. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  177351. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  177352. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  177353. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  177354. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  177355. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  177356. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  177357. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  177358. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  177359. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  177360. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  177361. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  177362. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  177363. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  177364. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  177365. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  177366. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  177367. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  177368. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  177369. #endif /* PNG_USE_GLOBAL_ARRAYS */
  177370. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177371. /* Initialize png_ptr struct for reading, and allocate any other memory.
  177372. * (old interface - DEPRECATED - use png_create_read_struct instead).
  177373. */
  177374. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  177375. #undef png_read_init
  177376. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  177377. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  177378. #endif
  177379. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  177380. png_const_charp user_png_ver, png_size_t png_struct_size));
  177381. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177382. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  177383. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  177384. png_info_size));
  177385. #endif
  177386. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177387. /* Initialize png_ptr struct for writing, and allocate any other memory.
  177388. * (old interface - DEPRECATED - use png_create_write_struct instead).
  177389. */
  177390. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  177391. #undef png_write_init
  177392. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  177393. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  177394. #endif
  177395. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  177396. png_const_charp user_png_ver, png_size_t png_struct_size));
  177397. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  177398. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  177399. png_info_size));
  177400. /* Allocate memory for an internal libpng struct */
  177401. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  177402. /* Free memory from internal libpng struct */
  177403. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  177404. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  177405. malloc_fn, png_voidp mem_ptr));
  177406. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  177407. png_free_ptr free_fn, png_voidp mem_ptr));
  177408. /* Free any memory that info_ptr points to and reset struct. */
  177409. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  177410. png_infop info_ptr));
  177411. #ifndef PNG_1_0_X
  177412. /* Function to allocate memory for zlib. */
  177413. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  177414. /* Function to free memory for zlib */
  177415. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  177416. #ifdef PNG_SIZE_T
  177417. /* Function to convert a sizeof an item to png_sizeof item */
  177418. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  177419. #endif
  177420. /* Next four functions are used internally as callbacks. PNGAPI is required
  177421. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  177422. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  177423. png_bytep data, png_size_t length));
  177424. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177425. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  177426. png_bytep buffer, png_size_t length));
  177427. #endif
  177428. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  177429. png_bytep data, png_size_t length));
  177430. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177431. #if !defined(PNG_NO_STDIO)
  177432. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  177433. #endif
  177434. #endif
  177435. #else /* PNG_1_0_X */
  177436. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177437. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  177438. png_bytep buffer, png_size_t length));
  177439. #endif
  177440. #endif /* PNG_1_0_X */
  177441. /* Reset the CRC variable */
  177442. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  177443. /* Write the "data" buffer to whatever output you are using. */
  177444. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  177445. png_size_t length));
  177446. /* Read data from whatever input you are using into the "data" buffer */
  177447. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  177448. png_size_t length));
  177449. /* Read bytes into buf, and update png_ptr->crc */
  177450. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  177451. png_size_t length));
  177452. /* Decompress data in a chunk that uses compression */
  177453. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  177454. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  177455. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  177456. int comp_type, png_charp chunkdata, png_size_t chunklength,
  177457. png_size_t prefix_length, png_size_t *data_length));
  177458. #endif
  177459. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  177460. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  177461. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  177462. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  177463. /* Calculate the CRC over a section of data. Note that we are only
  177464. * passing a maximum of 64K on systems that have this as a memory limit,
  177465. * since this is the maximum buffer size we can specify.
  177466. */
  177467. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  177468. png_size_t length));
  177469. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177470. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  177471. #endif
  177472. /* simple function to write the signature */
  177473. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  177474. /* write various chunks */
  177475. /* Write the IHDR chunk, and update the png_struct with the necessary
  177476. * information.
  177477. */
  177478. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  177479. png_uint_32 height,
  177480. int bit_depth, int color_type, int compression_method, int filter_method,
  177481. int interlace_method));
  177482. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  177483. png_uint_32 num_pal));
  177484. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  177485. png_size_t length));
  177486. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  177487. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  177488. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177489. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  177490. #endif
  177491. #ifdef PNG_FIXED_POINT_SUPPORTED
  177492. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  177493. file_gamma));
  177494. #endif
  177495. #endif
  177496. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  177497. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  177498. int color_type));
  177499. #endif
  177500. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  177501. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177502. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  177503. double white_x, double white_y,
  177504. double red_x, double red_y, double green_x, double green_y,
  177505. double blue_x, double blue_y));
  177506. #endif
  177507. #ifdef PNG_FIXED_POINT_SUPPORTED
  177508. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  177509. png_fixed_point int_white_x, png_fixed_point int_white_y,
  177510. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  177511. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  177512. png_fixed_point int_blue_y));
  177513. #endif
  177514. #endif
  177515. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  177516. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  177517. int intent));
  177518. #endif
  177519. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  177520. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  177521. png_charp name, int compression_type,
  177522. png_charp profile, int proflen));
  177523. /* Note to maintainer: profile should be png_bytep */
  177524. #endif
  177525. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  177526. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  177527. png_sPLT_tp palette));
  177528. #endif
  177529. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  177530. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  177531. png_color_16p values, int number, int color_type));
  177532. #endif
  177533. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  177534. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  177535. png_color_16p values, int color_type));
  177536. #endif
  177537. #if defined(PNG_WRITE_hIST_SUPPORTED)
  177538. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  177539. int num_hist));
  177540. #endif
  177541. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  177542. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  177543. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  177544. png_charp key, png_charpp new_key));
  177545. #endif
  177546. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  177547. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  177548. png_charp text, png_size_t text_len));
  177549. #endif
  177550. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  177551. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  177552. png_charp text, png_size_t text_len, int compression));
  177553. #endif
  177554. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  177555. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  177556. int compression, png_charp key, png_charp lang, png_charp lang_key,
  177557. png_charp text));
  177558. #endif
  177559. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  177560. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  177561. png_infop info_ptr, png_textp text_ptr, int num_text));
  177562. #endif
  177563. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  177564. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  177565. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  177566. #endif
  177567. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  177568. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  177569. png_int_32 X0, png_int_32 X1, int type, int nparams,
  177570. png_charp units, png_charpp params));
  177571. #endif
  177572. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  177573. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  177574. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  177575. int unit_type));
  177576. #endif
  177577. #if defined(PNG_WRITE_tIME_SUPPORTED)
  177578. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  177579. png_timep mod_time));
  177580. #endif
  177581. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  177582. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  177583. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  177584. int unit, double width, double height));
  177585. #else
  177586. #ifdef PNG_FIXED_POINT_SUPPORTED
  177587. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  177588. int unit, png_charp width, png_charp height));
  177589. #endif
  177590. #endif
  177591. #endif
  177592. /* Called when finished processing a row of data */
  177593. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  177594. /* Internal use only. Called before first row of data */
  177595. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  177596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177597. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  177598. #endif
  177599. /* combine a row of data, dealing with alpha, etc. if requested */
  177600. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  177601. int mask));
  177602. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  177603. /* expand an interlaced row */
  177604. /* OLD pre-1.0.9 interface:
  177605. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  177606. png_bytep row, int pass, png_uint_32 transformations));
  177607. */
  177608. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  177609. #endif
  177610. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  177611. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177612. /* grab pixels out of a row for an interlaced pass */
  177613. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  177614. png_bytep row, int pass));
  177615. #endif
  177616. /* unfilter a row */
  177617. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  177618. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  177619. /* Choose the best filter to use and filter the row data */
  177620. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  177621. png_row_infop row_info));
  177622. /* Write out the filtered row. */
  177623. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  177624. png_bytep filtered_row));
  177625. /* finish a row while reading, dealing with interlacing passes, etc. */
  177626. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  177627. /* initialize the row buffers, etc. */
  177628. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  177629. /* optional call to update the users info structure */
  177630. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  177631. png_infop info_ptr));
  177632. /* these are the functions that do the transformations */
  177633. #if defined(PNG_READ_FILLER_SUPPORTED)
  177634. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  177635. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  177636. #endif
  177637. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  177638. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  177639. png_bytep row));
  177640. #endif
  177641. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  177642. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  177643. png_bytep row));
  177644. #endif
  177645. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  177646. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  177647. png_bytep row));
  177648. #endif
  177649. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  177650. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  177651. png_bytep row));
  177652. #endif
  177653. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  177654. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  177655. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  177656. png_bytep row, png_uint_32 flags));
  177657. #endif
  177658. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  177659. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  177660. #endif
  177661. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  177662. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  177663. #endif
  177664. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177665. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  177666. row_info, png_bytep row));
  177667. #endif
  177668. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  177669. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  177670. png_bytep row));
  177671. #endif
  177672. #if defined(PNG_READ_PACK_SUPPORTED)
  177673. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  177674. #endif
  177675. #if defined(PNG_READ_SHIFT_SUPPORTED)
  177676. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  177677. png_color_8p sig_bits));
  177678. #endif
  177679. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177680. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  177681. #endif
  177682. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177683. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  177684. #endif
  177685. #if defined(PNG_READ_DITHER_SUPPORTED)
  177686. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  177687. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  177688. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  177689. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  177690. png_colorp palette, int num_palette));
  177691. # endif
  177692. #endif
  177693. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  177694. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  177695. #endif
  177696. #if defined(PNG_WRITE_PACK_SUPPORTED)
  177697. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  177698. png_bytep row, png_uint_32 bit_depth));
  177699. #endif
  177700. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  177701. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  177702. png_color_8p bit_depth));
  177703. #endif
  177704. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177705. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177706. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  177707. png_color_16p trans_values, png_color_16p background,
  177708. png_color_16p background_1,
  177709. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  177710. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  177711. png_uint_16pp gamma_16_to_1, int gamma_shift));
  177712. #else
  177713. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  177714. png_color_16p trans_values, png_color_16p background));
  177715. #endif
  177716. #endif
  177717. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177718. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  177719. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  177720. int gamma_shift));
  177721. #endif
  177722. #if defined(PNG_READ_EXPAND_SUPPORTED)
  177723. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  177724. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  177725. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  177726. png_bytep row, png_color_16p trans_value));
  177727. #endif
  177728. /* The following decodes the appropriate chunks, and does error correction,
  177729. * then calls the appropriate callback for the chunk if it is valid.
  177730. */
  177731. /* decode the IHDR chunk */
  177732. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  177733. png_uint_32 length));
  177734. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  177735. png_uint_32 length));
  177736. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  177737. png_uint_32 length));
  177738. #if defined(PNG_READ_bKGD_SUPPORTED)
  177739. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  177740. png_uint_32 length));
  177741. #endif
  177742. #if defined(PNG_READ_cHRM_SUPPORTED)
  177743. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  177744. png_uint_32 length));
  177745. #endif
  177746. #if defined(PNG_READ_gAMA_SUPPORTED)
  177747. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  177748. png_uint_32 length));
  177749. #endif
  177750. #if defined(PNG_READ_hIST_SUPPORTED)
  177751. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  177752. png_uint_32 length));
  177753. #endif
  177754. #if defined(PNG_READ_iCCP_SUPPORTED)
  177755. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  177756. png_uint_32 length));
  177757. #endif /* PNG_READ_iCCP_SUPPORTED */
  177758. #if defined(PNG_READ_iTXt_SUPPORTED)
  177759. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177760. png_uint_32 length));
  177761. #endif
  177762. #if defined(PNG_READ_oFFs_SUPPORTED)
  177763. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  177764. png_uint_32 length));
  177765. #endif
  177766. #if defined(PNG_READ_pCAL_SUPPORTED)
  177767. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  177768. png_uint_32 length));
  177769. #endif
  177770. #if defined(PNG_READ_pHYs_SUPPORTED)
  177771. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  177772. png_uint_32 length));
  177773. #endif
  177774. #if defined(PNG_READ_sBIT_SUPPORTED)
  177775. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  177776. png_uint_32 length));
  177777. #endif
  177778. #if defined(PNG_READ_sCAL_SUPPORTED)
  177779. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  177780. png_uint_32 length));
  177781. #endif
  177782. #if defined(PNG_READ_sPLT_SUPPORTED)
  177783. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  177784. png_uint_32 length));
  177785. #endif /* PNG_READ_sPLT_SUPPORTED */
  177786. #if defined(PNG_READ_sRGB_SUPPORTED)
  177787. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  177788. png_uint_32 length));
  177789. #endif
  177790. #if defined(PNG_READ_tEXt_SUPPORTED)
  177791. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177792. png_uint_32 length));
  177793. #endif
  177794. #if defined(PNG_READ_tIME_SUPPORTED)
  177795. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  177796. png_uint_32 length));
  177797. #endif
  177798. #if defined(PNG_READ_tRNS_SUPPORTED)
  177799. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  177800. png_uint_32 length));
  177801. #endif
  177802. #if defined(PNG_READ_zTXt_SUPPORTED)
  177803. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177804. png_uint_32 length));
  177805. #endif
  177806. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  177807. png_infop info_ptr, png_uint_32 length));
  177808. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  177809. png_bytep chunk_name));
  177810. /* handle the transformations for reading and writing */
  177811. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  177812. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  177813. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  177814. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177815. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  177816. png_infop info_ptr));
  177817. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  177818. png_infop info_ptr));
  177819. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  177820. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  177821. png_uint_32 length));
  177822. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  177823. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  177824. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  177825. png_bytep buffer, png_size_t buffer_length));
  177826. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  177827. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  177828. png_bytep buffer, png_size_t buffer_length));
  177829. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  177830. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  177831. png_infop info_ptr, png_uint_32 length));
  177832. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  177833. png_infop info_ptr));
  177834. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  177835. png_infop info_ptr));
  177836. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  177837. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  177838. png_infop info_ptr));
  177839. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  177840. png_infop info_ptr));
  177841. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  177842. #if defined(PNG_READ_tEXt_SUPPORTED)
  177843. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  177844. png_infop info_ptr, png_uint_32 length));
  177845. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  177846. png_infop info_ptr));
  177847. #endif
  177848. #if defined(PNG_READ_zTXt_SUPPORTED)
  177849. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  177850. png_infop info_ptr, png_uint_32 length));
  177851. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  177852. png_infop info_ptr));
  177853. #endif
  177854. #if defined(PNG_READ_iTXt_SUPPORTED)
  177855. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  177856. png_infop info_ptr, png_uint_32 length));
  177857. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  177858. png_infop info_ptr));
  177859. #endif
  177860. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177861. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177862. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  177863. png_bytep row));
  177864. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  177865. png_bytep row));
  177866. #endif
  177867. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177868. #if defined(PNG_MMX_CODE_SUPPORTED)
  177869. /* png.c */ /* PRIVATE */
  177870. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  177871. #endif
  177872. #endif
  177873. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177874. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  177875. png_infop info_ptr));
  177876. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  177877. png_infop info_ptr));
  177878. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  177879. png_infop info_ptr));
  177880. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  177881. png_infop info_ptr));
  177882. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  177883. png_infop info_ptr));
  177884. #if defined(PNG_pHYs_SUPPORTED)
  177885. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  177886. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  177887. #endif /* PNG_pHYs_SUPPORTED */
  177888. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  177889. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  177890. #endif /* PNG_INTERNAL */
  177891. #ifdef __cplusplus
  177892. }
  177893. #endif
  177894. #endif /* PNG_VERSION_INFO_ONLY */
  177895. /* do not put anything past this line */
  177896. #endif /* PNG_H */
  177897. /********* End of inlined file: png.h *********/
  177898. #define PNG_NO_EXTERN
  177899. /********* Start of inlined file: png.c *********/
  177900. /* png.c - location for general purpose libpng functions
  177901. *
  177902. * Last changed in libpng 1.2.21 [October 4, 2007]
  177903. * For conditions of distribution and use, see copyright notice in png.h
  177904. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177905. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177906. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177907. */
  177908. #define PNG_INTERNAL
  177909. #define PNG_NO_EXTERN
  177910. /* Generate a compiler error if there is an old png.h in the search path. */
  177911. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  177912. /* Version information for C files. This had better match the version
  177913. * string defined in png.h. */
  177914. #ifdef PNG_USE_GLOBAL_ARRAYS
  177915. /* png_libpng_ver was changed to a function in version 1.0.5c */
  177916. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  177917. #ifdef PNG_READ_SUPPORTED
  177918. /* png_sig was changed to a function in version 1.0.5c */
  177919. /* Place to hold the signature string for a PNG file. */
  177920. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  177921. #endif /* PNG_READ_SUPPORTED */
  177922. /* Invoke global declarations for constant strings for known chunk types */
  177923. PNG_IHDR;
  177924. PNG_IDAT;
  177925. PNG_IEND;
  177926. PNG_PLTE;
  177927. PNG_bKGD;
  177928. PNG_cHRM;
  177929. PNG_gAMA;
  177930. PNG_hIST;
  177931. PNG_iCCP;
  177932. PNG_iTXt;
  177933. PNG_oFFs;
  177934. PNG_pCAL;
  177935. PNG_sCAL;
  177936. PNG_pHYs;
  177937. PNG_sBIT;
  177938. PNG_sPLT;
  177939. PNG_sRGB;
  177940. PNG_tEXt;
  177941. PNG_tIME;
  177942. PNG_tRNS;
  177943. PNG_zTXt;
  177944. #ifdef PNG_READ_SUPPORTED
  177945. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  177946. /* start of interlace block */
  177947. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  177948. /* offset to next interlace block */
  177949. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  177950. /* start of interlace block in the y direction */
  177951. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  177952. /* offset to next interlace block in the y direction */
  177953. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  177954. /* Height of interlace block. This is not currently used - if you need
  177955. * it, uncomment it here and in png.h
  177956. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  177957. */
  177958. /* Mask to determine which pixels are valid in a pass */
  177959. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  177960. /* Mask to determine which pixels to overwrite while displaying */
  177961. PNG_CONST int FARDATA png_pass_dsp_mask[]
  177962. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  177963. #endif /* PNG_READ_SUPPORTED */
  177964. #endif /* PNG_USE_GLOBAL_ARRAYS */
  177965. /* Tells libpng that we have already handled the first "num_bytes" bytes
  177966. * of the PNG file signature. If the PNG data is embedded into another
  177967. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  177968. * or write any of the magic bytes before it starts on the IHDR.
  177969. */
  177970. #ifdef PNG_READ_SUPPORTED
  177971. void PNGAPI
  177972. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  177973. {
  177974. if(png_ptr == NULL) return;
  177975. png_debug(1, "in png_set_sig_bytes\n");
  177976. if (num_bytes > 8)
  177977. png_error(png_ptr, "Too many bytes for PNG signature.");
  177978. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  177979. }
  177980. /* Checks whether the supplied bytes match the PNG signature. We allow
  177981. * checking less than the full 8-byte signature so that those apps that
  177982. * already read the first few bytes of a file to determine the file type
  177983. * can simply check the remaining bytes for extra assurance. Returns
  177984. * an integer less than, equal to, or greater than zero if sig is found,
  177985. * respectively, to be less than, to match, or be greater than the correct
  177986. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  177987. */
  177988. int PNGAPI
  177989. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  177990. {
  177991. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  177992. if (num_to_check > 8)
  177993. num_to_check = 8;
  177994. else if (num_to_check < 1)
  177995. return (-1);
  177996. if (start > 7)
  177997. return (-1);
  177998. if (start + num_to_check > 8)
  177999. num_to_check = 8 - start;
  178000. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  178001. }
  178002. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178003. /* (Obsolete) function to check signature bytes. It does not allow one
  178004. * to check a partial signature. This function might be removed in the
  178005. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  178006. */
  178007. int PNGAPI
  178008. png_check_sig(png_bytep sig, int num)
  178009. {
  178010. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  178011. }
  178012. #endif
  178013. #endif /* PNG_READ_SUPPORTED */
  178014. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178015. /* Function to allocate memory for zlib and clear it to 0. */
  178016. #ifdef PNG_1_0_X
  178017. voidpf PNGAPI
  178018. #else
  178019. voidpf /* private */
  178020. #endif
  178021. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  178022. {
  178023. png_voidp ptr;
  178024. png_structp p=(png_structp)png_ptr;
  178025. png_uint_32 save_flags=p->flags;
  178026. png_uint_32 num_bytes;
  178027. if(png_ptr == NULL) return (NULL);
  178028. if (items > PNG_UINT_32_MAX/size)
  178029. {
  178030. png_warning (p, "Potential overflow in png_zalloc()");
  178031. return (NULL);
  178032. }
  178033. num_bytes = (png_uint_32)items * size;
  178034. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  178035. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  178036. p->flags=save_flags;
  178037. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  178038. if (ptr == NULL)
  178039. return ((voidpf)ptr);
  178040. if (num_bytes > (png_uint_32)0x8000L)
  178041. {
  178042. png_memset(ptr, 0, (png_size_t)0x8000L);
  178043. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  178044. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  178045. }
  178046. else
  178047. {
  178048. png_memset(ptr, 0, (png_size_t)num_bytes);
  178049. }
  178050. #endif
  178051. return ((voidpf)ptr);
  178052. }
  178053. /* function to free memory for zlib */
  178054. #ifdef PNG_1_0_X
  178055. void PNGAPI
  178056. #else
  178057. void /* private */
  178058. #endif
  178059. png_zfree(voidpf png_ptr, voidpf ptr)
  178060. {
  178061. png_free((png_structp)png_ptr, (png_voidp)ptr);
  178062. }
  178063. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  178064. * in case CRC is > 32 bits to leave the top bits 0.
  178065. */
  178066. void /* PRIVATE */
  178067. png_reset_crc(png_structp png_ptr)
  178068. {
  178069. png_ptr->crc = crc32(0, Z_NULL, 0);
  178070. }
  178071. /* Calculate the CRC over a section of data. We can only pass as
  178072. * much data to this routine as the largest single buffer size. We
  178073. * also check that this data will actually be used before going to the
  178074. * trouble of calculating it.
  178075. */
  178076. void /* PRIVATE */
  178077. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  178078. {
  178079. int need_crc = 1;
  178080. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  178081. {
  178082. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  178083. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  178084. need_crc = 0;
  178085. }
  178086. else /* critical */
  178087. {
  178088. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  178089. need_crc = 0;
  178090. }
  178091. if (need_crc)
  178092. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  178093. }
  178094. /* Allocate the memory for an info_struct for the application. We don't
  178095. * really need the png_ptr, but it could potentially be useful in the
  178096. * future. This should be used in favour of malloc(png_sizeof(png_info))
  178097. * and png_info_init() so that applications that want to use a shared
  178098. * libpng don't have to be recompiled if png_info changes size.
  178099. */
  178100. png_infop PNGAPI
  178101. png_create_info_struct(png_structp png_ptr)
  178102. {
  178103. png_infop info_ptr;
  178104. png_debug(1, "in png_create_info_struct\n");
  178105. if(png_ptr == NULL) return (NULL);
  178106. #ifdef PNG_USER_MEM_SUPPORTED
  178107. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  178108. png_ptr->malloc_fn, png_ptr->mem_ptr);
  178109. #else
  178110. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178111. #endif
  178112. if (info_ptr != NULL)
  178113. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178114. return (info_ptr);
  178115. }
  178116. /* This function frees the memory associated with a single info struct.
  178117. * Normally, one would use either png_destroy_read_struct() or
  178118. * png_destroy_write_struct() to free an info struct, but this may be
  178119. * useful for some applications.
  178120. */
  178121. void PNGAPI
  178122. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  178123. {
  178124. png_infop info_ptr = NULL;
  178125. if(png_ptr == NULL) return;
  178126. png_debug(1, "in png_destroy_info_struct\n");
  178127. if (info_ptr_ptr != NULL)
  178128. info_ptr = *info_ptr_ptr;
  178129. if (info_ptr != NULL)
  178130. {
  178131. png_info_destroy(png_ptr, info_ptr);
  178132. #ifdef PNG_USER_MEM_SUPPORTED
  178133. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  178134. png_ptr->mem_ptr);
  178135. #else
  178136. png_destroy_struct((png_voidp)info_ptr);
  178137. #endif
  178138. *info_ptr_ptr = NULL;
  178139. }
  178140. }
  178141. /* Initialize the info structure. This is now an internal function (0.89)
  178142. * and applications using it are urged to use png_create_info_struct()
  178143. * instead.
  178144. */
  178145. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178146. #undef png_info_init
  178147. void PNGAPI
  178148. png_info_init(png_infop info_ptr)
  178149. {
  178150. /* We only come here via pre-1.0.12-compiled applications */
  178151. png_info_init_3(&info_ptr, 0);
  178152. }
  178153. #endif
  178154. void PNGAPI
  178155. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  178156. {
  178157. png_infop info_ptr = *ptr_ptr;
  178158. if(info_ptr == NULL) return;
  178159. png_debug(1, "in png_info_init_3\n");
  178160. if(png_sizeof(png_info) > png_info_struct_size)
  178161. {
  178162. png_destroy_struct(info_ptr);
  178163. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178164. *ptr_ptr = info_ptr;
  178165. }
  178166. /* set everything to 0 */
  178167. png_memset(info_ptr, 0, png_sizeof (png_info));
  178168. }
  178169. #ifdef PNG_FREE_ME_SUPPORTED
  178170. void PNGAPI
  178171. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  178172. int freer, png_uint_32 mask)
  178173. {
  178174. png_debug(1, "in png_data_freer\n");
  178175. if (png_ptr == NULL || info_ptr == NULL)
  178176. return;
  178177. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  178178. info_ptr->free_me |= mask;
  178179. else if(freer == PNG_USER_WILL_FREE_DATA)
  178180. info_ptr->free_me &= ~mask;
  178181. else
  178182. png_warning(png_ptr,
  178183. "Unknown freer parameter in png_data_freer.");
  178184. }
  178185. #endif
  178186. void PNGAPI
  178187. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  178188. int num)
  178189. {
  178190. png_debug(1, "in png_free_data\n");
  178191. if (png_ptr == NULL || info_ptr == NULL)
  178192. return;
  178193. #if defined(PNG_TEXT_SUPPORTED)
  178194. /* free text item num or (if num == -1) all text items */
  178195. #ifdef PNG_FREE_ME_SUPPORTED
  178196. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  178197. #else
  178198. if (mask & PNG_FREE_TEXT)
  178199. #endif
  178200. {
  178201. if (num != -1)
  178202. {
  178203. if (info_ptr->text && info_ptr->text[num].key)
  178204. {
  178205. png_free(png_ptr, info_ptr->text[num].key);
  178206. info_ptr->text[num].key = NULL;
  178207. }
  178208. }
  178209. else
  178210. {
  178211. int i;
  178212. for (i = 0; i < info_ptr->num_text; i++)
  178213. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  178214. png_free(png_ptr, info_ptr->text);
  178215. info_ptr->text = NULL;
  178216. info_ptr->num_text=0;
  178217. }
  178218. }
  178219. #endif
  178220. #if defined(PNG_tRNS_SUPPORTED)
  178221. /* free any tRNS entry */
  178222. #ifdef PNG_FREE_ME_SUPPORTED
  178223. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  178224. #else
  178225. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  178226. #endif
  178227. {
  178228. png_free(png_ptr, info_ptr->trans);
  178229. info_ptr->valid &= ~PNG_INFO_tRNS;
  178230. #ifndef PNG_FREE_ME_SUPPORTED
  178231. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  178232. #endif
  178233. info_ptr->trans = NULL;
  178234. }
  178235. #endif
  178236. #if defined(PNG_sCAL_SUPPORTED)
  178237. /* free any sCAL entry */
  178238. #ifdef PNG_FREE_ME_SUPPORTED
  178239. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  178240. #else
  178241. if (mask & PNG_FREE_SCAL)
  178242. #endif
  178243. {
  178244. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  178245. png_free(png_ptr, info_ptr->scal_s_width);
  178246. png_free(png_ptr, info_ptr->scal_s_height);
  178247. info_ptr->scal_s_width = NULL;
  178248. info_ptr->scal_s_height = NULL;
  178249. #endif
  178250. info_ptr->valid &= ~PNG_INFO_sCAL;
  178251. }
  178252. #endif
  178253. #if defined(PNG_pCAL_SUPPORTED)
  178254. /* free any pCAL entry */
  178255. #ifdef PNG_FREE_ME_SUPPORTED
  178256. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  178257. #else
  178258. if (mask & PNG_FREE_PCAL)
  178259. #endif
  178260. {
  178261. png_free(png_ptr, info_ptr->pcal_purpose);
  178262. png_free(png_ptr, info_ptr->pcal_units);
  178263. info_ptr->pcal_purpose = NULL;
  178264. info_ptr->pcal_units = NULL;
  178265. if (info_ptr->pcal_params != NULL)
  178266. {
  178267. int i;
  178268. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  178269. {
  178270. png_free(png_ptr, info_ptr->pcal_params[i]);
  178271. info_ptr->pcal_params[i]=NULL;
  178272. }
  178273. png_free(png_ptr, info_ptr->pcal_params);
  178274. info_ptr->pcal_params = NULL;
  178275. }
  178276. info_ptr->valid &= ~PNG_INFO_pCAL;
  178277. }
  178278. #endif
  178279. #if defined(PNG_iCCP_SUPPORTED)
  178280. /* free any iCCP entry */
  178281. #ifdef PNG_FREE_ME_SUPPORTED
  178282. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  178283. #else
  178284. if (mask & PNG_FREE_ICCP)
  178285. #endif
  178286. {
  178287. png_free(png_ptr, info_ptr->iccp_name);
  178288. png_free(png_ptr, info_ptr->iccp_profile);
  178289. info_ptr->iccp_name = NULL;
  178290. info_ptr->iccp_profile = NULL;
  178291. info_ptr->valid &= ~PNG_INFO_iCCP;
  178292. }
  178293. #endif
  178294. #if defined(PNG_sPLT_SUPPORTED)
  178295. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  178296. #ifdef PNG_FREE_ME_SUPPORTED
  178297. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  178298. #else
  178299. if (mask & PNG_FREE_SPLT)
  178300. #endif
  178301. {
  178302. if (num != -1)
  178303. {
  178304. if(info_ptr->splt_palettes)
  178305. {
  178306. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  178307. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  178308. info_ptr->splt_palettes[num].name = NULL;
  178309. info_ptr->splt_palettes[num].entries = NULL;
  178310. }
  178311. }
  178312. else
  178313. {
  178314. if(info_ptr->splt_palettes_num)
  178315. {
  178316. int i;
  178317. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  178318. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  178319. png_free(png_ptr, info_ptr->splt_palettes);
  178320. info_ptr->splt_palettes = NULL;
  178321. info_ptr->splt_palettes_num = 0;
  178322. }
  178323. info_ptr->valid &= ~PNG_INFO_sPLT;
  178324. }
  178325. }
  178326. #endif
  178327. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178328. if(png_ptr->unknown_chunk.data)
  178329. {
  178330. png_free(png_ptr, png_ptr->unknown_chunk.data);
  178331. png_ptr->unknown_chunk.data = NULL;
  178332. }
  178333. #ifdef PNG_FREE_ME_SUPPORTED
  178334. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  178335. #else
  178336. if (mask & PNG_FREE_UNKN)
  178337. #endif
  178338. {
  178339. if (num != -1)
  178340. {
  178341. if(info_ptr->unknown_chunks)
  178342. {
  178343. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  178344. info_ptr->unknown_chunks[num].data = NULL;
  178345. }
  178346. }
  178347. else
  178348. {
  178349. int i;
  178350. if(info_ptr->unknown_chunks_num)
  178351. {
  178352. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  178353. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  178354. png_free(png_ptr, info_ptr->unknown_chunks);
  178355. info_ptr->unknown_chunks = NULL;
  178356. info_ptr->unknown_chunks_num = 0;
  178357. }
  178358. }
  178359. }
  178360. #endif
  178361. #if defined(PNG_hIST_SUPPORTED)
  178362. /* free any hIST entry */
  178363. #ifdef PNG_FREE_ME_SUPPORTED
  178364. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  178365. #else
  178366. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  178367. #endif
  178368. {
  178369. png_free(png_ptr, info_ptr->hist);
  178370. info_ptr->hist = NULL;
  178371. info_ptr->valid &= ~PNG_INFO_hIST;
  178372. #ifndef PNG_FREE_ME_SUPPORTED
  178373. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  178374. #endif
  178375. }
  178376. #endif
  178377. /* free any PLTE entry that was internally allocated */
  178378. #ifdef PNG_FREE_ME_SUPPORTED
  178379. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  178380. #else
  178381. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  178382. #endif
  178383. {
  178384. png_zfree(png_ptr, info_ptr->palette);
  178385. info_ptr->palette = NULL;
  178386. info_ptr->valid &= ~PNG_INFO_PLTE;
  178387. #ifndef PNG_FREE_ME_SUPPORTED
  178388. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  178389. #endif
  178390. info_ptr->num_palette = 0;
  178391. }
  178392. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178393. /* free any image bits attached to the info structure */
  178394. #ifdef PNG_FREE_ME_SUPPORTED
  178395. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  178396. #else
  178397. if (mask & PNG_FREE_ROWS)
  178398. #endif
  178399. {
  178400. if(info_ptr->row_pointers)
  178401. {
  178402. int row;
  178403. for (row = 0; row < (int)info_ptr->height; row++)
  178404. {
  178405. png_free(png_ptr, info_ptr->row_pointers[row]);
  178406. info_ptr->row_pointers[row]=NULL;
  178407. }
  178408. png_free(png_ptr, info_ptr->row_pointers);
  178409. info_ptr->row_pointers=NULL;
  178410. }
  178411. info_ptr->valid &= ~PNG_INFO_IDAT;
  178412. }
  178413. #endif
  178414. #ifdef PNG_FREE_ME_SUPPORTED
  178415. if(num == -1)
  178416. info_ptr->free_me &= ~mask;
  178417. else
  178418. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  178419. #endif
  178420. }
  178421. /* This is an internal routine to free any memory that the info struct is
  178422. * pointing to before re-using it or freeing the struct itself. Recall
  178423. * that png_free() checks for NULL pointers for us.
  178424. */
  178425. void /* PRIVATE */
  178426. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  178427. {
  178428. png_debug(1, "in png_info_destroy\n");
  178429. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  178430. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178431. if (png_ptr->num_chunk_list)
  178432. {
  178433. png_free(png_ptr, png_ptr->chunk_list);
  178434. png_ptr->chunk_list=NULL;
  178435. png_ptr->num_chunk_list=0;
  178436. }
  178437. #endif
  178438. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178439. }
  178440. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178441. /* This function returns a pointer to the io_ptr associated with the user
  178442. * functions. The application should free any memory associated with this
  178443. * pointer before png_write_destroy() or png_read_destroy() are called.
  178444. */
  178445. png_voidp PNGAPI
  178446. png_get_io_ptr(png_structp png_ptr)
  178447. {
  178448. if(png_ptr == NULL) return (NULL);
  178449. return (png_ptr->io_ptr);
  178450. }
  178451. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178452. #if !defined(PNG_NO_STDIO)
  178453. /* Initialize the default input/output functions for the PNG file. If you
  178454. * use your own read or write routines, you can call either png_set_read_fn()
  178455. * or png_set_write_fn() instead of png_init_io(). If you have defined
  178456. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  178457. * necessarily available.
  178458. */
  178459. void PNGAPI
  178460. png_init_io(png_structp png_ptr, png_FILE_p fp)
  178461. {
  178462. png_debug(1, "in png_init_io\n");
  178463. if(png_ptr == NULL) return;
  178464. png_ptr->io_ptr = (png_voidp)fp;
  178465. }
  178466. #endif
  178467. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178468. /* Convert the supplied time into an RFC 1123 string suitable for use in
  178469. * a "Creation Time" or other text-based time string.
  178470. */
  178471. png_charp PNGAPI
  178472. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  178473. {
  178474. static PNG_CONST char short_months[12][4] =
  178475. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  178476. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  178477. if(png_ptr == NULL) return (NULL);
  178478. if (png_ptr->time_buffer == NULL)
  178479. {
  178480. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  178481. png_sizeof(char)));
  178482. }
  178483. #if defined(_WIN32_WCE)
  178484. {
  178485. wchar_t time_buf[29];
  178486. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  178487. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178488. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178489. ptime->second % 61);
  178490. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  178491. NULL, NULL);
  178492. }
  178493. #else
  178494. #ifdef USE_FAR_KEYWORD
  178495. {
  178496. char near_time_buf[29];
  178497. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  178498. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178499. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178500. ptime->second % 61);
  178501. png_memcpy(png_ptr->time_buffer, near_time_buf,
  178502. 29*png_sizeof(char));
  178503. }
  178504. #else
  178505. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  178506. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178507. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178508. ptime->second % 61);
  178509. #endif
  178510. #endif /* _WIN32_WCE */
  178511. return ((png_charp)png_ptr->time_buffer);
  178512. }
  178513. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  178514. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178515. png_charp PNGAPI
  178516. png_get_copyright(png_structp png_ptr)
  178517. {
  178518. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178519. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  178520. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  178521. Copyright (c) 1996-1997 Andreas Dilger\n\
  178522. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  178523. }
  178524. /* The following return the library version as a short string in the
  178525. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  178526. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  178527. * is defined in png.h.
  178528. * Note: now there is no difference between png_get_libpng_ver() and
  178529. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  178530. * it is guaranteed that png.c uses the correct version of png.h.
  178531. */
  178532. png_charp PNGAPI
  178533. png_get_libpng_ver(png_structp png_ptr)
  178534. {
  178535. /* Version of *.c files used when building libpng */
  178536. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178537. return ((png_charp) PNG_LIBPNG_VER_STRING);
  178538. }
  178539. png_charp PNGAPI
  178540. png_get_header_ver(png_structp png_ptr)
  178541. {
  178542. /* Version of *.h files used when building libpng */
  178543. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178544. return ((png_charp) PNG_LIBPNG_VER_STRING);
  178545. }
  178546. png_charp PNGAPI
  178547. png_get_header_version(png_structp png_ptr)
  178548. {
  178549. /* Returns longer string containing both version and date */
  178550. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178551. return ((png_charp) PNG_HEADER_VERSION_STRING
  178552. #ifndef PNG_READ_SUPPORTED
  178553. " (NO READ SUPPORT)"
  178554. #endif
  178555. "\n");
  178556. }
  178557. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178558. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178559. int PNGAPI
  178560. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  178561. {
  178562. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  178563. int i;
  178564. png_bytep p;
  178565. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  178566. return 0;
  178567. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  178568. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  178569. if (!png_memcmp(chunk_name, p, 4))
  178570. return ((int)*(p+4));
  178571. return 0;
  178572. }
  178573. #endif
  178574. /* This function, added to libpng-1.0.6g, is untested. */
  178575. int PNGAPI
  178576. png_reset_zstream(png_structp png_ptr)
  178577. {
  178578. if (png_ptr == NULL) return Z_STREAM_ERROR;
  178579. return (inflateReset(&png_ptr->zstream));
  178580. }
  178581. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178582. /* This function was added to libpng-1.0.7 */
  178583. png_uint_32 PNGAPI
  178584. png_access_version_number(void)
  178585. {
  178586. /* Version of *.c files used when building libpng */
  178587. return((png_uint_32) PNG_LIBPNG_VER);
  178588. }
  178589. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178590. #if !defined(PNG_1_0_X)
  178591. /* this function was added to libpng 1.2.0 */
  178592. int PNGAPI
  178593. png_mmx_support(void)
  178594. {
  178595. /* obsolete, to be removed from libpng-1.4.0 */
  178596. return -1;
  178597. }
  178598. #endif /* PNG_1_0_X */
  178599. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  178600. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178601. #ifdef PNG_SIZE_T
  178602. /* Added at libpng version 1.2.6 */
  178603. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178604. png_size_t PNGAPI
  178605. png_convert_size(size_t size)
  178606. {
  178607. if (size > (png_size_t)-1)
  178608. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  178609. return ((png_size_t)size);
  178610. }
  178611. #endif /* PNG_SIZE_T */
  178612. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178613. /********* End of inlined file: png.c *********/
  178614. /********* Start of inlined file: pngerror.c *********/
  178615. /* pngerror.c - stub functions for i/o and memory allocation
  178616. *
  178617. * Last changed in libpng 1.2.20 October 4, 2007
  178618. * For conditions of distribution and use, see copyright notice in png.h
  178619. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178620. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178621. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178622. *
  178623. * This file provides a location for all error handling. Users who
  178624. * need special error handling are expected to write replacement functions
  178625. * and use png_set_error_fn() to use those functions. See the instructions
  178626. * at each function.
  178627. */
  178628. #define PNG_INTERNAL
  178629. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178630. static void /* PRIVATE */
  178631. png_default_error PNGARG((png_structp png_ptr,
  178632. png_const_charp error_message));
  178633. #ifndef PNG_NO_WARNINGS
  178634. static void /* PRIVATE */
  178635. png_default_warning PNGARG((png_structp png_ptr,
  178636. png_const_charp warning_message));
  178637. #endif /* PNG_NO_WARNINGS */
  178638. /* This function is called whenever there is a fatal error. This function
  178639. * should not be changed. If there is a need to handle errors differently,
  178640. * you should supply a replacement error function and use png_set_error_fn()
  178641. * to replace the error function at run-time.
  178642. */
  178643. #ifndef PNG_NO_ERROR_TEXT
  178644. void PNGAPI
  178645. png_error(png_structp png_ptr, png_const_charp error_message)
  178646. {
  178647. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178648. char msg[16];
  178649. if (png_ptr != NULL)
  178650. {
  178651. if (png_ptr->flags&
  178652. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  178653. {
  178654. if (*error_message == '#')
  178655. {
  178656. int offset;
  178657. for (offset=1; offset<15; offset++)
  178658. if (*(error_message+offset) == ' ')
  178659. break;
  178660. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  178661. {
  178662. int i;
  178663. for (i=0; i<offset-1; i++)
  178664. msg[i]=error_message[i+1];
  178665. msg[i]='\0';
  178666. error_message=msg;
  178667. }
  178668. else
  178669. error_message+=offset;
  178670. }
  178671. else
  178672. {
  178673. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  178674. {
  178675. msg[0]='0';
  178676. msg[1]='\0';
  178677. error_message=msg;
  178678. }
  178679. }
  178680. }
  178681. }
  178682. #endif
  178683. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  178684. (*(png_ptr->error_fn))(png_ptr, error_message);
  178685. /* If the custom handler doesn't exist, or if it returns,
  178686. use the default handler, which will not return. */
  178687. png_default_error(png_ptr, error_message);
  178688. }
  178689. #else
  178690. void PNGAPI
  178691. png_err(png_structp png_ptr)
  178692. {
  178693. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  178694. (*(png_ptr->error_fn))(png_ptr, '\0');
  178695. /* If the custom handler doesn't exist, or if it returns,
  178696. use the default handler, which will not return. */
  178697. png_default_error(png_ptr, '\0');
  178698. }
  178699. #endif /* PNG_NO_ERROR_TEXT */
  178700. #ifndef PNG_NO_WARNINGS
  178701. /* This function is called whenever there is a non-fatal error. This function
  178702. * should not be changed. If there is a need to handle warnings differently,
  178703. * you should supply a replacement warning function and use
  178704. * png_set_error_fn() to replace the warning function at run-time.
  178705. */
  178706. void PNGAPI
  178707. png_warning(png_structp png_ptr, png_const_charp warning_message)
  178708. {
  178709. int offset = 0;
  178710. if (png_ptr != NULL)
  178711. {
  178712. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178713. if (png_ptr->flags&
  178714. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  178715. #endif
  178716. {
  178717. if (*warning_message == '#')
  178718. {
  178719. for (offset=1; offset<15; offset++)
  178720. if (*(warning_message+offset) == ' ')
  178721. break;
  178722. }
  178723. }
  178724. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  178725. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  178726. }
  178727. else
  178728. png_default_warning(png_ptr, warning_message+offset);
  178729. }
  178730. #endif /* PNG_NO_WARNINGS */
  178731. /* These utilities are used internally to build an error message that relates
  178732. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  178733. * this is used to prefix the message. The message is limited in length
  178734. * to 63 bytes, the name characters are output as hex digits wrapped in []
  178735. * if the character is invalid.
  178736. */
  178737. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  178738. /*static PNG_CONST char png_digit[16] = {
  178739. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  178740. 'A', 'B', 'C', 'D', 'E', 'F'
  178741. };*/
  178742. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  178743. static void /* PRIVATE */
  178744. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  178745. error_message)
  178746. {
  178747. int iout = 0, iin = 0;
  178748. while (iin < 4)
  178749. {
  178750. int c = png_ptr->chunk_name[iin++];
  178751. if (isnonalpha(c))
  178752. {
  178753. buffer[iout++] = '[';
  178754. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  178755. buffer[iout++] = png_digit[c & 0x0f];
  178756. buffer[iout++] = ']';
  178757. }
  178758. else
  178759. {
  178760. buffer[iout++] = (png_byte)c;
  178761. }
  178762. }
  178763. if (error_message == NULL)
  178764. buffer[iout] = 0;
  178765. else
  178766. {
  178767. buffer[iout++] = ':';
  178768. buffer[iout++] = ' ';
  178769. png_strncpy(buffer+iout, error_message, 63);
  178770. buffer[iout+63] = 0;
  178771. }
  178772. }
  178773. #ifdef PNG_READ_SUPPORTED
  178774. void PNGAPI
  178775. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  178776. {
  178777. char msg[18+64];
  178778. if (png_ptr == NULL)
  178779. png_error(png_ptr, error_message);
  178780. else
  178781. {
  178782. png_format_buffer(png_ptr, msg, error_message);
  178783. png_error(png_ptr, msg);
  178784. }
  178785. }
  178786. #endif /* PNG_READ_SUPPORTED */
  178787. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  178788. #ifndef PNG_NO_WARNINGS
  178789. void PNGAPI
  178790. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  178791. {
  178792. char msg[18+64];
  178793. if (png_ptr == NULL)
  178794. png_warning(png_ptr, warning_message);
  178795. else
  178796. {
  178797. png_format_buffer(png_ptr, msg, warning_message);
  178798. png_warning(png_ptr, msg);
  178799. }
  178800. }
  178801. #endif /* PNG_NO_WARNINGS */
  178802. /* This is the default error handling function. Note that replacements for
  178803. * this function MUST NOT RETURN, or the program will likely crash. This
  178804. * function is used by default, or if the program supplies NULL for the
  178805. * error function pointer in png_set_error_fn().
  178806. */
  178807. static void /* PRIVATE */
  178808. png_default_error(png_structp png_ptr, png_const_charp error_message)
  178809. {
  178810. #ifndef PNG_NO_CONSOLE_IO
  178811. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178812. if (*error_message == '#')
  178813. {
  178814. int offset;
  178815. char error_number[16];
  178816. for (offset=0; offset<15; offset++)
  178817. {
  178818. error_number[offset] = *(error_message+offset+1);
  178819. if (*(error_message+offset) == ' ')
  178820. break;
  178821. }
  178822. if((offset > 1) && (offset < 15))
  178823. {
  178824. error_number[offset-1]='\0';
  178825. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  178826. error_message+offset);
  178827. }
  178828. else
  178829. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  178830. }
  178831. else
  178832. #endif
  178833. fprintf(stderr, "libpng error: %s\n", error_message);
  178834. #endif
  178835. #ifdef PNG_SETJMP_SUPPORTED
  178836. if (png_ptr)
  178837. {
  178838. # ifdef USE_FAR_KEYWORD
  178839. {
  178840. jmp_buf jmpbuf;
  178841. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  178842. longjmp(jmpbuf, 1);
  178843. }
  178844. # else
  178845. longjmp(png_ptr->jmpbuf, 1);
  178846. # endif
  178847. }
  178848. #else
  178849. PNG_ABORT();
  178850. #endif
  178851. #ifdef PNG_NO_CONSOLE_IO
  178852. error_message = error_message; /* make compiler happy */
  178853. #endif
  178854. }
  178855. #ifndef PNG_NO_WARNINGS
  178856. /* This function is called when there is a warning, but the library thinks
  178857. * it can continue anyway. Replacement functions don't have to do anything
  178858. * here if you don't want them to. In the default configuration, png_ptr is
  178859. * not used, but it is passed in case it may be useful.
  178860. */
  178861. static void /* PRIVATE */
  178862. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  178863. {
  178864. #ifndef PNG_NO_CONSOLE_IO
  178865. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178866. if (*warning_message == '#')
  178867. {
  178868. int offset;
  178869. char warning_number[16];
  178870. for (offset=0; offset<15; offset++)
  178871. {
  178872. warning_number[offset]=*(warning_message+offset+1);
  178873. if (*(warning_message+offset) == ' ')
  178874. break;
  178875. }
  178876. if((offset > 1) && (offset < 15))
  178877. {
  178878. warning_number[offset-1]='\0';
  178879. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  178880. warning_message+offset);
  178881. }
  178882. else
  178883. fprintf(stderr, "libpng warning: %s\n", warning_message);
  178884. }
  178885. else
  178886. # endif
  178887. fprintf(stderr, "libpng warning: %s\n", warning_message);
  178888. #else
  178889. warning_message = warning_message; /* make compiler happy */
  178890. #endif
  178891. png_ptr = png_ptr; /* make compiler happy */
  178892. }
  178893. #endif /* PNG_NO_WARNINGS */
  178894. /* This function is called when the application wants to use another method
  178895. * of handling errors and warnings. Note that the error function MUST NOT
  178896. * return to the calling routine or serious problems will occur. The return
  178897. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  178898. */
  178899. void PNGAPI
  178900. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  178901. png_error_ptr error_fn, png_error_ptr warning_fn)
  178902. {
  178903. if (png_ptr == NULL)
  178904. return;
  178905. png_ptr->error_ptr = error_ptr;
  178906. png_ptr->error_fn = error_fn;
  178907. png_ptr->warning_fn = warning_fn;
  178908. }
  178909. /* This function returns a pointer to the error_ptr associated with the user
  178910. * functions. The application should free any memory associated with this
  178911. * pointer before png_write_destroy and png_read_destroy are called.
  178912. */
  178913. png_voidp PNGAPI
  178914. png_get_error_ptr(png_structp png_ptr)
  178915. {
  178916. if (png_ptr == NULL)
  178917. return NULL;
  178918. return ((png_voidp)png_ptr->error_ptr);
  178919. }
  178920. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178921. void PNGAPI
  178922. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  178923. {
  178924. if(png_ptr != NULL)
  178925. {
  178926. png_ptr->flags &=
  178927. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  178928. }
  178929. }
  178930. #endif
  178931. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  178932. /********* End of inlined file: pngerror.c *********/
  178933. /********* Start of inlined file: pngget.c *********/
  178934. /* pngget.c - retrieval of values from info struct
  178935. *
  178936. * Last changed in libpng 1.2.15 January 5, 2007
  178937. * For conditions of distribution and use, see copyright notice in png.h
  178938. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178939. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178940. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178941. */
  178942. #define PNG_INTERNAL
  178943. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178944. png_uint_32 PNGAPI
  178945. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  178946. {
  178947. if (png_ptr != NULL && info_ptr != NULL)
  178948. return(info_ptr->valid & flag);
  178949. else
  178950. return(0);
  178951. }
  178952. png_uint_32 PNGAPI
  178953. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  178954. {
  178955. if (png_ptr != NULL && info_ptr != NULL)
  178956. return(info_ptr->rowbytes);
  178957. else
  178958. return(0);
  178959. }
  178960. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178961. png_bytepp PNGAPI
  178962. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  178963. {
  178964. if (png_ptr != NULL && info_ptr != NULL)
  178965. return(info_ptr->row_pointers);
  178966. else
  178967. return(0);
  178968. }
  178969. #endif
  178970. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178971. /* easy access to info, added in libpng-0.99 */
  178972. png_uint_32 PNGAPI
  178973. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  178974. {
  178975. if (png_ptr != NULL && info_ptr != NULL)
  178976. {
  178977. return info_ptr->width;
  178978. }
  178979. return (0);
  178980. }
  178981. png_uint_32 PNGAPI
  178982. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  178983. {
  178984. if (png_ptr != NULL && info_ptr != NULL)
  178985. {
  178986. return info_ptr->height;
  178987. }
  178988. return (0);
  178989. }
  178990. png_byte PNGAPI
  178991. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  178992. {
  178993. if (png_ptr != NULL && info_ptr != NULL)
  178994. {
  178995. return info_ptr->bit_depth;
  178996. }
  178997. return (0);
  178998. }
  178999. png_byte PNGAPI
  179000. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  179001. {
  179002. if (png_ptr != NULL && info_ptr != NULL)
  179003. {
  179004. return info_ptr->color_type;
  179005. }
  179006. return (0);
  179007. }
  179008. png_byte PNGAPI
  179009. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  179010. {
  179011. if (png_ptr != NULL && info_ptr != NULL)
  179012. {
  179013. return info_ptr->filter_type;
  179014. }
  179015. return (0);
  179016. }
  179017. png_byte PNGAPI
  179018. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  179019. {
  179020. if (png_ptr != NULL && info_ptr != NULL)
  179021. {
  179022. return info_ptr->interlace_type;
  179023. }
  179024. return (0);
  179025. }
  179026. png_byte PNGAPI
  179027. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  179028. {
  179029. if (png_ptr != NULL && info_ptr != NULL)
  179030. {
  179031. return info_ptr->compression_type;
  179032. }
  179033. return (0);
  179034. }
  179035. png_uint_32 PNGAPI
  179036. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179037. {
  179038. if (png_ptr != NULL && info_ptr != NULL)
  179039. #if defined(PNG_pHYs_SUPPORTED)
  179040. if (info_ptr->valid & PNG_INFO_pHYs)
  179041. {
  179042. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  179043. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179044. return (0);
  179045. else return (info_ptr->x_pixels_per_unit);
  179046. }
  179047. #else
  179048. return (0);
  179049. #endif
  179050. return (0);
  179051. }
  179052. png_uint_32 PNGAPI
  179053. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179054. {
  179055. if (png_ptr != NULL && info_ptr != NULL)
  179056. #if defined(PNG_pHYs_SUPPORTED)
  179057. if (info_ptr->valid & PNG_INFO_pHYs)
  179058. {
  179059. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  179060. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179061. return (0);
  179062. else return (info_ptr->y_pixels_per_unit);
  179063. }
  179064. #else
  179065. return (0);
  179066. #endif
  179067. return (0);
  179068. }
  179069. png_uint_32 PNGAPI
  179070. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179071. {
  179072. if (png_ptr != NULL && info_ptr != NULL)
  179073. #if defined(PNG_pHYs_SUPPORTED)
  179074. if (info_ptr->valid & PNG_INFO_pHYs)
  179075. {
  179076. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  179077. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  179078. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  179079. return (0);
  179080. else return (info_ptr->x_pixels_per_unit);
  179081. }
  179082. #else
  179083. return (0);
  179084. #endif
  179085. return (0);
  179086. }
  179087. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179088. float PNGAPI
  179089. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  179090. {
  179091. if (png_ptr != NULL && info_ptr != NULL)
  179092. #if defined(PNG_pHYs_SUPPORTED)
  179093. if (info_ptr->valid & PNG_INFO_pHYs)
  179094. {
  179095. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  179096. if (info_ptr->x_pixels_per_unit == 0)
  179097. return ((float)0.0);
  179098. else
  179099. return ((float)((float)info_ptr->y_pixels_per_unit
  179100. /(float)info_ptr->x_pixels_per_unit));
  179101. }
  179102. #else
  179103. return (0.0);
  179104. #endif
  179105. return ((float)0.0);
  179106. }
  179107. #endif
  179108. png_int_32 PNGAPI
  179109. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179110. {
  179111. if (png_ptr != NULL && info_ptr != NULL)
  179112. #if defined(PNG_oFFs_SUPPORTED)
  179113. if (info_ptr->valid & PNG_INFO_oFFs)
  179114. {
  179115. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179116. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179117. return (0);
  179118. else return (info_ptr->x_offset);
  179119. }
  179120. #else
  179121. return (0);
  179122. #endif
  179123. return (0);
  179124. }
  179125. png_int_32 PNGAPI
  179126. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179127. {
  179128. if (png_ptr != NULL && info_ptr != NULL)
  179129. #if defined(PNG_oFFs_SUPPORTED)
  179130. if (info_ptr->valid & PNG_INFO_oFFs)
  179131. {
  179132. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179133. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179134. return (0);
  179135. else return (info_ptr->y_offset);
  179136. }
  179137. #else
  179138. return (0);
  179139. #endif
  179140. return (0);
  179141. }
  179142. png_int_32 PNGAPI
  179143. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179144. {
  179145. if (png_ptr != NULL && info_ptr != NULL)
  179146. #if defined(PNG_oFFs_SUPPORTED)
  179147. if (info_ptr->valid & PNG_INFO_oFFs)
  179148. {
  179149. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179150. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179151. return (0);
  179152. else return (info_ptr->x_offset);
  179153. }
  179154. #else
  179155. return (0);
  179156. #endif
  179157. return (0);
  179158. }
  179159. png_int_32 PNGAPI
  179160. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179161. {
  179162. if (png_ptr != NULL && info_ptr != NULL)
  179163. #if defined(PNG_oFFs_SUPPORTED)
  179164. if (info_ptr->valid & PNG_INFO_oFFs)
  179165. {
  179166. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179167. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179168. return (0);
  179169. else return (info_ptr->y_offset);
  179170. }
  179171. #else
  179172. return (0);
  179173. #endif
  179174. return (0);
  179175. }
  179176. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179177. png_uint_32 PNGAPI
  179178. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179179. {
  179180. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  179181. *.0254 +.5));
  179182. }
  179183. png_uint_32 PNGAPI
  179184. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179185. {
  179186. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  179187. *.0254 +.5));
  179188. }
  179189. png_uint_32 PNGAPI
  179190. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179191. {
  179192. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  179193. *.0254 +.5));
  179194. }
  179195. float PNGAPI
  179196. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179197. {
  179198. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  179199. *.00003937);
  179200. }
  179201. float PNGAPI
  179202. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179203. {
  179204. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  179205. *.00003937);
  179206. }
  179207. #if defined(PNG_pHYs_SUPPORTED)
  179208. png_uint_32 PNGAPI
  179209. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  179210. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179211. {
  179212. png_uint_32 retval = 0;
  179213. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  179214. {
  179215. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179216. if (res_x != NULL)
  179217. {
  179218. *res_x = info_ptr->x_pixels_per_unit;
  179219. retval |= PNG_INFO_pHYs;
  179220. }
  179221. if (res_y != NULL)
  179222. {
  179223. *res_y = info_ptr->y_pixels_per_unit;
  179224. retval |= PNG_INFO_pHYs;
  179225. }
  179226. if (unit_type != NULL)
  179227. {
  179228. *unit_type = (int)info_ptr->phys_unit_type;
  179229. retval |= PNG_INFO_pHYs;
  179230. if(*unit_type == 1)
  179231. {
  179232. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  179233. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  179234. }
  179235. }
  179236. }
  179237. return (retval);
  179238. }
  179239. #endif /* PNG_pHYs_SUPPORTED */
  179240. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179241. /* png_get_channels really belongs in here, too, but it's been around longer */
  179242. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179243. png_byte PNGAPI
  179244. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  179245. {
  179246. if (png_ptr != NULL && info_ptr != NULL)
  179247. return(info_ptr->channels);
  179248. else
  179249. return (0);
  179250. }
  179251. png_bytep PNGAPI
  179252. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  179253. {
  179254. if (png_ptr != NULL && info_ptr != NULL)
  179255. return(info_ptr->signature);
  179256. else
  179257. return (NULL);
  179258. }
  179259. #if defined(PNG_bKGD_SUPPORTED)
  179260. png_uint_32 PNGAPI
  179261. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  179262. png_color_16p *background)
  179263. {
  179264. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  179265. && background != NULL)
  179266. {
  179267. png_debug1(1, "in %s retrieval function\n", "bKGD");
  179268. *background = &(info_ptr->background);
  179269. return (PNG_INFO_bKGD);
  179270. }
  179271. return (0);
  179272. }
  179273. #endif
  179274. #if defined(PNG_cHRM_SUPPORTED)
  179275. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179276. png_uint_32 PNGAPI
  179277. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  179278. double *white_x, double *white_y, double *red_x, double *red_y,
  179279. double *green_x, double *green_y, double *blue_x, double *blue_y)
  179280. {
  179281. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  179282. {
  179283. png_debug1(1, "in %s retrieval function\n", "cHRM");
  179284. if (white_x != NULL)
  179285. *white_x = (double)info_ptr->x_white;
  179286. if (white_y != NULL)
  179287. *white_y = (double)info_ptr->y_white;
  179288. if (red_x != NULL)
  179289. *red_x = (double)info_ptr->x_red;
  179290. if (red_y != NULL)
  179291. *red_y = (double)info_ptr->y_red;
  179292. if (green_x != NULL)
  179293. *green_x = (double)info_ptr->x_green;
  179294. if (green_y != NULL)
  179295. *green_y = (double)info_ptr->y_green;
  179296. if (blue_x != NULL)
  179297. *blue_x = (double)info_ptr->x_blue;
  179298. if (blue_y != NULL)
  179299. *blue_y = (double)info_ptr->y_blue;
  179300. return (PNG_INFO_cHRM);
  179301. }
  179302. return (0);
  179303. }
  179304. #endif
  179305. #ifdef PNG_FIXED_POINT_SUPPORTED
  179306. png_uint_32 PNGAPI
  179307. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  179308. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  179309. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  179310. png_fixed_point *blue_x, png_fixed_point *blue_y)
  179311. {
  179312. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  179313. {
  179314. png_debug1(1, "in %s retrieval function\n", "cHRM");
  179315. if (white_x != NULL)
  179316. *white_x = info_ptr->int_x_white;
  179317. if (white_y != NULL)
  179318. *white_y = info_ptr->int_y_white;
  179319. if (red_x != NULL)
  179320. *red_x = info_ptr->int_x_red;
  179321. if (red_y != NULL)
  179322. *red_y = info_ptr->int_y_red;
  179323. if (green_x != NULL)
  179324. *green_x = info_ptr->int_x_green;
  179325. if (green_y != NULL)
  179326. *green_y = info_ptr->int_y_green;
  179327. if (blue_x != NULL)
  179328. *blue_x = info_ptr->int_x_blue;
  179329. if (blue_y != NULL)
  179330. *blue_y = info_ptr->int_y_blue;
  179331. return (PNG_INFO_cHRM);
  179332. }
  179333. return (0);
  179334. }
  179335. #endif
  179336. #endif
  179337. #if defined(PNG_gAMA_SUPPORTED)
  179338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179339. png_uint_32 PNGAPI
  179340. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  179341. {
  179342. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  179343. && file_gamma != NULL)
  179344. {
  179345. png_debug1(1, "in %s retrieval function\n", "gAMA");
  179346. *file_gamma = (double)info_ptr->gamma;
  179347. return (PNG_INFO_gAMA);
  179348. }
  179349. return (0);
  179350. }
  179351. #endif
  179352. #ifdef PNG_FIXED_POINT_SUPPORTED
  179353. png_uint_32 PNGAPI
  179354. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  179355. png_fixed_point *int_file_gamma)
  179356. {
  179357. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  179358. && int_file_gamma != NULL)
  179359. {
  179360. png_debug1(1, "in %s retrieval function\n", "gAMA");
  179361. *int_file_gamma = info_ptr->int_gamma;
  179362. return (PNG_INFO_gAMA);
  179363. }
  179364. return (0);
  179365. }
  179366. #endif
  179367. #endif
  179368. #if defined(PNG_sRGB_SUPPORTED)
  179369. png_uint_32 PNGAPI
  179370. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  179371. {
  179372. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  179373. && file_srgb_intent != NULL)
  179374. {
  179375. png_debug1(1, "in %s retrieval function\n", "sRGB");
  179376. *file_srgb_intent = (int)info_ptr->srgb_intent;
  179377. return (PNG_INFO_sRGB);
  179378. }
  179379. return (0);
  179380. }
  179381. #endif
  179382. #if defined(PNG_iCCP_SUPPORTED)
  179383. png_uint_32 PNGAPI
  179384. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  179385. png_charpp name, int *compression_type,
  179386. png_charpp profile, png_uint_32 *proflen)
  179387. {
  179388. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  179389. && name != NULL && profile != NULL && proflen != NULL)
  179390. {
  179391. png_debug1(1, "in %s retrieval function\n", "iCCP");
  179392. *name = info_ptr->iccp_name;
  179393. *profile = info_ptr->iccp_profile;
  179394. /* compression_type is a dummy so the API won't have to change
  179395. if we introduce multiple compression types later. */
  179396. *proflen = (int)info_ptr->iccp_proflen;
  179397. *compression_type = (int)info_ptr->iccp_compression;
  179398. return (PNG_INFO_iCCP);
  179399. }
  179400. return (0);
  179401. }
  179402. #endif
  179403. #if defined(PNG_sPLT_SUPPORTED)
  179404. png_uint_32 PNGAPI
  179405. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  179406. png_sPLT_tpp spalettes)
  179407. {
  179408. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  179409. {
  179410. *spalettes = info_ptr->splt_palettes;
  179411. return ((png_uint_32)info_ptr->splt_palettes_num);
  179412. }
  179413. return (0);
  179414. }
  179415. #endif
  179416. #if defined(PNG_hIST_SUPPORTED)
  179417. png_uint_32 PNGAPI
  179418. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  179419. {
  179420. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  179421. && hist != NULL)
  179422. {
  179423. png_debug1(1, "in %s retrieval function\n", "hIST");
  179424. *hist = info_ptr->hist;
  179425. return (PNG_INFO_hIST);
  179426. }
  179427. return (0);
  179428. }
  179429. #endif
  179430. png_uint_32 PNGAPI
  179431. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  179432. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  179433. int *color_type, int *interlace_type, int *compression_type,
  179434. int *filter_type)
  179435. {
  179436. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  179437. bit_depth != NULL && color_type != NULL)
  179438. {
  179439. png_debug1(1, "in %s retrieval function\n", "IHDR");
  179440. *width = info_ptr->width;
  179441. *height = info_ptr->height;
  179442. *bit_depth = info_ptr->bit_depth;
  179443. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  179444. png_error(png_ptr, "Invalid bit depth");
  179445. *color_type = info_ptr->color_type;
  179446. if (info_ptr->color_type > 6)
  179447. png_error(png_ptr, "Invalid color type");
  179448. if (compression_type != NULL)
  179449. *compression_type = info_ptr->compression_type;
  179450. if (filter_type != NULL)
  179451. *filter_type = info_ptr->filter_type;
  179452. if (interlace_type != NULL)
  179453. *interlace_type = info_ptr->interlace_type;
  179454. /* check for potential overflow of rowbytes */
  179455. if (*width == 0 || *width > PNG_UINT_31_MAX)
  179456. png_error(png_ptr, "Invalid image width");
  179457. if (*height == 0 || *height > PNG_UINT_31_MAX)
  179458. png_error(png_ptr, "Invalid image height");
  179459. if (info_ptr->width > (PNG_UINT_32_MAX
  179460. >> 3) /* 8-byte RGBA pixels */
  179461. - 64 /* bigrowbuf hack */
  179462. - 1 /* filter byte */
  179463. - 7*8 /* rounding of width to multiple of 8 pixels */
  179464. - 8) /* extra max_pixel_depth pad */
  179465. {
  179466. png_warning(png_ptr,
  179467. "Width too large for libpng to process image data.");
  179468. }
  179469. return (1);
  179470. }
  179471. return (0);
  179472. }
  179473. #if defined(PNG_oFFs_SUPPORTED)
  179474. png_uint_32 PNGAPI
  179475. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  179476. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  179477. {
  179478. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  179479. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  179480. {
  179481. png_debug1(1, "in %s retrieval function\n", "oFFs");
  179482. *offset_x = info_ptr->x_offset;
  179483. *offset_y = info_ptr->y_offset;
  179484. *unit_type = (int)info_ptr->offset_unit_type;
  179485. return (PNG_INFO_oFFs);
  179486. }
  179487. return (0);
  179488. }
  179489. #endif
  179490. #if defined(PNG_pCAL_SUPPORTED)
  179491. png_uint_32 PNGAPI
  179492. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  179493. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  179494. png_charp *units, png_charpp *params)
  179495. {
  179496. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  179497. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  179498. nparams != NULL && units != NULL && params != NULL)
  179499. {
  179500. png_debug1(1, "in %s retrieval function\n", "pCAL");
  179501. *purpose = info_ptr->pcal_purpose;
  179502. *X0 = info_ptr->pcal_X0;
  179503. *X1 = info_ptr->pcal_X1;
  179504. *type = (int)info_ptr->pcal_type;
  179505. *nparams = (int)info_ptr->pcal_nparams;
  179506. *units = info_ptr->pcal_units;
  179507. *params = info_ptr->pcal_params;
  179508. return (PNG_INFO_pCAL);
  179509. }
  179510. return (0);
  179511. }
  179512. #endif
  179513. #if defined(PNG_sCAL_SUPPORTED)
  179514. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179515. png_uint_32 PNGAPI
  179516. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  179517. int *unit, double *width, double *height)
  179518. {
  179519. if (png_ptr != NULL && info_ptr != NULL &&
  179520. (info_ptr->valid & PNG_INFO_sCAL))
  179521. {
  179522. *unit = info_ptr->scal_unit;
  179523. *width = info_ptr->scal_pixel_width;
  179524. *height = info_ptr->scal_pixel_height;
  179525. return (PNG_INFO_sCAL);
  179526. }
  179527. return(0);
  179528. }
  179529. #else
  179530. #ifdef PNG_FIXED_POINT_SUPPORTED
  179531. png_uint_32 PNGAPI
  179532. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  179533. int *unit, png_charpp width, png_charpp height)
  179534. {
  179535. if (png_ptr != NULL && info_ptr != NULL &&
  179536. (info_ptr->valid & PNG_INFO_sCAL))
  179537. {
  179538. *unit = info_ptr->scal_unit;
  179539. *width = info_ptr->scal_s_width;
  179540. *height = info_ptr->scal_s_height;
  179541. return (PNG_INFO_sCAL);
  179542. }
  179543. return(0);
  179544. }
  179545. #endif
  179546. #endif
  179547. #endif
  179548. #if defined(PNG_pHYs_SUPPORTED)
  179549. png_uint_32 PNGAPI
  179550. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  179551. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179552. {
  179553. png_uint_32 retval = 0;
  179554. if (png_ptr != NULL && info_ptr != NULL &&
  179555. (info_ptr->valid & PNG_INFO_pHYs))
  179556. {
  179557. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179558. if (res_x != NULL)
  179559. {
  179560. *res_x = info_ptr->x_pixels_per_unit;
  179561. retval |= PNG_INFO_pHYs;
  179562. }
  179563. if (res_y != NULL)
  179564. {
  179565. *res_y = info_ptr->y_pixels_per_unit;
  179566. retval |= PNG_INFO_pHYs;
  179567. }
  179568. if (unit_type != NULL)
  179569. {
  179570. *unit_type = (int)info_ptr->phys_unit_type;
  179571. retval |= PNG_INFO_pHYs;
  179572. }
  179573. }
  179574. return (retval);
  179575. }
  179576. #endif
  179577. png_uint_32 PNGAPI
  179578. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  179579. int *num_palette)
  179580. {
  179581. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  179582. && palette != NULL)
  179583. {
  179584. png_debug1(1, "in %s retrieval function\n", "PLTE");
  179585. *palette = info_ptr->palette;
  179586. *num_palette = info_ptr->num_palette;
  179587. png_debug1(3, "num_palette = %d\n", *num_palette);
  179588. return (PNG_INFO_PLTE);
  179589. }
  179590. return (0);
  179591. }
  179592. #if defined(PNG_sBIT_SUPPORTED)
  179593. png_uint_32 PNGAPI
  179594. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  179595. {
  179596. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  179597. && sig_bit != NULL)
  179598. {
  179599. png_debug1(1, "in %s retrieval function\n", "sBIT");
  179600. *sig_bit = &(info_ptr->sig_bit);
  179601. return (PNG_INFO_sBIT);
  179602. }
  179603. return (0);
  179604. }
  179605. #endif
  179606. #if defined(PNG_TEXT_SUPPORTED)
  179607. png_uint_32 PNGAPI
  179608. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  179609. int *num_text)
  179610. {
  179611. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  179612. {
  179613. png_debug1(1, "in %s retrieval function\n",
  179614. (png_ptr->chunk_name[0] == '\0' ? "text"
  179615. : (png_const_charp)png_ptr->chunk_name));
  179616. if (text_ptr != NULL)
  179617. *text_ptr = info_ptr->text;
  179618. if (num_text != NULL)
  179619. *num_text = info_ptr->num_text;
  179620. return ((png_uint_32)info_ptr->num_text);
  179621. }
  179622. if (num_text != NULL)
  179623. *num_text = 0;
  179624. return(0);
  179625. }
  179626. #endif
  179627. #if defined(PNG_tIME_SUPPORTED)
  179628. png_uint_32 PNGAPI
  179629. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  179630. {
  179631. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  179632. && mod_time != NULL)
  179633. {
  179634. png_debug1(1, "in %s retrieval function\n", "tIME");
  179635. *mod_time = &(info_ptr->mod_time);
  179636. return (PNG_INFO_tIME);
  179637. }
  179638. return (0);
  179639. }
  179640. #endif
  179641. #if defined(PNG_tRNS_SUPPORTED)
  179642. png_uint_32 PNGAPI
  179643. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  179644. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  179645. {
  179646. png_uint_32 retval = 0;
  179647. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  179648. {
  179649. png_debug1(1, "in %s retrieval function\n", "tRNS");
  179650. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  179651. {
  179652. if (trans != NULL)
  179653. {
  179654. *trans = info_ptr->trans;
  179655. retval |= PNG_INFO_tRNS;
  179656. }
  179657. if (trans_values != NULL)
  179658. *trans_values = &(info_ptr->trans_values);
  179659. }
  179660. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  179661. {
  179662. if (trans_values != NULL)
  179663. {
  179664. *trans_values = &(info_ptr->trans_values);
  179665. retval |= PNG_INFO_tRNS;
  179666. }
  179667. if(trans != NULL)
  179668. *trans = NULL;
  179669. }
  179670. if(num_trans != NULL)
  179671. {
  179672. *num_trans = info_ptr->num_trans;
  179673. retval |= PNG_INFO_tRNS;
  179674. }
  179675. }
  179676. return (retval);
  179677. }
  179678. #endif
  179679. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179680. png_uint_32 PNGAPI
  179681. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  179682. png_unknown_chunkpp unknowns)
  179683. {
  179684. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  179685. {
  179686. *unknowns = info_ptr->unknown_chunks;
  179687. return ((png_uint_32)info_ptr->unknown_chunks_num);
  179688. }
  179689. return (0);
  179690. }
  179691. #endif
  179692. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179693. png_byte PNGAPI
  179694. png_get_rgb_to_gray_status (png_structp png_ptr)
  179695. {
  179696. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  179697. }
  179698. #endif
  179699. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179700. png_voidp PNGAPI
  179701. png_get_user_chunk_ptr(png_structp png_ptr)
  179702. {
  179703. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  179704. }
  179705. #endif
  179706. #ifdef PNG_WRITE_SUPPORTED
  179707. png_uint_32 PNGAPI
  179708. png_get_compression_buffer_size(png_structp png_ptr)
  179709. {
  179710. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  179711. }
  179712. #endif
  179713. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  179714. #ifndef PNG_1_0_X
  179715. /* this function was added to libpng 1.2.0 and should exist by default */
  179716. png_uint_32 PNGAPI
  179717. png_get_asm_flags (png_structp png_ptr)
  179718. {
  179719. /* obsolete, to be removed from libpng-1.4.0 */
  179720. return (png_ptr? 0L: 0L);
  179721. }
  179722. /* this function was added to libpng 1.2.0 and should exist by default */
  179723. png_uint_32 PNGAPI
  179724. png_get_asm_flagmask (int flag_select)
  179725. {
  179726. /* obsolete, to be removed from libpng-1.4.0 */
  179727. flag_select=flag_select;
  179728. return 0L;
  179729. }
  179730. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  179731. /* this function was added to libpng 1.2.0 */
  179732. png_uint_32 PNGAPI
  179733. png_get_mmx_flagmask (int flag_select, int *compilerID)
  179734. {
  179735. /* obsolete, to be removed from libpng-1.4.0 */
  179736. flag_select=flag_select;
  179737. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  179738. return 0L;
  179739. }
  179740. /* this function was added to libpng 1.2.0 */
  179741. png_byte PNGAPI
  179742. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  179743. {
  179744. /* obsolete, to be removed from libpng-1.4.0 */
  179745. return (png_ptr? 0: 0);
  179746. }
  179747. /* this function was added to libpng 1.2.0 */
  179748. png_uint_32 PNGAPI
  179749. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  179750. {
  179751. /* obsolete, to be removed from libpng-1.4.0 */
  179752. return (png_ptr? 0L: 0L);
  179753. }
  179754. #endif /* ?PNG_1_0_X */
  179755. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  179756. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179757. /* these functions were added to libpng 1.2.6 */
  179758. png_uint_32 PNGAPI
  179759. png_get_user_width_max (png_structp png_ptr)
  179760. {
  179761. return (png_ptr? png_ptr->user_width_max : 0);
  179762. }
  179763. png_uint_32 PNGAPI
  179764. png_get_user_height_max (png_structp png_ptr)
  179765. {
  179766. return (png_ptr? png_ptr->user_height_max : 0);
  179767. }
  179768. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  179769. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  179770. /********* End of inlined file: pngget.c *********/
  179771. /********* Start of inlined file: pngmem.c *********/
  179772. /* pngmem.c - stub functions for memory allocation
  179773. *
  179774. * Last changed in libpng 1.2.13 November 13, 2006
  179775. * For conditions of distribution and use, see copyright notice in png.h
  179776. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  179777. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179778. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179779. *
  179780. * This file provides a location for all memory allocation. Users who
  179781. * need special memory handling are expected to supply replacement
  179782. * functions for png_malloc() and png_free(), and to use
  179783. * png_create_read_struct_2() and png_create_write_struct_2() to
  179784. * identify the replacement functions.
  179785. */
  179786. #define PNG_INTERNAL
  179787. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179788. /* Borland DOS special memory handler */
  179789. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179790. /* if you change this, be sure to change the one in png.h also */
  179791. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  179792. by a single call to calloc() if this is thought to improve performance. */
  179793. png_voidp /* PRIVATE */
  179794. png_create_struct(int type)
  179795. {
  179796. #ifdef PNG_USER_MEM_SUPPORTED
  179797. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  179798. }
  179799. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  179800. png_voidp /* PRIVATE */
  179801. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  179802. {
  179803. #endif /* PNG_USER_MEM_SUPPORTED */
  179804. png_size_t size;
  179805. png_voidp struct_ptr;
  179806. if (type == PNG_STRUCT_INFO)
  179807. size = png_sizeof(png_info);
  179808. else if (type == PNG_STRUCT_PNG)
  179809. size = png_sizeof(png_struct);
  179810. else
  179811. return (png_get_copyright(NULL));
  179812. #ifdef PNG_USER_MEM_SUPPORTED
  179813. if(malloc_fn != NULL)
  179814. {
  179815. png_struct dummy_struct;
  179816. png_structp png_ptr = &dummy_struct;
  179817. png_ptr->mem_ptr=mem_ptr;
  179818. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  179819. }
  179820. else
  179821. #endif /* PNG_USER_MEM_SUPPORTED */
  179822. struct_ptr = (png_voidp)farmalloc(size);
  179823. if (struct_ptr != NULL)
  179824. png_memset(struct_ptr, 0, size);
  179825. return (struct_ptr);
  179826. }
  179827. /* Free memory allocated by a png_create_struct() call */
  179828. void /* PRIVATE */
  179829. png_destroy_struct(png_voidp struct_ptr)
  179830. {
  179831. #ifdef PNG_USER_MEM_SUPPORTED
  179832. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  179833. }
  179834. /* Free memory allocated by a png_create_struct() call */
  179835. void /* PRIVATE */
  179836. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  179837. png_voidp mem_ptr)
  179838. {
  179839. #endif
  179840. if (struct_ptr != NULL)
  179841. {
  179842. #ifdef PNG_USER_MEM_SUPPORTED
  179843. if(free_fn != NULL)
  179844. {
  179845. png_struct dummy_struct;
  179846. png_structp png_ptr = &dummy_struct;
  179847. png_ptr->mem_ptr=mem_ptr;
  179848. (*(free_fn))(png_ptr, struct_ptr);
  179849. return;
  179850. }
  179851. #endif /* PNG_USER_MEM_SUPPORTED */
  179852. farfree (struct_ptr);
  179853. }
  179854. }
  179855. /* Allocate memory. For reasonable files, size should never exceed
  179856. * 64K. However, zlib may allocate more then 64K if you don't tell
  179857. * it not to. See zconf.h and png.h for more information. zlib does
  179858. * need to allocate exactly 64K, so whatever you call here must
  179859. * have the ability to do that.
  179860. *
  179861. * Borland seems to have a problem in DOS mode for exactly 64K.
  179862. * It gives you a segment with an offset of 8 (perhaps to store its
  179863. * memory stuff). zlib doesn't like this at all, so we have to
  179864. * detect and deal with it. This code should not be needed in
  179865. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  179866. * been updated by Alexander Lehmann for version 0.89 to waste less
  179867. * memory.
  179868. *
  179869. * Note that we can't use png_size_t for the "size" declaration,
  179870. * since on some systems a png_size_t is a 16-bit quantity, and as a
  179871. * result, we would be truncating potentially larger memory requests
  179872. * (which should cause a fatal error) and introducing major problems.
  179873. */
  179874. png_voidp PNGAPI
  179875. png_malloc(png_structp png_ptr, png_uint_32 size)
  179876. {
  179877. png_voidp ret;
  179878. if (png_ptr == NULL || size == 0)
  179879. return (NULL);
  179880. #ifdef PNG_USER_MEM_SUPPORTED
  179881. if(png_ptr->malloc_fn != NULL)
  179882. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  179883. else
  179884. ret = (png_malloc_default(png_ptr, size));
  179885. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179886. png_error(png_ptr, "Out of memory!");
  179887. return (ret);
  179888. }
  179889. png_voidp PNGAPI
  179890. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  179891. {
  179892. png_voidp ret;
  179893. #endif /* PNG_USER_MEM_SUPPORTED */
  179894. if (png_ptr == NULL || size == 0)
  179895. return (NULL);
  179896. #ifdef PNG_MAX_MALLOC_64K
  179897. if (size > (png_uint_32)65536L)
  179898. {
  179899. png_warning(png_ptr, "Cannot Allocate > 64K");
  179900. ret = NULL;
  179901. }
  179902. else
  179903. #endif
  179904. if (size != (size_t)size)
  179905. ret = NULL;
  179906. else if (size == (png_uint_32)65536L)
  179907. {
  179908. if (png_ptr->offset_table == NULL)
  179909. {
  179910. /* try to see if we need to do any of this fancy stuff */
  179911. ret = farmalloc(size);
  179912. if (ret == NULL || ((png_size_t)ret & 0xffff))
  179913. {
  179914. int num_blocks;
  179915. png_uint_32 total_size;
  179916. png_bytep table;
  179917. int i;
  179918. png_byte huge * hptr;
  179919. if (ret != NULL)
  179920. {
  179921. farfree(ret);
  179922. ret = NULL;
  179923. }
  179924. if(png_ptr->zlib_window_bits > 14)
  179925. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  179926. else
  179927. num_blocks = 1;
  179928. if (png_ptr->zlib_mem_level >= 7)
  179929. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  179930. else
  179931. num_blocks++;
  179932. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  179933. table = farmalloc(total_size);
  179934. if (table == NULL)
  179935. {
  179936. #ifndef PNG_USER_MEM_SUPPORTED
  179937. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179938. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  179939. else
  179940. png_warning(png_ptr, "Out Of Memory.");
  179941. #endif
  179942. return (NULL);
  179943. }
  179944. if ((png_size_t)table & 0xfff0)
  179945. {
  179946. #ifndef PNG_USER_MEM_SUPPORTED
  179947. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179948. png_error(png_ptr,
  179949. "Farmalloc didn't return normalized pointer");
  179950. else
  179951. png_warning(png_ptr,
  179952. "Farmalloc didn't return normalized pointer");
  179953. #endif
  179954. return (NULL);
  179955. }
  179956. png_ptr->offset_table = table;
  179957. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  179958. png_sizeof (png_bytep));
  179959. if (png_ptr->offset_table_ptr == NULL)
  179960. {
  179961. #ifndef PNG_USER_MEM_SUPPORTED
  179962. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179963. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  179964. else
  179965. png_warning(png_ptr, "Out Of memory.");
  179966. #endif
  179967. return (NULL);
  179968. }
  179969. hptr = (png_byte huge *)table;
  179970. if ((png_size_t)hptr & 0xf)
  179971. {
  179972. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  179973. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  179974. }
  179975. for (i = 0; i < num_blocks; i++)
  179976. {
  179977. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  179978. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  179979. }
  179980. png_ptr->offset_table_number = num_blocks;
  179981. png_ptr->offset_table_count = 0;
  179982. png_ptr->offset_table_count_free = 0;
  179983. }
  179984. }
  179985. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  179986. {
  179987. #ifndef PNG_USER_MEM_SUPPORTED
  179988. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179989. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  179990. else
  179991. png_warning(png_ptr, "Out of Memory.");
  179992. #endif
  179993. return (NULL);
  179994. }
  179995. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  179996. }
  179997. else
  179998. ret = farmalloc(size);
  179999. #ifndef PNG_USER_MEM_SUPPORTED
  180000. if (ret == NULL)
  180001. {
  180002. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180003. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180004. else
  180005. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180006. }
  180007. #endif
  180008. return (ret);
  180009. }
  180010. /* free a pointer allocated by png_malloc(). In the default
  180011. configuration, png_ptr is not used, but is passed in case it
  180012. is needed. If ptr is NULL, return without taking any action. */
  180013. void PNGAPI
  180014. png_free(png_structp png_ptr, png_voidp ptr)
  180015. {
  180016. if (png_ptr == NULL || ptr == NULL)
  180017. return;
  180018. #ifdef PNG_USER_MEM_SUPPORTED
  180019. if (png_ptr->free_fn != NULL)
  180020. {
  180021. (*(png_ptr->free_fn))(png_ptr, ptr);
  180022. return;
  180023. }
  180024. else png_free_default(png_ptr, ptr);
  180025. }
  180026. void PNGAPI
  180027. png_free_default(png_structp png_ptr, png_voidp ptr)
  180028. {
  180029. #endif /* PNG_USER_MEM_SUPPORTED */
  180030. if(png_ptr == NULL) return;
  180031. if (png_ptr->offset_table != NULL)
  180032. {
  180033. int i;
  180034. for (i = 0; i < png_ptr->offset_table_count; i++)
  180035. {
  180036. if (ptr == png_ptr->offset_table_ptr[i])
  180037. {
  180038. ptr = NULL;
  180039. png_ptr->offset_table_count_free++;
  180040. break;
  180041. }
  180042. }
  180043. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  180044. {
  180045. farfree(png_ptr->offset_table);
  180046. farfree(png_ptr->offset_table_ptr);
  180047. png_ptr->offset_table = NULL;
  180048. png_ptr->offset_table_ptr = NULL;
  180049. }
  180050. }
  180051. if (ptr != NULL)
  180052. {
  180053. farfree(ptr);
  180054. }
  180055. }
  180056. #else /* Not the Borland DOS special memory handler */
  180057. /* Allocate memory for a png_struct or a png_info. The malloc and
  180058. memset can be replaced by a single call to calloc() if this is thought
  180059. to improve performance noticably. */
  180060. png_voidp /* PRIVATE */
  180061. png_create_struct(int type)
  180062. {
  180063. #ifdef PNG_USER_MEM_SUPPORTED
  180064. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180065. }
  180066. /* Allocate memory for a png_struct or a png_info. The malloc and
  180067. memset can be replaced by a single call to calloc() if this is thought
  180068. to improve performance noticably. */
  180069. png_voidp /* PRIVATE */
  180070. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180071. {
  180072. #endif /* PNG_USER_MEM_SUPPORTED */
  180073. png_size_t size;
  180074. png_voidp struct_ptr;
  180075. if (type == PNG_STRUCT_INFO)
  180076. size = png_sizeof(png_info);
  180077. else if (type == PNG_STRUCT_PNG)
  180078. size = png_sizeof(png_struct);
  180079. else
  180080. return (NULL);
  180081. #ifdef PNG_USER_MEM_SUPPORTED
  180082. if(malloc_fn != NULL)
  180083. {
  180084. png_struct dummy_struct;
  180085. png_structp png_ptr = &dummy_struct;
  180086. png_ptr->mem_ptr=mem_ptr;
  180087. struct_ptr = (*(malloc_fn))(png_ptr, size);
  180088. if (struct_ptr != NULL)
  180089. png_memset(struct_ptr, 0, size);
  180090. return (struct_ptr);
  180091. }
  180092. #endif /* PNG_USER_MEM_SUPPORTED */
  180093. #if defined(__TURBOC__) && !defined(__FLAT__)
  180094. struct_ptr = (png_voidp)farmalloc(size);
  180095. #else
  180096. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180097. struct_ptr = (png_voidp)halloc(size,1);
  180098. # else
  180099. struct_ptr = (png_voidp)malloc(size);
  180100. # endif
  180101. #endif
  180102. if (struct_ptr != NULL)
  180103. png_memset(struct_ptr, 0, size);
  180104. return (struct_ptr);
  180105. }
  180106. /* Free memory allocated by a png_create_struct() call */
  180107. void /* PRIVATE */
  180108. png_destroy_struct(png_voidp struct_ptr)
  180109. {
  180110. #ifdef PNG_USER_MEM_SUPPORTED
  180111. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180112. }
  180113. /* Free memory allocated by a png_create_struct() call */
  180114. void /* PRIVATE */
  180115. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180116. png_voidp mem_ptr)
  180117. {
  180118. #endif /* PNG_USER_MEM_SUPPORTED */
  180119. if (struct_ptr != NULL)
  180120. {
  180121. #ifdef PNG_USER_MEM_SUPPORTED
  180122. if(free_fn != NULL)
  180123. {
  180124. png_struct dummy_struct;
  180125. png_structp png_ptr = &dummy_struct;
  180126. png_ptr->mem_ptr=mem_ptr;
  180127. (*(free_fn))(png_ptr, struct_ptr);
  180128. return;
  180129. }
  180130. #endif /* PNG_USER_MEM_SUPPORTED */
  180131. #if defined(__TURBOC__) && !defined(__FLAT__)
  180132. farfree(struct_ptr);
  180133. #else
  180134. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180135. hfree(struct_ptr);
  180136. # else
  180137. free(struct_ptr);
  180138. # endif
  180139. #endif
  180140. }
  180141. }
  180142. /* Allocate memory. For reasonable files, size should never exceed
  180143. 64K. However, zlib may allocate more then 64K if you don't tell
  180144. it not to. See zconf.h and png.h for more information. zlib does
  180145. need to allocate exactly 64K, so whatever you call here must
  180146. have the ability to do that. */
  180147. png_voidp PNGAPI
  180148. png_malloc(png_structp png_ptr, png_uint_32 size)
  180149. {
  180150. png_voidp ret;
  180151. #ifdef PNG_USER_MEM_SUPPORTED
  180152. if (png_ptr == NULL || size == 0)
  180153. return (NULL);
  180154. if(png_ptr->malloc_fn != NULL)
  180155. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180156. else
  180157. ret = (png_malloc_default(png_ptr, size));
  180158. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180159. png_error(png_ptr, "Out of Memory!");
  180160. return (ret);
  180161. }
  180162. png_voidp PNGAPI
  180163. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180164. {
  180165. png_voidp ret;
  180166. #endif /* PNG_USER_MEM_SUPPORTED */
  180167. if (png_ptr == NULL || size == 0)
  180168. return (NULL);
  180169. #ifdef PNG_MAX_MALLOC_64K
  180170. if (size > (png_uint_32)65536L)
  180171. {
  180172. #ifndef PNG_USER_MEM_SUPPORTED
  180173. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180174. png_error(png_ptr, "Cannot Allocate > 64K");
  180175. else
  180176. #endif
  180177. return NULL;
  180178. }
  180179. #endif
  180180. /* Check for overflow */
  180181. #if defined(__TURBOC__) && !defined(__FLAT__)
  180182. if (size != (unsigned long)size)
  180183. ret = NULL;
  180184. else
  180185. ret = farmalloc(size);
  180186. #else
  180187. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180188. if (size != (unsigned long)size)
  180189. ret = NULL;
  180190. else
  180191. ret = halloc(size, 1);
  180192. # else
  180193. if (size != (size_t)size)
  180194. ret = NULL;
  180195. else
  180196. ret = malloc((size_t)size);
  180197. # endif
  180198. #endif
  180199. #ifndef PNG_USER_MEM_SUPPORTED
  180200. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180201. png_error(png_ptr, "Out of Memory");
  180202. #endif
  180203. return (ret);
  180204. }
  180205. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  180206. without taking any action. */
  180207. void PNGAPI
  180208. png_free(png_structp png_ptr, png_voidp ptr)
  180209. {
  180210. if (png_ptr == NULL || ptr == NULL)
  180211. return;
  180212. #ifdef PNG_USER_MEM_SUPPORTED
  180213. if (png_ptr->free_fn != NULL)
  180214. {
  180215. (*(png_ptr->free_fn))(png_ptr, ptr);
  180216. return;
  180217. }
  180218. else png_free_default(png_ptr, ptr);
  180219. }
  180220. void PNGAPI
  180221. png_free_default(png_structp png_ptr, png_voidp ptr)
  180222. {
  180223. if (png_ptr == NULL || ptr == NULL)
  180224. return;
  180225. #endif /* PNG_USER_MEM_SUPPORTED */
  180226. #if defined(__TURBOC__) && !defined(__FLAT__)
  180227. farfree(ptr);
  180228. #else
  180229. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180230. hfree(ptr);
  180231. # else
  180232. free(ptr);
  180233. # endif
  180234. #endif
  180235. }
  180236. #endif /* Not Borland DOS special memory handler */
  180237. #if defined(PNG_1_0_X)
  180238. # define png_malloc_warn png_malloc
  180239. #else
  180240. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  180241. * function will set up png_malloc() to issue a png_warning and return NULL
  180242. * instead of issuing a png_error, if it fails to allocate the requested
  180243. * memory.
  180244. */
  180245. png_voidp PNGAPI
  180246. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  180247. {
  180248. png_voidp ptr;
  180249. png_uint_32 save_flags;
  180250. if(png_ptr == NULL) return (NULL);
  180251. save_flags=png_ptr->flags;
  180252. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180253. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  180254. png_ptr->flags=save_flags;
  180255. return(ptr);
  180256. }
  180257. #endif
  180258. png_voidp PNGAPI
  180259. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  180260. png_uint_32 length)
  180261. {
  180262. png_size_t size;
  180263. size = (png_size_t)length;
  180264. if ((png_uint_32)size != length)
  180265. png_error(png_ptr,"Overflow in png_memcpy_check.");
  180266. return(png_memcpy (s1, s2, size));
  180267. }
  180268. png_voidp PNGAPI
  180269. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  180270. png_uint_32 length)
  180271. {
  180272. png_size_t size;
  180273. size = (png_size_t)length;
  180274. if ((png_uint_32)size != length)
  180275. png_error(png_ptr,"Overflow in png_memset_check.");
  180276. return (png_memset (s1, value, size));
  180277. }
  180278. #ifdef PNG_USER_MEM_SUPPORTED
  180279. /* This function is called when the application wants to use another method
  180280. * of allocating and freeing memory.
  180281. */
  180282. void PNGAPI
  180283. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  180284. malloc_fn, png_free_ptr free_fn)
  180285. {
  180286. if(png_ptr != NULL) {
  180287. png_ptr->mem_ptr = mem_ptr;
  180288. png_ptr->malloc_fn = malloc_fn;
  180289. png_ptr->free_fn = free_fn;
  180290. }
  180291. }
  180292. /* This function returns a pointer to the mem_ptr associated with the user
  180293. * functions. The application should free any memory associated with this
  180294. * pointer before png_write_destroy and png_read_destroy are called.
  180295. */
  180296. png_voidp PNGAPI
  180297. png_get_mem_ptr(png_structp png_ptr)
  180298. {
  180299. if(png_ptr == NULL) return (NULL);
  180300. return ((png_voidp)png_ptr->mem_ptr);
  180301. }
  180302. #endif /* PNG_USER_MEM_SUPPORTED */
  180303. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180304. /********* End of inlined file: pngmem.c *********/
  180305. /********* Start of inlined file: pngread.c *********/
  180306. /* pngread.c - read a PNG file
  180307. *
  180308. * Last changed in libpng 1.2.20 September 7, 2007
  180309. * For conditions of distribution and use, see copyright notice in png.h
  180310. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180311. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180312. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180313. *
  180314. * This file contains routines that an application calls directly to
  180315. * read a PNG file or stream.
  180316. */
  180317. #define PNG_INTERNAL
  180318. #if defined(PNG_READ_SUPPORTED)
  180319. /* Create a PNG structure for reading, and allocate any memory needed. */
  180320. png_structp PNGAPI
  180321. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  180322. png_error_ptr error_fn, png_error_ptr warn_fn)
  180323. {
  180324. #ifdef PNG_USER_MEM_SUPPORTED
  180325. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  180326. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  180327. }
  180328. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  180329. png_structp PNGAPI
  180330. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  180331. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  180332. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  180333. {
  180334. #endif /* PNG_USER_MEM_SUPPORTED */
  180335. png_structp png_ptr;
  180336. #ifdef PNG_SETJMP_SUPPORTED
  180337. #ifdef USE_FAR_KEYWORD
  180338. jmp_buf jmpbuf;
  180339. #endif
  180340. #endif
  180341. int i;
  180342. png_debug(1, "in png_create_read_struct\n");
  180343. #ifdef PNG_USER_MEM_SUPPORTED
  180344. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  180345. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  180346. #else
  180347. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  180348. #endif
  180349. if (png_ptr == NULL)
  180350. return (NULL);
  180351. /* added at libpng-1.2.6 */
  180352. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180353. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  180354. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  180355. #endif
  180356. #ifdef PNG_SETJMP_SUPPORTED
  180357. #ifdef USE_FAR_KEYWORD
  180358. if (setjmp(jmpbuf))
  180359. #else
  180360. if (setjmp(png_ptr->jmpbuf))
  180361. #endif
  180362. {
  180363. png_free(png_ptr, png_ptr->zbuf);
  180364. png_ptr->zbuf=NULL;
  180365. #ifdef PNG_USER_MEM_SUPPORTED
  180366. png_destroy_struct_2((png_voidp)png_ptr,
  180367. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  180368. #else
  180369. png_destroy_struct((png_voidp)png_ptr);
  180370. #endif
  180371. return (NULL);
  180372. }
  180373. #ifdef USE_FAR_KEYWORD
  180374. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  180375. #endif
  180376. #endif
  180377. #ifdef PNG_USER_MEM_SUPPORTED
  180378. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  180379. #endif
  180380. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  180381. i=0;
  180382. do
  180383. {
  180384. if(user_png_ver[i] != png_libpng_ver[i])
  180385. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  180386. } while (png_libpng_ver[i++]);
  180387. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  180388. {
  180389. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  180390. * we must recompile any applications that use any older library version.
  180391. * For versions after libpng 1.0, we will be compatible, so we need
  180392. * only check the first digit.
  180393. */
  180394. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  180395. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  180396. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  180397. {
  180398. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  180399. char msg[80];
  180400. if (user_png_ver)
  180401. {
  180402. png_snprintf(msg, 80,
  180403. "Application was compiled with png.h from libpng-%.20s",
  180404. user_png_ver);
  180405. png_warning(png_ptr, msg);
  180406. }
  180407. png_snprintf(msg, 80,
  180408. "Application is running with png.c from libpng-%.20s",
  180409. png_libpng_ver);
  180410. png_warning(png_ptr, msg);
  180411. #endif
  180412. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180413. png_ptr->flags=0;
  180414. #endif
  180415. png_error(png_ptr,
  180416. "Incompatible libpng version in application and library");
  180417. }
  180418. }
  180419. /* initialize zbuf - compression buffer */
  180420. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  180421. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  180422. (png_uint_32)png_ptr->zbuf_size);
  180423. png_ptr->zstream.zalloc = png_zalloc;
  180424. png_ptr->zstream.zfree = png_zfree;
  180425. png_ptr->zstream.opaque = (voidpf)png_ptr;
  180426. switch (inflateInit(&png_ptr->zstream))
  180427. {
  180428. case Z_OK: /* Do nothing */ break;
  180429. case Z_MEM_ERROR:
  180430. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  180431. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  180432. default: png_error(png_ptr, "Unknown zlib error");
  180433. }
  180434. png_ptr->zstream.next_out = png_ptr->zbuf;
  180435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  180436. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  180437. #ifdef PNG_SETJMP_SUPPORTED
  180438. /* Applications that neglect to set up their own setjmp() and then encounter
  180439. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  180440. abort instead of returning. */
  180441. #ifdef USE_FAR_KEYWORD
  180442. if (setjmp(jmpbuf))
  180443. PNG_ABORT();
  180444. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  180445. #else
  180446. if (setjmp(png_ptr->jmpbuf))
  180447. PNG_ABORT();
  180448. #endif
  180449. #endif
  180450. return (png_ptr);
  180451. }
  180452. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180453. /* Initialize PNG structure for reading, and allocate any memory needed.
  180454. This interface is deprecated in favour of the png_create_read_struct(),
  180455. and it will disappear as of libpng-1.3.0. */
  180456. #undef png_read_init
  180457. void PNGAPI
  180458. png_read_init(png_structp png_ptr)
  180459. {
  180460. /* We only come here via pre-1.0.7-compiled applications */
  180461. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  180462. }
  180463. void PNGAPI
  180464. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  180465. png_size_t png_struct_size, png_size_t png_info_size)
  180466. {
  180467. /* We only come here via pre-1.0.12-compiled applications */
  180468. if(png_ptr == NULL) return;
  180469. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  180470. if(png_sizeof(png_struct) > png_struct_size ||
  180471. png_sizeof(png_info) > png_info_size)
  180472. {
  180473. char msg[80];
  180474. png_ptr->warning_fn=NULL;
  180475. if (user_png_ver)
  180476. {
  180477. png_snprintf(msg, 80,
  180478. "Application was compiled with png.h from libpng-%.20s",
  180479. user_png_ver);
  180480. png_warning(png_ptr, msg);
  180481. }
  180482. png_snprintf(msg, 80,
  180483. "Application is running with png.c from libpng-%.20s",
  180484. png_libpng_ver);
  180485. png_warning(png_ptr, msg);
  180486. }
  180487. #endif
  180488. if(png_sizeof(png_struct) > png_struct_size)
  180489. {
  180490. png_ptr->error_fn=NULL;
  180491. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180492. png_ptr->flags=0;
  180493. #endif
  180494. png_error(png_ptr,
  180495. "The png struct allocated by the application for reading is too small.");
  180496. }
  180497. if(png_sizeof(png_info) > png_info_size)
  180498. {
  180499. png_ptr->error_fn=NULL;
  180500. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180501. png_ptr->flags=0;
  180502. #endif
  180503. png_error(png_ptr,
  180504. "The info struct allocated by application for reading is too small.");
  180505. }
  180506. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  180507. }
  180508. #endif /* PNG_1_0_X || PNG_1_2_X */
  180509. void PNGAPI
  180510. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  180511. png_size_t png_struct_size)
  180512. {
  180513. #ifdef PNG_SETJMP_SUPPORTED
  180514. jmp_buf tmp_jmp; /* to save current jump buffer */
  180515. #endif
  180516. int i=0;
  180517. png_structp png_ptr=*ptr_ptr;
  180518. if(png_ptr == NULL) return;
  180519. do
  180520. {
  180521. if(user_png_ver[i] != png_libpng_ver[i])
  180522. {
  180523. #ifdef PNG_LEGACY_SUPPORTED
  180524. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  180525. #else
  180526. png_ptr->warning_fn=NULL;
  180527. png_warning(png_ptr,
  180528. "Application uses deprecated png_read_init() and should be recompiled.");
  180529. break;
  180530. #endif
  180531. }
  180532. } while (png_libpng_ver[i++]);
  180533. png_debug(1, "in png_read_init_3\n");
  180534. #ifdef PNG_SETJMP_SUPPORTED
  180535. /* save jump buffer and error functions */
  180536. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  180537. #endif
  180538. if(png_sizeof(png_struct) > png_struct_size)
  180539. {
  180540. png_destroy_struct(png_ptr);
  180541. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  180542. png_ptr = *ptr_ptr;
  180543. }
  180544. /* reset all variables to 0 */
  180545. png_memset(png_ptr, 0, png_sizeof (png_struct));
  180546. #ifdef PNG_SETJMP_SUPPORTED
  180547. /* restore jump buffer */
  180548. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  180549. #endif
  180550. /* added at libpng-1.2.6 */
  180551. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180552. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  180553. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  180554. #endif
  180555. /* initialize zbuf - compression buffer */
  180556. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  180557. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  180558. (png_uint_32)png_ptr->zbuf_size);
  180559. png_ptr->zstream.zalloc = png_zalloc;
  180560. png_ptr->zstream.zfree = png_zfree;
  180561. png_ptr->zstream.opaque = (voidpf)png_ptr;
  180562. switch (inflateInit(&png_ptr->zstream))
  180563. {
  180564. case Z_OK: /* Do nothing */ break;
  180565. case Z_MEM_ERROR:
  180566. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  180567. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  180568. default: png_error(png_ptr, "Unknown zlib error");
  180569. }
  180570. png_ptr->zstream.next_out = png_ptr->zbuf;
  180571. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  180572. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  180573. }
  180574. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180575. /* Read the information before the actual image data. This has been
  180576. * changed in v0.90 to allow reading a file that already has the magic
  180577. * bytes read from the stream. You can tell libpng how many bytes have
  180578. * been read from the beginning of the stream (up to the maximum of 8)
  180579. * via png_set_sig_bytes(), and we will only check the remaining bytes
  180580. * here. The application can then have access to the signature bytes we
  180581. * read if it is determined that this isn't a valid PNG file.
  180582. */
  180583. void PNGAPI
  180584. png_read_info(png_structp png_ptr, png_infop info_ptr)
  180585. {
  180586. if(png_ptr == NULL) return;
  180587. png_debug(1, "in png_read_info\n");
  180588. /* If we haven't checked all of the PNG signature bytes, do so now. */
  180589. if (png_ptr->sig_bytes < 8)
  180590. {
  180591. png_size_t num_checked = png_ptr->sig_bytes,
  180592. num_to_check = 8 - num_checked;
  180593. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  180594. png_ptr->sig_bytes = 8;
  180595. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  180596. {
  180597. if (num_checked < 4 &&
  180598. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  180599. png_error(png_ptr, "Not a PNG file");
  180600. else
  180601. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  180602. }
  180603. if (num_checked < 3)
  180604. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  180605. }
  180606. for(;;)
  180607. {
  180608. #ifdef PNG_USE_LOCAL_ARRAYS
  180609. PNG_CONST PNG_IHDR;
  180610. PNG_CONST PNG_IDAT;
  180611. PNG_CONST PNG_IEND;
  180612. PNG_CONST PNG_PLTE;
  180613. #if defined(PNG_READ_bKGD_SUPPORTED)
  180614. PNG_CONST PNG_bKGD;
  180615. #endif
  180616. #if defined(PNG_READ_cHRM_SUPPORTED)
  180617. PNG_CONST PNG_cHRM;
  180618. #endif
  180619. #if defined(PNG_READ_gAMA_SUPPORTED)
  180620. PNG_CONST PNG_gAMA;
  180621. #endif
  180622. #if defined(PNG_READ_hIST_SUPPORTED)
  180623. PNG_CONST PNG_hIST;
  180624. #endif
  180625. #if defined(PNG_READ_iCCP_SUPPORTED)
  180626. PNG_CONST PNG_iCCP;
  180627. #endif
  180628. #if defined(PNG_READ_iTXt_SUPPORTED)
  180629. PNG_CONST PNG_iTXt;
  180630. #endif
  180631. #if defined(PNG_READ_oFFs_SUPPORTED)
  180632. PNG_CONST PNG_oFFs;
  180633. #endif
  180634. #if defined(PNG_READ_pCAL_SUPPORTED)
  180635. PNG_CONST PNG_pCAL;
  180636. #endif
  180637. #if defined(PNG_READ_pHYs_SUPPORTED)
  180638. PNG_CONST PNG_pHYs;
  180639. #endif
  180640. #if defined(PNG_READ_sBIT_SUPPORTED)
  180641. PNG_CONST PNG_sBIT;
  180642. #endif
  180643. #if defined(PNG_READ_sCAL_SUPPORTED)
  180644. PNG_CONST PNG_sCAL;
  180645. #endif
  180646. #if defined(PNG_READ_sPLT_SUPPORTED)
  180647. PNG_CONST PNG_sPLT;
  180648. #endif
  180649. #if defined(PNG_READ_sRGB_SUPPORTED)
  180650. PNG_CONST PNG_sRGB;
  180651. #endif
  180652. #if defined(PNG_READ_tEXt_SUPPORTED)
  180653. PNG_CONST PNG_tEXt;
  180654. #endif
  180655. #if defined(PNG_READ_tIME_SUPPORTED)
  180656. PNG_CONST PNG_tIME;
  180657. #endif
  180658. #if defined(PNG_READ_tRNS_SUPPORTED)
  180659. PNG_CONST PNG_tRNS;
  180660. #endif
  180661. #if defined(PNG_READ_zTXt_SUPPORTED)
  180662. PNG_CONST PNG_zTXt;
  180663. #endif
  180664. #endif /* PNG_USE_LOCAL_ARRAYS */
  180665. png_byte chunk_length[4];
  180666. png_uint_32 length;
  180667. png_read_data(png_ptr, chunk_length, 4);
  180668. length = png_get_uint_31(png_ptr,chunk_length);
  180669. png_reset_crc(png_ptr);
  180670. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  180671. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  180672. length);
  180673. /* This should be a binary subdivision search or a hash for
  180674. * matching the chunk name rather than a linear search.
  180675. */
  180676. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180677. if(png_ptr->mode & PNG_AFTER_IDAT)
  180678. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  180679. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  180680. png_handle_IHDR(png_ptr, info_ptr, length);
  180681. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  180682. png_handle_IEND(png_ptr, info_ptr, length);
  180683. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180684. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  180685. {
  180686. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180687. png_ptr->mode |= PNG_HAVE_IDAT;
  180688. png_handle_unknown(png_ptr, info_ptr, length);
  180689. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  180690. png_ptr->mode |= PNG_HAVE_PLTE;
  180691. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180692. {
  180693. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  180694. png_error(png_ptr, "Missing IHDR before IDAT");
  180695. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  180696. !(png_ptr->mode & PNG_HAVE_PLTE))
  180697. png_error(png_ptr, "Missing PLTE before IDAT");
  180698. break;
  180699. }
  180700. }
  180701. #endif
  180702. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  180703. png_handle_PLTE(png_ptr, info_ptr, length);
  180704. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180705. {
  180706. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  180707. png_error(png_ptr, "Missing IHDR before IDAT");
  180708. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  180709. !(png_ptr->mode & PNG_HAVE_PLTE))
  180710. png_error(png_ptr, "Missing PLTE before IDAT");
  180711. png_ptr->idat_size = length;
  180712. png_ptr->mode |= PNG_HAVE_IDAT;
  180713. break;
  180714. }
  180715. #if defined(PNG_READ_bKGD_SUPPORTED)
  180716. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  180717. png_handle_bKGD(png_ptr, info_ptr, length);
  180718. #endif
  180719. #if defined(PNG_READ_cHRM_SUPPORTED)
  180720. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  180721. png_handle_cHRM(png_ptr, info_ptr, length);
  180722. #endif
  180723. #if defined(PNG_READ_gAMA_SUPPORTED)
  180724. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  180725. png_handle_gAMA(png_ptr, info_ptr, length);
  180726. #endif
  180727. #if defined(PNG_READ_hIST_SUPPORTED)
  180728. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  180729. png_handle_hIST(png_ptr, info_ptr, length);
  180730. #endif
  180731. #if defined(PNG_READ_oFFs_SUPPORTED)
  180732. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  180733. png_handle_oFFs(png_ptr, info_ptr, length);
  180734. #endif
  180735. #if defined(PNG_READ_pCAL_SUPPORTED)
  180736. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  180737. png_handle_pCAL(png_ptr, info_ptr, length);
  180738. #endif
  180739. #if defined(PNG_READ_sCAL_SUPPORTED)
  180740. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  180741. png_handle_sCAL(png_ptr, info_ptr, length);
  180742. #endif
  180743. #if defined(PNG_READ_pHYs_SUPPORTED)
  180744. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  180745. png_handle_pHYs(png_ptr, info_ptr, length);
  180746. #endif
  180747. #if defined(PNG_READ_sBIT_SUPPORTED)
  180748. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  180749. png_handle_sBIT(png_ptr, info_ptr, length);
  180750. #endif
  180751. #if defined(PNG_READ_sRGB_SUPPORTED)
  180752. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  180753. png_handle_sRGB(png_ptr, info_ptr, length);
  180754. #endif
  180755. #if defined(PNG_READ_iCCP_SUPPORTED)
  180756. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  180757. png_handle_iCCP(png_ptr, info_ptr, length);
  180758. #endif
  180759. #if defined(PNG_READ_sPLT_SUPPORTED)
  180760. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  180761. png_handle_sPLT(png_ptr, info_ptr, length);
  180762. #endif
  180763. #if defined(PNG_READ_tEXt_SUPPORTED)
  180764. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  180765. png_handle_tEXt(png_ptr, info_ptr, length);
  180766. #endif
  180767. #if defined(PNG_READ_tIME_SUPPORTED)
  180768. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  180769. png_handle_tIME(png_ptr, info_ptr, length);
  180770. #endif
  180771. #if defined(PNG_READ_tRNS_SUPPORTED)
  180772. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  180773. png_handle_tRNS(png_ptr, info_ptr, length);
  180774. #endif
  180775. #if defined(PNG_READ_zTXt_SUPPORTED)
  180776. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  180777. png_handle_zTXt(png_ptr, info_ptr, length);
  180778. #endif
  180779. #if defined(PNG_READ_iTXt_SUPPORTED)
  180780. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  180781. png_handle_iTXt(png_ptr, info_ptr, length);
  180782. #endif
  180783. else
  180784. png_handle_unknown(png_ptr, info_ptr, length);
  180785. }
  180786. }
  180787. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  180788. /* optional call to update the users info_ptr structure */
  180789. void PNGAPI
  180790. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  180791. {
  180792. png_debug(1, "in png_read_update_info\n");
  180793. if(png_ptr == NULL) return;
  180794. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180795. png_read_start_row(png_ptr);
  180796. else
  180797. png_warning(png_ptr,
  180798. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  180799. png_read_transform_info(png_ptr, info_ptr);
  180800. }
  180801. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180802. /* Initialize palette, background, etc, after transformations
  180803. * are set, but before any reading takes place. This allows
  180804. * the user to obtain a gamma-corrected palette, for example.
  180805. * If the user doesn't call this, we will do it ourselves.
  180806. */
  180807. void PNGAPI
  180808. png_start_read_image(png_structp png_ptr)
  180809. {
  180810. png_debug(1, "in png_start_read_image\n");
  180811. if(png_ptr == NULL) return;
  180812. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180813. png_read_start_row(png_ptr);
  180814. }
  180815. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  180816. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180817. void PNGAPI
  180818. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  180819. {
  180820. #ifdef PNG_USE_LOCAL_ARRAYS
  180821. PNG_CONST PNG_IDAT;
  180822. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  180823. 0xff};
  180824. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180825. #endif
  180826. int ret;
  180827. if(png_ptr == NULL) return;
  180828. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  180829. png_ptr->row_number, png_ptr->pass);
  180830. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180831. png_read_start_row(png_ptr);
  180832. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  180833. {
  180834. /* check for transforms that have been set but were defined out */
  180835. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  180836. if (png_ptr->transformations & PNG_INVERT_MONO)
  180837. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  180838. #endif
  180839. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  180840. if (png_ptr->transformations & PNG_FILLER)
  180841. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  180842. #endif
  180843. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  180844. if (png_ptr->transformations & PNG_PACKSWAP)
  180845. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  180846. #endif
  180847. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  180848. if (png_ptr->transformations & PNG_PACK)
  180849. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  180850. #endif
  180851. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  180852. if (png_ptr->transformations & PNG_SHIFT)
  180853. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  180854. #endif
  180855. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  180856. if (png_ptr->transformations & PNG_BGR)
  180857. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  180858. #endif
  180859. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  180860. if (png_ptr->transformations & PNG_SWAP_BYTES)
  180861. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  180862. #endif
  180863. }
  180864. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180865. /* if interlaced and we do not need a new row, combine row and return */
  180866. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  180867. {
  180868. switch (png_ptr->pass)
  180869. {
  180870. case 0:
  180871. if (png_ptr->row_number & 0x07)
  180872. {
  180873. if (dsp_row != NULL)
  180874. png_combine_row(png_ptr, dsp_row,
  180875. png_pass_dsp_mask[png_ptr->pass]);
  180876. png_read_finish_row(png_ptr);
  180877. return;
  180878. }
  180879. break;
  180880. case 1:
  180881. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  180882. {
  180883. if (dsp_row != NULL)
  180884. png_combine_row(png_ptr, dsp_row,
  180885. png_pass_dsp_mask[png_ptr->pass]);
  180886. png_read_finish_row(png_ptr);
  180887. return;
  180888. }
  180889. break;
  180890. case 2:
  180891. if ((png_ptr->row_number & 0x07) != 4)
  180892. {
  180893. if (dsp_row != NULL && (png_ptr->row_number & 4))
  180894. png_combine_row(png_ptr, dsp_row,
  180895. png_pass_dsp_mask[png_ptr->pass]);
  180896. png_read_finish_row(png_ptr);
  180897. return;
  180898. }
  180899. break;
  180900. case 3:
  180901. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  180902. {
  180903. if (dsp_row != NULL)
  180904. png_combine_row(png_ptr, dsp_row,
  180905. png_pass_dsp_mask[png_ptr->pass]);
  180906. png_read_finish_row(png_ptr);
  180907. return;
  180908. }
  180909. break;
  180910. case 4:
  180911. if ((png_ptr->row_number & 3) != 2)
  180912. {
  180913. if (dsp_row != NULL && (png_ptr->row_number & 2))
  180914. png_combine_row(png_ptr, dsp_row,
  180915. png_pass_dsp_mask[png_ptr->pass]);
  180916. png_read_finish_row(png_ptr);
  180917. return;
  180918. }
  180919. break;
  180920. case 5:
  180921. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  180922. {
  180923. if (dsp_row != NULL)
  180924. png_combine_row(png_ptr, dsp_row,
  180925. png_pass_dsp_mask[png_ptr->pass]);
  180926. png_read_finish_row(png_ptr);
  180927. return;
  180928. }
  180929. break;
  180930. case 6:
  180931. if (!(png_ptr->row_number & 1))
  180932. {
  180933. png_read_finish_row(png_ptr);
  180934. return;
  180935. }
  180936. break;
  180937. }
  180938. }
  180939. #endif
  180940. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  180941. png_error(png_ptr, "Invalid attempt to read row data");
  180942. png_ptr->zstream.next_out = png_ptr->row_buf;
  180943. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  180944. do
  180945. {
  180946. if (!(png_ptr->zstream.avail_in))
  180947. {
  180948. while (!png_ptr->idat_size)
  180949. {
  180950. png_byte chunk_length[4];
  180951. png_crc_finish(png_ptr, 0);
  180952. png_read_data(png_ptr, chunk_length, 4);
  180953. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  180954. png_reset_crc(png_ptr);
  180955. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  180956. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180957. png_error(png_ptr, "Not enough image data");
  180958. }
  180959. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  180960. png_ptr->zstream.next_in = png_ptr->zbuf;
  180961. if (png_ptr->zbuf_size > png_ptr->idat_size)
  180962. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  180963. png_crc_read(png_ptr, png_ptr->zbuf,
  180964. (png_size_t)png_ptr->zstream.avail_in);
  180965. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  180966. }
  180967. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  180968. if (ret == Z_STREAM_END)
  180969. {
  180970. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  180971. png_ptr->idat_size)
  180972. png_error(png_ptr, "Extra compressed data");
  180973. png_ptr->mode |= PNG_AFTER_IDAT;
  180974. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  180975. break;
  180976. }
  180977. if (ret != Z_OK)
  180978. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  180979. "Decompression error");
  180980. } while (png_ptr->zstream.avail_out);
  180981. png_ptr->row_info.color_type = png_ptr->color_type;
  180982. png_ptr->row_info.width = png_ptr->iwidth;
  180983. png_ptr->row_info.channels = png_ptr->channels;
  180984. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  180985. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  180986. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  180987. png_ptr->row_info.width);
  180988. if(png_ptr->row_buf[0])
  180989. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  180990. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  180991. (int)(png_ptr->row_buf[0]));
  180992. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  180993. png_ptr->rowbytes + 1);
  180994. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  180995. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  180996. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  180997. {
  180998. /* Intrapixel differencing */
  180999. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  181000. }
  181001. #endif
  181002. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  181003. png_do_read_transformations(png_ptr);
  181004. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181005. /* blow up interlaced rows to full size */
  181006. if (png_ptr->interlaced &&
  181007. (png_ptr->transformations & PNG_INTERLACE))
  181008. {
  181009. if (png_ptr->pass < 6)
  181010. /* old interface (pre-1.0.9):
  181011. png_do_read_interlace(&(png_ptr->row_info),
  181012. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  181013. */
  181014. png_do_read_interlace(png_ptr);
  181015. if (dsp_row != NULL)
  181016. png_combine_row(png_ptr, dsp_row,
  181017. png_pass_dsp_mask[png_ptr->pass]);
  181018. if (row != NULL)
  181019. png_combine_row(png_ptr, row,
  181020. png_pass_mask[png_ptr->pass]);
  181021. }
  181022. else
  181023. #endif
  181024. {
  181025. if (row != NULL)
  181026. png_combine_row(png_ptr, row, 0xff);
  181027. if (dsp_row != NULL)
  181028. png_combine_row(png_ptr, dsp_row, 0xff);
  181029. }
  181030. png_read_finish_row(png_ptr);
  181031. if (png_ptr->read_row_fn != NULL)
  181032. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  181033. }
  181034. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181035. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181036. /* Read one or more rows of image data. If the image is interlaced,
  181037. * and png_set_interlace_handling() has been called, the rows need to
  181038. * contain the contents of the rows from the previous pass. If the
  181039. * image has alpha or transparency, and png_handle_alpha()[*] has been
  181040. * called, the rows contents must be initialized to the contents of the
  181041. * screen.
  181042. *
  181043. * "row" holds the actual image, and pixels are placed in it
  181044. * as they arrive. If the image is displayed after each pass, it will
  181045. * appear to "sparkle" in. "display_row" can be used to display a
  181046. * "chunky" progressive image, with finer detail added as it becomes
  181047. * available. If you do not want this "chunky" display, you may pass
  181048. * NULL for display_row. If you do not want the sparkle display, and
  181049. * you have not called png_handle_alpha(), you may pass NULL for rows.
  181050. * If you have called png_handle_alpha(), and the image has either an
  181051. * alpha channel or a transparency chunk, you must provide a buffer for
  181052. * rows. In this case, you do not have to provide a display_row buffer
  181053. * also, but you may. If the image is not interlaced, or if you have
  181054. * not called png_set_interlace_handling(), the display_row buffer will
  181055. * be ignored, so pass NULL to it.
  181056. *
  181057. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181058. */
  181059. void PNGAPI
  181060. png_read_rows(png_structp png_ptr, png_bytepp row,
  181061. png_bytepp display_row, png_uint_32 num_rows)
  181062. {
  181063. png_uint_32 i;
  181064. png_bytepp rp;
  181065. png_bytepp dp;
  181066. png_debug(1, "in png_read_rows\n");
  181067. if(png_ptr == NULL) return;
  181068. rp = row;
  181069. dp = display_row;
  181070. if (rp != NULL && dp != NULL)
  181071. for (i = 0; i < num_rows; i++)
  181072. {
  181073. png_bytep rptr = *rp++;
  181074. png_bytep dptr = *dp++;
  181075. png_read_row(png_ptr, rptr, dptr);
  181076. }
  181077. else if(rp != NULL)
  181078. for (i = 0; i < num_rows; i++)
  181079. {
  181080. png_bytep rptr = *rp;
  181081. png_read_row(png_ptr, rptr, png_bytep_NULL);
  181082. rp++;
  181083. }
  181084. else if(dp != NULL)
  181085. for (i = 0; i < num_rows; i++)
  181086. {
  181087. png_bytep dptr = *dp;
  181088. png_read_row(png_ptr, png_bytep_NULL, dptr);
  181089. dp++;
  181090. }
  181091. }
  181092. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181093. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181094. /* Read the entire image. If the image has an alpha channel or a tRNS
  181095. * chunk, and you have called png_handle_alpha()[*], you will need to
  181096. * initialize the image to the current image that PNG will be overlaying.
  181097. * We set the num_rows again here, in case it was incorrectly set in
  181098. * png_read_start_row() by a call to png_read_update_info() or
  181099. * png_start_read_image() if png_set_interlace_handling() wasn't called
  181100. * prior to either of these functions like it should have been. You can
  181101. * only call this function once. If you desire to have an image for
  181102. * each pass of a interlaced image, use png_read_rows() instead.
  181103. *
  181104. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181105. */
  181106. void PNGAPI
  181107. png_read_image(png_structp png_ptr, png_bytepp image)
  181108. {
  181109. png_uint_32 i,image_height;
  181110. int pass, j;
  181111. png_bytepp rp;
  181112. png_debug(1, "in png_read_image\n");
  181113. if(png_ptr == NULL) return;
  181114. #ifdef PNG_READ_INTERLACING_SUPPORTED
  181115. pass = png_set_interlace_handling(png_ptr);
  181116. #else
  181117. if (png_ptr->interlaced)
  181118. png_error(png_ptr,
  181119. "Cannot read interlaced image -- interlace handler disabled.");
  181120. pass = 1;
  181121. #endif
  181122. image_height=png_ptr->height;
  181123. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  181124. for (j = 0; j < pass; j++)
  181125. {
  181126. rp = image;
  181127. for (i = 0; i < image_height; i++)
  181128. {
  181129. png_read_row(png_ptr, *rp, png_bytep_NULL);
  181130. rp++;
  181131. }
  181132. }
  181133. }
  181134. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181135. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181136. /* Read the end of the PNG file. Will not read past the end of the
  181137. * file, will verify the end is accurate, and will read any comments
  181138. * or time information at the end of the file, if info is not NULL.
  181139. */
  181140. void PNGAPI
  181141. png_read_end(png_structp png_ptr, png_infop info_ptr)
  181142. {
  181143. png_byte chunk_length[4];
  181144. png_uint_32 length;
  181145. png_debug(1, "in png_read_end\n");
  181146. if(png_ptr == NULL) return;
  181147. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  181148. do
  181149. {
  181150. #ifdef PNG_USE_LOCAL_ARRAYS
  181151. PNG_CONST PNG_IHDR;
  181152. PNG_CONST PNG_IDAT;
  181153. PNG_CONST PNG_IEND;
  181154. PNG_CONST PNG_PLTE;
  181155. #if defined(PNG_READ_bKGD_SUPPORTED)
  181156. PNG_CONST PNG_bKGD;
  181157. #endif
  181158. #if defined(PNG_READ_cHRM_SUPPORTED)
  181159. PNG_CONST PNG_cHRM;
  181160. #endif
  181161. #if defined(PNG_READ_gAMA_SUPPORTED)
  181162. PNG_CONST PNG_gAMA;
  181163. #endif
  181164. #if defined(PNG_READ_hIST_SUPPORTED)
  181165. PNG_CONST PNG_hIST;
  181166. #endif
  181167. #if defined(PNG_READ_iCCP_SUPPORTED)
  181168. PNG_CONST PNG_iCCP;
  181169. #endif
  181170. #if defined(PNG_READ_iTXt_SUPPORTED)
  181171. PNG_CONST PNG_iTXt;
  181172. #endif
  181173. #if defined(PNG_READ_oFFs_SUPPORTED)
  181174. PNG_CONST PNG_oFFs;
  181175. #endif
  181176. #if defined(PNG_READ_pCAL_SUPPORTED)
  181177. PNG_CONST PNG_pCAL;
  181178. #endif
  181179. #if defined(PNG_READ_pHYs_SUPPORTED)
  181180. PNG_CONST PNG_pHYs;
  181181. #endif
  181182. #if defined(PNG_READ_sBIT_SUPPORTED)
  181183. PNG_CONST PNG_sBIT;
  181184. #endif
  181185. #if defined(PNG_READ_sCAL_SUPPORTED)
  181186. PNG_CONST PNG_sCAL;
  181187. #endif
  181188. #if defined(PNG_READ_sPLT_SUPPORTED)
  181189. PNG_CONST PNG_sPLT;
  181190. #endif
  181191. #if defined(PNG_READ_sRGB_SUPPORTED)
  181192. PNG_CONST PNG_sRGB;
  181193. #endif
  181194. #if defined(PNG_READ_tEXt_SUPPORTED)
  181195. PNG_CONST PNG_tEXt;
  181196. #endif
  181197. #if defined(PNG_READ_tIME_SUPPORTED)
  181198. PNG_CONST PNG_tIME;
  181199. #endif
  181200. #if defined(PNG_READ_tRNS_SUPPORTED)
  181201. PNG_CONST PNG_tRNS;
  181202. #endif
  181203. #if defined(PNG_READ_zTXt_SUPPORTED)
  181204. PNG_CONST PNG_zTXt;
  181205. #endif
  181206. #endif /* PNG_USE_LOCAL_ARRAYS */
  181207. png_read_data(png_ptr, chunk_length, 4);
  181208. length = png_get_uint_31(png_ptr,chunk_length);
  181209. png_reset_crc(png_ptr);
  181210. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181211. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  181212. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181213. png_handle_IHDR(png_ptr, info_ptr, length);
  181214. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181215. png_handle_IEND(png_ptr, info_ptr, length);
  181216. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181217. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181218. {
  181219. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181220. {
  181221. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181222. png_error(png_ptr, "Too many IDAT's found");
  181223. }
  181224. png_handle_unknown(png_ptr, info_ptr, length);
  181225. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181226. png_ptr->mode |= PNG_HAVE_PLTE;
  181227. }
  181228. #endif
  181229. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181230. {
  181231. /* Zero length IDATs are legal after the last IDAT has been
  181232. * read, but not after other chunks have been read.
  181233. */
  181234. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181235. png_error(png_ptr, "Too many IDAT's found");
  181236. png_crc_finish(png_ptr, length);
  181237. }
  181238. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181239. png_handle_PLTE(png_ptr, info_ptr, length);
  181240. #if defined(PNG_READ_bKGD_SUPPORTED)
  181241. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181242. png_handle_bKGD(png_ptr, info_ptr, length);
  181243. #endif
  181244. #if defined(PNG_READ_cHRM_SUPPORTED)
  181245. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181246. png_handle_cHRM(png_ptr, info_ptr, length);
  181247. #endif
  181248. #if defined(PNG_READ_gAMA_SUPPORTED)
  181249. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181250. png_handle_gAMA(png_ptr, info_ptr, length);
  181251. #endif
  181252. #if defined(PNG_READ_hIST_SUPPORTED)
  181253. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181254. png_handle_hIST(png_ptr, info_ptr, length);
  181255. #endif
  181256. #if defined(PNG_READ_oFFs_SUPPORTED)
  181257. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181258. png_handle_oFFs(png_ptr, info_ptr, length);
  181259. #endif
  181260. #if defined(PNG_READ_pCAL_SUPPORTED)
  181261. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181262. png_handle_pCAL(png_ptr, info_ptr, length);
  181263. #endif
  181264. #if defined(PNG_READ_sCAL_SUPPORTED)
  181265. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181266. png_handle_sCAL(png_ptr, info_ptr, length);
  181267. #endif
  181268. #if defined(PNG_READ_pHYs_SUPPORTED)
  181269. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181270. png_handle_pHYs(png_ptr, info_ptr, length);
  181271. #endif
  181272. #if defined(PNG_READ_sBIT_SUPPORTED)
  181273. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181274. png_handle_sBIT(png_ptr, info_ptr, length);
  181275. #endif
  181276. #if defined(PNG_READ_sRGB_SUPPORTED)
  181277. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181278. png_handle_sRGB(png_ptr, info_ptr, length);
  181279. #endif
  181280. #if defined(PNG_READ_iCCP_SUPPORTED)
  181281. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181282. png_handle_iCCP(png_ptr, info_ptr, length);
  181283. #endif
  181284. #if defined(PNG_READ_sPLT_SUPPORTED)
  181285. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181286. png_handle_sPLT(png_ptr, info_ptr, length);
  181287. #endif
  181288. #if defined(PNG_READ_tEXt_SUPPORTED)
  181289. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181290. png_handle_tEXt(png_ptr, info_ptr, length);
  181291. #endif
  181292. #if defined(PNG_READ_tIME_SUPPORTED)
  181293. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181294. png_handle_tIME(png_ptr, info_ptr, length);
  181295. #endif
  181296. #if defined(PNG_READ_tRNS_SUPPORTED)
  181297. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181298. png_handle_tRNS(png_ptr, info_ptr, length);
  181299. #endif
  181300. #if defined(PNG_READ_zTXt_SUPPORTED)
  181301. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  181302. png_handle_zTXt(png_ptr, info_ptr, length);
  181303. #endif
  181304. #if defined(PNG_READ_iTXt_SUPPORTED)
  181305. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  181306. png_handle_iTXt(png_ptr, info_ptr, length);
  181307. #endif
  181308. else
  181309. png_handle_unknown(png_ptr, info_ptr, length);
  181310. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  181311. }
  181312. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181313. /* free all memory used by the read */
  181314. void PNGAPI
  181315. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  181316. png_infopp end_info_ptr_ptr)
  181317. {
  181318. png_structp png_ptr = NULL;
  181319. png_infop info_ptr = NULL, end_info_ptr = NULL;
  181320. #ifdef PNG_USER_MEM_SUPPORTED
  181321. png_free_ptr free_fn;
  181322. png_voidp mem_ptr;
  181323. #endif
  181324. png_debug(1, "in png_destroy_read_struct\n");
  181325. if (png_ptr_ptr != NULL)
  181326. png_ptr = *png_ptr_ptr;
  181327. if (info_ptr_ptr != NULL)
  181328. info_ptr = *info_ptr_ptr;
  181329. if (end_info_ptr_ptr != NULL)
  181330. end_info_ptr = *end_info_ptr_ptr;
  181331. #ifdef PNG_USER_MEM_SUPPORTED
  181332. free_fn = png_ptr->free_fn;
  181333. mem_ptr = png_ptr->mem_ptr;
  181334. #endif
  181335. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  181336. if (info_ptr != NULL)
  181337. {
  181338. #if defined(PNG_TEXT_SUPPORTED)
  181339. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  181340. #endif
  181341. #ifdef PNG_USER_MEM_SUPPORTED
  181342. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  181343. (png_voidp)mem_ptr);
  181344. #else
  181345. png_destroy_struct((png_voidp)info_ptr);
  181346. #endif
  181347. *info_ptr_ptr = NULL;
  181348. }
  181349. if (end_info_ptr != NULL)
  181350. {
  181351. #if defined(PNG_READ_TEXT_SUPPORTED)
  181352. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  181353. #endif
  181354. #ifdef PNG_USER_MEM_SUPPORTED
  181355. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  181356. (png_voidp)mem_ptr);
  181357. #else
  181358. png_destroy_struct((png_voidp)end_info_ptr);
  181359. #endif
  181360. *end_info_ptr_ptr = NULL;
  181361. }
  181362. if (png_ptr != NULL)
  181363. {
  181364. #ifdef PNG_USER_MEM_SUPPORTED
  181365. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  181366. (png_voidp)mem_ptr);
  181367. #else
  181368. png_destroy_struct((png_voidp)png_ptr);
  181369. #endif
  181370. *png_ptr_ptr = NULL;
  181371. }
  181372. }
  181373. /* free all memory used by the read (old method) */
  181374. void /* PRIVATE */
  181375. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  181376. {
  181377. #ifdef PNG_SETJMP_SUPPORTED
  181378. jmp_buf tmp_jmp;
  181379. #endif
  181380. png_error_ptr error_fn;
  181381. png_error_ptr warning_fn;
  181382. png_voidp error_ptr;
  181383. #ifdef PNG_USER_MEM_SUPPORTED
  181384. png_free_ptr free_fn;
  181385. #endif
  181386. png_debug(1, "in png_read_destroy\n");
  181387. if (info_ptr != NULL)
  181388. png_info_destroy(png_ptr, info_ptr);
  181389. if (end_info_ptr != NULL)
  181390. png_info_destroy(png_ptr, end_info_ptr);
  181391. png_free(png_ptr, png_ptr->zbuf);
  181392. png_free(png_ptr, png_ptr->big_row_buf);
  181393. png_free(png_ptr, png_ptr->prev_row);
  181394. #if defined(PNG_READ_DITHER_SUPPORTED)
  181395. png_free(png_ptr, png_ptr->palette_lookup);
  181396. png_free(png_ptr, png_ptr->dither_index);
  181397. #endif
  181398. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181399. png_free(png_ptr, png_ptr->gamma_table);
  181400. #endif
  181401. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181402. png_free(png_ptr, png_ptr->gamma_from_1);
  181403. png_free(png_ptr, png_ptr->gamma_to_1);
  181404. #endif
  181405. #ifdef PNG_FREE_ME_SUPPORTED
  181406. if (png_ptr->free_me & PNG_FREE_PLTE)
  181407. png_zfree(png_ptr, png_ptr->palette);
  181408. png_ptr->free_me &= ~PNG_FREE_PLTE;
  181409. #else
  181410. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  181411. png_zfree(png_ptr, png_ptr->palette);
  181412. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  181413. #endif
  181414. #if defined(PNG_tRNS_SUPPORTED) || \
  181415. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181416. #ifdef PNG_FREE_ME_SUPPORTED
  181417. if (png_ptr->free_me & PNG_FREE_TRNS)
  181418. png_free(png_ptr, png_ptr->trans);
  181419. png_ptr->free_me &= ~PNG_FREE_TRNS;
  181420. #else
  181421. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  181422. png_free(png_ptr, png_ptr->trans);
  181423. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  181424. #endif
  181425. #endif
  181426. #if defined(PNG_READ_hIST_SUPPORTED)
  181427. #ifdef PNG_FREE_ME_SUPPORTED
  181428. if (png_ptr->free_me & PNG_FREE_HIST)
  181429. png_free(png_ptr, png_ptr->hist);
  181430. png_ptr->free_me &= ~PNG_FREE_HIST;
  181431. #else
  181432. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  181433. png_free(png_ptr, png_ptr->hist);
  181434. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  181435. #endif
  181436. #endif
  181437. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181438. if (png_ptr->gamma_16_table != NULL)
  181439. {
  181440. int i;
  181441. int istop = (1 << (8 - png_ptr->gamma_shift));
  181442. for (i = 0; i < istop; i++)
  181443. {
  181444. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  181445. }
  181446. png_free(png_ptr, png_ptr->gamma_16_table);
  181447. }
  181448. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181449. if (png_ptr->gamma_16_from_1 != NULL)
  181450. {
  181451. int i;
  181452. int istop = (1 << (8 - png_ptr->gamma_shift));
  181453. for (i = 0; i < istop; i++)
  181454. {
  181455. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  181456. }
  181457. png_free(png_ptr, png_ptr->gamma_16_from_1);
  181458. }
  181459. if (png_ptr->gamma_16_to_1 != NULL)
  181460. {
  181461. int i;
  181462. int istop = (1 << (8 - png_ptr->gamma_shift));
  181463. for (i = 0; i < istop; i++)
  181464. {
  181465. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  181466. }
  181467. png_free(png_ptr, png_ptr->gamma_16_to_1);
  181468. }
  181469. #endif
  181470. #endif
  181471. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181472. png_free(png_ptr, png_ptr->time_buffer);
  181473. #endif
  181474. inflateEnd(&png_ptr->zstream);
  181475. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181476. png_free(png_ptr, png_ptr->save_buffer);
  181477. #endif
  181478. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181479. #ifdef PNG_TEXT_SUPPORTED
  181480. png_free(png_ptr, png_ptr->current_text);
  181481. #endif /* PNG_TEXT_SUPPORTED */
  181482. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181483. /* Save the important info out of the png_struct, in case it is
  181484. * being used again.
  181485. */
  181486. #ifdef PNG_SETJMP_SUPPORTED
  181487. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  181488. #endif
  181489. error_fn = png_ptr->error_fn;
  181490. warning_fn = png_ptr->warning_fn;
  181491. error_ptr = png_ptr->error_ptr;
  181492. #ifdef PNG_USER_MEM_SUPPORTED
  181493. free_fn = png_ptr->free_fn;
  181494. #endif
  181495. png_memset(png_ptr, 0, png_sizeof (png_struct));
  181496. png_ptr->error_fn = error_fn;
  181497. png_ptr->warning_fn = warning_fn;
  181498. png_ptr->error_ptr = error_ptr;
  181499. #ifdef PNG_USER_MEM_SUPPORTED
  181500. png_ptr->free_fn = free_fn;
  181501. #endif
  181502. #ifdef PNG_SETJMP_SUPPORTED
  181503. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  181504. #endif
  181505. }
  181506. void PNGAPI
  181507. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  181508. {
  181509. if(png_ptr == NULL) return;
  181510. png_ptr->read_row_fn = read_row_fn;
  181511. }
  181512. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181513. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181514. void PNGAPI
  181515. png_read_png(png_structp png_ptr, png_infop info_ptr,
  181516. int transforms,
  181517. voidp params)
  181518. {
  181519. int row;
  181520. if(png_ptr == NULL) return;
  181521. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  181522. /* invert the alpha channel from opacity to transparency
  181523. */
  181524. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  181525. png_set_invert_alpha(png_ptr);
  181526. #endif
  181527. /* png_read_info() gives us all of the information from the
  181528. * PNG file before the first IDAT (image data chunk).
  181529. */
  181530. png_read_info(png_ptr, info_ptr);
  181531. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  181532. png_error(png_ptr,"Image is too high to process with png_read_png()");
  181533. /* -------------- image transformations start here ------------------- */
  181534. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  181535. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  181536. */
  181537. if (transforms & PNG_TRANSFORM_STRIP_16)
  181538. png_set_strip_16(png_ptr);
  181539. #endif
  181540. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181541. /* Strip alpha bytes from the input data without combining with
  181542. * the background (not recommended).
  181543. */
  181544. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  181545. png_set_strip_alpha(png_ptr);
  181546. #endif
  181547. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  181548. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  181549. * byte into separate bytes (useful for paletted and grayscale images).
  181550. */
  181551. if (transforms & PNG_TRANSFORM_PACKING)
  181552. png_set_packing(png_ptr);
  181553. #endif
  181554. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  181555. /* Change the order of packed pixels to least significant bit first
  181556. * (not useful if you are using png_set_packing).
  181557. */
  181558. if (transforms & PNG_TRANSFORM_PACKSWAP)
  181559. png_set_packswap(png_ptr);
  181560. #endif
  181561. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181562. /* Expand paletted colors into true RGB triplets
  181563. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  181564. * Expand paletted or RGB images with transparency to full alpha
  181565. * channels so the data will be available as RGBA quartets.
  181566. */
  181567. if (transforms & PNG_TRANSFORM_EXPAND)
  181568. if ((png_ptr->bit_depth < 8) ||
  181569. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  181570. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  181571. png_set_expand(png_ptr);
  181572. #endif
  181573. /* We don't handle background color or gamma transformation or dithering.
  181574. */
  181575. #if defined(PNG_READ_INVERT_SUPPORTED)
  181576. /* invert monochrome files to have 0 as white and 1 as black
  181577. */
  181578. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  181579. png_set_invert_mono(png_ptr);
  181580. #endif
  181581. #if defined(PNG_READ_SHIFT_SUPPORTED)
  181582. /* If you want to shift the pixel values from the range [0,255] or
  181583. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  181584. * colors were originally in:
  181585. */
  181586. if ((transforms & PNG_TRANSFORM_SHIFT)
  181587. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  181588. {
  181589. png_color_8p sig_bit;
  181590. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  181591. png_set_shift(png_ptr, sig_bit);
  181592. }
  181593. #endif
  181594. #if defined(PNG_READ_BGR_SUPPORTED)
  181595. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  181596. */
  181597. if (transforms & PNG_TRANSFORM_BGR)
  181598. png_set_bgr(png_ptr);
  181599. #endif
  181600. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  181601. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  181602. */
  181603. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  181604. png_set_swap_alpha(png_ptr);
  181605. #endif
  181606. #if defined(PNG_READ_SWAP_SUPPORTED)
  181607. /* swap bytes of 16 bit files to least significant byte first
  181608. */
  181609. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  181610. png_set_swap(png_ptr);
  181611. #endif
  181612. /* We don't handle adding filler bytes */
  181613. /* Optional call to gamma correct and add the background to the palette
  181614. * and update info structure. REQUIRED if you are expecting libpng to
  181615. * update the palette for you (i.e., you selected such a transform above).
  181616. */
  181617. png_read_update_info(png_ptr, info_ptr);
  181618. /* -------------- image transformations end here ------------------- */
  181619. #ifdef PNG_FREE_ME_SUPPORTED
  181620. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  181621. #endif
  181622. if(info_ptr->row_pointers == NULL)
  181623. {
  181624. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  181625. info_ptr->height * png_sizeof(png_bytep));
  181626. #ifdef PNG_FREE_ME_SUPPORTED
  181627. info_ptr->free_me |= PNG_FREE_ROWS;
  181628. #endif
  181629. for (row = 0; row < (int)info_ptr->height; row++)
  181630. {
  181631. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  181632. png_get_rowbytes(png_ptr, info_ptr));
  181633. }
  181634. }
  181635. png_read_image(png_ptr, info_ptr->row_pointers);
  181636. info_ptr->valid |= PNG_INFO_IDAT;
  181637. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  181638. png_read_end(png_ptr, info_ptr);
  181639. transforms = transforms; /* quiet compiler warnings */
  181640. params = params;
  181641. }
  181642. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  181643. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181644. #endif /* PNG_READ_SUPPORTED */
  181645. /********* End of inlined file: pngread.c *********/
  181646. /********* Start of inlined file: pngpread.c *********/
  181647. /* pngpread.c - read a png file in push mode
  181648. *
  181649. * Last changed in libpng 1.2.21 October 4, 2007
  181650. * For conditions of distribution and use, see copyright notice in png.h
  181651. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181652. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181653. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181654. */
  181655. #define PNG_INTERNAL
  181656. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181657. /* push model modes */
  181658. #define PNG_READ_SIG_MODE 0
  181659. #define PNG_READ_CHUNK_MODE 1
  181660. #define PNG_READ_IDAT_MODE 2
  181661. #define PNG_SKIP_MODE 3
  181662. #define PNG_READ_tEXt_MODE 4
  181663. #define PNG_READ_zTXt_MODE 5
  181664. #define PNG_READ_DONE_MODE 6
  181665. #define PNG_READ_iTXt_MODE 7
  181666. #define PNG_ERROR_MODE 8
  181667. void PNGAPI
  181668. png_process_data(png_structp png_ptr, png_infop info_ptr,
  181669. png_bytep buffer, png_size_t buffer_size)
  181670. {
  181671. if(png_ptr == NULL) return;
  181672. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  181673. while (png_ptr->buffer_size)
  181674. {
  181675. png_process_some_data(png_ptr, info_ptr);
  181676. }
  181677. }
  181678. /* What we do with the incoming data depends on what we were previously
  181679. * doing before we ran out of data...
  181680. */
  181681. void /* PRIVATE */
  181682. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  181683. {
  181684. if(png_ptr == NULL) return;
  181685. switch (png_ptr->process_mode)
  181686. {
  181687. case PNG_READ_SIG_MODE:
  181688. {
  181689. png_push_read_sig(png_ptr, info_ptr);
  181690. break;
  181691. }
  181692. case PNG_READ_CHUNK_MODE:
  181693. {
  181694. png_push_read_chunk(png_ptr, info_ptr);
  181695. break;
  181696. }
  181697. case PNG_READ_IDAT_MODE:
  181698. {
  181699. png_push_read_IDAT(png_ptr);
  181700. break;
  181701. }
  181702. #if defined(PNG_READ_tEXt_SUPPORTED)
  181703. case PNG_READ_tEXt_MODE:
  181704. {
  181705. png_push_read_tEXt(png_ptr, info_ptr);
  181706. break;
  181707. }
  181708. #endif
  181709. #if defined(PNG_READ_zTXt_SUPPORTED)
  181710. case PNG_READ_zTXt_MODE:
  181711. {
  181712. png_push_read_zTXt(png_ptr, info_ptr);
  181713. break;
  181714. }
  181715. #endif
  181716. #if defined(PNG_READ_iTXt_SUPPORTED)
  181717. case PNG_READ_iTXt_MODE:
  181718. {
  181719. png_push_read_iTXt(png_ptr, info_ptr);
  181720. break;
  181721. }
  181722. #endif
  181723. case PNG_SKIP_MODE:
  181724. {
  181725. png_push_crc_finish(png_ptr);
  181726. break;
  181727. }
  181728. default:
  181729. {
  181730. png_ptr->buffer_size = 0;
  181731. break;
  181732. }
  181733. }
  181734. }
  181735. /* Read any remaining signature bytes from the stream and compare them with
  181736. * the correct PNG signature. It is possible that this routine is called
  181737. * with bytes already read from the signature, either because they have been
  181738. * checked by the calling application, or because of multiple calls to this
  181739. * routine.
  181740. */
  181741. void /* PRIVATE */
  181742. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  181743. {
  181744. png_size_t num_checked = png_ptr->sig_bytes,
  181745. num_to_check = 8 - num_checked;
  181746. if (png_ptr->buffer_size < num_to_check)
  181747. {
  181748. num_to_check = png_ptr->buffer_size;
  181749. }
  181750. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  181751. num_to_check);
  181752. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  181753. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  181754. {
  181755. if (num_checked < 4 &&
  181756. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  181757. png_error(png_ptr, "Not a PNG file");
  181758. else
  181759. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  181760. }
  181761. else
  181762. {
  181763. if (png_ptr->sig_bytes >= 8)
  181764. {
  181765. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  181766. }
  181767. }
  181768. }
  181769. void /* PRIVATE */
  181770. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  181771. {
  181772. #ifdef PNG_USE_LOCAL_ARRAYS
  181773. PNG_CONST PNG_IHDR;
  181774. PNG_CONST PNG_IDAT;
  181775. PNG_CONST PNG_IEND;
  181776. PNG_CONST PNG_PLTE;
  181777. #if defined(PNG_READ_bKGD_SUPPORTED)
  181778. PNG_CONST PNG_bKGD;
  181779. #endif
  181780. #if defined(PNG_READ_cHRM_SUPPORTED)
  181781. PNG_CONST PNG_cHRM;
  181782. #endif
  181783. #if defined(PNG_READ_gAMA_SUPPORTED)
  181784. PNG_CONST PNG_gAMA;
  181785. #endif
  181786. #if defined(PNG_READ_hIST_SUPPORTED)
  181787. PNG_CONST PNG_hIST;
  181788. #endif
  181789. #if defined(PNG_READ_iCCP_SUPPORTED)
  181790. PNG_CONST PNG_iCCP;
  181791. #endif
  181792. #if defined(PNG_READ_iTXt_SUPPORTED)
  181793. PNG_CONST PNG_iTXt;
  181794. #endif
  181795. #if defined(PNG_READ_oFFs_SUPPORTED)
  181796. PNG_CONST PNG_oFFs;
  181797. #endif
  181798. #if defined(PNG_READ_pCAL_SUPPORTED)
  181799. PNG_CONST PNG_pCAL;
  181800. #endif
  181801. #if defined(PNG_READ_pHYs_SUPPORTED)
  181802. PNG_CONST PNG_pHYs;
  181803. #endif
  181804. #if defined(PNG_READ_sBIT_SUPPORTED)
  181805. PNG_CONST PNG_sBIT;
  181806. #endif
  181807. #if defined(PNG_READ_sCAL_SUPPORTED)
  181808. PNG_CONST PNG_sCAL;
  181809. #endif
  181810. #if defined(PNG_READ_sRGB_SUPPORTED)
  181811. PNG_CONST PNG_sRGB;
  181812. #endif
  181813. #if defined(PNG_READ_sPLT_SUPPORTED)
  181814. PNG_CONST PNG_sPLT;
  181815. #endif
  181816. #if defined(PNG_READ_tEXt_SUPPORTED)
  181817. PNG_CONST PNG_tEXt;
  181818. #endif
  181819. #if defined(PNG_READ_tIME_SUPPORTED)
  181820. PNG_CONST PNG_tIME;
  181821. #endif
  181822. #if defined(PNG_READ_tRNS_SUPPORTED)
  181823. PNG_CONST PNG_tRNS;
  181824. #endif
  181825. #if defined(PNG_READ_zTXt_SUPPORTED)
  181826. PNG_CONST PNG_zTXt;
  181827. #endif
  181828. #endif /* PNG_USE_LOCAL_ARRAYS */
  181829. /* First we make sure we have enough data for the 4 byte chunk name
  181830. * and the 4 byte chunk length before proceeding with decoding the
  181831. * chunk data. To fully decode each of these chunks, we also make
  181832. * sure we have enough data in the buffer for the 4 byte CRC at the
  181833. * end of every chunk (except IDAT, which is handled separately).
  181834. */
  181835. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  181836. {
  181837. png_byte chunk_length[4];
  181838. if (png_ptr->buffer_size < 8)
  181839. {
  181840. png_push_save_buffer(png_ptr);
  181841. return;
  181842. }
  181843. png_push_fill_buffer(png_ptr, chunk_length, 4);
  181844. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  181845. png_reset_crc(png_ptr);
  181846. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181847. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  181848. }
  181849. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181850. if(png_ptr->mode & PNG_AFTER_IDAT)
  181851. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  181852. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181853. {
  181854. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181855. {
  181856. png_push_save_buffer(png_ptr);
  181857. return;
  181858. }
  181859. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  181860. }
  181861. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181862. {
  181863. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181864. {
  181865. png_push_save_buffer(png_ptr);
  181866. return;
  181867. }
  181868. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  181869. png_ptr->process_mode = PNG_READ_DONE_MODE;
  181870. png_push_have_end(png_ptr, info_ptr);
  181871. }
  181872. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181873. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181874. {
  181875. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181876. {
  181877. png_push_save_buffer(png_ptr);
  181878. return;
  181879. }
  181880. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181881. png_ptr->mode |= PNG_HAVE_IDAT;
  181882. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  181883. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181884. png_ptr->mode |= PNG_HAVE_PLTE;
  181885. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181886. {
  181887. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181888. png_error(png_ptr, "Missing IHDR before IDAT");
  181889. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181890. !(png_ptr->mode & PNG_HAVE_PLTE))
  181891. png_error(png_ptr, "Missing PLTE before IDAT");
  181892. }
  181893. }
  181894. #endif
  181895. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181896. {
  181897. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181898. {
  181899. png_push_save_buffer(png_ptr);
  181900. return;
  181901. }
  181902. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  181903. }
  181904. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181905. {
  181906. /* If we reach an IDAT chunk, this means we have read all of the
  181907. * header chunks, and we can start reading the image (or if this
  181908. * is called after the image has been read - we have an error).
  181909. */
  181910. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181911. png_error(png_ptr, "Missing IHDR before IDAT");
  181912. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181913. !(png_ptr->mode & PNG_HAVE_PLTE))
  181914. png_error(png_ptr, "Missing PLTE before IDAT");
  181915. if (png_ptr->mode & PNG_HAVE_IDAT)
  181916. {
  181917. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181918. if (png_ptr->push_length == 0)
  181919. return;
  181920. if (png_ptr->mode & PNG_AFTER_IDAT)
  181921. png_error(png_ptr, "Too many IDAT's found");
  181922. }
  181923. png_ptr->idat_size = png_ptr->push_length;
  181924. png_ptr->mode |= PNG_HAVE_IDAT;
  181925. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  181926. png_push_have_info(png_ptr, info_ptr);
  181927. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  181928. png_ptr->zstream.next_out = png_ptr->row_buf;
  181929. return;
  181930. }
  181931. #if defined(PNG_READ_gAMA_SUPPORTED)
  181932. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181933. {
  181934. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181935. {
  181936. png_push_save_buffer(png_ptr);
  181937. return;
  181938. }
  181939. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  181940. }
  181941. #endif
  181942. #if defined(PNG_READ_sBIT_SUPPORTED)
  181943. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181944. {
  181945. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181946. {
  181947. png_push_save_buffer(png_ptr);
  181948. return;
  181949. }
  181950. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  181951. }
  181952. #endif
  181953. #if defined(PNG_READ_cHRM_SUPPORTED)
  181954. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181955. {
  181956. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181957. {
  181958. png_push_save_buffer(png_ptr);
  181959. return;
  181960. }
  181961. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  181962. }
  181963. #endif
  181964. #if defined(PNG_READ_sRGB_SUPPORTED)
  181965. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181966. {
  181967. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181968. {
  181969. png_push_save_buffer(png_ptr);
  181970. return;
  181971. }
  181972. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  181973. }
  181974. #endif
  181975. #if defined(PNG_READ_iCCP_SUPPORTED)
  181976. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181977. {
  181978. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181979. {
  181980. png_push_save_buffer(png_ptr);
  181981. return;
  181982. }
  181983. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  181984. }
  181985. #endif
  181986. #if defined(PNG_READ_sPLT_SUPPORTED)
  181987. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181988. {
  181989. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181990. {
  181991. png_push_save_buffer(png_ptr);
  181992. return;
  181993. }
  181994. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  181995. }
  181996. #endif
  181997. #if defined(PNG_READ_tRNS_SUPPORTED)
  181998. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181999. {
  182000. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182001. {
  182002. png_push_save_buffer(png_ptr);
  182003. return;
  182004. }
  182005. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  182006. }
  182007. #endif
  182008. #if defined(PNG_READ_bKGD_SUPPORTED)
  182009. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182010. {
  182011. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182012. {
  182013. png_push_save_buffer(png_ptr);
  182014. return;
  182015. }
  182016. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  182017. }
  182018. #endif
  182019. #if defined(PNG_READ_hIST_SUPPORTED)
  182020. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182021. {
  182022. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182023. {
  182024. png_push_save_buffer(png_ptr);
  182025. return;
  182026. }
  182027. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  182028. }
  182029. #endif
  182030. #if defined(PNG_READ_pHYs_SUPPORTED)
  182031. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182032. {
  182033. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182034. {
  182035. png_push_save_buffer(png_ptr);
  182036. return;
  182037. }
  182038. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  182039. }
  182040. #endif
  182041. #if defined(PNG_READ_oFFs_SUPPORTED)
  182042. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182043. {
  182044. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182045. {
  182046. png_push_save_buffer(png_ptr);
  182047. return;
  182048. }
  182049. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  182050. }
  182051. #endif
  182052. #if defined(PNG_READ_pCAL_SUPPORTED)
  182053. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182054. {
  182055. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182056. {
  182057. png_push_save_buffer(png_ptr);
  182058. return;
  182059. }
  182060. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  182061. }
  182062. #endif
  182063. #if defined(PNG_READ_sCAL_SUPPORTED)
  182064. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182065. {
  182066. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182067. {
  182068. png_push_save_buffer(png_ptr);
  182069. return;
  182070. }
  182071. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  182072. }
  182073. #endif
  182074. #if defined(PNG_READ_tIME_SUPPORTED)
  182075. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182076. {
  182077. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182078. {
  182079. png_push_save_buffer(png_ptr);
  182080. return;
  182081. }
  182082. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  182083. }
  182084. #endif
  182085. #if defined(PNG_READ_tEXt_SUPPORTED)
  182086. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182087. {
  182088. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182089. {
  182090. png_push_save_buffer(png_ptr);
  182091. return;
  182092. }
  182093. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  182094. }
  182095. #endif
  182096. #if defined(PNG_READ_zTXt_SUPPORTED)
  182097. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182098. {
  182099. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182100. {
  182101. png_push_save_buffer(png_ptr);
  182102. return;
  182103. }
  182104. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  182105. }
  182106. #endif
  182107. #if defined(PNG_READ_iTXt_SUPPORTED)
  182108. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182109. {
  182110. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182111. {
  182112. png_push_save_buffer(png_ptr);
  182113. return;
  182114. }
  182115. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  182116. }
  182117. #endif
  182118. else
  182119. {
  182120. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182121. {
  182122. png_push_save_buffer(png_ptr);
  182123. return;
  182124. }
  182125. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182126. }
  182127. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182128. }
  182129. void /* PRIVATE */
  182130. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  182131. {
  182132. png_ptr->process_mode = PNG_SKIP_MODE;
  182133. png_ptr->skip_length = skip;
  182134. }
  182135. void /* PRIVATE */
  182136. png_push_crc_finish(png_structp png_ptr)
  182137. {
  182138. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  182139. {
  182140. png_size_t save_size;
  182141. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  182142. save_size = (png_size_t)png_ptr->skip_length;
  182143. else
  182144. save_size = png_ptr->save_buffer_size;
  182145. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182146. png_ptr->skip_length -= save_size;
  182147. png_ptr->buffer_size -= save_size;
  182148. png_ptr->save_buffer_size -= save_size;
  182149. png_ptr->save_buffer_ptr += save_size;
  182150. }
  182151. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  182152. {
  182153. png_size_t save_size;
  182154. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  182155. save_size = (png_size_t)png_ptr->skip_length;
  182156. else
  182157. save_size = png_ptr->current_buffer_size;
  182158. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182159. png_ptr->skip_length -= save_size;
  182160. png_ptr->buffer_size -= save_size;
  182161. png_ptr->current_buffer_size -= save_size;
  182162. png_ptr->current_buffer_ptr += save_size;
  182163. }
  182164. if (!png_ptr->skip_length)
  182165. {
  182166. if (png_ptr->buffer_size < 4)
  182167. {
  182168. png_push_save_buffer(png_ptr);
  182169. return;
  182170. }
  182171. png_crc_finish(png_ptr, 0);
  182172. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182173. }
  182174. }
  182175. void PNGAPI
  182176. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  182177. {
  182178. png_bytep ptr;
  182179. if(png_ptr == NULL) return;
  182180. ptr = buffer;
  182181. if (png_ptr->save_buffer_size)
  182182. {
  182183. png_size_t save_size;
  182184. if (length < png_ptr->save_buffer_size)
  182185. save_size = length;
  182186. else
  182187. save_size = png_ptr->save_buffer_size;
  182188. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  182189. length -= save_size;
  182190. ptr += save_size;
  182191. png_ptr->buffer_size -= save_size;
  182192. png_ptr->save_buffer_size -= save_size;
  182193. png_ptr->save_buffer_ptr += save_size;
  182194. }
  182195. if (length && png_ptr->current_buffer_size)
  182196. {
  182197. png_size_t save_size;
  182198. if (length < png_ptr->current_buffer_size)
  182199. save_size = length;
  182200. else
  182201. save_size = png_ptr->current_buffer_size;
  182202. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  182203. png_ptr->buffer_size -= save_size;
  182204. png_ptr->current_buffer_size -= save_size;
  182205. png_ptr->current_buffer_ptr += save_size;
  182206. }
  182207. }
  182208. void /* PRIVATE */
  182209. png_push_save_buffer(png_structp png_ptr)
  182210. {
  182211. if (png_ptr->save_buffer_size)
  182212. {
  182213. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  182214. {
  182215. png_size_t i,istop;
  182216. png_bytep sp;
  182217. png_bytep dp;
  182218. istop = png_ptr->save_buffer_size;
  182219. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  182220. i < istop; i++, sp++, dp++)
  182221. {
  182222. *dp = *sp;
  182223. }
  182224. }
  182225. }
  182226. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  182227. png_ptr->save_buffer_max)
  182228. {
  182229. png_size_t new_max;
  182230. png_bytep old_buffer;
  182231. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  182232. (png_ptr->current_buffer_size + 256))
  182233. {
  182234. png_error(png_ptr, "Potential overflow of save_buffer");
  182235. }
  182236. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  182237. old_buffer = png_ptr->save_buffer;
  182238. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  182239. (png_uint_32)new_max);
  182240. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  182241. png_free(png_ptr, old_buffer);
  182242. png_ptr->save_buffer_max = new_max;
  182243. }
  182244. if (png_ptr->current_buffer_size)
  182245. {
  182246. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  182247. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  182248. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  182249. png_ptr->current_buffer_size = 0;
  182250. }
  182251. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  182252. png_ptr->buffer_size = 0;
  182253. }
  182254. void /* PRIVATE */
  182255. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  182256. png_size_t buffer_length)
  182257. {
  182258. png_ptr->current_buffer = buffer;
  182259. png_ptr->current_buffer_size = buffer_length;
  182260. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  182261. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  182262. }
  182263. void /* PRIVATE */
  182264. png_push_read_IDAT(png_structp png_ptr)
  182265. {
  182266. #ifdef PNG_USE_LOCAL_ARRAYS
  182267. PNG_CONST PNG_IDAT;
  182268. #endif
  182269. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182270. {
  182271. png_byte chunk_length[4];
  182272. if (png_ptr->buffer_size < 8)
  182273. {
  182274. png_push_save_buffer(png_ptr);
  182275. return;
  182276. }
  182277. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182278. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182279. png_reset_crc(png_ptr);
  182280. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182281. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182282. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182283. {
  182284. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182285. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182286. png_error(png_ptr, "Not enough compressed data");
  182287. return;
  182288. }
  182289. png_ptr->idat_size = png_ptr->push_length;
  182290. }
  182291. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  182292. {
  182293. png_size_t save_size;
  182294. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  182295. {
  182296. save_size = (png_size_t)png_ptr->idat_size;
  182297. /* check for overflow */
  182298. if((png_uint_32)save_size != png_ptr->idat_size)
  182299. png_error(png_ptr, "save_size overflowed in pngpread");
  182300. }
  182301. else
  182302. save_size = png_ptr->save_buffer_size;
  182303. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182304. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182305. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182306. png_ptr->idat_size -= save_size;
  182307. png_ptr->buffer_size -= save_size;
  182308. png_ptr->save_buffer_size -= save_size;
  182309. png_ptr->save_buffer_ptr += save_size;
  182310. }
  182311. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  182312. {
  182313. png_size_t save_size;
  182314. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  182315. {
  182316. save_size = (png_size_t)png_ptr->idat_size;
  182317. /* check for overflow */
  182318. if((png_uint_32)save_size != png_ptr->idat_size)
  182319. png_error(png_ptr, "save_size overflowed in pngpread");
  182320. }
  182321. else
  182322. save_size = png_ptr->current_buffer_size;
  182323. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182324. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182325. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182326. png_ptr->idat_size -= save_size;
  182327. png_ptr->buffer_size -= save_size;
  182328. png_ptr->current_buffer_size -= save_size;
  182329. png_ptr->current_buffer_ptr += save_size;
  182330. }
  182331. if (!png_ptr->idat_size)
  182332. {
  182333. if (png_ptr->buffer_size < 4)
  182334. {
  182335. png_push_save_buffer(png_ptr);
  182336. return;
  182337. }
  182338. png_crc_finish(png_ptr, 0);
  182339. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182340. png_ptr->mode |= PNG_AFTER_IDAT;
  182341. }
  182342. }
  182343. void /* PRIVATE */
  182344. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  182345. png_size_t buffer_length)
  182346. {
  182347. int ret;
  182348. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  182349. png_error(png_ptr, "Extra compression data");
  182350. png_ptr->zstream.next_in = buffer;
  182351. png_ptr->zstream.avail_in = (uInt)buffer_length;
  182352. for(;;)
  182353. {
  182354. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182355. if (ret != Z_OK)
  182356. {
  182357. if (ret == Z_STREAM_END)
  182358. {
  182359. if (png_ptr->zstream.avail_in)
  182360. png_error(png_ptr, "Extra compressed data");
  182361. if (!(png_ptr->zstream.avail_out))
  182362. {
  182363. png_push_process_row(png_ptr);
  182364. }
  182365. png_ptr->mode |= PNG_AFTER_IDAT;
  182366. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182367. break;
  182368. }
  182369. else if (ret == Z_BUF_ERROR)
  182370. break;
  182371. else
  182372. png_error(png_ptr, "Decompression Error");
  182373. }
  182374. if (!(png_ptr->zstream.avail_out))
  182375. {
  182376. if ((
  182377. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182378. png_ptr->interlaced && png_ptr->pass > 6) ||
  182379. (!png_ptr->interlaced &&
  182380. #endif
  182381. png_ptr->row_number == png_ptr->num_rows))
  182382. {
  182383. if (png_ptr->zstream.avail_in)
  182384. {
  182385. png_warning(png_ptr, "Too much data in IDAT chunks");
  182386. }
  182387. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182388. break;
  182389. }
  182390. png_push_process_row(png_ptr);
  182391. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182392. png_ptr->zstream.next_out = png_ptr->row_buf;
  182393. }
  182394. else
  182395. break;
  182396. }
  182397. }
  182398. void /* PRIVATE */
  182399. png_push_process_row(png_structp png_ptr)
  182400. {
  182401. png_ptr->row_info.color_type = png_ptr->color_type;
  182402. png_ptr->row_info.width = png_ptr->iwidth;
  182403. png_ptr->row_info.channels = png_ptr->channels;
  182404. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  182405. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  182406. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  182407. png_ptr->row_info.width);
  182408. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  182409. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  182410. (int)(png_ptr->row_buf[0]));
  182411. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  182412. png_ptr->rowbytes + 1);
  182413. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  182414. png_do_read_transformations(png_ptr);
  182415. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182416. /* blow up interlaced rows to full size */
  182417. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  182418. {
  182419. if (png_ptr->pass < 6)
  182420. /* old interface (pre-1.0.9):
  182421. png_do_read_interlace(&(png_ptr->row_info),
  182422. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  182423. */
  182424. png_do_read_interlace(png_ptr);
  182425. switch (png_ptr->pass)
  182426. {
  182427. case 0:
  182428. {
  182429. int i;
  182430. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  182431. {
  182432. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182433. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  182434. }
  182435. if (png_ptr->pass == 2) /* pass 1 might be empty */
  182436. {
  182437. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182438. {
  182439. png_push_have_row(png_ptr, png_bytep_NULL);
  182440. png_read_push_finish_row(png_ptr);
  182441. }
  182442. }
  182443. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  182444. {
  182445. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182446. {
  182447. png_push_have_row(png_ptr, png_bytep_NULL);
  182448. png_read_push_finish_row(png_ptr);
  182449. }
  182450. }
  182451. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  182452. {
  182453. png_push_have_row(png_ptr, png_bytep_NULL);
  182454. png_read_push_finish_row(png_ptr);
  182455. }
  182456. break;
  182457. }
  182458. case 1:
  182459. {
  182460. int i;
  182461. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  182462. {
  182463. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182464. png_read_push_finish_row(png_ptr);
  182465. }
  182466. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  182467. {
  182468. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182469. {
  182470. png_push_have_row(png_ptr, png_bytep_NULL);
  182471. png_read_push_finish_row(png_ptr);
  182472. }
  182473. }
  182474. break;
  182475. }
  182476. case 2:
  182477. {
  182478. int i;
  182479. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182480. {
  182481. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182482. png_read_push_finish_row(png_ptr);
  182483. }
  182484. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182485. {
  182486. png_push_have_row(png_ptr, png_bytep_NULL);
  182487. png_read_push_finish_row(png_ptr);
  182488. }
  182489. if (png_ptr->pass == 4) /* pass 3 might be empty */
  182490. {
  182491. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182492. {
  182493. png_push_have_row(png_ptr, png_bytep_NULL);
  182494. png_read_push_finish_row(png_ptr);
  182495. }
  182496. }
  182497. break;
  182498. }
  182499. case 3:
  182500. {
  182501. int i;
  182502. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  182503. {
  182504. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182505. png_read_push_finish_row(png_ptr);
  182506. }
  182507. if (png_ptr->pass == 4) /* skip top two generated rows */
  182508. {
  182509. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182510. {
  182511. png_push_have_row(png_ptr, png_bytep_NULL);
  182512. png_read_push_finish_row(png_ptr);
  182513. }
  182514. }
  182515. break;
  182516. }
  182517. case 4:
  182518. {
  182519. int i;
  182520. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182521. {
  182522. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182523. png_read_push_finish_row(png_ptr);
  182524. }
  182525. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182526. {
  182527. png_push_have_row(png_ptr, png_bytep_NULL);
  182528. png_read_push_finish_row(png_ptr);
  182529. }
  182530. if (png_ptr->pass == 6) /* pass 5 might be empty */
  182531. {
  182532. png_push_have_row(png_ptr, png_bytep_NULL);
  182533. png_read_push_finish_row(png_ptr);
  182534. }
  182535. break;
  182536. }
  182537. case 5:
  182538. {
  182539. int i;
  182540. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  182541. {
  182542. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182543. png_read_push_finish_row(png_ptr);
  182544. }
  182545. if (png_ptr->pass == 6) /* skip top generated row */
  182546. {
  182547. png_push_have_row(png_ptr, png_bytep_NULL);
  182548. png_read_push_finish_row(png_ptr);
  182549. }
  182550. break;
  182551. }
  182552. case 6:
  182553. {
  182554. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182555. png_read_push_finish_row(png_ptr);
  182556. if (png_ptr->pass != 6)
  182557. break;
  182558. png_push_have_row(png_ptr, png_bytep_NULL);
  182559. png_read_push_finish_row(png_ptr);
  182560. }
  182561. }
  182562. }
  182563. else
  182564. #endif
  182565. {
  182566. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182567. png_read_push_finish_row(png_ptr);
  182568. }
  182569. }
  182570. void /* PRIVATE */
  182571. png_read_push_finish_row(png_structp png_ptr)
  182572. {
  182573. #ifdef PNG_USE_LOCAL_ARRAYS
  182574. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  182575. /* start of interlace block */
  182576. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  182577. /* offset to next interlace block */
  182578. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  182579. /* start of interlace block in the y direction */
  182580. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  182581. /* offset to next interlace block in the y direction */
  182582. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  182583. /* Height of interlace block. This is not currently used - if you need
  182584. * it, uncomment it here and in png.h
  182585. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  182586. */
  182587. #endif
  182588. png_ptr->row_number++;
  182589. if (png_ptr->row_number < png_ptr->num_rows)
  182590. return;
  182591. if (png_ptr->interlaced)
  182592. {
  182593. png_ptr->row_number = 0;
  182594. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  182595. png_ptr->rowbytes + 1);
  182596. do
  182597. {
  182598. png_ptr->pass++;
  182599. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  182600. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  182601. (png_ptr->pass == 5 && png_ptr->width < 2))
  182602. png_ptr->pass++;
  182603. if (png_ptr->pass > 7)
  182604. png_ptr->pass--;
  182605. if (png_ptr->pass >= 7)
  182606. break;
  182607. png_ptr->iwidth = (png_ptr->width +
  182608. png_pass_inc[png_ptr->pass] - 1 -
  182609. png_pass_start[png_ptr->pass]) /
  182610. png_pass_inc[png_ptr->pass];
  182611. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  182612. png_ptr->iwidth) + 1;
  182613. if (png_ptr->transformations & PNG_INTERLACE)
  182614. break;
  182615. png_ptr->num_rows = (png_ptr->height +
  182616. png_pass_yinc[png_ptr->pass] - 1 -
  182617. png_pass_ystart[png_ptr->pass]) /
  182618. png_pass_yinc[png_ptr->pass];
  182619. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  182620. }
  182621. }
  182622. #if defined(PNG_READ_tEXt_SUPPORTED)
  182623. void /* PRIVATE */
  182624. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182625. length)
  182626. {
  182627. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182628. {
  182629. png_error(png_ptr, "Out of place tEXt");
  182630. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182631. }
  182632. #ifdef PNG_MAX_MALLOC_64K
  182633. png_ptr->skip_length = 0; /* This may not be necessary */
  182634. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  182635. {
  182636. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  182637. png_ptr->skip_length = length - (png_uint_32)65535L;
  182638. length = (png_uint_32)65535L;
  182639. }
  182640. #endif
  182641. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182642. (png_uint_32)(length+1));
  182643. png_ptr->current_text[length] = '\0';
  182644. png_ptr->current_text_ptr = png_ptr->current_text;
  182645. png_ptr->current_text_size = (png_size_t)length;
  182646. png_ptr->current_text_left = (png_size_t)length;
  182647. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  182648. }
  182649. void /* PRIVATE */
  182650. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  182651. {
  182652. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182653. {
  182654. png_size_t text_size;
  182655. if (png_ptr->buffer_size < png_ptr->current_text_left)
  182656. text_size = png_ptr->buffer_size;
  182657. else
  182658. text_size = png_ptr->current_text_left;
  182659. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182660. png_ptr->current_text_left -= text_size;
  182661. png_ptr->current_text_ptr += text_size;
  182662. }
  182663. if (!(png_ptr->current_text_left))
  182664. {
  182665. png_textp text_ptr;
  182666. png_charp text;
  182667. png_charp key;
  182668. int ret;
  182669. if (png_ptr->buffer_size < 4)
  182670. {
  182671. png_push_save_buffer(png_ptr);
  182672. return;
  182673. }
  182674. png_push_crc_finish(png_ptr);
  182675. #if defined(PNG_MAX_MALLOC_64K)
  182676. if (png_ptr->skip_length)
  182677. return;
  182678. #endif
  182679. key = png_ptr->current_text;
  182680. for (text = key; *text; text++)
  182681. /* empty loop */ ;
  182682. if (text < key + png_ptr->current_text_size)
  182683. text++;
  182684. text_ptr = (png_textp)png_malloc(png_ptr,
  182685. (png_uint_32)png_sizeof(png_text));
  182686. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  182687. text_ptr->key = key;
  182688. #ifdef PNG_iTXt_SUPPORTED
  182689. text_ptr->lang = NULL;
  182690. text_ptr->lang_key = NULL;
  182691. #endif
  182692. text_ptr->text = text;
  182693. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182694. png_free(png_ptr, key);
  182695. png_free(png_ptr, text_ptr);
  182696. png_ptr->current_text = NULL;
  182697. if (ret)
  182698. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  182699. }
  182700. }
  182701. #endif
  182702. #if defined(PNG_READ_zTXt_SUPPORTED)
  182703. void /* PRIVATE */
  182704. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182705. length)
  182706. {
  182707. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182708. {
  182709. png_error(png_ptr, "Out of place zTXt");
  182710. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182711. }
  182712. #ifdef PNG_MAX_MALLOC_64K
  182713. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  182714. * to be able to store the uncompressed data. Actually, the threshold
  182715. * is probably around 32K, but it isn't as definite as 64K is.
  182716. */
  182717. if (length > (png_uint_32)65535L)
  182718. {
  182719. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  182720. png_push_crc_skip(png_ptr, length);
  182721. return;
  182722. }
  182723. #endif
  182724. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182725. (png_uint_32)(length+1));
  182726. png_ptr->current_text[length] = '\0';
  182727. png_ptr->current_text_ptr = png_ptr->current_text;
  182728. png_ptr->current_text_size = (png_size_t)length;
  182729. png_ptr->current_text_left = (png_size_t)length;
  182730. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  182731. }
  182732. void /* PRIVATE */
  182733. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  182734. {
  182735. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182736. {
  182737. png_size_t text_size;
  182738. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  182739. text_size = png_ptr->buffer_size;
  182740. else
  182741. text_size = png_ptr->current_text_left;
  182742. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182743. png_ptr->current_text_left -= text_size;
  182744. png_ptr->current_text_ptr += text_size;
  182745. }
  182746. if (!(png_ptr->current_text_left))
  182747. {
  182748. png_textp text_ptr;
  182749. png_charp text;
  182750. png_charp key;
  182751. int ret;
  182752. png_size_t text_size, key_size;
  182753. if (png_ptr->buffer_size < 4)
  182754. {
  182755. png_push_save_buffer(png_ptr);
  182756. return;
  182757. }
  182758. png_push_crc_finish(png_ptr);
  182759. key = png_ptr->current_text;
  182760. for (text = key; *text; text++)
  182761. /* empty loop */ ;
  182762. /* zTXt can't have zero text */
  182763. if (text >= key + png_ptr->current_text_size)
  182764. {
  182765. png_ptr->current_text = NULL;
  182766. png_free(png_ptr, key);
  182767. return;
  182768. }
  182769. text++;
  182770. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  182771. {
  182772. png_ptr->current_text = NULL;
  182773. png_free(png_ptr, key);
  182774. return;
  182775. }
  182776. text++;
  182777. png_ptr->zstream.next_in = (png_bytep )text;
  182778. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  182779. (text - key));
  182780. png_ptr->zstream.next_out = png_ptr->zbuf;
  182781. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182782. key_size = text - key;
  182783. text_size = 0;
  182784. text = NULL;
  182785. ret = Z_STREAM_END;
  182786. while (png_ptr->zstream.avail_in)
  182787. {
  182788. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182789. if (ret != Z_OK && ret != Z_STREAM_END)
  182790. {
  182791. inflateReset(&png_ptr->zstream);
  182792. png_ptr->zstream.avail_in = 0;
  182793. png_ptr->current_text = NULL;
  182794. png_free(png_ptr, key);
  182795. png_free(png_ptr, text);
  182796. return;
  182797. }
  182798. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  182799. {
  182800. if (text == NULL)
  182801. {
  182802. text = (png_charp)png_malloc(png_ptr,
  182803. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  182804. + key_size + 1));
  182805. png_memcpy(text + key_size, png_ptr->zbuf,
  182806. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  182807. png_memcpy(text, key, key_size);
  182808. text_size = key_size + png_ptr->zbuf_size -
  182809. png_ptr->zstream.avail_out;
  182810. *(text + text_size) = '\0';
  182811. }
  182812. else
  182813. {
  182814. png_charp tmp;
  182815. tmp = text;
  182816. text = (png_charp)png_malloc(png_ptr, text_size +
  182817. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  182818. + 1));
  182819. png_memcpy(text, tmp, text_size);
  182820. png_free(png_ptr, tmp);
  182821. png_memcpy(text + text_size, png_ptr->zbuf,
  182822. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  182823. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  182824. *(text + text_size) = '\0';
  182825. }
  182826. if (ret != Z_STREAM_END)
  182827. {
  182828. png_ptr->zstream.next_out = png_ptr->zbuf;
  182829. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182830. }
  182831. }
  182832. else
  182833. {
  182834. break;
  182835. }
  182836. if (ret == Z_STREAM_END)
  182837. break;
  182838. }
  182839. inflateReset(&png_ptr->zstream);
  182840. png_ptr->zstream.avail_in = 0;
  182841. if (ret != Z_STREAM_END)
  182842. {
  182843. png_ptr->current_text = NULL;
  182844. png_free(png_ptr, key);
  182845. png_free(png_ptr, text);
  182846. return;
  182847. }
  182848. png_ptr->current_text = NULL;
  182849. png_free(png_ptr, key);
  182850. key = text;
  182851. text += key_size;
  182852. text_ptr = (png_textp)png_malloc(png_ptr,
  182853. (png_uint_32)png_sizeof(png_text));
  182854. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  182855. text_ptr->key = key;
  182856. #ifdef PNG_iTXt_SUPPORTED
  182857. text_ptr->lang = NULL;
  182858. text_ptr->lang_key = NULL;
  182859. #endif
  182860. text_ptr->text = text;
  182861. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182862. png_free(png_ptr, key);
  182863. png_free(png_ptr, text_ptr);
  182864. if (ret)
  182865. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  182866. }
  182867. }
  182868. #endif
  182869. #if defined(PNG_READ_iTXt_SUPPORTED)
  182870. void /* PRIVATE */
  182871. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182872. length)
  182873. {
  182874. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182875. {
  182876. png_error(png_ptr, "Out of place iTXt");
  182877. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182878. }
  182879. #ifdef PNG_MAX_MALLOC_64K
  182880. png_ptr->skip_length = 0; /* This may not be necessary */
  182881. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  182882. {
  182883. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  182884. png_ptr->skip_length = length - (png_uint_32)65535L;
  182885. length = (png_uint_32)65535L;
  182886. }
  182887. #endif
  182888. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182889. (png_uint_32)(length+1));
  182890. png_ptr->current_text[length] = '\0';
  182891. png_ptr->current_text_ptr = png_ptr->current_text;
  182892. png_ptr->current_text_size = (png_size_t)length;
  182893. png_ptr->current_text_left = (png_size_t)length;
  182894. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  182895. }
  182896. void /* PRIVATE */
  182897. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  182898. {
  182899. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182900. {
  182901. png_size_t text_size;
  182902. if (png_ptr->buffer_size < png_ptr->current_text_left)
  182903. text_size = png_ptr->buffer_size;
  182904. else
  182905. text_size = png_ptr->current_text_left;
  182906. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182907. png_ptr->current_text_left -= text_size;
  182908. png_ptr->current_text_ptr += text_size;
  182909. }
  182910. if (!(png_ptr->current_text_left))
  182911. {
  182912. png_textp text_ptr;
  182913. png_charp key;
  182914. int comp_flag;
  182915. png_charp lang;
  182916. png_charp lang_key;
  182917. png_charp text;
  182918. int ret;
  182919. if (png_ptr->buffer_size < 4)
  182920. {
  182921. png_push_save_buffer(png_ptr);
  182922. return;
  182923. }
  182924. png_push_crc_finish(png_ptr);
  182925. #if defined(PNG_MAX_MALLOC_64K)
  182926. if (png_ptr->skip_length)
  182927. return;
  182928. #endif
  182929. key = png_ptr->current_text;
  182930. for (lang = key; *lang; lang++)
  182931. /* empty loop */ ;
  182932. if (lang < key + png_ptr->current_text_size - 3)
  182933. lang++;
  182934. comp_flag = *lang++;
  182935. lang++; /* skip comp_type, always zero */
  182936. for (lang_key = lang; *lang_key; lang_key++)
  182937. /* empty loop */ ;
  182938. lang_key++; /* skip NUL separator */
  182939. text=lang_key;
  182940. if (lang_key < key + png_ptr->current_text_size - 1)
  182941. {
  182942. for (; *text; text++)
  182943. /* empty loop */ ;
  182944. }
  182945. if (text < key + png_ptr->current_text_size)
  182946. text++;
  182947. text_ptr = (png_textp)png_malloc(png_ptr,
  182948. (png_uint_32)png_sizeof(png_text));
  182949. text_ptr->compression = comp_flag + 2;
  182950. text_ptr->key = key;
  182951. text_ptr->lang = lang;
  182952. text_ptr->lang_key = lang_key;
  182953. text_ptr->text = text;
  182954. text_ptr->text_length = 0;
  182955. text_ptr->itxt_length = png_strlen(text);
  182956. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182957. png_ptr->current_text = NULL;
  182958. png_free(png_ptr, text_ptr);
  182959. if (ret)
  182960. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  182961. }
  182962. }
  182963. #endif
  182964. /* This function is called when we haven't found a handler for this
  182965. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  182966. * name or a critical chunk), the chunk is (currently) silently ignored.
  182967. */
  182968. void /* PRIVATE */
  182969. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182970. length)
  182971. {
  182972. png_uint_32 skip=0;
  182973. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  182974. if (!(png_ptr->chunk_name[0] & 0x20))
  182975. {
  182976. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  182977. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  182978. PNG_HANDLE_CHUNK_ALWAYS
  182979. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  182980. && png_ptr->read_user_chunk_fn == NULL
  182981. #endif
  182982. )
  182983. #endif
  182984. png_chunk_error(png_ptr, "unknown critical chunk");
  182985. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182986. }
  182987. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  182988. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  182989. {
  182990. #ifdef PNG_MAX_MALLOC_64K
  182991. if (length > (png_uint_32)65535L)
  182992. {
  182993. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  182994. skip = length - (png_uint_32)65535L;
  182995. length = (png_uint_32)65535L;
  182996. }
  182997. #endif
  182998. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  182999. (png_charp)png_ptr->chunk_name, 5);
  183000. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  183001. png_ptr->unknown_chunk.size = (png_size_t)length;
  183002. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  183003. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183004. if(png_ptr->read_user_chunk_fn != NULL)
  183005. {
  183006. /* callback to user unknown chunk handler */
  183007. int ret;
  183008. ret = (*(png_ptr->read_user_chunk_fn))
  183009. (png_ptr, &png_ptr->unknown_chunk);
  183010. if (ret < 0)
  183011. png_chunk_error(png_ptr, "error in user chunk");
  183012. if (ret == 0)
  183013. {
  183014. if (!(png_ptr->chunk_name[0] & 0x20))
  183015. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183016. PNG_HANDLE_CHUNK_ALWAYS)
  183017. png_chunk_error(png_ptr, "unknown critical chunk");
  183018. png_set_unknown_chunks(png_ptr, info_ptr,
  183019. &png_ptr->unknown_chunk, 1);
  183020. }
  183021. }
  183022. #else
  183023. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  183024. #endif
  183025. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183026. png_ptr->unknown_chunk.data = NULL;
  183027. }
  183028. else
  183029. #endif
  183030. skip=length;
  183031. png_push_crc_skip(png_ptr, skip);
  183032. }
  183033. void /* PRIVATE */
  183034. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  183035. {
  183036. if (png_ptr->info_fn != NULL)
  183037. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  183038. }
  183039. void /* PRIVATE */
  183040. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  183041. {
  183042. if (png_ptr->end_fn != NULL)
  183043. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  183044. }
  183045. void /* PRIVATE */
  183046. png_push_have_row(png_structp png_ptr, png_bytep row)
  183047. {
  183048. if (png_ptr->row_fn != NULL)
  183049. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  183050. (int)png_ptr->pass);
  183051. }
  183052. void PNGAPI
  183053. png_progressive_combine_row (png_structp png_ptr,
  183054. png_bytep old_row, png_bytep new_row)
  183055. {
  183056. #ifdef PNG_USE_LOCAL_ARRAYS
  183057. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  183058. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183059. #endif
  183060. if(png_ptr == NULL) return;
  183061. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  183062. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  183063. }
  183064. void PNGAPI
  183065. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  183066. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183067. png_progressive_end_ptr end_fn)
  183068. {
  183069. if(png_ptr == NULL) return;
  183070. png_ptr->info_fn = info_fn;
  183071. png_ptr->row_fn = row_fn;
  183072. png_ptr->end_fn = end_fn;
  183073. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  183074. }
  183075. png_voidp PNGAPI
  183076. png_get_progressive_ptr(png_structp png_ptr)
  183077. {
  183078. if(png_ptr == NULL) return (NULL);
  183079. return png_ptr->io_ptr;
  183080. }
  183081. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183082. /********* End of inlined file: pngpread.c *********/
  183083. /********* Start of inlined file: pngrio.c *********/
  183084. /* pngrio.c - functions for data input
  183085. *
  183086. * Last changed in libpng 1.2.13 November 13, 2006
  183087. * For conditions of distribution and use, see copyright notice in png.h
  183088. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183089. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183090. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183091. *
  183092. * This file provides a location for all input. Users who need
  183093. * special handling are expected to write a function that has the same
  183094. * arguments as this and performs a similar function, but that possibly
  183095. * has a different input method. Note that you shouldn't change this
  183096. * function, but rather write a replacement function and then make
  183097. * libpng use it at run time with png_set_read_fn(...).
  183098. */
  183099. #define PNG_INTERNAL
  183100. #if defined(PNG_READ_SUPPORTED)
  183101. /* Read the data from whatever input you are using. The default routine
  183102. reads from a file pointer. Note that this routine sometimes gets called
  183103. with very small lengths, so you should implement some kind of simple
  183104. buffering if you are using unbuffered reads. This should never be asked
  183105. to read more then 64K on a 16 bit machine. */
  183106. void /* PRIVATE */
  183107. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183108. {
  183109. png_debug1(4,"reading %d bytes\n", (int)length);
  183110. if (png_ptr->read_data_fn != NULL)
  183111. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  183112. else
  183113. png_error(png_ptr, "Call to NULL read function");
  183114. }
  183115. #if !defined(PNG_NO_STDIO)
  183116. /* This is the function that does the actual reading of data. If you are
  183117. not reading from a standard C stream, you should create a replacement
  183118. read_data function and use it at run time with png_set_read_fn(), rather
  183119. than changing the library. */
  183120. #ifndef USE_FAR_KEYWORD
  183121. void PNGAPI
  183122. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183123. {
  183124. png_size_t check;
  183125. if(png_ptr == NULL) return;
  183126. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  183127. * instead of an int, which is what fread() actually returns.
  183128. */
  183129. #if defined(_WIN32_WCE)
  183130. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183131. check = 0;
  183132. #else
  183133. check = (png_size_t)fread(data, (png_size_t)1, length,
  183134. (png_FILE_p)png_ptr->io_ptr);
  183135. #endif
  183136. if (check != length)
  183137. png_error(png_ptr, "Read Error");
  183138. }
  183139. #else
  183140. /* this is the model-independent version. Since the standard I/O library
  183141. can't handle far buffers in the medium and small models, we have to copy
  183142. the data.
  183143. */
  183144. #define NEAR_BUF_SIZE 1024
  183145. #define MIN(a,b) (a <= b ? a : b)
  183146. static void PNGAPI
  183147. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183148. {
  183149. int check;
  183150. png_byte *n_data;
  183151. png_FILE_p io_ptr;
  183152. if(png_ptr == NULL) return;
  183153. /* Check if data really is near. If so, use usual code. */
  183154. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  183155. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  183156. if ((png_bytep)n_data == data)
  183157. {
  183158. #if defined(_WIN32_WCE)
  183159. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183160. check = 0;
  183161. #else
  183162. check = fread(n_data, 1, length, io_ptr);
  183163. #endif
  183164. }
  183165. else
  183166. {
  183167. png_byte buf[NEAR_BUF_SIZE];
  183168. png_size_t read, remaining, err;
  183169. check = 0;
  183170. remaining = length;
  183171. do
  183172. {
  183173. read = MIN(NEAR_BUF_SIZE, remaining);
  183174. #if defined(_WIN32_WCE)
  183175. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  183176. err = 0;
  183177. #else
  183178. err = fread(buf, (png_size_t)1, read, io_ptr);
  183179. #endif
  183180. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  183181. if(err != read)
  183182. break;
  183183. else
  183184. check += err;
  183185. data += read;
  183186. remaining -= read;
  183187. }
  183188. while (remaining != 0);
  183189. }
  183190. if ((png_uint_32)check != (png_uint_32)length)
  183191. png_error(png_ptr, "read Error");
  183192. }
  183193. #endif
  183194. #endif
  183195. /* This function allows the application to supply a new input function
  183196. for libpng if standard C streams aren't being used.
  183197. This function takes as its arguments:
  183198. png_ptr - pointer to a png input data structure
  183199. io_ptr - pointer to user supplied structure containing info about
  183200. the input functions. May be NULL.
  183201. read_data_fn - pointer to a new input function that takes as its
  183202. arguments a pointer to a png_struct, a pointer to
  183203. a location where input data can be stored, and a 32-bit
  183204. unsigned int that is the number of bytes to be read.
  183205. To exit and output any fatal error messages the new write
  183206. function should call png_error(png_ptr, "Error msg"). */
  183207. void PNGAPI
  183208. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  183209. png_rw_ptr read_data_fn)
  183210. {
  183211. if(png_ptr == NULL) return;
  183212. png_ptr->io_ptr = io_ptr;
  183213. #if !defined(PNG_NO_STDIO)
  183214. if (read_data_fn != NULL)
  183215. png_ptr->read_data_fn = read_data_fn;
  183216. else
  183217. png_ptr->read_data_fn = png_default_read_data;
  183218. #else
  183219. png_ptr->read_data_fn = read_data_fn;
  183220. #endif
  183221. /* It is an error to write to a read device */
  183222. if (png_ptr->write_data_fn != NULL)
  183223. {
  183224. png_ptr->write_data_fn = NULL;
  183225. png_warning(png_ptr,
  183226. "It's an error to set both read_data_fn and write_data_fn in the ");
  183227. png_warning(png_ptr,
  183228. "same structure. Resetting write_data_fn to NULL.");
  183229. }
  183230. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183231. png_ptr->output_flush_fn = NULL;
  183232. #endif
  183233. }
  183234. #endif /* PNG_READ_SUPPORTED */
  183235. /********* End of inlined file: pngrio.c *********/
  183236. /********* Start of inlined file: pngrtran.c *********/
  183237. /* pngrtran.c - transforms the data in a row for PNG readers
  183238. *
  183239. * Last changed in libpng 1.2.21 [October 4, 2007]
  183240. * For conditions of distribution and use, see copyright notice in png.h
  183241. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183242. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183243. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183244. *
  183245. * This file contains functions optionally called by an application
  183246. * in order to tell libpng how to handle data when reading a PNG.
  183247. * Transformations that are used in both reading and writing are
  183248. * in pngtrans.c.
  183249. */
  183250. #define PNG_INTERNAL
  183251. #if defined(PNG_READ_SUPPORTED)
  183252. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  183253. void PNGAPI
  183254. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  183255. {
  183256. png_debug(1, "in png_set_crc_action\n");
  183257. /* Tell libpng how we react to CRC errors in critical chunks */
  183258. if(png_ptr == NULL) return;
  183259. switch (crit_action)
  183260. {
  183261. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183262. break;
  183263. case PNG_CRC_WARN_USE: /* warn/use data */
  183264. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183265. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  183266. break;
  183267. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183268. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183269. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  183270. PNG_FLAG_CRC_CRITICAL_IGNORE;
  183271. break;
  183272. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  183273. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  183274. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183275. case PNG_CRC_DEFAULT:
  183276. default:
  183277. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183278. break;
  183279. }
  183280. switch (ancil_action)
  183281. {
  183282. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183283. break;
  183284. case PNG_CRC_WARN_USE: /* warn/use data */
  183285. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183286. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  183287. break;
  183288. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183289. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183290. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  183291. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  183292. break;
  183293. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183294. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183295. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  183296. break;
  183297. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  183298. case PNG_CRC_DEFAULT:
  183299. default:
  183300. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183301. break;
  183302. }
  183303. }
  183304. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  183305. defined(PNG_FLOATING_POINT_SUPPORTED)
  183306. /* handle alpha and tRNS via a background color */
  183307. void PNGAPI
  183308. png_set_background(png_structp png_ptr,
  183309. png_color_16p background_color, int background_gamma_code,
  183310. int need_expand, double background_gamma)
  183311. {
  183312. png_debug(1, "in png_set_background\n");
  183313. if(png_ptr == NULL) return;
  183314. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  183315. {
  183316. png_warning(png_ptr, "Application must supply a known background gamma");
  183317. return;
  183318. }
  183319. png_ptr->transformations |= PNG_BACKGROUND;
  183320. png_memcpy(&(png_ptr->background), background_color,
  183321. png_sizeof(png_color_16));
  183322. png_ptr->background_gamma = (float)background_gamma;
  183323. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  183324. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  183325. }
  183326. #endif
  183327. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183328. /* strip 16 bit depth files to 8 bit depth */
  183329. void PNGAPI
  183330. png_set_strip_16(png_structp png_ptr)
  183331. {
  183332. png_debug(1, "in png_set_strip_16\n");
  183333. if(png_ptr == NULL) return;
  183334. png_ptr->transformations |= PNG_16_TO_8;
  183335. }
  183336. #endif
  183337. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183338. void PNGAPI
  183339. png_set_strip_alpha(png_structp png_ptr)
  183340. {
  183341. png_debug(1, "in png_set_strip_alpha\n");
  183342. if(png_ptr == NULL) return;
  183343. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  183344. }
  183345. #endif
  183346. #if defined(PNG_READ_DITHER_SUPPORTED)
  183347. /* Dither file to 8 bit. Supply a palette, the current number
  183348. * of elements in the palette, the maximum number of elements
  183349. * allowed, and a histogram if possible. If the current number
  183350. * of colors is greater then the maximum number, the palette will be
  183351. * modified to fit in the maximum number. "full_dither" indicates
  183352. * whether we need a dithering cube set up for RGB images, or if we
  183353. * simply are reducing the number of colors in a paletted image.
  183354. */
  183355. typedef struct png_dsort_struct
  183356. {
  183357. struct png_dsort_struct FAR * next;
  183358. png_byte left;
  183359. png_byte right;
  183360. } png_dsort;
  183361. typedef png_dsort FAR * png_dsortp;
  183362. typedef png_dsort FAR * FAR * png_dsortpp;
  183363. void PNGAPI
  183364. png_set_dither(png_structp png_ptr, png_colorp palette,
  183365. int num_palette, int maximum_colors, png_uint_16p histogram,
  183366. int full_dither)
  183367. {
  183368. png_debug(1, "in png_set_dither\n");
  183369. if(png_ptr == NULL) return;
  183370. png_ptr->transformations |= PNG_DITHER;
  183371. if (!full_dither)
  183372. {
  183373. int i;
  183374. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  183375. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183376. for (i = 0; i < num_palette; i++)
  183377. png_ptr->dither_index[i] = (png_byte)i;
  183378. }
  183379. if (num_palette > maximum_colors)
  183380. {
  183381. if (histogram != NULL)
  183382. {
  183383. /* This is easy enough, just throw out the least used colors.
  183384. Perhaps not the best solution, but good enough. */
  183385. int i;
  183386. /* initialize an array to sort colors */
  183387. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  183388. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183389. /* initialize the dither_sort array */
  183390. for (i = 0; i < num_palette; i++)
  183391. png_ptr->dither_sort[i] = (png_byte)i;
  183392. /* Find the least used palette entries by starting a
  183393. bubble sort, and running it until we have sorted
  183394. out enough colors. Note that we don't care about
  183395. sorting all the colors, just finding which are
  183396. least used. */
  183397. for (i = num_palette - 1; i >= maximum_colors; i--)
  183398. {
  183399. int done; /* to stop early if the list is pre-sorted */
  183400. int j;
  183401. done = 1;
  183402. for (j = 0; j < i; j++)
  183403. {
  183404. if (histogram[png_ptr->dither_sort[j]]
  183405. < histogram[png_ptr->dither_sort[j + 1]])
  183406. {
  183407. png_byte t;
  183408. t = png_ptr->dither_sort[j];
  183409. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  183410. png_ptr->dither_sort[j + 1] = t;
  183411. done = 0;
  183412. }
  183413. }
  183414. if (done)
  183415. break;
  183416. }
  183417. /* swap the palette around, and set up a table, if necessary */
  183418. if (full_dither)
  183419. {
  183420. int j = num_palette;
  183421. /* put all the useful colors within the max, but don't
  183422. move the others */
  183423. for (i = 0; i < maximum_colors; i++)
  183424. {
  183425. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  183426. {
  183427. do
  183428. j--;
  183429. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  183430. palette[i] = palette[j];
  183431. }
  183432. }
  183433. }
  183434. else
  183435. {
  183436. int j = num_palette;
  183437. /* move all the used colors inside the max limit, and
  183438. develop a translation table */
  183439. for (i = 0; i < maximum_colors; i++)
  183440. {
  183441. /* only move the colors we need to */
  183442. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  183443. {
  183444. png_color tmp_color;
  183445. do
  183446. j--;
  183447. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  183448. tmp_color = palette[j];
  183449. palette[j] = palette[i];
  183450. palette[i] = tmp_color;
  183451. /* indicate where the color went */
  183452. png_ptr->dither_index[j] = (png_byte)i;
  183453. png_ptr->dither_index[i] = (png_byte)j;
  183454. }
  183455. }
  183456. /* find closest color for those colors we are not using */
  183457. for (i = 0; i < num_palette; i++)
  183458. {
  183459. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  183460. {
  183461. int min_d, k, min_k, d_index;
  183462. /* find the closest color to one we threw out */
  183463. d_index = png_ptr->dither_index[i];
  183464. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  183465. for (k = 1, min_k = 0; k < maximum_colors; k++)
  183466. {
  183467. int d;
  183468. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  183469. if (d < min_d)
  183470. {
  183471. min_d = d;
  183472. min_k = k;
  183473. }
  183474. }
  183475. /* point to closest color */
  183476. png_ptr->dither_index[i] = (png_byte)min_k;
  183477. }
  183478. }
  183479. }
  183480. png_free(png_ptr, png_ptr->dither_sort);
  183481. png_ptr->dither_sort=NULL;
  183482. }
  183483. else
  183484. {
  183485. /* This is much harder to do simply (and quickly). Perhaps
  183486. we need to go through a median cut routine, but those
  183487. don't always behave themselves with only a few colors
  183488. as input. So we will just find the closest two colors,
  183489. and throw out one of them (chosen somewhat randomly).
  183490. [We don't understand this at all, so if someone wants to
  183491. work on improving it, be our guest - AED, GRP]
  183492. */
  183493. int i;
  183494. int max_d;
  183495. int num_new_palette;
  183496. png_dsortp t;
  183497. png_dsortpp hash;
  183498. t=NULL;
  183499. /* initialize palette index arrays */
  183500. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  183501. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183502. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  183503. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183504. /* initialize the sort array */
  183505. for (i = 0; i < num_palette; i++)
  183506. {
  183507. png_ptr->index_to_palette[i] = (png_byte)i;
  183508. png_ptr->palette_to_index[i] = (png_byte)i;
  183509. }
  183510. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  183511. png_sizeof (png_dsortp)));
  183512. for (i = 0; i < 769; i++)
  183513. hash[i] = NULL;
  183514. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  183515. num_new_palette = num_palette;
  183516. /* initial wild guess at how far apart the farthest pixel
  183517. pair we will be eliminating will be. Larger
  183518. numbers mean more areas will be allocated, Smaller
  183519. numbers run the risk of not saving enough data, and
  183520. having to do this all over again.
  183521. I have not done extensive checking on this number.
  183522. */
  183523. max_d = 96;
  183524. while (num_new_palette > maximum_colors)
  183525. {
  183526. for (i = 0; i < num_new_palette - 1; i++)
  183527. {
  183528. int j;
  183529. for (j = i + 1; j < num_new_palette; j++)
  183530. {
  183531. int d;
  183532. d = PNG_COLOR_DIST(palette[i], palette[j]);
  183533. if (d <= max_d)
  183534. {
  183535. t = (png_dsortp)png_malloc_warn(png_ptr,
  183536. (png_uint_32)(png_sizeof(png_dsort)));
  183537. if (t == NULL)
  183538. break;
  183539. t->next = hash[d];
  183540. t->left = (png_byte)i;
  183541. t->right = (png_byte)j;
  183542. hash[d] = t;
  183543. }
  183544. }
  183545. if (t == NULL)
  183546. break;
  183547. }
  183548. if (t != NULL)
  183549. for (i = 0; i <= max_d; i++)
  183550. {
  183551. if (hash[i] != NULL)
  183552. {
  183553. png_dsortp p;
  183554. for (p = hash[i]; p; p = p->next)
  183555. {
  183556. if ((int)png_ptr->index_to_palette[p->left]
  183557. < num_new_palette &&
  183558. (int)png_ptr->index_to_palette[p->right]
  183559. < num_new_palette)
  183560. {
  183561. int j, next_j;
  183562. if (num_new_palette & 0x01)
  183563. {
  183564. j = p->left;
  183565. next_j = p->right;
  183566. }
  183567. else
  183568. {
  183569. j = p->right;
  183570. next_j = p->left;
  183571. }
  183572. num_new_palette--;
  183573. palette[png_ptr->index_to_palette[j]]
  183574. = palette[num_new_palette];
  183575. if (!full_dither)
  183576. {
  183577. int k;
  183578. for (k = 0; k < num_palette; k++)
  183579. {
  183580. if (png_ptr->dither_index[k] ==
  183581. png_ptr->index_to_palette[j])
  183582. png_ptr->dither_index[k] =
  183583. png_ptr->index_to_palette[next_j];
  183584. if ((int)png_ptr->dither_index[k] ==
  183585. num_new_palette)
  183586. png_ptr->dither_index[k] =
  183587. png_ptr->index_to_palette[j];
  183588. }
  183589. }
  183590. png_ptr->index_to_palette[png_ptr->palette_to_index
  183591. [num_new_palette]] = png_ptr->index_to_palette[j];
  183592. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  183593. = png_ptr->palette_to_index[num_new_palette];
  183594. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  183595. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  183596. }
  183597. if (num_new_palette <= maximum_colors)
  183598. break;
  183599. }
  183600. if (num_new_palette <= maximum_colors)
  183601. break;
  183602. }
  183603. }
  183604. for (i = 0; i < 769; i++)
  183605. {
  183606. if (hash[i] != NULL)
  183607. {
  183608. png_dsortp p = hash[i];
  183609. while (p)
  183610. {
  183611. t = p->next;
  183612. png_free(png_ptr, p);
  183613. p = t;
  183614. }
  183615. }
  183616. hash[i] = 0;
  183617. }
  183618. max_d += 96;
  183619. }
  183620. png_free(png_ptr, hash);
  183621. png_free(png_ptr, png_ptr->palette_to_index);
  183622. png_free(png_ptr, png_ptr->index_to_palette);
  183623. png_ptr->palette_to_index=NULL;
  183624. png_ptr->index_to_palette=NULL;
  183625. }
  183626. num_palette = maximum_colors;
  183627. }
  183628. if (png_ptr->palette == NULL)
  183629. {
  183630. png_ptr->palette = palette;
  183631. }
  183632. png_ptr->num_palette = (png_uint_16)num_palette;
  183633. if (full_dither)
  183634. {
  183635. int i;
  183636. png_bytep distance;
  183637. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  183638. PNG_DITHER_BLUE_BITS;
  183639. int num_red = (1 << PNG_DITHER_RED_BITS);
  183640. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  183641. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  183642. png_size_t num_entries = ((png_size_t)1 << total_bits);
  183643. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  183644. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  183645. png_memset(png_ptr->palette_lookup, 0, num_entries *
  183646. png_sizeof (png_byte));
  183647. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  183648. png_sizeof(png_byte)));
  183649. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  183650. for (i = 0; i < num_palette; i++)
  183651. {
  183652. int ir, ig, ib;
  183653. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  183654. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  183655. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  183656. for (ir = 0; ir < num_red; ir++)
  183657. {
  183658. /* int dr = abs(ir - r); */
  183659. int dr = ((ir > r) ? ir - r : r - ir);
  183660. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  183661. for (ig = 0; ig < num_green; ig++)
  183662. {
  183663. /* int dg = abs(ig - g); */
  183664. int dg = ((ig > g) ? ig - g : g - ig);
  183665. int dt = dr + dg;
  183666. int dm = ((dr > dg) ? dr : dg);
  183667. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  183668. for (ib = 0; ib < num_blue; ib++)
  183669. {
  183670. int d_index = index_g | ib;
  183671. /* int db = abs(ib - b); */
  183672. int db = ((ib > b) ? ib - b : b - ib);
  183673. int dmax = ((dm > db) ? dm : db);
  183674. int d = dmax + dt + db;
  183675. if (d < (int)distance[d_index])
  183676. {
  183677. distance[d_index] = (png_byte)d;
  183678. png_ptr->palette_lookup[d_index] = (png_byte)i;
  183679. }
  183680. }
  183681. }
  183682. }
  183683. }
  183684. png_free(png_ptr, distance);
  183685. }
  183686. }
  183687. #endif
  183688. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183689. /* Transform the image from the file_gamma to the screen_gamma. We
  183690. * only do transformations on images where the file_gamma and screen_gamma
  183691. * are not close reciprocals, otherwise it slows things down slightly, and
  183692. * also needlessly introduces small errors.
  183693. *
  183694. * We will turn off gamma transformation later if no semitransparent entries
  183695. * are present in the tRNS array for palette images. We can't do it here
  183696. * because we don't necessarily have the tRNS chunk yet.
  183697. */
  183698. void PNGAPI
  183699. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  183700. {
  183701. png_debug(1, "in png_set_gamma\n");
  183702. if(png_ptr == NULL) return;
  183703. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  183704. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  183705. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  183706. png_ptr->transformations |= PNG_GAMMA;
  183707. png_ptr->gamma = (float)file_gamma;
  183708. png_ptr->screen_gamma = (float)scrn_gamma;
  183709. }
  183710. #endif
  183711. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183712. /* Expand paletted images to RGB, expand grayscale images of
  183713. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  183714. * to alpha channels.
  183715. */
  183716. void PNGAPI
  183717. png_set_expand(png_structp png_ptr)
  183718. {
  183719. png_debug(1, "in png_set_expand\n");
  183720. if(png_ptr == NULL) return;
  183721. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183722. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183723. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183724. #endif
  183725. }
  183726. /* GRR 19990627: the following three functions currently are identical
  183727. * to png_set_expand(). However, it is entirely reasonable that someone
  183728. * might wish to expand an indexed image to RGB but *not* expand a single,
  183729. * fully transparent palette entry to a full alpha channel--perhaps instead
  183730. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  183731. * the transparent color with a particular RGB value, or drop tRNS entirely.
  183732. * IOW, a future version of the library may make the transformations flag
  183733. * a bit more fine-grained, with separate bits for each of these three
  183734. * functions.
  183735. *
  183736. * More to the point, these functions make it obvious what libpng will be
  183737. * doing, whereas "expand" can (and does) mean any number of things.
  183738. *
  183739. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  183740. * to expand only the sample depth but not to expand the tRNS to alpha.
  183741. */
  183742. /* Expand paletted images to RGB. */
  183743. void PNGAPI
  183744. png_set_palette_to_rgb(png_structp png_ptr)
  183745. {
  183746. png_debug(1, "in png_set_palette_to_rgb\n");
  183747. if(png_ptr == NULL) return;
  183748. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183749. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183750. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  183751. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183752. #endif
  183753. }
  183754. #if !defined(PNG_1_0_X)
  183755. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  183756. void PNGAPI
  183757. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  183758. {
  183759. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  183760. if(png_ptr == NULL) return;
  183761. png_ptr->transformations |= PNG_EXPAND;
  183762. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183763. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183764. #endif
  183765. }
  183766. #endif
  183767. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183768. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  183769. /* Deprecated as of libpng-1.2.9 */
  183770. void PNGAPI
  183771. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  183772. {
  183773. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  183774. if(png_ptr == NULL) return;
  183775. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183776. }
  183777. #endif
  183778. /* Expand tRNS chunks to alpha channels. */
  183779. void PNGAPI
  183780. png_set_tRNS_to_alpha(png_structp png_ptr)
  183781. {
  183782. png_debug(1, "in png_set_tRNS_to_alpha\n");
  183783. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183784. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183785. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183786. #endif
  183787. }
  183788. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  183789. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183790. void PNGAPI
  183791. png_set_gray_to_rgb(png_structp png_ptr)
  183792. {
  183793. png_debug(1, "in png_set_gray_to_rgb\n");
  183794. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  183795. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183796. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183797. #endif
  183798. }
  183799. #endif
  183800. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183801. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  183802. /* Convert a RGB image to a grayscale of the same width. This allows us,
  183803. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  183804. */
  183805. void PNGAPI
  183806. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  183807. double green)
  183808. {
  183809. int red_fixed = (int)((float)red*100000.0 + 0.5);
  183810. int green_fixed = (int)((float)green*100000.0 + 0.5);
  183811. if(png_ptr == NULL) return;
  183812. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  183813. }
  183814. #endif
  183815. void PNGAPI
  183816. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  183817. png_fixed_point red, png_fixed_point green)
  183818. {
  183819. png_debug(1, "in png_set_rgb_to_gray\n");
  183820. if(png_ptr == NULL) return;
  183821. switch(error_action)
  183822. {
  183823. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  183824. break;
  183825. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  183826. break;
  183827. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  183828. }
  183829. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  183830. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183831. png_ptr->transformations |= PNG_EXPAND;
  183832. #else
  183833. {
  183834. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  183835. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  183836. }
  183837. #endif
  183838. {
  183839. png_uint_16 red_int, green_int;
  183840. if(red < 0 || green < 0)
  183841. {
  183842. red_int = 6968; /* .212671 * 32768 + .5 */
  183843. green_int = 23434; /* .715160 * 32768 + .5 */
  183844. }
  183845. else if(red + green < 100000L)
  183846. {
  183847. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  183848. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  183849. }
  183850. else
  183851. {
  183852. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  183853. red_int = 6968;
  183854. green_int = 23434;
  183855. }
  183856. png_ptr->rgb_to_gray_red_coeff = red_int;
  183857. png_ptr->rgb_to_gray_green_coeff = green_int;
  183858. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  183859. }
  183860. }
  183861. #endif
  183862. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183863. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183864. defined(PNG_LEGACY_SUPPORTED)
  183865. void PNGAPI
  183866. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  183867. read_user_transform_fn)
  183868. {
  183869. png_debug(1, "in png_set_read_user_transform_fn\n");
  183870. if(png_ptr == NULL) return;
  183871. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  183872. png_ptr->transformations |= PNG_USER_TRANSFORM;
  183873. png_ptr->read_user_transform_fn = read_user_transform_fn;
  183874. #endif
  183875. #ifdef PNG_LEGACY_SUPPORTED
  183876. if(read_user_transform_fn)
  183877. png_warning(png_ptr,
  183878. "This version of libpng does not support user transforms");
  183879. #endif
  183880. }
  183881. #endif
  183882. /* Initialize everything needed for the read. This includes modifying
  183883. * the palette.
  183884. */
  183885. void /* PRIVATE */
  183886. png_init_read_transformations(png_structp png_ptr)
  183887. {
  183888. png_debug(1, "in png_init_read_transformations\n");
  183889. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  183890. if(png_ptr != NULL)
  183891. #endif
  183892. {
  183893. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  183894. || defined(PNG_READ_GAMMA_SUPPORTED)
  183895. int color_type = png_ptr->color_type;
  183896. #endif
  183897. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  183898. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183899. /* Detect gray background and attempt to enable optimization
  183900. * for gray --> RGB case */
  183901. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  183902. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  183903. * background color might actually be gray yet not be flagged as such.
  183904. * This is not a problem for the current code, which uses
  183905. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  183906. * png_do_gray_to_rgb() transformation.
  183907. */
  183908. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183909. !(color_type & PNG_COLOR_MASK_COLOR))
  183910. {
  183911. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  183912. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  183913. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183914. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  183915. png_ptr->background.red == png_ptr->background.green &&
  183916. png_ptr->background.red == png_ptr->background.blue)
  183917. {
  183918. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  183919. png_ptr->background.gray = png_ptr->background.red;
  183920. }
  183921. #endif
  183922. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183923. (png_ptr->transformations & PNG_EXPAND))
  183924. {
  183925. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  183926. {
  183927. /* expand background and tRNS chunks */
  183928. switch (png_ptr->bit_depth)
  183929. {
  183930. case 1:
  183931. png_ptr->background.gray *= (png_uint_16)0xff;
  183932. png_ptr->background.red = png_ptr->background.green
  183933. = png_ptr->background.blue = png_ptr->background.gray;
  183934. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183935. {
  183936. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  183937. png_ptr->trans_values.red = png_ptr->trans_values.green
  183938. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183939. }
  183940. break;
  183941. case 2:
  183942. png_ptr->background.gray *= (png_uint_16)0x55;
  183943. png_ptr->background.red = png_ptr->background.green
  183944. = png_ptr->background.blue = png_ptr->background.gray;
  183945. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183946. {
  183947. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  183948. png_ptr->trans_values.red = png_ptr->trans_values.green
  183949. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183950. }
  183951. break;
  183952. case 4:
  183953. png_ptr->background.gray *= (png_uint_16)0x11;
  183954. png_ptr->background.red = png_ptr->background.green
  183955. = png_ptr->background.blue = png_ptr->background.gray;
  183956. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183957. {
  183958. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  183959. png_ptr->trans_values.red = png_ptr->trans_values.green
  183960. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183961. }
  183962. break;
  183963. case 8:
  183964. case 16:
  183965. png_ptr->background.red = png_ptr->background.green
  183966. = png_ptr->background.blue = png_ptr->background.gray;
  183967. break;
  183968. }
  183969. }
  183970. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  183971. {
  183972. png_ptr->background.red =
  183973. png_ptr->palette[png_ptr->background.index].red;
  183974. png_ptr->background.green =
  183975. png_ptr->palette[png_ptr->background.index].green;
  183976. png_ptr->background.blue =
  183977. png_ptr->palette[png_ptr->background.index].blue;
  183978. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183979. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  183980. {
  183981. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183982. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183983. #endif
  183984. {
  183985. /* invert the alpha channel (in tRNS) unless the pixels are
  183986. going to be expanded, in which case leave it for later */
  183987. int i,istop;
  183988. istop=(int)png_ptr->num_trans;
  183989. for (i=0; i<istop; i++)
  183990. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  183991. }
  183992. }
  183993. #endif
  183994. }
  183995. }
  183996. #endif
  183997. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  183998. png_ptr->background_1 = png_ptr->background;
  183999. #endif
  184000. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184001. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  184002. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  184003. < PNG_GAMMA_THRESHOLD))
  184004. {
  184005. int i,k;
  184006. k=0;
  184007. for (i=0; i<png_ptr->num_trans; i++)
  184008. {
  184009. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  184010. k=1; /* partial transparency is present */
  184011. }
  184012. if (k == 0)
  184013. png_ptr->transformations &= (~PNG_GAMMA);
  184014. }
  184015. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  184016. png_ptr->gamma != 0.0)
  184017. {
  184018. png_build_gamma_table(png_ptr);
  184019. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184020. if (png_ptr->transformations & PNG_BACKGROUND)
  184021. {
  184022. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184023. {
  184024. /* could skip if no transparency and
  184025. */
  184026. png_color back, back_1;
  184027. png_colorp palette = png_ptr->palette;
  184028. int num_palette = png_ptr->num_palette;
  184029. int i;
  184030. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  184031. {
  184032. back.red = png_ptr->gamma_table[png_ptr->background.red];
  184033. back.green = png_ptr->gamma_table[png_ptr->background.green];
  184034. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  184035. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  184036. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  184037. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  184038. }
  184039. else
  184040. {
  184041. double g, gs;
  184042. switch (png_ptr->background_gamma_type)
  184043. {
  184044. case PNG_BACKGROUND_GAMMA_SCREEN:
  184045. g = (png_ptr->screen_gamma);
  184046. gs = 1.0;
  184047. break;
  184048. case PNG_BACKGROUND_GAMMA_FILE:
  184049. g = 1.0 / (png_ptr->gamma);
  184050. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184051. break;
  184052. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184053. g = 1.0 / (png_ptr->background_gamma);
  184054. gs = 1.0 / (png_ptr->background_gamma *
  184055. png_ptr->screen_gamma);
  184056. break;
  184057. default:
  184058. g = 1.0; /* back_1 */
  184059. gs = 1.0; /* back */
  184060. }
  184061. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  184062. {
  184063. back.red = (png_byte)png_ptr->background.red;
  184064. back.green = (png_byte)png_ptr->background.green;
  184065. back.blue = (png_byte)png_ptr->background.blue;
  184066. }
  184067. else
  184068. {
  184069. back.red = (png_byte)(pow(
  184070. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  184071. back.green = (png_byte)(pow(
  184072. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  184073. back.blue = (png_byte)(pow(
  184074. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  184075. }
  184076. back_1.red = (png_byte)(pow(
  184077. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  184078. back_1.green = (png_byte)(pow(
  184079. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  184080. back_1.blue = (png_byte)(pow(
  184081. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  184082. }
  184083. for (i = 0; i < num_palette; i++)
  184084. {
  184085. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  184086. {
  184087. if (png_ptr->trans[i] == 0)
  184088. {
  184089. palette[i] = back;
  184090. }
  184091. else /* if (png_ptr->trans[i] != 0xff) */
  184092. {
  184093. png_byte v, w;
  184094. v = png_ptr->gamma_to_1[palette[i].red];
  184095. png_composite(w, v, png_ptr->trans[i], back_1.red);
  184096. palette[i].red = png_ptr->gamma_from_1[w];
  184097. v = png_ptr->gamma_to_1[palette[i].green];
  184098. png_composite(w, v, png_ptr->trans[i], back_1.green);
  184099. palette[i].green = png_ptr->gamma_from_1[w];
  184100. v = png_ptr->gamma_to_1[palette[i].blue];
  184101. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  184102. palette[i].blue = png_ptr->gamma_from_1[w];
  184103. }
  184104. }
  184105. else
  184106. {
  184107. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184108. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184109. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184110. }
  184111. }
  184112. }
  184113. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  184114. else
  184115. /* color_type != PNG_COLOR_TYPE_PALETTE */
  184116. {
  184117. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  184118. double g = 1.0;
  184119. double gs = 1.0;
  184120. switch (png_ptr->background_gamma_type)
  184121. {
  184122. case PNG_BACKGROUND_GAMMA_SCREEN:
  184123. g = (png_ptr->screen_gamma);
  184124. gs = 1.0;
  184125. break;
  184126. case PNG_BACKGROUND_GAMMA_FILE:
  184127. g = 1.0 / (png_ptr->gamma);
  184128. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184129. break;
  184130. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184131. g = 1.0 / (png_ptr->background_gamma);
  184132. gs = 1.0 / (png_ptr->background_gamma *
  184133. png_ptr->screen_gamma);
  184134. break;
  184135. }
  184136. png_ptr->background_1.gray = (png_uint_16)(pow(
  184137. (double)png_ptr->background.gray / m, g) * m + .5);
  184138. png_ptr->background.gray = (png_uint_16)(pow(
  184139. (double)png_ptr->background.gray / m, gs) * m + .5);
  184140. if ((png_ptr->background.red != png_ptr->background.green) ||
  184141. (png_ptr->background.red != png_ptr->background.blue) ||
  184142. (png_ptr->background.red != png_ptr->background.gray))
  184143. {
  184144. /* RGB or RGBA with color background */
  184145. png_ptr->background_1.red = (png_uint_16)(pow(
  184146. (double)png_ptr->background.red / m, g) * m + .5);
  184147. png_ptr->background_1.green = (png_uint_16)(pow(
  184148. (double)png_ptr->background.green / m, g) * m + .5);
  184149. png_ptr->background_1.blue = (png_uint_16)(pow(
  184150. (double)png_ptr->background.blue / m, g) * m + .5);
  184151. png_ptr->background.red = (png_uint_16)(pow(
  184152. (double)png_ptr->background.red / m, gs) * m + .5);
  184153. png_ptr->background.green = (png_uint_16)(pow(
  184154. (double)png_ptr->background.green / m, gs) * m + .5);
  184155. png_ptr->background.blue = (png_uint_16)(pow(
  184156. (double)png_ptr->background.blue / m, gs) * m + .5);
  184157. }
  184158. else
  184159. {
  184160. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  184161. png_ptr->background_1.red = png_ptr->background_1.green
  184162. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  184163. png_ptr->background.red = png_ptr->background.green
  184164. = png_ptr->background.blue = png_ptr->background.gray;
  184165. }
  184166. }
  184167. }
  184168. else
  184169. /* transformation does not include PNG_BACKGROUND */
  184170. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184171. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184172. {
  184173. png_colorp palette = png_ptr->palette;
  184174. int num_palette = png_ptr->num_palette;
  184175. int i;
  184176. for (i = 0; i < num_palette; i++)
  184177. {
  184178. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184179. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184180. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184181. }
  184182. }
  184183. }
  184184. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184185. else
  184186. #endif
  184187. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  184188. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184189. /* No GAMMA transformation */
  184190. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184191. (color_type == PNG_COLOR_TYPE_PALETTE))
  184192. {
  184193. int i;
  184194. int istop = (int)png_ptr->num_trans;
  184195. png_color back;
  184196. png_colorp palette = png_ptr->palette;
  184197. back.red = (png_byte)png_ptr->background.red;
  184198. back.green = (png_byte)png_ptr->background.green;
  184199. back.blue = (png_byte)png_ptr->background.blue;
  184200. for (i = 0; i < istop; i++)
  184201. {
  184202. if (png_ptr->trans[i] == 0)
  184203. {
  184204. palette[i] = back;
  184205. }
  184206. else if (png_ptr->trans[i] != 0xff)
  184207. {
  184208. /* The png_composite() macro is defined in png.h */
  184209. png_composite(palette[i].red, palette[i].red,
  184210. png_ptr->trans[i], back.red);
  184211. png_composite(palette[i].green, palette[i].green,
  184212. png_ptr->trans[i], back.green);
  184213. png_composite(palette[i].blue, palette[i].blue,
  184214. png_ptr->trans[i], back.blue);
  184215. }
  184216. }
  184217. }
  184218. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184219. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184220. if ((png_ptr->transformations & PNG_SHIFT) &&
  184221. (color_type == PNG_COLOR_TYPE_PALETTE))
  184222. {
  184223. png_uint_16 i;
  184224. png_uint_16 istop = png_ptr->num_palette;
  184225. int sr = 8 - png_ptr->sig_bit.red;
  184226. int sg = 8 - png_ptr->sig_bit.green;
  184227. int sb = 8 - png_ptr->sig_bit.blue;
  184228. if (sr < 0 || sr > 8)
  184229. sr = 0;
  184230. if (sg < 0 || sg > 8)
  184231. sg = 0;
  184232. if (sb < 0 || sb > 8)
  184233. sb = 0;
  184234. for (i = 0; i < istop; i++)
  184235. {
  184236. png_ptr->palette[i].red >>= sr;
  184237. png_ptr->palette[i].green >>= sg;
  184238. png_ptr->palette[i].blue >>= sb;
  184239. }
  184240. }
  184241. #endif /* PNG_READ_SHIFT_SUPPORTED */
  184242. }
  184243. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  184244. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  184245. if(png_ptr)
  184246. return;
  184247. #endif
  184248. }
  184249. /* Modify the info structure to reflect the transformations. The
  184250. * info should be updated so a PNG file could be written with it,
  184251. * assuming the transformations result in valid PNG data.
  184252. */
  184253. void /* PRIVATE */
  184254. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  184255. {
  184256. png_debug(1, "in png_read_transform_info\n");
  184257. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184258. if (png_ptr->transformations & PNG_EXPAND)
  184259. {
  184260. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184261. {
  184262. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  184263. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  184264. else
  184265. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  184266. info_ptr->bit_depth = 8;
  184267. info_ptr->num_trans = 0;
  184268. }
  184269. else
  184270. {
  184271. if (png_ptr->num_trans)
  184272. {
  184273. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  184274. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184275. else
  184276. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  184277. }
  184278. if (info_ptr->bit_depth < 8)
  184279. info_ptr->bit_depth = 8;
  184280. info_ptr->num_trans = 0;
  184281. }
  184282. }
  184283. #endif
  184284. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184285. if (png_ptr->transformations & PNG_BACKGROUND)
  184286. {
  184287. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  184288. info_ptr->num_trans = 0;
  184289. info_ptr->background = png_ptr->background;
  184290. }
  184291. #endif
  184292. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184293. if (png_ptr->transformations & PNG_GAMMA)
  184294. {
  184295. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184296. info_ptr->gamma = png_ptr->gamma;
  184297. #endif
  184298. #ifdef PNG_FIXED_POINT_SUPPORTED
  184299. info_ptr->int_gamma = png_ptr->int_gamma;
  184300. #endif
  184301. }
  184302. #endif
  184303. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184304. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  184305. info_ptr->bit_depth = 8;
  184306. #endif
  184307. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184308. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  184309. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  184310. #endif
  184311. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184312. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  184313. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  184314. #endif
  184315. #if defined(PNG_READ_DITHER_SUPPORTED)
  184316. if (png_ptr->transformations & PNG_DITHER)
  184317. {
  184318. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  184319. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  184320. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  184321. {
  184322. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  184323. }
  184324. }
  184325. #endif
  184326. #if defined(PNG_READ_PACK_SUPPORTED)
  184327. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  184328. info_ptr->bit_depth = 8;
  184329. #endif
  184330. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184331. info_ptr->channels = 1;
  184332. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  184333. info_ptr->channels = 3;
  184334. else
  184335. info_ptr->channels = 1;
  184336. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184337. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  184338. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  184339. #endif
  184340. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  184341. info_ptr->channels++;
  184342. #if defined(PNG_READ_FILLER_SUPPORTED)
  184343. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  184344. if ((png_ptr->transformations & PNG_FILLER) &&
  184345. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  184346. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  184347. {
  184348. info_ptr->channels++;
  184349. /* if adding a true alpha channel not just filler */
  184350. #if !defined(PNG_1_0_X)
  184351. if (png_ptr->transformations & PNG_ADD_ALPHA)
  184352. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184353. #endif
  184354. }
  184355. #endif
  184356. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  184357. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184358. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  184359. {
  184360. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  184361. info_ptr->bit_depth = png_ptr->user_transform_depth;
  184362. if(info_ptr->channels < png_ptr->user_transform_channels)
  184363. info_ptr->channels = png_ptr->user_transform_channels;
  184364. }
  184365. #endif
  184366. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  184367. info_ptr->bit_depth);
  184368. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  184369. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  184370. if(png_ptr)
  184371. return;
  184372. #endif
  184373. }
  184374. /* Transform the row. The order of transformations is significant,
  184375. * and is very touchy. If you add a transformation, take care to
  184376. * decide how it fits in with the other transformations here.
  184377. */
  184378. void /* PRIVATE */
  184379. png_do_read_transformations(png_structp png_ptr)
  184380. {
  184381. png_debug(1, "in png_do_read_transformations\n");
  184382. if (png_ptr->row_buf == NULL)
  184383. {
  184384. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184385. char msg[50];
  184386. png_snprintf2(msg, 50,
  184387. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  184388. png_ptr->pass);
  184389. png_error(png_ptr, msg);
  184390. #else
  184391. png_error(png_ptr, "NULL row buffer");
  184392. #endif
  184393. }
  184394. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184395. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184396. /* Application has failed to call either png_read_start_image()
  184397. * or png_read_update_info() after setting transforms that expand
  184398. * pixels. This check added to libpng-1.2.19 */
  184399. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  184400. png_error(png_ptr, "Uninitialized row");
  184401. #else
  184402. png_warning(png_ptr, "Uninitialized row");
  184403. #endif
  184404. #endif
  184405. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184406. if (png_ptr->transformations & PNG_EXPAND)
  184407. {
  184408. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  184409. {
  184410. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184411. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  184412. }
  184413. else
  184414. {
  184415. if (png_ptr->num_trans &&
  184416. (png_ptr->transformations & PNG_EXPAND_tRNS))
  184417. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184418. &(png_ptr->trans_values));
  184419. else
  184420. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184421. NULL);
  184422. }
  184423. }
  184424. #endif
  184425. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184426. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  184427. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184428. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  184429. #endif
  184430. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184431. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  184432. {
  184433. int rgb_error =
  184434. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  184435. if(rgb_error)
  184436. {
  184437. png_ptr->rgb_to_gray_status=1;
  184438. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  184439. PNG_RGB_TO_GRAY_WARN)
  184440. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  184441. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  184442. PNG_RGB_TO_GRAY_ERR)
  184443. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  184444. }
  184445. }
  184446. #endif
  184447. /*
  184448. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  184449. In most cases, the "simple transparency" should be done prior to doing
  184450. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  184451. pixel is transparent. You would also need to make sure that the
  184452. transparency information is upgraded to RGB.
  184453. To summarize, the current flow is:
  184454. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  184455. with background "in place" if transparent,
  184456. convert to RGB if necessary
  184457. - Gray + alpha -> composite with gray background and remove alpha bytes,
  184458. convert to RGB if necessary
  184459. To support RGB backgrounds for gray images we need:
  184460. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  184461. 3 or 6 bytes and composite with background
  184462. "in place" if transparent (3x compare/pixel
  184463. compared to doing composite with gray bkgrnd)
  184464. - Gray + alpha -> convert to RGB + alpha, composite with background and
  184465. remove alpha bytes (3x float operations/pixel
  184466. compared with composite on gray background)
  184467. Greg's change will do this. The reason it wasn't done before is for
  184468. performance, as this increases the per-pixel operations. If we would check
  184469. in advance if the background was gray or RGB, and position the gray-to-RGB
  184470. transform appropriately, then it would save a lot of work/time.
  184471. */
  184472. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184473. /* if gray -> RGB, do so now only if background is non-gray; else do later
  184474. * for performance reasons */
  184475. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184476. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  184477. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184478. #endif
  184479. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184480. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184481. ((png_ptr->num_trans != 0 ) ||
  184482. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  184483. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184484. &(png_ptr->trans_values), &(png_ptr->background)
  184485. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184486. , &(png_ptr->background_1),
  184487. png_ptr->gamma_table, png_ptr->gamma_from_1,
  184488. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  184489. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  184490. png_ptr->gamma_shift
  184491. #endif
  184492. );
  184493. #endif
  184494. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184495. if ((png_ptr->transformations & PNG_GAMMA) &&
  184496. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184497. !((png_ptr->transformations & PNG_BACKGROUND) &&
  184498. ((png_ptr->num_trans != 0) ||
  184499. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  184500. #endif
  184501. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  184502. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184503. png_ptr->gamma_table, png_ptr->gamma_16_table,
  184504. png_ptr->gamma_shift);
  184505. #endif
  184506. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184507. if (png_ptr->transformations & PNG_16_TO_8)
  184508. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184509. #endif
  184510. #if defined(PNG_READ_DITHER_SUPPORTED)
  184511. if (png_ptr->transformations & PNG_DITHER)
  184512. {
  184513. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  184514. png_ptr->palette_lookup, png_ptr->dither_index);
  184515. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  184516. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  184517. }
  184518. #endif
  184519. #if defined(PNG_READ_INVERT_SUPPORTED)
  184520. if (png_ptr->transformations & PNG_INVERT_MONO)
  184521. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184522. #endif
  184523. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184524. if (png_ptr->transformations & PNG_SHIFT)
  184525. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184526. &(png_ptr->shift));
  184527. #endif
  184528. #if defined(PNG_READ_PACK_SUPPORTED)
  184529. if (png_ptr->transformations & PNG_PACK)
  184530. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184531. #endif
  184532. #if defined(PNG_READ_BGR_SUPPORTED)
  184533. if (png_ptr->transformations & PNG_BGR)
  184534. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184535. #endif
  184536. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  184537. if (png_ptr->transformations & PNG_PACKSWAP)
  184538. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184539. #endif
  184540. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184541. /* if gray -> RGB, do so now only if we did not do so above */
  184542. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184543. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  184544. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184545. #endif
  184546. #if defined(PNG_READ_FILLER_SUPPORTED)
  184547. if (png_ptr->transformations & PNG_FILLER)
  184548. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184549. (png_uint_32)png_ptr->filler, png_ptr->flags);
  184550. #endif
  184551. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184552. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  184553. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184554. #endif
  184555. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184556. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  184557. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184558. #endif
  184559. #if defined(PNG_READ_SWAP_SUPPORTED)
  184560. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184561. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184562. #endif
  184563. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184564. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  184565. {
  184566. if(png_ptr->read_user_transform_fn != NULL)
  184567. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  184568. (png_ptr, /* png_ptr */
  184569. &(png_ptr->row_info), /* row_info: */
  184570. /* png_uint_32 width; width of row */
  184571. /* png_uint_32 rowbytes; number of bytes in row */
  184572. /* png_byte color_type; color type of pixels */
  184573. /* png_byte bit_depth; bit depth of samples */
  184574. /* png_byte channels; number of channels (1-4) */
  184575. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  184576. png_ptr->row_buf + 1); /* start of pixel data for row */
  184577. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  184578. if(png_ptr->user_transform_depth)
  184579. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  184580. if(png_ptr->user_transform_channels)
  184581. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  184582. #endif
  184583. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  184584. png_ptr->row_info.channels);
  184585. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184586. png_ptr->row_info.width);
  184587. }
  184588. #endif
  184589. }
  184590. #if defined(PNG_READ_PACK_SUPPORTED)
  184591. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  184592. * without changing the actual values. Thus, if you had a row with
  184593. * a bit depth of 1, you would end up with bytes that only contained
  184594. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  184595. * png_do_shift() after this.
  184596. */
  184597. void /* PRIVATE */
  184598. png_do_unpack(png_row_infop row_info, png_bytep row)
  184599. {
  184600. png_debug(1, "in png_do_unpack\n");
  184601. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184602. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  184603. #else
  184604. if (row_info->bit_depth < 8)
  184605. #endif
  184606. {
  184607. png_uint_32 i;
  184608. png_uint_32 row_width=row_info->width;
  184609. switch (row_info->bit_depth)
  184610. {
  184611. case 1:
  184612. {
  184613. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  184614. png_bytep dp = row + (png_size_t)row_width - 1;
  184615. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  184616. for (i = 0; i < row_width; i++)
  184617. {
  184618. *dp = (png_byte)((*sp >> shift) & 0x01);
  184619. if (shift == 7)
  184620. {
  184621. shift = 0;
  184622. sp--;
  184623. }
  184624. else
  184625. shift++;
  184626. dp--;
  184627. }
  184628. break;
  184629. }
  184630. case 2:
  184631. {
  184632. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  184633. png_bytep dp = row + (png_size_t)row_width - 1;
  184634. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  184635. for (i = 0; i < row_width; i++)
  184636. {
  184637. *dp = (png_byte)((*sp >> shift) & 0x03);
  184638. if (shift == 6)
  184639. {
  184640. shift = 0;
  184641. sp--;
  184642. }
  184643. else
  184644. shift += 2;
  184645. dp--;
  184646. }
  184647. break;
  184648. }
  184649. case 4:
  184650. {
  184651. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  184652. png_bytep dp = row + (png_size_t)row_width - 1;
  184653. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  184654. for (i = 0; i < row_width; i++)
  184655. {
  184656. *dp = (png_byte)((*sp >> shift) & 0x0f);
  184657. if (shift == 4)
  184658. {
  184659. shift = 0;
  184660. sp--;
  184661. }
  184662. else
  184663. shift = 4;
  184664. dp--;
  184665. }
  184666. break;
  184667. }
  184668. }
  184669. row_info->bit_depth = 8;
  184670. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  184671. row_info->rowbytes = row_width * row_info->channels;
  184672. }
  184673. }
  184674. #endif
  184675. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184676. /* Reverse the effects of png_do_shift. This routine merely shifts the
  184677. * pixels back to their significant bits values. Thus, if you have
  184678. * a row of bit depth 8, but only 5 are significant, this will shift
  184679. * the values back to 0 through 31.
  184680. */
  184681. void /* PRIVATE */
  184682. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  184683. {
  184684. png_debug(1, "in png_do_unshift\n");
  184685. if (
  184686. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184687. row != NULL && row_info != NULL && sig_bits != NULL &&
  184688. #endif
  184689. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  184690. {
  184691. int shift[4];
  184692. int channels = 0;
  184693. int c;
  184694. png_uint_16 value = 0;
  184695. png_uint_32 row_width = row_info->width;
  184696. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  184697. {
  184698. shift[channels++] = row_info->bit_depth - sig_bits->red;
  184699. shift[channels++] = row_info->bit_depth - sig_bits->green;
  184700. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  184701. }
  184702. else
  184703. {
  184704. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  184705. }
  184706. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  184707. {
  184708. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  184709. }
  184710. for (c = 0; c < channels; c++)
  184711. {
  184712. if (shift[c] <= 0)
  184713. shift[c] = 0;
  184714. else
  184715. value = 1;
  184716. }
  184717. if (!value)
  184718. return;
  184719. switch (row_info->bit_depth)
  184720. {
  184721. case 2:
  184722. {
  184723. png_bytep bp;
  184724. png_uint_32 i;
  184725. png_uint_32 istop = row_info->rowbytes;
  184726. for (bp = row, i = 0; i < istop; i++)
  184727. {
  184728. *bp >>= 1;
  184729. *bp++ &= 0x55;
  184730. }
  184731. break;
  184732. }
  184733. case 4:
  184734. {
  184735. png_bytep bp = row;
  184736. png_uint_32 i;
  184737. png_uint_32 istop = row_info->rowbytes;
  184738. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  184739. (png_byte)((int)0xf >> shift[0]));
  184740. for (i = 0; i < istop; i++)
  184741. {
  184742. *bp >>= shift[0];
  184743. *bp++ &= mask;
  184744. }
  184745. break;
  184746. }
  184747. case 8:
  184748. {
  184749. png_bytep bp = row;
  184750. png_uint_32 i;
  184751. png_uint_32 istop = row_width * channels;
  184752. for (i = 0; i < istop; i++)
  184753. {
  184754. *bp++ >>= shift[i%channels];
  184755. }
  184756. break;
  184757. }
  184758. case 16:
  184759. {
  184760. png_bytep bp = row;
  184761. png_uint_32 i;
  184762. png_uint_32 istop = channels * row_width;
  184763. for (i = 0; i < istop; i++)
  184764. {
  184765. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  184766. value >>= shift[i%channels];
  184767. *bp++ = (png_byte)(value >> 8);
  184768. *bp++ = (png_byte)(value & 0xff);
  184769. }
  184770. break;
  184771. }
  184772. }
  184773. }
  184774. }
  184775. #endif
  184776. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184777. /* chop rows of bit depth 16 down to 8 */
  184778. void /* PRIVATE */
  184779. png_do_chop(png_row_infop row_info, png_bytep row)
  184780. {
  184781. png_debug(1, "in png_do_chop\n");
  184782. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184783. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  184784. #else
  184785. if (row_info->bit_depth == 16)
  184786. #endif
  184787. {
  184788. png_bytep sp = row;
  184789. png_bytep dp = row;
  184790. png_uint_32 i;
  184791. png_uint_32 istop = row_info->width * row_info->channels;
  184792. for (i = 0; i<istop; i++, sp += 2, dp++)
  184793. {
  184794. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  184795. /* This does a more accurate scaling of the 16-bit color
  184796. * value, rather than a simple low-byte truncation.
  184797. *
  184798. * What the ideal calculation should be:
  184799. * *dp = (((((png_uint_32)(*sp) << 8) |
  184800. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  184801. *
  184802. * GRR: no, I think this is what it really should be:
  184803. * *dp = (((((png_uint_32)(*sp) << 8) |
  184804. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  184805. *
  184806. * GRR: here's the exact calculation with shifts:
  184807. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  184808. * *dp = (temp - (temp >> 8)) >> 8;
  184809. *
  184810. * Approximate calculation with shift/add instead of multiply/divide:
  184811. * *dp = ((((png_uint_32)(*sp) << 8) |
  184812. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  184813. *
  184814. * What we actually do to avoid extra shifting and conversion:
  184815. */
  184816. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  184817. #else
  184818. /* Simply discard the low order byte */
  184819. *dp = *sp;
  184820. #endif
  184821. }
  184822. row_info->bit_depth = 8;
  184823. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  184824. row_info->rowbytes = row_info->width * row_info->channels;
  184825. }
  184826. }
  184827. #endif
  184828. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184829. void /* PRIVATE */
  184830. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  184831. {
  184832. png_debug(1, "in png_do_read_swap_alpha\n");
  184833. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184834. if (row != NULL && row_info != NULL)
  184835. #endif
  184836. {
  184837. png_uint_32 row_width = row_info->width;
  184838. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  184839. {
  184840. /* This converts from RGBA to ARGB */
  184841. if (row_info->bit_depth == 8)
  184842. {
  184843. png_bytep sp = row + row_info->rowbytes;
  184844. png_bytep dp = sp;
  184845. png_byte save;
  184846. png_uint_32 i;
  184847. for (i = 0; i < row_width; i++)
  184848. {
  184849. save = *(--sp);
  184850. *(--dp) = *(--sp);
  184851. *(--dp) = *(--sp);
  184852. *(--dp) = *(--sp);
  184853. *(--dp) = save;
  184854. }
  184855. }
  184856. /* This converts from RRGGBBAA to AARRGGBB */
  184857. else
  184858. {
  184859. png_bytep sp = row + row_info->rowbytes;
  184860. png_bytep dp = sp;
  184861. png_byte save[2];
  184862. png_uint_32 i;
  184863. for (i = 0; i < row_width; i++)
  184864. {
  184865. save[0] = *(--sp);
  184866. save[1] = *(--sp);
  184867. *(--dp) = *(--sp);
  184868. *(--dp) = *(--sp);
  184869. *(--dp) = *(--sp);
  184870. *(--dp) = *(--sp);
  184871. *(--dp) = *(--sp);
  184872. *(--dp) = *(--sp);
  184873. *(--dp) = save[0];
  184874. *(--dp) = save[1];
  184875. }
  184876. }
  184877. }
  184878. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  184879. {
  184880. /* This converts from GA to AG */
  184881. if (row_info->bit_depth == 8)
  184882. {
  184883. png_bytep sp = row + row_info->rowbytes;
  184884. png_bytep dp = sp;
  184885. png_byte save;
  184886. png_uint_32 i;
  184887. for (i = 0; i < row_width; i++)
  184888. {
  184889. save = *(--sp);
  184890. *(--dp) = *(--sp);
  184891. *(--dp) = save;
  184892. }
  184893. }
  184894. /* This converts from GGAA to AAGG */
  184895. else
  184896. {
  184897. png_bytep sp = row + row_info->rowbytes;
  184898. png_bytep dp = sp;
  184899. png_byte save[2];
  184900. png_uint_32 i;
  184901. for (i = 0; i < row_width; i++)
  184902. {
  184903. save[0] = *(--sp);
  184904. save[1] = *(--sp);
  184905. *(--dp) = *(--sp);
  184906. *(--dp) = *(--sp);
  184907. *(--dp) = save[0];
  184908. *(--dp) = save[1];
  184909. }
  184910. }
  184911. }
  184912. }
  184913. }
  184914. #endif
  184915. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184916. void /* PRIVATE */
  184917. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  184918. {
  184919. png_debug(1, "in png_do_read_invert_alpha\n");
  184920. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184921. if (row != NULL && row_info != NULL)
  184922. #endif
  184923. {
  184924. png_uint_32 row_width = row_info->width;
  184925. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  184926. {
  184927. /* This inverts the alpha channel in RGBA */
  184928. if (row_info->bit_depth == 8)
  184929. {
  184930. png_bytep sp = row + row_info->rowbytes;
  184931. png_bytep dp = sp;
  184932. png_uint_32 i;
  184933. for (i = 0; i < row_width; i++)
  184934. {
  184935. *(--dp) = (png_byte)(255 - *(--sp));
  184936. /* This does nothing:
  184937. *(--dp) = *(--sp);
  184938. *(--dp) = *(--sp);
  184939. *(--dp) = *(--sp);
  184940. We can replace it with:
  184941. */
  184942. sp-=3;
  184943. dp=sp;
  184944. }
  184945. }
  184946. /* This inverts the alpha channel in RRGGBBAA */
  184947. else
  184948. {
  184949. png_bytep sp = row + row_info->rowbytes;
  184950. png_bytep dp = sp;
  184951. png_uint_32 i;
  184952. for (i = 0; i < row_width; i++)
  184953. {
  184954. *(--dp) = (png_byte)(255 - *(--sp));
  184955. *(--dp) = (png_byte)(255 - *(--sp));
  184956. /* This does nothing:
  184957. *(--dp) = *(--sp);
  184958. *(--dp) = *(--sp);
  184959. *(--dp) = *(--sp);
  184960. *(--dp) = *(--sp);
  184961. *(--dp) = *(--sp);
  184962. *(--dp) = *(--sp);
  184963. We can replace it with:
  184964. */
  184965. sp-=6;
  184966. dp=sp;
  184967. }
  184968. }
  184969. }
  184970. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  184971. {
  184972. /* This inverts the alpha channel in GA */
  184973. if (row_info->bit_depth == 8)
  184974. {
  184975. png_bytep sp = row + row_info->rowbytes;
  184976. png_bytep dp = sp;
  184977. png_uint_32 i;
  184978. for (i = 0; i < row_width; i++)
  184979. {
  184980. *(--dp) = (png_byte)(255 - *(--sp));
  184981. *(--dp) = *(--sp);
  184982. }
  184983. }
  184984. /* This inverts the alpha channel in GGAA */
  184985. else
  184986. {
  184987. png_bytep sp = row + row_info->rowbytes;
  184988. png_bytep dp = sp;
  184989. png_uint_32 i;
  184990. for (i = 0; i < row_width; i++)
  184991. {
  184992. *(--dp) = (png_byte)(255 - *(--sp));
  184993. *(--dp) = (png_byte)(255 - *(--sp));
  184994. /*
  184995. *(--dp) = *(--sp);
  184996. *(--dp) = *(--sp);
  184997. */
  184998. sp-=2;
  184999. dp=sp;
  185000. }
  185001. }
  185002. }
  185003. }
  185004. }
  185005. #endif
  185006. #if defined(PNG_READ_FILLER_SUPPORTED)
  185007. /* Add filler channel if we have RGB color */
  185008. void /* PRIVATE */
  185009. png_do_read_filler(png_row_infop row_info, png_bytep row,
  185010. png_uint_32 filler, png_uint_32 flags)
  185011. {
  185012. png_uint_32 i;
  185013. png_uint_32 row_width = row_info->width;
  185014. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  185015. png_byte lo_filler = (png_byte)(filler & 0xff);
  185016. png_debug(1, "in png_do_read_filler\n");
  185017. if (
  185018. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185019. row != NULL && row_info != NULL &&
  185020. #endif
  185021. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185022. {
  185023. if(row_info->bit_depth == 8)
  185024. {
  185025. /* This changes the data from G to GX */
  185026. if (flags & PNG_FLAG_FILLER_AFTER)
  185027. {
  185028. png_bytep sp = row + (png_size_t)row_width;
  185029. png_bytep dp = sp + (png_size_t)row_width;
  185030. for (i = 1; i < row_width; i++)
  185031. {
  185032. *(--dp) = lo_filler;
  185033. *(--dp) = *(--sp);
  185034. }
  185035. *(--dp) = lo_filler;
  185036. row_info->channels = 2;
  185037. row_info->pixel_depth = 16;
  185038. row_info->rowbytes = row_width * 2;
  185039. }
  185040. /* This changes the data from G to XG */
  185041. else
  185042. {
  185043. png_bytep sp = row + (png_size_t)row_width;
  185044. png_bytep dp = sp + (png_size_t)row_width;
  185045. for (i = 0; i < row_width; i++)
  185046. {
  185047. *(--dp) = *(--sp);
  185048. *(--dp) = lo_filler;
  185049. }
  185050. row_info->channels = 2;
  185051. row_info->pixel_depth = 16;
  185052. row_info->rowbytes = row_width * 2;
  185053. }
  185054. }
  185055. else if(row_info->bit_depth == 16)
  185056. {
  185057. /* This changes the data from GG to GGXX */
  185058. if (flags & PNG_FLAG_FILLER_AFTER)
  185059. {
  185060. png_bytep sp = row + (png_size_t)row_width * 2;
  185061. png_bytep dp = sp + (png_size_t)row_width * 2;
  185062. for (i = 1; i < row_width; i++)
  185063. {
  185064. *(--dp) = hi_filler;
  185065. *(--dp) = lo_filler;
  185066. *(--dp) = *(--sp);
  185067. *(--dp) = *(--sp);
  185068. }
  185069. *(--dp) = hi_filler;
  185070. *(--dp) = lo_filler;
  185071. row_info->channels = 2;
  185072. row_info->pixel_depth = 32;
  185073. row_info->rowbytes = row_width * 4;
  185074. }
  185075. /* This changes the data from GG to XXGG */
  185076. else
  185077. {
  185078. png_bytep sp = row + (png_size_t)row_width * 2;
  185079. png_bytep dp = sp + (png_size_t)row_width * 2;
  185080. for (i = 0; i < row_width; i++)
  185081. {
  185082. *(--dp) = *(--sp);
  185083. *(--dp) = *(--sp);
  185084. *(--dp) = hi_filler;
  185085. *(--dp) = lo_filler;
  185086. }
  185087. row_info->channels = 2;
  185088. row_info->pixel_depth = 32;
  185089. row_info->rowbytes = row_width * 4;
  185090. }
  185091. }
  185092. } /* COLOR_TYPE == GRAY */
  185093. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185094. {
  185095. if(row_info->bit_depth == 8)
  185096. {
  185097. /* This changes the data from RGB to RGBX */
  185098. if (flags & PNG_FLAG_FILLER_AFTER)
  185099. {
  185100. png_bytep sp = row + (png_size_t)row_width * 3;
  185101. png_bytep dp = sp + (png_size_t)row_width;
  185102. for (i = 1; i < row_width; i++)
  185103. {
  185104. *(--dp) = lo_filler;
  185105. *(--dp) = *(--sp);
  185106. *(--dp) = *(--sp);
  185107. *(--dp) = *(--sp);
  185108. }
  185109. *(--dp) = lo_filler;
  185110. row_info->channels = 4;
  185111. row_info->pixel_depth = 32;
  185112. row_info->rowbytes = row_width * 4;
  185113. }
  185114. /* This changes the data from RGB to XRGB */
  185115. else
  185116. {
  185117. png_bytep sp = row + (png_size_t)row_width * 3;
  185118. png_bytep dp = sp + (png_size_t)row_width;
  185119. for (i = 0; i < row_width; i++)
  185120. {
  185121. *(--dp) = *(--sp);
  185122. *(--dp) = *(--sp);
  185123. *(--dp) = *(--sp);
  185124. *(--dp) = lo_filler;
  185125. }
  185126. row_info->channels = 4;
  185127. row_info->pixel_depth = 32;
  185128. row_info->rowbytes = row_width * 4;
  185129. }
  185130. }
  185131. else if(row_info->bit_depth == 16)
  185132. {
  185133. /* This changes the data from RRGGBB to RRGGBBXX */
  185134. if (flags & PNG_FLAG_FILLER_AFTER)
  185135. {
  185136. png_bytep sp = row + (png_size_t)row_width * 6;
  185137. png_bytep dp = sp + (png_size_t)row_width * 2;
  185138. for (i = 1; i < row_width; i++)
  185139. {
  185140. *(--dp) = hi_filler;
  185141. *(--dp) = lo_filler;
  185142. *(--dp) = *(--sp);
  185143. *(--dp) = *(--sp);
  185144. *(--dp) = *(--sp);
  185145. *(--dp) = *(--sp);
  185146. *(--dp) = *(--sp);
  185147. *(--dp) = *(--sp);
  185148. }
  185149. *(--dp) = hi_filler;
  185150. *(--dp) = lo_filler;
  185151. row_info->channels = 4;
  185152. row_info->pixel_depth = 64;
  185153. row_info->rowbytes = row_width * 8;
  185154. }
  185155. /* This changes the data from RRGGBB to XXRRGGBB */
  185156. else
  185157. {
  185158. png_bytep sp = row + (png_size_t)row_width * 6;
  185159. png_bytep dp = sp + (png_size_t)row_width * 2;
  185160. for (i = 0; i < row_width; i++)
  185161. {
  185162. *(--dp) = *(--sp);
  185163. *(--dp) = *(--sp);
  185164. *(--dp) = *(--sp);
  185165. *(--dp) = *(--sp);
  185166. *(--dp) = *(--sp);
  185167. *(--dp) = *(--sp);
  185168. *(--dp) = hi_filler;
  185169. *(--dp) = lo_filler;
  185170. }
  185171. row_info->channels = 4;
  185172. row_info->pixel_depth = 64;
  185173. row_info->rowbytes = row_width * 8;
  185174. }
  185175. }
  185176. } /* COLOR_TYPE == RGB */
  185177. }
  185178. #endif
  185179. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185180. /* expand grayscale files to RGB, with or without alpha */
  185181. void /* PRIVATE */
  185182. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  185183. {
  185184. png_uint_32 i;
  185185. png_uint_32 row_width = row_info->width;
  185186. png_debug(1, "in png_do_gray_to_rgb\n");
  185187. if (row_info->bit_depth >= 8 &&
  185188. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185189. row != NULL && row_info != NULL &&
  185190. #endif
  185191. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  185192. {
  185193. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185194. {
  185195. if (row_info->bit_depth == 8)
  185196. {
  185197. png_bytep sp = row + (png_size_t)row_width - 1;
  185198. png_bytep dp = sp + (png_size_t)row_width * 2;
  185199. for (i = 0; i < row_width; i++)
  185200. {
  185201. *(dp--) = *sp;
  185202. *(dp--) = *sp;
  185203. *(dp--) = *(sp--);
  185204. }
  185205. }
  185206. else
  185207. {
  185208. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185209. png_bytep dp = sp + (png_size_t)row_width * 4;
  185210. for (i = 0; i < row_width; i++)
  185211. {
  185212. *(dp--) = *sp;
  185213. *(dp--) = *(sp - 1);
  185214. *(dp--) = *sp;
  185215. *(dp--) = *(sp - 1);
  185216. *(dp--) = *(sp--);
  185217. *(dp--) = *(sp--);
  185218. }
  185219. }
  185220. }
  185221. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185222. {
  185223. if (row_info->bit_depth == 8)
  185224. {
  185225. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185226. png_bytep dp = sp + (png_size_t)row_width * 2;
  185227. for (i = 0; i < row_width; i++)
  185228. {
  185229. *(dp--) = *(sp--);
  185230. *(dp--) = *sp;
  185231. *(dp--) = *sp;
  185232. *(dp--) = *(sp--);
  185233. }
  185234. }
  185235. else
  185236. {
  185237. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  185238. png_bytep dp = sp + (png_size_t)row_width * 4;
  185239. for (i = 0; i < row_width; i++)
  185240. {
  185241. *(dp--) = *(sp--);
  185242. *(dp--) = *(sp--);
  185243. *(dp--) = *sp;
  185244. *(dp--) = *(sp - 1);
  185245. *(dp--) = *sp;
  185246. *(dp--) = *(sp - 1);
  185247. *(dp--) = *(sp--);
  185248. *(dp--) = *(sp--);
  185249. }
  185250. }
  185251. }
  185252. row_info->channels += (png_byte)2;
  185253. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  185254. row_info->pixel_depth = (png_byte)(row_info->channels *
  185255. row_info->bit_depth);
  185256. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185257. }
  185258. }
  185259. #endif
  185260. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185261. /* reduce RGB files to grayscale, with or without alpha
  185262. * using the equation given in Poynton's ColorFAQ at
  185263. * <http://www.inforamp.net/~poynton/>
  185264. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  185265. *
  185266. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  185267. *
  185268. * We approximate this with
  185269. *
  185270. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  185271. *
  185272. * which can be expressed with integers as
  185273. *
  185274. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  185275. *
  185276. * The calculation is to be done in a linear colorspace.
  185277. *
  185278. * Other integer coefficents can be used via png_set_rgb_to_gray().
  185279. */
  185280. int /* PRIVATE */
  185281. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  185282. {
  185283. png_uint_32 i;
  185284. png_uint_32 row_width = row_info->width;
  185285. int rgb_error = 0;
  185286. png_debug(1, "in png_do_rgb_to_gray\n");
  185287. if (
  185288. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185289. row != NULL && row_info != NULL &&
  185290. #endif
  185291. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  185292. {
  185293. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  185294. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  185295. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  185296. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185297. {
  185298. if (row_info->bit_depth == 8)
  185299. {
  185300. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185301. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  185302. {
  185303. png_bytep sp = row;
  185304. png_bytep dp = row;
  185305. for (i = 0; i < row_width; i++)
  185306. {
  185307. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  185308. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  185309. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  185310. if(red != green || red != blue)
  185311. {
  185312. rgb_error |= 1;
  185313. *(dp++) = png_ptr->gamma_from_1[
  185314. (rc*red+gc*green+bc*blue)>>15];
  185315. }
  185316. else
  185317. *(dp++) = *(sp-1);
  185318. }
  185319. }
  185320. else
  185321. #endif
  185322. {
  185323. png_bytep sp = row;
  185324. png_bytep dp = row;
  185325. for (i = 0; i < row_width; i++)
  185326. {
  185327. png_byte red = *(sp++);
  185328. png_byte green = *(sp++);
  185329. png_byte blue = *(sp++);
  185330. if(red != green || red != blue)
  185331. {
  185332. rgb_error |= 1;
  185333. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  185334. }
  185335. else
  185336. *(dp++) = *(sp-1);
  185337. }
  185338. }
  185339. }
  185340. else /* RGB bit_depth == 16 */
  185341. {
  185342. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185343. if (png_ptr->gamma_16_to_1 != NULL &&
  185344. png_ptr->gamma_16_from_1 != NULL)
  185345. {
  185346. png_bytep sp = row;
  185347. png_bytep dp = row;
  185348. for (i = 0; i < row_width; i++)
  185349. {
  185350. png_uint_16 red, green, blue, w;
  185351. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185352. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185353. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185354. if(red == green && red == blue)
  185355. w = red;
  185356. else
  185357. {
  185358. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  185359. png_ptr->gamma_shift][red>>8];
  185360. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  185361. png_ptr->gamma_shift][green>>8];
  185362. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  185363. png_ptr->gamma_shift][blue>>8];
  185364. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  185365. + bc*blue_1)>>15);
  185366. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  185367. png_ptr->gamma_shift][gray16 >> 8];
  185368. rgb_error |= 1;
  185369. }
  185370. *(dp++) = (png_byte)((w>>8) & 0xff);
  185371. *(dp++) = (png_byte)(w & 0xff);
  185372. }
  185373. }
  185374. else
  185375. #endif
  185376. {
  185377. png_bytep sp = row;
  185378. png_bytep dp = row;
  185379. for (i = 0; i < row_width; i++)
  185380. {
  185381. png_uint_16 red, green, blue, gray16;
  185382. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185383. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185384. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185385. if(red != green || red != blue)
  185386. rgb_error |= 1;
  185387. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  185388. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  185389. *(dp++) = (png_byte)(gray16 & 0xff);
  185390. }
  185391. }
  185392. }
  185393. }
  185394. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185395. {
  185396. if (row_info->bit_depth == 8)
  185397. {
  185398. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185399. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  185400. {
  185401. png_bytep sp = row;
  185402. png_bytep dp = row;
  185403. for (i = 0; i < row_width; i++)
  185404. {
  185405. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  185406. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  185407. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  185408. if(red != green || red != blue)
  185409. rgb_error |= 1;
  185410. *(dp++) = png_ptr->gamma_from_1
  185411. [(rc*red + gc*green + bc*blue)>>15];
  185412. *(dp++) = *(sp++); /* alpha */
  185413. }
  185414. }
  185415. else
  185416. #endif
  185417. {
  185418. png_bytep sp = row;
  185419. png_bytep dp = row;
  185420. for (i = 0; i < row_width; i++)
  185421. {
  185422. png_byte red = *(sp++);
  185423. png_byte green = *(sp++);
  185424. png_byte blue = *(sp++);
  185425. if(red != green || red != blue)
  185426. rgb_error |= 1;
  185427. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  185428. *(dp++) = *(sp++); /* alpha */
  185429. }
  185430. }
  185431. }
  185432. else /* RGBA bit_depth == 16 */
  185433. {
  185434. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185435. if (png_ptr->gamma_16_to_1 != NULL &&
  185436. png_ptr->gamma_16_from_1 != NULL)
  185437. {
  185438. png_bytep sp = row;
  185439. png_bytep dp = row;
  185440. for (i = 0; i < row_width; i++)
  185441. {
  185442. png_uint_16 red, green, blue, w;
  185443. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185444. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185445. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185446. if(red == green && red == blue)
  185447. w = red;
  185448. else
  185449. {
  185450. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  185451. png_ptr->gamma_shift][red>>8];
  185452. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  185453. png_ptr->gamma_shift][green>>8];
  185454. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  185455. png_ptr->gamma_shift][blue>>8];
  185456. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  185457. + gc * green_1 + bc * blue_1)>>15);
  185458. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  185459. png_ptr->gamma_shift][gray16 >> 8];
  185460. rgb_error |= 1;
  185461. }
  185462. *(dp++) = (png_byte)((w>>8) & 0xff);
  185463. *(dp++) = (png_byte)(w & 0xff);
  185464. *(dp++) = *(sp++); /* alpha */
  185465. *(dp++) = *(sp++);
  185466. }
  185467. }
  185468. else
  185469. #endif
  185470. {
  185471. png_bytep sp = row;
  185472. png_bytep dp = row;
  185473. for (i = 0; i < row_width; i++)
  185474. {
  185475. png_uint_16 red, green, blue, gray16;
  185476. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185477. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185478. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185479. if(red != green || red != blue)
  185480. rgb_error |= 1;
  185481. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  185482. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  185483. *(dp++) = (png_byte)(gray16 & 0xff);
  185484. *(dp++) = *(sp++); /* alpha */
  185485. *(dp++) = *(sp++);
  185486. }
  185487. }
  185488. }
  185489. }
  185490. row_info->channels -= (png_byte)2;
  185491. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  185492. row_info->pixel_depth = (png_byte)(row_info->channels *
  185493. row_info->bit_depth);
  185494. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185495. }
  185496. return rgb_error;
  185497. }
  185498. #endif
  185499. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  185500. * large of png_color. This lets grayscale images be treated as
  185501. * paletted. Most useful for gamma correction and simplification
  185502. * of code.
  185503. */
  185504. void PNGAPI
  185505. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  185506. {
  185507. int num_palette;
  185508. int color_inc;
  185509. int i;
  185510. int v;
  185511. png_debug(1, "in png_do_build_grayscale_palette\n");
  185512. if (palette == NULL)
  185513. return;
  185514. switch (bit_depth)
  185515. {
  185516. case 1:
  185517. num_palette = 2;
  185518. color_inc = 0xff;
  185519. break;
  185520. case 2:
  185521. num_palette = 4;
  185522. color_inc = 0x55;
  185523. break;
  185524. case 4:
  185525. num_palette = 16;
  185526. color_inc = 0x11;
  185527. break;
  185528. case 8:
  185529. num_palette = 256;
  185530. color_inc = 1;
  185531. break;
  185532. default:
  185533. num_palette = 0;
  185534. color_inc = 0;
  185535. break;
  185536. }
  185537. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  185538. {
  185539. palette[i].red = (png_byte)v;
  185540. palette[i].green = (png_byte)v;
  185541. palette[i].blue = (png_byte)v;
  185542. }
  185543. }
  185544. /* This function is currently unused. Do we really need it? */
  185545. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  185546. void /* PRIVATE */
  185547. png_correct_palette(png_structp png_ptr, png_colorp palette,
  185548. int num_palette)
  185549. {
  185550. png_debug(1, "in png_correct_palette\n");
  185551. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185552. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185553. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  185554. {
  185555. png_color back, back_1;
  185556. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  185557. {
  185558. back.red = png_ptr->gamma_table[png_ptr->background.red];
  185559. back.green = png_ptr->gamma_table[png_ptr->background.green];
  185560. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  185561. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  185562. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  185563. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  185564. }
  185565. else
  185566. {
  185567. double g;
  185568. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  185569. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  185570. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  185571. {
  185572. back.red = png_ptr->background.red;
  185573. back.green = png_ptr->background.green;
  185574. back.blue = png_ptr->background.blue;
  185575. }
  185576. else
  185577. {
  185578. back.red =
  185579. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  185580. 255.0 + 0.5);
  185581. back.green =
  185582. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  185583. 255.0 + 0.5);
  185584. back.blue =
  185585. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  185586. 255.0 + 0.5);
  185587. }
  185588. g = 1.0 / png_ptr->background_gamma;
  185589. back_1.red =
  185590. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  185591. 255.0 + 0.5);
  185592. back_1.green =
  185593. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  185594. 255.0 + 0.5);
  185595. back_1.blue =
  185596. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  185597. 255.0 + 0.5);
  185598. }
  185599. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185600. {
  185601. png_uint_32 i;
  185602. for (i = 0; i < (png_uint_32)num_palette; i++)
  185603. {
  185604. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  185605. {
  185606. palette[i] = back;
  185607. }
  185608. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  185609. {
  185610. png_byte v, w;
  185611. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  185612. png_composite(w, v, png_ptr->trans[i], back_1.red);
  185613. palette[i].red = png_ptr->gamma_from_1[w];
  185614. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  185615. png_composite(w, v, png_ptr->trans[i], back_1.green);
  185616. palette[i].green = png_ptr->gamma_from_1[w];
  185617. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  185618. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  185619. palette[i].blue = png_ptr->gamma_from_1[w];
  185620. }
  185621. else
  185622. {
  185623. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185624. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185625. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185626. }
  185627. }
  185628. }
  185629. else
  185630. {
  185631. int i;
  185632. for (i = 0; i < num_palette; i++)
  185633. {
  185634. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  185635. {
  185636. palette[i] = back;
  185637. }
  185638. else
  185639. {
  185640. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185641. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185642. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185643. }
  185644. }
  185645. }
  185646. }
  185647. else
  185648. #endif
  185649. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185650. if (png_ptr->transformations & PNG_GAMMA)
  185651. {
  185652. int i;
  185653. for (i = 0; i < num_palette; i++)
  185654. {
  185655. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185656. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185657. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185658. }
  185659. }
  185660. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185661. else
  185662. #endif
  185663. #endif
  185664. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185665. if (png_ptr->transformations & PNG_BACKGROUND)
  185666. {
  185667. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185668. {
  185669. png_color back;
  185670. back.red = (png_byte)png_ptr->background.red;
  185671. back.green = (png_byte)png_ptr->background.green;
  185672. back.blue = (png_byte)png_ptr->background.blue;
  185673. for (i = 0; i < (int)png_ptr->num_trans; i++)
  185674. {
  185675. if (png_ptr->trans[i] == 0)
  185676. {
  185677. palette[i].red = back.red;
  185678. palette[i].green = back.green;
  185679. palette[i].blue = back.blue;
  185680. }
  185681. else if (png_ptr->trans[i] != 0xff)
  185682. {
  185683. png_composite(palette[i].red, png_ptr->palette[i].red,
  185684. png_ptr->trans[i], back.red);
  185685. png_composite(palette[i].green, png_ptr->palette[i].green,
  185686. png_ptr->trans[i], back.green);
  185687. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  185688. png_ptr->trans[i], back.blue);
  185689. }
  185690. }
  185691. }
  185692. else /* assume grayscale palette (what else could it be?) */
  185693. {
  185694. int i;
  185695. for (i = 0; i < num_palette; i++)
  185696. {
  185697. if (i == (png_byte)png_ptr->trans_values.gray)
  185698. {
  185699. palette[i].red = (png_byte)png_ptr->background.red;
  185700. palette[i].green = (png_byte)png_ptr->background.green;
  185701. palette[i].blue = (png_byte)png_ptr->background.blue;
  185702. }
  185703. }
  185704. }
  185705. }
  185706. #endif
  185707. }
  185708. #endif
  185709. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185710. /* Replace any alpha or transparency with the supplied background color.
  185711. * "background" is already in the screen gamma, while "background_1" is
  185712. * at a gamma of 1.0. Paletted files have already been taken care of.
  185713. */
  185714. void /* PRIVATE */
  185715. png_do_background(png_row_infop row_info, png_bytep row,
  185716. png_color_16p trans_values, png_color_16p background
  185717. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185718. , png_color_16p background_1,
  185719. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  185720. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  185721. png_uint_16pp gamma_16_to_1, int gamma_shift
  185722. #endif
  185723. )
  185724. {
  185725. png_bytep sp, dp;
  185726. png_uint_32 i;
  185727. png_uint_32 row_width=row_info->width;
  185728. int shift;
  185729. png_debug(1, "in png_do_background\n");
  185730. if (background != NULL &&
  185731. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185732. row != NULL && row_info != NULL &&
  185733. #endif
  185734. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  185735. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  185736. {
  185737. switch (row_info->color_type)
  185738. {
  185739. case PNG_COLOR_TYPE_GRAY:
  185740. {
  185741. switch (row_info->bit_depth)
  185742. {
  185743. case 1:
  185744. {
  185745. sp = row;
  185746. shift = 7;
  185747. for (i = 0; i < row_width; i++)
  185748. {
  185749. if ((png_uint_16)((*sp >> shift) & 0x01)
  185750. == trans_values->gray)
  185751. {
  185752. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  185753. *sp |= (png_byte)(background->gray << shift);
  185754. }
  185755. if (!shift)
  185756. {
  185757. shift = 7;
  185758. sp++;
  185759. }
  185760. else
  185761. shift--;
  185762. }
  185763. break;
  185764. }
  185765. case 2:
  185766. {
  185767. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185768. if (gamma_table != NULL)
  185769. {
  185770. sp = row;
  185771. shift = 6;
  185772. for (i = 0; i < row_width; i++)
  185773. {
  185774. if ((png_uint_16)((*sp >> shift) & 0x03)
  185775. == trans_values->gray)
  185776. {
  185777. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185778. *sp |= (png_byte)(background->gray << shift);
  185779. }
  185780. else
  185781. {
  185782. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  185783. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  185784. (p << 4) | (p << 6)] >> 6) & 0x03);
  185785. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185786. *sp |= (png_byte)(g << shift);
  185787. }
  185788. if (!shift)
  185789. {
  185790. shift = 6;
  185791. sp++;
  185792. }
  185793. else
  185794. shift -= 2;
  185795. }
  185796. }
  185797. else
  185798. #endif
  185799. {
  185800. sp = row;
  185801. shift = 6;
  185802. for (i = 0; i < row_width; i++)
  185803. {
  185804. if ((png_uint_16)((*sp >> shift) & 0x03)
  185805. == trans_values->gray)
  185806. {
  185807. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185808. *sp |= (png_byte)(background->gray << shift);
  185809. }
  185810. if (!shift)
  185811. {
  185812. shift = 6;
  185813. sp++;
  185814. }
  185815. else
  185816. shift -= 2;
  185817. }
  185818. }
  185819. break;
  185820. }
  185821. case 4:
  185822. {
  185823. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185824. if (gamma_table != NULL)
  185825. {
  185826. sp = row;
  185827. shift = 4;
  185828. for (i = 0; i < row_width; i++)
  185829. {
  185830. if ((png_uint_16)((*sp >> shift) & 0x0f)
  185831. == trans_values->gray)
  185832. {
  185833. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185834. *sp |= (png_byte)(background->gray << shift);
  185835. }
  185836. else
  185837. {
  185838. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  185839. png_byte g = (png_byte)((gamma_table[p |
  185840. (p << 4)] >> 4) & 0x0f);
  185841. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185842. *sp |= (png_byte)(g << shift);
  185843. }
  185844. if (!shift)
  185845. {
  185846. shift = 4;
  185847. sp++;
  185848. }
  185849. else
  185850. shift -= 4;
  185851. }
  185852. }
  185853. else
  185854. #endif
  185855. {
  185856. sp = row;
  185857. shift = 4;
  185858. for (i = 0; i < row_width; i++)
  185859. {
  185860. if ((png_uint_16)((*sp >> shift) & 0x0f)
  185861. == trans_values->gray)
  185862. {
  185863. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185864. *sp |= (png_byte)(background->gray << shift);
  185865. }
  185866. if (!shift)
  185867. {
  185868. shift = 4;
  185869. sp++;
  185870. }
  185871. else
  185872. shift -= 4;
  185873. }
  185874. }
  185875. break;
  185876. }
  185877. case 8:
  185878. {
  185879. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185880. if (gamma_table != NULL)
  185881. {
  185882. sp = row;
  185883. for (i = 0; i < row_width; i++, sp++)
  185884. {
  185885. if (*sp == trans_values->gray)
  185886. {
  185887. *sp = (png_byte)background->gray;
  185888. }
  185889. else
  185890. {
  185891. *sp = gamma_table[*sp];
  185892. }
  185893. }
  185894. }
  185895. else
  185896. #endif
  185897. {
  185898. sp = row;
  185899. for (i = 0; i < row_width; i++, sp++)
  185900. {
  185901. if (*sp == trans_values->gray)
  185902. {
  185903. *sp = (png_byte)background->gray;
  185904. }
  185905. }
  185906. }
  185907. break;
  185908. }
  185909. case 16:
  185910. {
  185911. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185912. if (gamma_16 != NULL)
  185913. {
  185914. sp = row;
  185915. for (i = 0; i < row_width; i++, sp += 2)
  185916. {
  185917. png_uint_16 v;
  185918. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  185919. if (v == trans_values->gray)
  185920. {
  185921. /* background is already in screen gamma */
  185922. *sp = (png_byte)((background->gray >> 8) & 0xff);
  185923. *(sp + 1) = (png_byte)(background->gray & 0xff);
  185924. }
  185925. else
  185926. {
  185927. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  185928. *sp = (png_byte)((v >> 8) & 0xff);
  185929. *(sp + 1) = (png_byte)(v & 0xff);
  185930. }
  185931. }
  185932. }
  185933. else
  185934. #endif
  185935. {
  185936. sp = row;
  185937. for (i = 0; i < row_width; i++, sp += 2)
  185938. {
  185939. png_uint_16 v;
  185940. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  185941. if (v == trans_values->gray)
  185942. {
  185943. *sp = (png_byte)((background->gray >> 8) & 0xff);
  185944. *(sp + 1) = (png_byte)(background->gray & 0xff);
  185945. }
  185946. }
  185947. }
  185948. break;
  185949. }
  185950. }
  185951. break;
  185952. }
  185953. case PNG_COLOR_TYPE_RGB:
  185954. {
  185955. if (row_info->bit_depth == 8)
  185956. {
  185957. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185958. if (gamma_table != NULL)
  185959. {
  185960. sp = row;
  185961. for (i = 0; i < row_width; i++, sp += 3)
  185962. {
  185963. if (*sp == trans_values->red &&
  185964. *(sp + 1) == trans_values->green &&
  185965. *(sp + 2) == trans_values->blue)
  185966. {
  185967. *sp = (png_byte)background->red;
  185968. *(sp + 1) = (png_byte)background->green;
  185969. *(sp + 2) = (png_byte)background->blue;
  185970. }
  185971. else
  185972. {
  185973. *sp = gamma_table[*sp];
  185974. *(sp + 1) = gamma_table[*(sp + 1)];
  185975. *(sp + 2) = gamma_table[*(sp + 2)];
  185976. }
  185977. }
  185978. }
  185979. else
  185980. #endif
  185981. {
  185982. sp = row;
  185983. for (i = 0; i < row_width; i++, sp += 3)
  185984. {
  185985. if (*sp == trans_values->red &&
  185986. *(sp + 1) == trans_values->green &&
  185987. *(sp + 2) == trans_values->blue)
  185988. {
  185989. *sp = (png_byte)background->red;
  185990. *(sp + 1) = (png_byte)background->green;
  185991. *(sp + 2) = (png_byte)background->blue;
  185992. }
  185993. }
  185994. }
  185995. }
  185996. else /* if (row_info->bit_depth == 16) */
  185997. {
  185998. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185999. if (gamma_16 != NULL)
  186000. {
  186001. sp = row;
  186002. for (i = 0; i < row_width; i++, sp += 6)
  186003. {
  186004. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186005. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186006. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186007. if (r == trans_values->red && g == trans_values->green &&
  186008. b == trans_values->blue)
  186009. {
  186010. /* background is already in screen gamma */
  186011. *sp = (png_byte)((background->red >> 8) & 0xff);
  186012. *(sp + 1) = (png_byte)(background->red & 0xff);
  186013. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186014. *(sp + 3) = (png_byte)(background->green & 0xff);
  186015. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186016. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186017. }
  186018. else
  186019. {
  186020. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186021. *sp = (png_byte)((v >> 8) & 0xff);
  186022. *(sp + 1) = (png_byte)(v & 0xff);
  186023. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186024. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  186025. *(sp + 3) = (png_byte)(v & 0xff);
  186026. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186027. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  186028. *(sp + 5) = (png_byte)(v & 0xff);
  186029. }
  186030. }
  186031. }
  186032. else
  186033. #endif
  186034. {
  186035. sp = row;
  186036. for (i = 0; i < row_width; i++, sp += 6)
  186037. {
  186038. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  186039. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186040. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186041. if (r == trans_values->red && g == trans_values->green &&
  186042. b == trans_values->blue)
  186043. {
  186044. *sp = (png_byte)((background->red >> 8) & 0xff);
  186045. *(sp + 1) = (png_byte)(background->red & 0xff);
  186046. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186047. *(sp + 3) = (png_byte)(background->green & 0xff);
  186048. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186049. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186050. }
  186051. }
  186052. }
  186053. }
  186054. break;
  186055. }
  186056. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186057. {
  186058. if (row_info->bit_depth == 8)
  186059. {
  186060. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186061. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186062. gamma_table != NULL)
  186063. {
  186064. sp = row;
  186065. dp = row;
  186066. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186067. {
  186068. png_uint_16 a = *(sp + 1);
  186069. if (a == 0xff)
  186070. {
  186071. *dp = gamma_table[*sp];
  186072. }
  186073. else if (a == 0)
  186074. {
  186075. /* background is already in screen gamma */
  186076. *dp = (png_byte)background->gray;
  186077. }
  186078. else
  186079. {
  186080. png_byte v, w;
  186081. v = gamma_to_1[*sp];
  186082. png_composite(w, v, a, background_1->gray);
  186083. *dp = gamma_from_1[w];
  186084. }
  186085. }
  186086. }
  186087. else
  186088. #endif
  186089. {
  186090. sp = row;
  186091. dp = row;
  186092. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186093. {
  186094. png_byte a = *(sp + 1);
  186095. if (a == 0xff)
  186096. {
  186097. *dp = *sp;
  186098. }
  186099. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186100. else if (a == 0)
  186101. {
  186102. *dp = (png_byte)background->gray;
  186103. }
  186104. else
  186105. {
  186106. png_composite(*dp, *sp, a, background_1->gray);
  186107. }
  186108. #else
  186109. *dp = (png_byte)background->gray;
  186110. #endif
  186111. }
  186112. }
  186113. }
  186114. else /* if (png_ptr->bit_depth == 16) */
  186115. {
  186116. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186117. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186118. gamma_16_to_1 != NULL)
  186119. {
  186120. sp = row;
  186121. dp = row;
  186122. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186123. {
  186124. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186125. if (a == (png_uint_16)0xffff)
  186126. {
  186127. png_uint_16 v;
  186128. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186129. *dp = (png_byte)((v >> 8) & 0xff);
  186130. *(dp + 1) = (png_byte)(v & 0xff);
  186131. }
  186132. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186133. else if (a == 0)
  186134. #else
  186135. else
  186136. #endif
  186137. {
  186138. /* background is already in screen gamma */
  186139. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186140. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186141. }
  186142. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186143. else
  186144. {
  186145. png_uint_16 g, v, w;
  186146. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186147. png_composite_16(v, g, a, background_1->gray);
  186148. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  186149. *dp = (png_byte)((w >> 8) & 0xff);
  186150. *(dp + 1) = (png_byte)(w & 0xff);
  186151. }
  186152. #endif
  186153. }
  186154. }
  186155. else
  186156. #endif
  186157. {
  186158. sp = row;
  186159. dp = row;
  186160. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186161. {
  186162. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186163. if (a == (png_uint_16)0xffff)
  186164. {
  186165. png_memcpy(dp, sp, 2);
  186166. }
  186167. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186168. else if (a == 0)
  186169. #else
  186170. else
  186171. #endif
  186172. {
  186173. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186174. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186175. }
  186176. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186177. else
  186178. {
  186179. png_uint_16 g, v;
  186180. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186181. png_composite_16(v, g, a, background_1->gray);
  186182. *dp = (png_byte)((v >> 8) & 0xff);
  186183. *(dp + 1) = (png_byte)(v & 0xff);
  186184. }
  186185. #endif
  186186. }
  186187. }
  186188. }
  186189. break;
  186190. }
  186191. case PNG_COLOR_TYPE_RGB_ALPHA:
  186192. {
  186193. if (row_info->bit_depth == 8)
  186194. {
  186195. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186196. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186197. gamma_table != NULL)
  186198. {
  186199. sp = row;
  186200. dp = row;
  186201. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186202. {
  186203. png_byte a = *(sp + 3);
  186204. if (a == 0xff)
  186205. {
  186206. *dp = gamma_table[*sp];
  186207. *(dp + 1) = gamma_table[*(sp + 1)];
  186208. *(dp + 2) = gamma_table[*(sp + 2)];
  186209. }
  186210. else if (a == 0)
  186211. {
  186212. /* background is already in screen gamma */
  186213. *dp = (png_byte)background->red;
  186214. *(dp + 1) = (png_byte)background->green;
  186215. *(dp + 2) = (png_byte)background->blue;
  186216. }
  186217. else
  186218. {
  186219. png_byte v, w;
  186220. v = gamma_to_1[*sp];
  186221. png_composite(w, v, a, background_1->red);
  186222. *dp = gamma_from_1[w];
  186223. v = gamma_to_1[*(sp + 1)];
  186224. png_composite(w, v, a, background_1->green);
  186225. *(dp + 1) = gamma_from_1[w];
  186226. v = gamma_to_1[*(sp + 2)];
  186227. png_composite(w, v, a, background_1->blue);
  186228. *(dp + 2) = gamma_from_1[w];
  186229. }
  186230. }
  186231. }
  186232. else
  186233. #endif
  186234. {
  186235. sp = row;
  186236. dp = row;
  186237. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186238. {
  186239. png_byte a = *(sp + 3);
  186240. if (a == 0xff)
  186241. {
  186242. *dp = *sp;
  186243. *(dp + 1) = *(sp + 1);
  186244. *(dp + 2) = *(sp + 2);
  186245. }
  186246. else if (a == 0)
  186247. {
  186248. *dp = (png_byte)background->red;
  186249. *(dp + 1) = (png_byte)background->green;
  186250. *(dp + 2) = (png_byte)background->blue;
  186251. }
  186252. else
  186253. {
  186254. png_composite(*dp, *sp, a, background->red);
  186255. png_composite(*(dp + 1), *(sp + 1), a,
  186256. background->green);
  186257. png_composite(*(dp + 2), *(sp + 2), a,
  186258. background->blue);
  186259. }
  186260. }
  186261. }
  186262. }
  186263. else /* if (row_info->bit_depth == 16) */
  186264. {
  186265. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186266. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186267. gamma_16_to_1 != NULL)
  186268. {
  186269. sp = row;
  186270. dp = row;
  186271. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186272. {
  186273. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186274. << 8) + (png_uint_16)(*(sp + 7)));
  186275. if (a == (png_uint_16)0xffff)
  186276. {
  186277. png_uint_16 v;
  186278. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186279. *dp = (png_byte)((v >> 8) & 0xff);
  186280. *(dp + 1) = (png_byte)(v & 0xff);
  186281. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186282. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  186283. *(dp + 3) = (png_byte)(v & 0xff);
  186284. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186285. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  186286. *(dp + 5) = (png_byte)(v & 0xff);
  186287. }
  186288. else if (a == 0)
  186289. {
  186290. /* background is already in screen gamma */
  186291. *dp = (png_byte)((background->red >> 8) & 0xff);
  186292. *(dp + 1) = (png_byte)(background->red & 0xff);
  186293. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186294. *(dp + 3) = (png_byte)(background->green & 0xff);
  186295. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186296. *(dp + 5) = (png_byte)(background->blue & 0xff);
  186297. }
  186298. else
  186299. {
  186300. png_uint_16 v, w, x;
  186301. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186302. png_composite_16(w, v, a, background_1->red);
  186303. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  186304. *dp = (png_byte)((x >> 8) & 0xff);
  186305. *(dp + 1) = (png_byte)(x & 0xff);
  186306. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186307. png_composite_16(w, v, a, background_1->green);
  186308. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  186309. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  186310. *(dp + 3) = (png_byte)(x & 0xff);
  186311. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186312. png_composite_16(w, v, a, background_1->blue);
  186313. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  186314. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  186315. *(dp + 5) = (png_byte)(x & 0xff);
  186316. }
  186317. }
  186318. }
  186319. else
  186320. #endif
  186321. {
  186322. sp = row;
  186323. dp = row;
  186324. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186325. {
  186326. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186327. << 8) + (png_uint_16)(*(sp + 7)));
  186328. if (a == (png_uint_16)0xffff)
  186329. {
  186330. png_memcpy(dp, sp, 6);
  186331. }
  186332. else if (a == 0)
  186333. {
  186334. *dp = (png_byte)((background->red >> 8) & 0xff);
  186335. *(dp + 1) = (png_byte)(background->red & 0xff);
  186336. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186337. *(dp + 3) = (png_byte)(background->green & 0xff);
  186338. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186339. *(dp + 5) = (png_byte)(background->blue & 0xff);
  186340. }
  186341. else
  186342. {
  186343. png_uint_16 v;
  186344. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186345. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  186346. + *(sp + 3));
  186347. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  186348. + *(sp + 5));
  186349. png_composite_16(v, r, a, background->red);
  186350. *dp = (png_byte)((v >> 8) & 0xff);
  186351. *(dp + 1) = (png_byte)(v & 0xff);
  186352. png_composite_16(v, g, a, background->green);
  186353. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  186354. *(dp + 3) = (png_byte)(v & 0xff);
  186355. png_composite_16(v, b, a, background->blue);
  186356. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  186357. *(dp + 5) = (png_byte)(v & 0xff);
  186358. }
  186359. }
  186360. }
  186361. }
  186362. break;
  186363. }
  186364. }
  186365. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186366. {
  186367. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186368. row_info->channels--;
  186369. row_info->pixel_depth = (png_byte)(row_info->channels *
  186370. row_info->bit_depth);
  186371. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186372. }
  186373. }
  186374. }
  186375. #endif
  186376. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186377. /* Gamma correct the image, avoiding the alpha channel. Make sure
  186378. * you do this after you deal with the transparency issue on grayscale
  186379. * or RGB images. If your bit depth is 8, use gamma_table, if it
  186380. * is 16, use gamma_16_table and gamma_shift. Build these with
  186381. * build_gamma_table().
  186382. */
  186383. void /* PRIVATE */
  186384. png_do_gamma(png_row_infop row_info, png_bytep row,
  186385. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  186386. int gamma_shift)
  186387. {
  186388. png_bytep sp;
  186389. png_uint_32 i;
  186390. png_uint_32 row_width=row_info->width;
  186391. png_debug(1, "in png_do_gamma\n");
  186392. if (
  186393. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186394. row != NULL && row_info != NULL &&
  186395. #endif
  186396. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  186397. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  186398. {
  186399. switch (row_info->color_type)
  186400. {
  186401. case PNG_COLOR_TYPE_RGB:
  186402. {
  186403. if (row_info->bit_depth == 8)
  186404. {
  186405. sp = row;
  186406. for (i = 0; i < row_width; i++)
  186407. {
  186408. *sp = gamma_table[*sp];
  186409. sp++;
  186410. *sp = gamma_table[*sp];
  186411. sp++;
  186412. *sp = gamma_table[*sp];
  186413. sp++;
  186414. }
  186415. }
  186416. else /* if (row_info->bit_depth == 16) */
  186417. {
  186418. sp = row;
  186419. for (i = 0; i < row_width; i++)
  186420. {
  186421. png_uint_16 v;
  186422. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186423. *sp = (png_byte)((v >> 8) & 0xff);
  186424. *(sp + 1) = (png_byte)(v & 0xff);
  186425. sp += 2;
  186426. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186427. *sp = (png_byte)((v >> 8) & 0xff);
  186428. *(sp + 1) = (png_byte)(v & 0xff);
  186429. sp += 2;
  186430. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186431. *sp = (png_byte)((v >> 8) & 0xff);
  186432. *(sp + 1) = (png_byte)(v & 0xff);
  186433. sp += 2;
  186434. }
  186435. }
  186436. break;
  186437. }
  186438. case PNG_COLOR_TYPE_RGB_ALPHA:
  186439. {
  186440. if (row_info->bit_depth == 8)
  186441. {
  186442. sp = row;
  186443. for (i = 0; i < row_width; i++)
  186444. {
  186445. *sp = gamma_table[*sp];
  186446. sp++;
  186447. *sp = gamma_table[*sp];
  186448. sp++;
  186449. *sp = gamma_table[*sp];
  186450. sp++;
  186451. sp++;
  186452. }
  186453. }
  186454. else /* if (row_info->bit_depth == 16) */
  186455. {
  186456. sp = row;
  186457. for (i = 0; i < row_width; i++)
  186458. {
  186459. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186460. *sp = (png_byte)((v >> 8) & 0xff);
  186461. *(sp + 1) = (png_byte)(v & 0xff);
  186462. sp += 2;
  186463. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186464. *sp = (png_byte)((v >> 8) & 0xff);
  186465. *(sp + 1) = (png_byte)(v & 0xff);
  186466. sp += 2;
  186467. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186468. *sp = (png_byte)((v >> 8) & 0xff);
  186469. *(sp + 1) = (png_byte)(v & 0xff);
  186470. sp += 4;
  186471. }
  186472. }
  186473. break;
  186474. }
  186475. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186476. {
  186477. if (row_info->bit_depth == 8)
  186478. {
  186479. sp = row;
  186480. for (i = 0; i < row_width; i++)
  186481. {
  186482. *sp = gamma_table[*sp];
  186483. sp += 2;
  186484. }
  186485. }
  186486. else /* if (row_info->bit_depth == 16) */
  186487. {
  186488. sp = row;
  186489. for (i = 0; i < row_width; i++)
  186490. {
  186491. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186492. *sp = (png_byte)((v >> 8) & 0xff);
  186493. *(sp + 1) = (png_byte)(v & 0xff);
  186494. sp += 4;
  186495. }
  186496. }
  186497. break;
  186498. }
  186499. case PNG_COLOR_TYPE_GRAY:
  186500. {
  186501. if (row_info->bit_depth == 2)
  186502. {
  186503. sp = row;
  186504. for (i = 0; i < row_width; i += 4)
  186505. {
  186506. int a = *sp & 0xc0;
  186507. int b = *sp & 0x30;
  186508. int c = *sp & 0x0c;
  186509. int d = *sp & 0x03;
  186510. *sp = (png_byte)(
  186511. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  186512. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  186513. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  186514. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  186515. sp++;
  186516. }
  186517. }
  186518. if (row_info->bit_depth == 4)
  186519. {
  186520. sp = row;
  186521. for (i = 0; i < row_width; i += 2)
  186522. {
  186523. int msb = *sp & 0xf0;
  186524. int lsb = *sp & 0x0f;
  186525. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  186526. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  186527. sp++;
  186528. }
  186529. }
  186530. else if (row_info->bit_depth == 8)
  186531. {
  186532. sp = row;
  186533. for (i = 0; i < row_width; i++)
  186534. {
  186535. *sp = gamma_table[*sp];
  186536. sp++;
  186537. }
  186538. }
  186539. else if (row_info->bit_depth == 16)
  186540. {
  186541. sp = row;
  186542. for (i = 0; i < row_width; i++)
  186543. {
  186544. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186545. *sp = (png_byte)((v >> 8) & 0xff);
  186546. *(sp + 1) = (png_byte)(v & 0xff);
  186547. sp += 2;
  186548. }
  186549. }
  186550. break;
  186551. }
  186552. }
  186553. }
  186554. }
  186555. #endif
  186556. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186557. /* Expands a palette row to an RGB or RGBA row depending
  186558. * upon whether you supply trans and num_trans.
  186559. */
  186560. void /* PRIVATE */
  186561. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  186562. png_colorp palette, png_bytep trans, int num_trans)
  186563. {
  186564. int shift, value;
  186565. png_bytep sp, dp;
  186566. png_uint_32 i;
  186567. png_uint_32 row_width=row_info->width;
  186568. png_debug(1, "in png_do_expand_palette\n");
  186569. if (
  186570. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186571. row != NULL && row_info != NULL &&
  186572. #endif
  186573. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  186574. {
  186575. if (row_info->bit_depth < 8)
  186576. {
  186577. switch (row_info->bit_depth)
  186578. {
  186579. case 1:
  186580. {
  186581. sp = row + (png_size_t)((row_width - 1) >> 3);
  186582. dp = row + (png_size_t)row_width - 1;
  186583. shift = 7 - (int)((row_width + 7) & 0x07);
  186584. for (i = 0; i < row_width; i++)
  186585. {
  186586. if ((*sp >> shift) & 0x01)
  186587. *dp = 1;
  186588. else
  186589. *dp = 0;
  186590. if (shift == 7)
  186591. {
  186592. shift = 0;
  186593. sp--;
  186594. }
  186595. else
  186596. shift++;
  186597. dp--;
  186598. }
  186599. break;
  186600. }
  186601. case 2:
  186602. {
  186603. sp = row + (png_size_t)((row_width - 1) >> 2);
  186604. dp = row + (png_size_t)row_width - 1;
  186605. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186606. for (i = 0; i < row_width; i++)
  186607. {
  186608. value = (*sp >> shift) & 0x03;
  186609. *dp = (png_byte)value;
  186610. if (shift == 6)
  186611. {
  186612. shift = 0;
  186613. sp--;
  186614. }
  186615. else
  186616. shift += 2;
  186617. dp--;
  186618. }
  186619. break;
  186620. }
  186621. case 4:
  186622. {
  186623. sp = row + (png_size_t)((row_width - 1) >> 1);
  186624. dp = row + (png_size_t)row_width - 1;
  186625. shift = (int)((row_width & 0x01) << 2);
  186626. for (i = 0; i < row_width; i++)
  186627. {
  186628. value = (*sp >> shift) & 0x0f;
  186629. *dp = (png_byte)value;
  186630. if (shift == 4)
  186631. {
  186632. shift = 0;
  186633. sp--;
  186634. }
  186635. else
  186636. shift += 4;
  186637. dp--;
  186638. }
  186639. break;
  186640. }
  186641. }
  186642. row_info->bit_depth = 8;
  186643. row_info->pixel_depth = 8;
  186644. row_info->rowbytes = row_width;
  186645. }
  186646. switch (row_info->bit_depth)
  186647. {
  186648. case 8:
  186649. {
  186650. if (trans != NULL)
  186651. {
  186652. sp = row + (png_size_t)row_width - 1;
  186653. dp = row + (png_size_t)(row_width << 2) - 1;
  186654. for (i = 0; i < row_width; i++)
  186655. {
  186656. if ((int)(*sp) >= num_trans)
  186657. *dp-- = 0xff;
  186658. else
  186659. *dp-- = trans[*sp];
  186660. *dp-- = palette[*sp].blue;
  186661. *dp-- = palette[*sp].green;
  186662. *dp-- = palette[*sp].red;
  186663. sp--;
  186664. }
  186665. row_info->bit_depth = 8;
  186666. row_info->pixel_depth = 32;
  186667. row_info->rowbytes = row_width * 4;
  186668. row_info->color_type = 6;
  186669. row_info->channels = 4;
  186670. }
  186671. else
  186672. {
  186673. sp = row + (png_size_t)row_width - 1;
  186674. dp = row + (png_size_t)(row_width * 3) - 1;
  186675. for (i = 0; i < row_width; i++)
  186676. {
  186677. *dp-- = palette[*sp].blue;
  186678. *dp-- = palette[*sp].green;
  186679. *dp-- = palette[*sp].red;
  186680. sp--;
  186681. }
  186682. row_info->bit_depth = 8;
  186683. row_info->pixel_depth = 24;
  186684. row_info->rowbytes = row_width * 3;
  186685. row_info->color_type = 2;
  186686. row_info->channels = 3;
  186687. }
  186688. break;
  186689. }
  186690. }
  186691. }
  186692. }
  186693. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  186694. * expanded transparency value is supplied, an alpha channel is built.
  186695. */
  186696. void /* PRIVATE */
  186697. png_do_expand(png_row_infop row_info, png_bytep row,
  186698. png_color_16p trans_value)
  186699. {
  186700. int shift, value;
  186701. png_bytep sp, dp;
  186702. png_uint_32 i;
  186703. png_uint_32 row_width=row_info->width;
  186704. png_debug(1, "in png_do_expand\n");
  186705. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186706. if (row != NULL && row_info != NULL)
  186707. #endif
  186708. {
  186709. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186710. {
  186711. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  186712. if (row_info->bit_depth < 8)
  186713. {
  186714. switch (row_info->bit_depth)
  186715. {
  186716. case 1:
  186717. {
  186718. gray = (png_uint_16)((gray&0x01)*0xff);
  186719. sp = row + (png_size_t)((row_width - 1) >> 3);
  186720. dp = row + (png_size_t)row_width - 1;
  186721. shift = 7 - (int)((row_width + 7) & 0x07);
  186722. for (i = 0; i < row_width; i++)
  186723. {
  186724. if ((*sp >> shift) & 0x01)
  186725. *dp = 0xff;
  186726. else
  186727. *dp = 0;
  186728. if (shift == 7)
  186729. {
  186730. shift = 0;
  186731. sp--;
  186732. }
  186733. else
  186734. shift++;
  186735. dp--;
  186736. }
  186737. break;
  186738. }
  186739. case 2:
  186740. {
  186741. gray = (png_uint_16)((gray&0x03)*0x55);
  186742. sp = row + (png_size_t)((row_width - 1) >> 2);
  186743. dp = row + (png_size_t)row_width - 1;
  186744. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186745. for (i = 0; i < row_width; i++)
  186746. {
  186747. value = (*sp >> shift) & 0x03;
  186748. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  186749. (value << 6));
  186750. if (shift == 6)
  186751. {
  186752. shift = 0;
  186753. sp--;
  186754. }
  186755. else
  186756. shift += 2;
  186757. dp--;
  186758. }
  186759. break;
  186760. }
  186761. case 4:
  186762. {
  186763. gray = (png_uint_16)((gray&0x0f)*0x11);
  186764. sp = row + (png_size_t)((row_width - 1) >> 1);
  186765. dp = row + (png_size_t)row_width - 1;
  186766. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186767. for (i = 0; i < row_width; i++)
  186768. {
  186769. value = (*sp >> shift) & 0x0f;
  186770. *dp = (png_byte)(value | (value << 4));
  186771. if (shift == 4)
  186772. {
  186773. shift = 0;
  186774. sp--;
  186775. }
  186776. else
  186777. shift = 4;
  186778. dp--;
  186779. }
  186780. break;
  186781. }
  186782. }
  186783. row_info->bit_depth = 8;
  186784. row_info->pixel_depth = 8;
  186785. row_info->rowbytes = row_width;
  186786. }
  186787. if (trans_value != NULL)
  186788. {
  186789. if (row_info->bit_depth == 8)
  186790. {
  186791. gray = gray & 0xff;
  186792. sp = row + (png_size_t)row_width - 1;
  186793. dp = row + (png_size_t)(row_width << 1) - 1;
  186794. for (i = 0; i < row_width; i++)
  186795. {
  186796. if (*sp == gray)
  186797. *dp-- = 0;
  186798. else
  186799. *dp-- = 0xff;
  186800. *dp-- = *sp--;
  186801. }
  186802. }
  186803. else if (row_info->bit_depth == 16)
  186804. {
  186805. png_byte gray_high = (gray >> 8) & 0xff;
  186806. png_byte gray_low = gray & 0xff;
  186807. sp = row + row_info->rowbytes - 1;
  186808. dp = row + (row_info->rowbytes << 1) - 1;
  186809. for (i = 0; i < row_width; i++)
  186810. {
  186811. if (*(sp-1) == gray_high && *(sp) == gray_low)
  186812. {
  186813. *dp-- = 0;
  186814. *dp-- = 0;
  186815. }
  186816. else
  186817. {
  186818. *dp-- = 0xff;
  186819. *dp-- = 0xff;
  186820. }
  186821. *dp-- = *sp--;
  186822. *dp-- = *sp--;
  186823. }
  186824. }
  186825. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  186826. row_info->channels = 2;
  186827. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  186828. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  186829. row_width);
  186830. }
  186831. }
  186832. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  186833. {
  186834. if (row_info->bit_depth == 8)
  186835. {
  186836. png_byte red = trans_value->red & 0xff;
  186837. png_byte green = trans_value->green & 0xff;
  186838. png_byte blue = trans_value->blue & 0xff;
  186839. sp = row + (png_size_t)row_info->rowbytes - 1;
  186840. dp = row + (png_size_t)(row_width << 2) - 1;
  186841. for (i = 0; i < row_width; i++)
  186842. {
  186843. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  186844. *dp-- = 0;
  186845. else
  186846. *dp-- = 0xff;
  186847. *dp-- = *sp--;
  186848. *dp-- = *sp--;
  186849. *dp-- = *sp--;
  186850. }
  186851. }
  186852. else if (row_info->bit_depth == 16)
  186853. {
  186854. png_byte red_high = (trans_value->red >> 8) & 0xff;
  186855. png_byte green_high = (trans_value->green >> 8) & 0xff;
  186856. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  186857. png_byte red_low = trans_value->red & 0xff;
  186858. png_byte green_low = trans_value->green & 0xff;
  186859. png_byte blue_low = trans_value->blue & 0xff;
  186860. sp = row + row_info->rowbytes - 1;
  186861. dp = row + (png_size_t)(row_width << 3) - 1;
  186862. for (i = 0; i < row_width; i++)
  186863. {
  186864. if (*(sp - 5) == red_high &&
  186865. *(sp - 4) == red_low &&
  186866. *(sp - 3) == green_high &&
  186867. *(sp - 2) == green_low &&
  186868. *(sp - 1) == blue_high &&
  186869. *(sp ) == blue_low)
  186870. {
  186871. *dp-- = 0;
  186872. *dp-- = 0;
  186873. }
  186874. else
  186875. {
  186876. *dp-- = 0xff;
  186877. *dp-- = 0xff;
  186878. }
  186879. *dp-- = *sp--;
  186880. *dp-- = *sp--;
  186881. *dp-- = *sp--;
  186882. *dp-- = *sp--;
  186883. *dp-- = *sp--;
  186884. *dp-- = *sp--;
  186885. }
  186886. }
  186887. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186888. row_info->channels = 4;
  186889. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  186890. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186891. }
  186892. }
  186893. }
  186894. #endif
  186895. #if defined(PNG_READ_DITHER_SUPPORTED)
  186896. void /* PRIVATE */
  186897. png_do_dither(png_row_infop row_info, png_bytep row,
  186898. png_bytep palette_lookup, png_bytep dither_lookup)
  186899. {
  186900. png_bytep sp, dp;
  186901. png_uint_32 i;
  186902. png_uint_32 row_width=row_info->width;
  186903. png_debug(1, "in png_do_dither\n");
  186904. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186905. if (row != NULL && row_info != NULL)
  186906. #endif
  186907. {
  186908. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  186909. palette_lookup && row_info->bit_depth == 8)
  186910. {
  186911. int r, g, b, p;
  186912. sp = row;
  186913. dp = row;
  186914. for (i = 0; i < row_width; i++)
  186915. {
  186916. r = *sp++;
  186917. g = *sp++;
  186918. b = *sp++;
  186919. /* this looks real messy, but the compiler will reduce
  186920. it down to a reasonable formula. For example, with
  186921. 5 bits per color, we get:
  186922. p = (((r >> 3) & 0x1f) << 10) |
  186923. (((g >> 3) & 0x1f) << 5) |
  186924. ((b >> 3) & 0x1f);
  186925. */
  186926. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  186927. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  186928. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  186929. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  186930. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  186931. (PNG_DITHER_BLUE_BITS)) |
  186932. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  186933. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  186934. *dp++ = palette_lookup[p];
  186935. }
  186936. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  186937. row_info->channels = 1;
  186938. row_info->pixel_depth = row_info->bit_depth;
  186939. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186940. }
  186941. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  186942. palette_lookup != NULL && row_info->bit_depth == 8)
  186943. {
  186944. int r, g, b, p;
  186945. sp = row;
  186946. dp = row;
  186947. for (i = 0; i < row_width; i++)
  186948. {
  186949. r = *sp++;
  186950. g = *sp++;
  186951. b = *sp++;
  186952. sp++;
  186953. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  186954. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  186955. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  186956. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  186957. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  186958. (PNG_DITHER_BLUE_BITS)) |
  186959. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  186960. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  186961. *dp++ = palette_lookup[p];
  186962. }
  186963. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  186964. row_info->channels = 1;
  186965. row_info->pixel_depth = row_info->bit_depth;
  186966. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186967. }
  186968. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  186969. dither_lookup && row_info->bit_depth == 8)
  186970. {
  186971. sp = row;
  186972. for (i = 0; i < row_width; i++, sp++)
  186973. {
  186974. *sp = dither_lookup[*sp];
  186975. }
  186976. }
  186977. }
  186978. }
  186979. #endif
  186980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186981. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186982. static PNG_CONST int png_gamma_shift[] =
  186983. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  186984. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  186985. * tables, we don't make a full table if we are reducing to 8-bit in
  186986. * the future. Note also how the gamma_16 tables are segmented so that
  186987. * we don't need to allocate > 64K chunks for a full 16-bit table.
  186988. */
  186989. void /* PRIVATE */
  186990. png_build_gamma_table(png_structp png_ptr)
  186991. {
  186992. png_debug(1, "in png_build_gamma_table\n");
  186993. if (png_ptr->bit_depth <= 8)
  186994. {
  186995. int i;
  186996. double g;
  186997. if (png_ptr->screen_gamma > .000001)
  186998. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186999. else
  187000. g = 1.0;
  187001. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  187002. (png_uint_32)256);
  187003. for (i = 0; i < 256; i++)
  187004. {
  187005. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  187006. g) * 255.0 + .5);
  187007. }
  187008. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187009. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187010. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  187011. {
  187012. g = 1.0 / (png_ptr->gamma);
  187013. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  187014. (png_uint_32)256);
  187015. for (i = 0; i < 256; i++)
  187016. {
  187017. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  187018. g) * 255.0 + .5);
  187019. }
  187020. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  187021. (png_uint_32)256);
  187022. if(png_ptr->screen_gamma > 0.000001)
  187023. g = 1.0 / png_ptr->screen_gamma;
  187024. else
  187025. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187026. for (i = 0; i < 256; i++)
  187027. {
  187028. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  187029. g) * 255.0 + .5);
  187030. }
  187031. }
  187032. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187033. }
  187034. else
  187035. {
  187036. double g;
  187037. int i, j, shift, num;
  187038. int sig_bit;
  187039. png_uint_32 ig;
  187040. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187041. {
  187042. sig_bit = (int)png_ptr->sig_bit.red;
  187043. if ((int)png_ptr->sig_bit.green > sig_bit)
  187044. sig_bit = png_ptr->sig_bit.green;
  187045. if ((int)png_ptr->sig_bit.blue > sig_bit)
  187046. sig_bit = png_ptr->sig_bit.blue;
  187047. }
  187048. else
  187049. {
  187050. sig_bit = (int)png_ptr->sig_bit.gray;
  187051. }
  187052. if (sig_bit > 0)
  187053. shift = 16 - sig_bit;
  187054. else
  187055. shift = 0;
  187056. if (png_ptr->transformations & PNG_16_TO_8)
  187057. {
  187058. if (shift < (16 - PNG_MAX_GAMMA_8))
  187059. shift = (16 - PNG_MAX_GAMMA_8);
  187060. }
  187061. if (shift > 8)
  187062. shift = 8;
  187063. if (shift < 0)
  187064. shift = 0;
  187065. png_ptr->gamma_shift = (png_byte)shift;
  187066. num = (1 << (8 - shift));
  187067. if (png_ptr->screen_gamma > .000001)
  187068. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187069. else
  187070. g = 1.0;
  187071. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  187072. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187073. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  187074. {
  187075. double fin, fout;
  187076. png_uint_32 last, max;
  187077. for (i = 0; i < num; i++)
  187078. {
  187079. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187080. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187081. }
  187082. g = 1.0 / g;
  187083. last = 0;
  187084. for (i = 0; i < 256; i++)
  187085. {
  187086. fout = ((double)i + 0.5) / 256.0;
  187087. fin = pow(fout, g);
  187088. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  187089. while (last <= max)
  187090. {
  187091. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187092. [(int)(last >> (8 - shift))] = (png_uint_16)(
  187093. (png_uint_16)i | ((png_uint_16)i << 8));
  187094. last++;
  187095. }
  187096. }
  187097. while (last < ((png_uint_32)num << 8))
  187098. {
  187099. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187100. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  187101. last++;
  187102. }
  187103. }
  187104. else
  187105. {
  187106. for (i = 0; i < num; i++)
  187107. {
  187108. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187109. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187110. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  187111. for (j = 0; j < 256; j++)
  187112. {
  187113. png_ptr->gamma_16_table[i][j] =
  187114. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187115. 65535.0, g) * 65535.0 + .5);
  187116. }
  187117. }
  187118. }
  187119. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187120. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187121. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  187122. {
  187123. g = 1.0 / (png_ptr->gamma);
  187124. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  187125. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  187126. for (i = 0; i < num; i++)
  187127. {
  187128. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187129. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187130. ig = (((png_uint_32)i *
  187131. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187132. for (j = 0; j < 256; j++)
  187133. {
  187134. png_ptr->gamma_16_to_1[i][j] =
  187135. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187136. 65535.0, g) * 65535.0 + .5);
  187137. }
  187138. }
  187139. if(png_ptr->screen_gamma > 0.000001)
  187140. g = 1.0 / png_ptr->screen_gamma;
  187141. else
  187142. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187143. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  187144. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187145. for (i = 0; i < num; i++)
  187146. {
  187147. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187148. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187149. ig = (((png_uint_32)i *
  187150. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187151. for (j = 0; j < 256; j++)
  187152. {
  187153. png_ptr->gamma_16_from_1[i][j] =
  187154. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187155. 65535.0, g) * 65535.0 + .5);
  187156. }
  187157. }
  187158. }
  187159. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187160. }
  187161. }
  187162. #endif
  187163. /* To do: install integer version of png_build_gamma_table here */
  187164. #endif
  187165. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187166. /* undoes intrapixel differencing */
  187167. void /* PRIVATE */
  187168. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  187169. {
  187170. png_debug(1, "in png_do_read_intrapixel\n");
  187171. if (
  187172. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187173. row != NULL && row_info != NULL &&
  187174. #endif
  187175. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187176. {
  187177. int bytes_per_pixel;
  187178. png_uint_32 row_width = row_info->width;
  187179. if (row_info->bit_depth == 8)
  187180. {
  187181. png_bytep rp;
  187182. png_uint_32 i;
  187183. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187184. bytes_per_pixel = 3;
  187185. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187186. bytes_per_pixel = 4;
  187187. else
  187188. return;
  187189. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187190. {
  187191. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  187192. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  187193. }
  187194. }
  187195. else if (row_info->bit_depth == 16)
  187196. {
  187197. png_bytep rp;
  187198. png_uint_32 i;
  187199. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187200. bytes_per_pixel = 6;
  187201. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187202. bytes_per_pixel = 8;
  187203. else
  187204. return;
  187205. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187206. {
  187207. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  187208. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  187209. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  187210. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  187211. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  187212. *(rp ) = (png_byte)((red >> 8) & 0xff);
  187213. *(rp+1) = (png_byte)(red & 0xff);
  187214. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  187215. *(rp+5) = (png_byte)(blue & 0xff);
  187216. }
  187217. }
  187218. }
  187219. }
  187220. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  187221. #endif /* PNG_READ_SUPPORTED */
  187222. /********* End of inlined file: pngrtran.c *********/
  187223. /********* Start of inlined file: pngrutil.c *********/
  187224. /* pngrutil.c - utilities to read a PNG file
  187225. *
  187226. * Last changed in libpng 1.2.21 [October 4, 2007]
  187227. * For conditions of distribution and use, see copyright notice in png.h
  187228. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187229. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187230. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187231. *
  187232. * This file contains routines that are only called from within
  187233. * libpng itself during the course of reading an image.
  187234. */
  187235. #define PNG_INTERNAL
  187236. #if defined(PNG_READ_SUPPORTED)
  187237. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  187238. # define WIN32_WCE_OLD
  187239. #endif
  187240. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187241. # if defined(WIN32_WCE_OLD)
  187242. /* strtod() function is not supported on WindowsCE */
  187243. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  187244. {
  187245. double result = 0;
  187246. int len;
  187247. wchar_t *str, *end;
  187248. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  187249. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  187250. if ( NULL != str )
  187251. {
  187252. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  187253. result = wcstod(str, &end);
  187254. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  187255. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  187256. png_free(png_ptr, str);
  187257. }
  187258. return result;
  187259. }
  187260. # else
  187261. # define png_strtod(p,a,b) strtod(a,b)
  187262. # endif
  187263. #endif
  187264. png_uint_32 PNGAPI
  187265. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  187266. {
  187267. png_uint_32 i = png_get_uint_32(buf);
  187268. if (i > PNG_UINT_31_MAX)
  187269. png_error(png_ptr, "PNG unsigned integer out of range.");
  187270. return (i);
  187271. }
  187272. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  187273. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  187274. png_uint_32 PNGAPI
  187275. png_get_uint_32(png_bytep buf)
  187276. {
  187277. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  187278. ((png_uint_32)(*(buf + 1)) << 16) +
  187279. ((png_uint_32)(*(buf + 2)) << 8) +
  187280. (png_uint_32)(*(buf + 3));
  187281. return (i);
  187282. }
  187283. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  187284. * data is stored in the PNG file in two's complement format, and it is
  187285. * assumed that the machine format for signed integers is the same. */
  187286. png_int_32 PNGAPI
  187287. png_get_int_32(png_bytep buf)
  187288. {
  187289. png_int_32 i = ((png_int_32)(*buf) << 24) +
  187290. ((png_int_32)(*(buf + 1)) << 16) +
  187291. ((png_int_32)(*(buf + 2)) << 8) +
  187292. (png_int_32)(*(buf + 3));
  187293. return (i);
  187294. }
  187295. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  187296. png_uint_16 PNGAPI
  187297. png_get_uint_16(png_bytep buf)
  187298. {
  187299. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  187300. (png_uint_16)(*(buf + 1)));
  187301. return (i);
  187302. }
  187303. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  187304. /* Read data, and (optionally) run it through the CRC. */
  187305. void /* PRIVATE */
  187306. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  187307. {
  187308. if(png_ptr == NULL) return;
  187309. png_read_data(png_ptr, buf, length);
  187310. png_calculate_crc(png_ptr, buf, length);
  187311. }
  187312. /* Optionally skip data and then check the CRC. Depending on whether we
  187313. are reading a ancillary or critical chunk, and how the program has set
  187314. things up, we may calculate the CRC on the data and print a message.
  187315. Returns '1' if there was a CRC error, '0' otherwise. */
  187316. int /* PRIVATE */
  187317. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  187318. {
  187319. png_size_t i;
  187320. png_size_t istop = png_ptr->zbuf_size;
  187321. for (i = (png_size_t)skip; i > istop; i -= istop)
  187322. {
  187323. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  187324. }
  187325. if (i)
  187326. {
  187327. png_crc_read(png_ptr, png_ptr->zbuf, i);
  187328. }
  187329. if (png_crc_error(png_ptr))
  187330. {
  187331. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  187332. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  187333. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  187334. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  187335. {
  187336. png_chunk_warning(png_ptr, "CRC error");
  187337. }
  187338. else
  187339. {
  187340. png_chunk_error(png_ptr, "CRC error");
  187341. }
  187342. return (1);
  187343. }
  187344. return (0);
  187345. }
  187346. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  187347. the data it has read thus far. */
  187348. int /* PRIVATE */
  187349. png_crc_error(png_structp png_ptr)
  187350. {
  187351. png_byte crc_bytes[4];
  187352. png_uint_32 crc;
  187353. int need_crc = 1;
  187354. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  187355. {
  187356. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  187357. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  187358. need_crc = 0;
  187359. }
  187360. else /* critical */
  187361. {
  187362. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  187363. need_crc = 0;
  187364. }
  187365. png_read_data(png_ptr, crc_bytes, 4);
  187366. if (need_crc)
  187367. {
  187368. crc = png_get_uint_32(crc_bytes);
  187369. return ((int)(crc != png_ptr->crc));
  187370. }
  187371. else
  187372. return (0);
  187373. }
  187374. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  187375. defined(PNG_READ_iCCP_SUPPORTED)
  187376. /*
  187377. * Decompress trailing data in a chunk. The assumption is that chunkdata
  187378. * points at an allocated area holding the contents of a chunk with a
  187379. * trailing compressed part. What we get back is an allocated area
  187380. * holding the original prefix part and an uncompressed version of the
  187381. * trailing part (the malloc area passed in is freed).
  187382. */
  187383. png_charp /* PRIVATE */
  187384. png_decompress_chunk(png_structp png_ptr, int comp_type,
  187385. png_charp chunkdata, png_size_t chunklength,
  187386. png_size_t prefix_size, png_size_t *newlength)
  187387. {
  187388. static PNG_CONST char msg[] = "Error decoding compressed text";
  187389. png_charp text;
  187390. png_size_t text_size;
  187391. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  187392. {
  187393. int ret = Z_OK;
  187394. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  187395. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  187396. png_ptr->zstream.next_out = png_ptr->zbuf;
  187397. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187398. text_size = 0;
  187399. text = NULL;
  187400. while (png_ptr->zstream.avail_in)
  187401. {
  187402. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187403. if (ret != Z_OK && ret != Z_STREAM_END)
  187404. {
  187405. if (png_ptr->zstream.msg != NULL)
  187406. png_warning(png_ptr, png_ptr->zstream.msg);
  187407. else
  187408. png_warning(png_ptr, msg);
  187409. inflateReset(&png_ptr->zstream);
  187410. png_ptr->zstream.avail_in = 0;
  187411. if (text == NULL)
  187412. {
  187413. text_size = prefix_size + png_sizeof(msg) + 1;
  187414. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  187415. if (text == NULL)
  187416. {
  187417. png_free(png_ptr,chunkdata);
  187418. png_error(png_ptr,"Not enough memory to decompress chunk");
  187419. }
  187420. png_memcpy(text, chunkdata, prefix_size);
  187421. }
  187422. text[text_size - 1] = 0x00;
  187423. /* Copy what we can of the error message into the text chunk */
  187424. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  187425. text_size = png_sizeof(msg) > text_size ? text_size :
  187426. png_sizeof(msg);
  187427. png_memcpy(text + prefix_size, msg, text_size + 1);
  187428. break;
  187429. }
  187430. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  187431. {
  187432. if (text == NULL)
  187433. {
  187434. text_size = prefix_size +
  187435. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  187436. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  187437. if (text == NULL)
  187438. {
  187439. png_free(png_ptr,chunkdata);
  187440. png_error(png_ptr,"Not enough memory to decompress chunk.");
  187441. }
  187442. png_memcpy(text + prefix_size, png_ptr->zbuf,
  187443. text_size - prefix_size);
  187444. png_memcpy(text, chunkdata, prefix_size);
  187445. *(text + text_size) = 0x00;
  187446. }
  187447. else
  187448. {
  187449. png_charp tmp;
  187450. tmp = text;
  187451. text = (png_charp)png_malloc_warn(png_ptr,
  187452. (png_uint_32)(text_size +
  187453. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  187454. if (text == NULL)
  187455. {
  187456. png_free(png_ptr, tmp);
  187457. png_free(png_ptr, chunkdata);
  187458. png_error(png_ptr,"Not enough memory to decompress chunk..");
  187459. }
  187460. png_memcpy(text, tmp, text_size);
  187461. png_free(png_ptr, tmp);
  187462. png_memcpy(text + text_size, png_ptr->zbuf,
  187463. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  187464. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  187465. *(text + text_size) = 0x00;
  187466. }
  187467. if (ret == Z_STREAM_END)
  187468. break;
  187469. else
  187470. {
  187471. png_ptr->zstream.next_out = png_ptr->zbuf;
  187472. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187473. }
  187474. }
  187475. }
  187476. if (ret != Z_STREAM_END)
  187477. {
  187478. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187479. char umsg[52];
  187480. if (ret == Z_BUF_ERROR)
  187481. png_snprintf(umsg, 52,
  187482. "Buffer error in compressed datastream in %s chunk",
  187483. png_ptr->chunk_name);
  187484. else if (ret == Z_DATA_ERROR)
  187485. png_snprintf(umsg, 52,
  187486. "Data error in compressed datastream in %s chunk",
  187487. png_ptr->chunk_name);
  187488. else
  187489. png_snprintf(umsg, 52,
  187490. "Incomplete compressed datastream in %s chunk",
  187491. png_ptr->chunk_name);
  187492. png_warning(png_ptr, umsg);
  187493. #else
  187494. png_warning(png_ptr,
  187495. "Incomplete compressed datastream in chunk other than IDAT");
  187496. #endif
  187497. text_size=prefix_size;
  187498. if (text == NULL)
  187499. {
  187500. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  187501. if (text == NULL)
  187502. {
  187503. png_free(png_ptr, chunkdata);
  187504. png_error(png_ptr,"Not enough memory for text.");
  187505. }
  187506. png_memcpy(text, chunkdata, prefix_size);
  187507. }
  187508. *(text + text_size) = 0x00;
  187509. }
  187510. inflateReset(&png_ptr->zstream);
  187511. png_ptr->zstream.avail_in = 0;
  187512. png_free(png_ptr, chunkdata);
  187513. chunkdata = text;
  187514. *newlength=text_size;
  187515. }
  187516. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  187517. {
  187518. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187519. char umsg[50];
  187520. png_snprintf(umsg, 50,
  187521. "Unknown zTXt compression type %d", comp_type);
  187522. png_warning(png_ptr, umsg);
  187523. #else
  187524. png_warning(png_ptr, "Unknown zTXt compression type");
  187525. #endif
  187526. *(chunkdata + prefix_size) = 0x00;
  187527. *newlength=prefix_size;
  187528. }
  187529. return chunkdata;
  187530. }
  187531. #endif
  187532. /* read and check the IDHR chunk */
  187533. void /* PRIVATE */
  187534. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187535. {
  187536. png_byte buf[13];
  187537. png_uint_32 width, height;
  187538. int bit_depth, color_type, compression_type, filter_type;
  187539. int interlace_type;
  187540. png_debug(1, "in png_handle_IHDR\n");
  187541. if (png_ptr->mode & PNG_HAVE_IHDR)
  187542. png_error(png_ptr, "Out of place IHDR");
  187543. /* check the length */
  187544. if (length != 13)
  187545. png_error(png_ptr, "Invalid IHDR chunk");
  187546. png_ptr->mode |= PNG_HAVE_IHDR;
  187547. png_crc_read(png_ptr, buf, 13);
  187548. png_crc_finish(png_ptr, 0);
  187549. width = png_get_uint_31(png_ptr, buf);
  187550. height = png_get_uint_31(png_ptr, buf + 4);
  187551. bit_depth = buf[8];
  187552. color_type = buf[9];
  187553. compression_type = buf[10];
  187554. filter_type = buf[11];
  187555. interlace_type = buf[12];
  187556. /* set internal variables */
  187557. png_ptr->width = width;
  187558. png_ptr->height = height;
  187559. png_ptr->bit_depth = (png_byte)bit_depth;
  187560. png_ptr->interlaced = (png_byte)interlace_type;
  187561. png_ptr->color_type = (png_byte)color_type;
  187562. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187563. png_ptr->filter_type = (png_byte)filter_type;
  187564. #endif
  187565. png_ptr->compression_type = (png_byte)compression_type;
  187566. /* find number of channels */
  187567. switch (png_ptr->color_type)
  187568. {
  187569. case PNG_COLOR_TYPE_GRAY:
  187570. case PNG_COLOR_TYPE_PALETTE:
  187571. png_ptr->channels = 1;
  187572. break;
  187573. case PNG_COLOR_TYPE_RGB:
  187574. png_ptr->channels = 3;
  187575. break;
  187576. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187577. png_ptr->channels = 2;
  187578. break;
  187579. case PNG_COLOR_TYPE_RGB_ALPHA:
  187580. png_ptr->channels = 4;
  187581. break;
  187582. }
  187583. /* set up other useful info */
  187584. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  187585. png_ptr->channels);
  187586. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  187587. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  187588. png_debug1(3,"channels = %d\n", png_ptr->channels);
  187589. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  187590. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  187591. color_type, interlace_type, compression_type, filter_type);
  187592. }
  187593. /* read and check the palette */
  187594. void /* PRIVATE */
  187595. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187596. {
  187597. png_color palette[PNG_MAX_PALETTE_LENGTH];
  187598. int num, i;
  187599. #ifndef PNG_NO_POINTER_INDEXING
  187600. png_colorp pal_ptr;
  187601. #endif
  187602. png_debug(1, "in png_handle_PLTE\n");
  187603. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187604. png_error(png_ptr, "Missing IHDR before PLTE");
  187605. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187606. {
  187607. png_warning(png_ptr, "Invalid PLTE after IDAT");
  187608. png_crc_finish(png_ptr, length);
  187609. return;
  187610. }
  187611. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187612. png_error(png_ptr, "Duplicate PLTE chunk");
  187613. png_ptr->mode |= PNG_HAVE_PLTE;
  187614. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  187615. {
  187616. png_warning(png_ptr,
  187617. "Ignoring PLTE chunk in grayscale PNG");
  187618. png_crc_finish(png_ptr, length);
  187619. return;
  187620. }
  187621. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187622. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  187623. {
  187624. png_crc_finish(png_ptr, length);
  187625. return;
  187626. }
  187627. #endif
  187628. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  187629. {
  187630. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  187631. {
  187632. png_warning(png_ptr, "Invalid palette chunk");
  187633. png_crc_finish(png_ptr, length);
  187634. return;
  187635. }
  187636. else
  187637. {
  187638. png_error(png_ptr, "Invalid palette chunk");
  187639. }
  187640. }
  187641. num = (int)length / 3;
  187642. #ifndef PNG_NO_POINTER_INDEXING
  187643. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  187644. {
  187645. png_byte buf[3];
  187646. png_crc_read(png_ptr, buf, 3);
  187647. pal_ptr->red = buf[0];
  187648. pal_ptr->green = buf[1];
  187649. pal_ptr->blue = buf[2];
  187650. }
  187651. #else
  187652. for (i = 0; i < num; i++)
  187653. {
  187654. png_byte buf[3];
  187655. png_crc_read(png_ptr, buf, 3);
  187656. /* don't depend upon png_color being any order */
  187657. palette[i].red = buf[0];
  187658. palette[i].green = buf[1];
  187659. palette[i].blue = buf[2];
  187660. }
  187661. #endif
  187662. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  187663. whatever the normal CRC configuration tells us. However, if we
  187664. have an RGB image, the PLTE can be considered ancillary, so
  187665. we will act as though it is. */
  187666. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187667. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187668. #endif
  187669. {
  187670. png_crc_finish(png_ptr, 0);
  187671. }
  187672. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187673. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  187674. {
  187675. /* If we don't want to use the data from an ancillary chunk,
  187676. we have two options: an error abort, or a warning and we
  187677. ignore the data in this chunk (which should be OK, since
  187678. it's considered ancillary for a RGB or RGBA image). */
  187679. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  187680. {
  187681. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  187682. {
  187683. png_chunk_error(png_ptr, "CRC error");
  187684. }
  187685. else
  187686. {
  187687. png_chunk_warning(png_ptr, "CRC error");
  187688. return;
  187689. }
  187690. }
  187691. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  187692. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  187693. {
  187694. png_chunk_warning(png_ptr, "CRC error");
  187695. }
  187696. }
  187697. #endif
  187698. png_set_PLTE(png_ptr, info_ptr, palette, num);
  187699. #if defined(PNG_READ_tRNS_SUPPORTED)
  187700. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187701. {
  187702. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  187703. {
  187704. if (png_ptr->num_trans > (png_uint_16)num)
  187705. {
  187706. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  187707. png_ptr->num_trans = (png_uint_16)num;
  187708. }
  187709. if (info_ptr->num_trans > (png_uint_16)num)
  187710. {
  187711. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  187712. info_ptr->num_trans = (png_uint_16)num;
  187713. }
  187714. }
  187715. }
  187716. #endif
  187717. }
  187718. void /* PRIVATE */
  187719. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187720. {
  187721. png_debug(1, "in png_handle_IEND\n");
  187722. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  187723. {
  187724. png_error(png_ptr, "No image in file");
  187725. }
  187726. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  187727. if (length != 0)
  187728. {
  187729. png_warning(png_ptr, "Incorrect IEND chunk length");
  187730. }
  187731. png_crc_finish(png_ptr, length);
  187732. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  187733. }
  187734. #if defined(PNG_READ_gAMA_SUPPORTED)
  187735. void /* PRIVATE */
  187736. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187737. {
  187738. png_fixed_point igamma;
  187739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187740. float file_gamma;
  187741. #endif
  187742. png_byte buf[4];
  187743. png_debug(1, "in png_handle_gAMA\n");
  187744. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187745. png_error(png_ptr, "Missing IHDR before gAMA");
  187746. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187747. {
  187748. png_warning(png_ptr, "Invalid gAMA after IDAT");
  187749. png_crc_finish(png_ptr, length);
  187750. return;
  187751. }
  187752. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187753. /* Should be an error, but we can cope with it */
  187754. png_warning(png_ptr, "Out of place gAMA chunk");
  187755. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  187756. #if defined(PNG_READ_sRGB_SUPPORTED)
  187757. && !(info_ptr->valid & PNG_INFO_sRGB)
  187758. #endif
  187759. )
  187760. {
  187761. png_warning(png_ptr, "Duplicate gAMA chunk");
  187762. png_crc_finish(png_ptr, length);
  187763. return;
  187764. }
  187765. if (length != 4)
  187766. {
  187767. png_warning(png_ptr, "Incorrect gAMA chunk length");
  187768. png_crc_finish(png_ptr, length);
  187769. return;
  187770. }
  187771. png_crc_read(png_ptr, buf, 4);
  187772. if (png_crc_finish(png_ptr, 0))
  187773. return;
  187774. igamma = (png_fixed_point)png_get_uint_32(buf);
  187775. /* check for zero gamma */
  187776. if (igamma == 0)
  187777. {
  187778. png_warning(png_ptr,
  187779. "Ignoring gAMA chunk with gamma=0");
  187780. return;
  187781. }
  187782. #if defined(PNG_READ_sRGB_SUPPORTED)
  187783. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  187784. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  187785. {
  187786. png_warning(png_ptr,
  187787. "Ignoring incorrect gAMA value when sRGB is also present");
  187788. #ifndef PNG_NO_CONSOLE_IO
  187789. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  187790. #endif
  187791. return;
  187792. }
  187793. #endif /* PNG_READ_sRGB_SUPPORTED */
  187794. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187795. file_gamma = (float)igamma / (float)100000.0;
  187796. # ifdef PNG_READ_GAMMA_SUPPORTED
  187797. png_ptr->gamma = file_gamma;
  187798. # endif
  187799. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  187800. #endif
  187801. #ifdef PNG_FIXED_POINT_SUPPORTED
  187802. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  187803. #endif
  187804. }
  187805. #endif
  187806. #if defined(PNG_READ_sBIT_SUPPORTED)
  187807. void /* PRIVATE */
  187808. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187809. {
  187810. png_size_t truelen;
  187811. png_byte buf[4];
  187812. png_debug(1, "in png_handle_sBIT\n");
  187813. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  187814. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187815. png_error(png_ptr, "Missing IHDR before sBIT");
  187816. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187817. {
  187818. png_warning(png_ptr, "Invalid sBIT after IDAT");
  187819. png_crc_finish(png_ptr, length);
  187820. return;
  187821. }
  187822. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187823. {
  187824. /* Should be an error, but we can cope with it */
  187825. png_warning(png_ptr, "Out of place sBIT chunk");
  187826. }
  187827. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  187828. {
  187829. png_warning(png_ptr, "Duplicate sBIT chunk");
  187830. png_crc_finish(png_ptr, length);
  187831. return;
  187832. }
  187833. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187834. truelen = 3;
  187835. else
  187836. truelen = (png_size_t)png_ptr->channels;
  187837. if (length != truelen || length > 4)
  187838. {
  187839. png_warning(png_ptr, "Incorrect sBIT chunk length");
  187840. png_crc_finish(png_ptr, length);
  187841. return;
  187842. }
  187843. png_crc_read(png_ptr, buf, truelen);
  187844. if (png_crc_finish(png_ptr, 0))
  187845. return;
  187846. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187847. {
  187848. png_ptr->sig_bit.red = buf[0];
  187849. png_ptr->sig_bit.green = buf[1];
  187850. png_ptr->sig_bit.blue = buf[2];
  187851. png_ptr->sig_bit.alpha = buf[3];
  187852. }
  187853. else
  187854. {
  187855. png_ptr->sig_bit.gray = buf[0];
  187856. png_ptr->sig_bit.red = buf[0];
  187857. png_ptr->sig_bit.green = buf[0];
  187858. png_ptr->sig_bit.blue = buf[0];
  187859. png_ptr->sig_bit.alpha = buf[1];
  187860. }
  187861. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  187862. }
  187863. #endif
  187864. #if defined(PNG_READ_cHRM_SUPPORTED)
  187865. void /* PRIVATE */
  187866. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187867. {
  187868. png_byte buf[4];
  187869. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187870. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  187871. #endif
  187872. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  187873. int_y_green, int_x_blue, int_y_blue;
  187874. png_uint_32 uint_x, uint_y;
  187875. png_debug(1, "in png_handle_cHRM\n");
  187876. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187877. png_error(png_ptr, "Missing IHDR before cHRM");
  187878. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187879. {
  187880. png_warning(png_ptr, "Invalid cHRM after IDAT");
  187881. png_crc_finish(png_ptr, length);
  187882. return;
  187883. }
  187884. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187885. /* Should be an error, but we can cope with it */
  187886. png_warning(png_ptr, "Missing PLTE before cHRM");
  187887. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  187888. #if defined(PNG_READ_sRGB_SUPPORTED)
  187889. && !(info_ptr->valid & PNG_INFO_sRGB)
  187890. #endif
  187891. )
  187892. {
  187893. png_warning(png_ptr, "Duplicate cHRM chunk");
  187894. png_crc_finish(png_ptr, length);
  187895. return;
  187896. }
  187897. if (length != 32)
  187898. {
  187899. png_warning(png_ptr, "Incorrect cHRM chunk length");
  187900. png_crc_finish(png_ptr, length);
  187901. return;
  187902. }
  187903. png_crc_read(png_ptr, buf, 4);
  187904. uint_x = png_get_uint_32(buf);
  187905. png_crc_read(png_ptr, buf, 4);
  187906. uint_y = png_get_uint_32(buf);
  187907. if (uint_x > 80000L || uint_y > 80000L ||
  187908. uint_x + uint_y > 100000L)
  187909. {
  187910. png_warning(png_ptr, "Invalid cHRM white point");
  187911. png_crc_finish(png_ptr, 24);
  187912. return;
  187913. }
  187914. int_x_white = (png_fixed_point)uint_x;
  187915. int_y_white = (png_fixed_point)uint_y;
  187916. png_crc_read(png_ptr, buf, 4);
  187917. uint_x = png_get_uint_32(buf);
  187918. png_crc_read(png_ptr, buf, 4);
  187919. uint_y = png_get_uint_32(buf);
  187920. if (uint_x + uint_y > 100000L)
  187921. {
  187922. png_warning(png_ptr, "Invalid cHRM red point");
  187923. png_crc_finish(png_ptr, 16);
  187924. return;
  187925. }
  187926. int_x_red = (png_fixed_point)uint_x;
  187927. int_y_red = (png_fixed_point)uint_y;
  187928. png_crc_read(png_ptr, buf, 4);
  187929. uint_x = png_get_uint_32(buf);
  187930. png_crc_read(png_ptr, buf, 4);
  187931. uint_y = png_get_uint_32(buf);
  187932. if (uint_x + uint_y > 100000L)
  187933. {
  187934. png_warning(png_ptr, "Invalid cHRM green point");
  187935. png_crc_finish(png_ptr, 8);
  187936. return;
  187937. }
  187938. int_x_green = (png_fixed_point)uint_x;
  187939. int_y_green = (png_fixed_point)uint_y;
  187940. png_crc_read(png_ptr, buf, 4);
  187941. uint_x = png_get_uint_32(buf);
  187942. png_crc_read(png_ptr, buf, 4);
  187943. uint_y = png_get_uint_32(buf);
  187944. if (uint_x + uint_y > 100000L)
  187945. {
  187946. png_warning(png_ptr, "Invalid cHRM blue point");
  187947. png_crc_finish(png_ptr, 0);
  187948. return;
  187949. }
  187950. int_x_blue = (png_fixed_point)uint_x;
  187951. int_y_blue = (png_fixed_point)uint_y;
  187952. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187953. white_x = (float)int_x_white / (float)100000.0;
  187954. white_y = (float)int_y_white / (float)100000.0;
  187955. red_x = (float)int_x_red / (float)100000.0;
  187956. red_y = (float)int_y_red / (float)100000.0;
  187957. green_x = (float)int_x_green / (float)100000.0;
  187958. green_y = (float)int_y_green / (float)100000.0;
  187959. blue_x = (float)int_x_blue / (float)100000.0;
  187960. blue_y = (float)int_y_blue / (float)100000.0;
  187961. #endif
  187962. #if defined(PNG_READ_sRGB_SUPPORTED)
  187963. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  187964. {
  187965. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  187966. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  187967. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  187968. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  187969. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  187970. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  187971. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  187972. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  187973. {
  187974. png_warning(png_ptr,
  187975. "Ignoring incorrect cHRM value when sRGB is also present");
  187976. #ifndef PNG_NO_CONSOLE_IO
  187977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187978. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  187979. white_x, white_y, red_x, red_y);
  187980. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  187981. green_x, green_y, blue_x, blue_y);
  187982. #else
  187983. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  187984. int_x_white, int_y_white, int_x_red, int_y_red);
  187985. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  187986. int_x_green, int_y_green, int_x_blue, int_y_blue);
  187987. #endif
  187988. #endif /* PNG_NO_CONSOLE_IO */
  187989. }
  187990. png_crc_finish(png_ptr, 0);
  187991. return;
  187992. }
  187993. #endif /* PNG_READ_sRGB_SUPPORTED */
  187994. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187995. png_set_cHRM(png_ptr, info_ptr,
  187996. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  187997. #endif
  187998. #ifdef PNG_FIXED_POINT_SUPPORTED
  187999. png_set_cHRM_fixed(png_ptr, info_ptr,
  188000. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188001. int_y_green, int_x_blue, int_y_blue);
  188002. #endif
  188003. if (png_crc_finish(png_ptr, 0))
  188004. return;
  188005. }
  188006. #endif
  188007. #if defined(PNG_READ_sRGB_SUPPORTED)
  188008. void /* PRIVATE */
  188009. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188010. {
  188011. int intent;
  188012. png_byte buf[1];
  188013. png_debug(1, "in png_handle_sRGB\n");
  188014. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188015. png_error(png_ptr, "Missing IHDR before sRGB");
  188016. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188017. {
  188018. png_warning(png_ptr, "Invalid sRGB after IDAT");
  188019. png_crc_finish(png_ptr, length);
  188020. return;
  188021. }
  188022. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188023. /* Should be an error, but we can cope with it */
  188024. png_warning(png_ptr, "Out of place sRGB chunk");
  188025. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188026. {
  188027. png_warning(png_ptr, "Duplicate sRGB chunk");
  188028. png_crc_finish(png_ptr, length);
  188029. return;
  188030. }
  188031. if (length != 1)
  188032. {
  188033. png_warning(png_ptr, "Incorrect sRGB chunk length");
  188034. png_crc_finish(png_ptr, length);
  188035. return;
  188036. }
  188037. png_crc_read(png_ptr, buf, 1);
  188038. if (png_crc_finish(png_ptr, 0))
  188039. return;
  188040. intent = buf[0];
  188041. /* check for bad intent */
  188042. if (intent >= PNG_sRGB_INTENT_LAST)
  188043. {
  188044. png_warning(png_ptr, "Unknown sRGB intent");
  188045. return;
  188046. }
  188047. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  188048. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  188049. {
  188050. png_fixed_point igamma;
  188051. #ifdef PNG_FIXED_POINT_SUPPORTED
  188052. igamma=info_ptr->int_gamma;
  188053. #else
  188054. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188055. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  188056. # endif
  188057. #endif
  188058. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188059. {
  188060. png_warning(png_ptr,
  188061. "Ignoring incorrect gAMA value when sRGB is also present");
  188062. #ifndef PNG_NO_CONSOLE_IO
  188063. # ifdef PNG_FIXED_POINT_SUPPORTED
  188064. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  188065. # else
  188066. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188067. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  188068. # endif
  188069. # endif
  188070. #endif
  188071. }
  188072. }
  188073. #endif /* PNG_READ_gAMA_SUPPORTED */
  188074. #ifdef PNG_READ_cHRM_SUPPORTED
  188075. #ifdef PNG_FIXED_POINT_SUPPORTED
  188076. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  188077. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  188078. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  188079. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  188080. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  188081. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  188082. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  188083. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  188084. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  188085. {
  188086. png_warning(png_ptr,
  188087. "Ignoring incorrect cHRM value when sRGB is also present");
  188088. }
  188089. #endif /* PNG_FIXED_POINT_SUPPORTED */
  188090. #endif /* PNG_READ_cHRM_SUPPORTED */
  188091. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  188092. }
  188093. #endif /* PNG_READ_sRGB_SUPPORTED */
  188094. #if defined(PNG_READ_iCCP_SUPPORTED)
  188095. void /* PRIVATE */
  188096. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188097. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188098. {
  188099. png_charp chunkdata;
  188100. png_byte compression_type;
  188101. png_bytep pC;
  188102. png_charp profile;
  188103. png_uint_32 skip = 0;
  188104. png_uint_32 profile_size, profile_length;
  188105. png_size_t slength, prefix_length, data_length;
  188106. png_debug(1, "in png_handle_iCCP\n");
  188107. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188108. png_error(png_ptr, "Missing IHDR before iCCP");
  188109. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188110. {
  188111. png_warning(png_ptr, "Invalid iCCP after IDAT");
  188112. png_crc_finish(png_ptr, length);
  188113. return;
  188114. }
  188115. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188116. /* Should be an error, but we can cope with it */
  188117. png_warning(png_ptr, "Out of place iCCP chunk");
  188118. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  188119. {
  188120. png_warning(png_ptr, "Duplicate iCCP chunk");
  188121. png_crc_finish(png_ptr, length);
  188122. return;
  188123. }
  188124. #ifdef PNG_MAX_MALLOC_64K
  188125. if (length > (png_uint_32)65535L)
  188126. {
  188127. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  188128. skip = length - (png_uint_32)65535L;
  188129. length = (png_uint_32)65535L;
  188130. }
  188131. #endif
  188132. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  188133. slength = (png_size_t)length;
  188134. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188135. if (png_crc_finish(png_ptr, skip))
  188136. {
  188137. png_free(png_ptr, chunkdata);
  188138. return;
  188139. }
  188140. chunkdata[slength] = 0x00;
  188141. for (profile = chunkdata; *profile; profile++)
  188142. /* empty loop to find end of name */ ;
  188143. ++profile;
  188144. /* there should be at least one zero (the compression type byte)
  188145. following the separator, and we should be on it */
  188146. if ( profile >= chunkdata + slength - 1)
  188147. {
  188148. png_free(png_ptr, chunkdata);
  188149. png_warning(png_ptr, "Malformed iCCP chunk");
  188150. return;
  188151. }
  188152. /* compression_type should always be zero */
  188153. compression_type = *profile++;
  188154. if (compression_type)
  188155. {
  188156. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  188157. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  188158. wrote nonzero) */
  188159. }
  188160. prefix_length = profile - chunkdata;
  188161. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  188162. slength, prefix_length, &data_length);
  188163. profile_length = data_length - prefix_length;
  188164. if ( prefix_length > data_length || profile_length < 4)
  188165. {
  188166. png_free(png_ptr, chunkdata);
  188167. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  188168. return;
  188169. }
  188170. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  188171. pC = (png_bytep)(chunkdata+prefix_length);
  188172. profile_size = ((*(pC ))<<24) |
  188173. ((*(pC+1))<<16) |
  188174. ((*(pC+2))<< 8) |
  188175. ((*(pC+3)) );
  188176. if(profile_size < profile_length)
  188177. profile_length = profile_size;
  188178. if(profile_size > profile_length)
  188179. {
  188180. png_free(png_ptr, chunkdata);
  188181. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  188182. return;
  188183. }
  188184. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  188185. chunkdata + prefix_length, profile_length);
  188186. png_free(png_ptr, chunkdata);
  188187. }
  188188. #endif /* PNG_READ_iCCP_SUPPORTED */
  188189. #if defined(PNG_READ_sPLT_SUPPORTED)
  188190. void /* PRIVATE */
  188191. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188192. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188193. {
  188194. png_bytep chunkdata;
  188195. png_bytep entry_start;
  188196. png_sPLT_t new_palette;
  188197. #ifdef PNG_NO_POINTER_INDEXING
  188198. png_sPLT_entryp pp;
  188199. #endif
  188200. int data_length, entry_size, i;
  188201. png_uint_32 skip = 0;
  188202. png_size_t slength;
  188203. png_debug(1, "in png_handle_sPLT\n");
  188204. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188205. png_error(png_ptr, "Missing IHDR before sPLT");
  188206. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188207. {
  188208. png_warning(png_ptr, "Invalid sPLT after IDAT");
  188209. png_crc_finish(png_ptr, length);
  188210. return;
  188211. }
  188212. #ifdef PNG_MAX_MALLOC_64K
  188213. if (length > (png_uint_32)65535L)
  188214. {
  188215. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  188216. skip = length - (png_uint_32)65535L;
  188217. length = (png_uint_32)65535L;
  188218. }
  188219. #endif
  188220. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  188221. slength = (png_size_t)length;
  188222. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188223. if (png_crc_finish(png_ptr, skip))
  188224. {
  188225. png_free(png_ptr, chunkdata);
  188226. return;
  188227. }
  188228. chunkdata[slength] = 0x00;
  188229. for (entry_start = chunkdata; *entry_start; entry_start++)
  188230. /* empty loop to find end of name */ ;
  188231. ++entry_start;
  188232. /* a sample depth should follow the separator, and we should be on it */
  188233. if (entry_start > chunkdata + slength - 2)
  188234. {
  188235. png_free(png_ptr, chunkdata);
  188236. png_warning(png_ptr, "malformed sPLT chunk");
  188237. return;
  188238. }
  188239. new_palette.depth = *entry_start++;
  188240. entry_size = (new_palette.depth == 8 ? 6 : 10);
  188241. data_length = (slength - (entry_start - chunkdata));
  188242. /* integrity-check the data length */
  188243. if (data_length % entry_size)
  188244. {
  188245. png_free(png_ptr, chunkdata);
  188246. png_warning(png_ptr, "sPLT chunk has bad length");
  188247. return;
  188248. }
  188249. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  188250. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  188251. png_sizeof(png_sPLT_entry)))
  188252. {
  188253. png_warning(png_ptr, "sPLT chunk too long");
  188254. return;
  188255. }
  188256. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  188257. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  188258. if (new_palette.entries == NULL)
  188259. {
  188260. png_warning(png_ptr, "sPLT chunk requires too much memory");
  188261. return;
  188262. }
  188263. #ifndef PNG_NO_POINTER_INDEXING
  188264. for (i = 0; i < new_palette.nentries; i++)
  188265. {
  188266. png_sPLT_entryp pp = new_palette.entries + i;
  188267. if (new_palette.depth == 8)
  188268. {
  188269. pp->red = *entry_start++;
  188270. pp->green = *entry_start++;
  188271. pp->blue = *entry_start++;
  188272. pp->alpha = *entry_start++;
  188273. }
  188274. else
  188275. {
  188276. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  188277. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  188278. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  188279. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  188280. }
  188281. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  188282. }
  188283. #else
  188284. pp = new_palette.entries;
  188285. for (i = 0; i < new_palette.nentries; i++)
  188286. {
  188287. if (new_palette.depth == 8)
  188288. {
  188289. pp[i].red = *entry_start++;
  188290. pp[i].green = *entry_start++;
  188291. pp[i].blue = *entry_start++;
  188292. pp[i].alpha = *entry_start++;
  188293. }
  188294. else
  188295. {
  188296. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  188297. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  188298. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  188299. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  188300. }
  188301. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  188302. }
  188303. #endif
  188304. /* discard all chunk data except the name and stash that */
  188305. new_palette.name = (png_charp)chunkdata;
  188306. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  188307. png_free(png_ptr, chunkdata);
  188308. png_free(png_ptr, new_palette.entries);
  188309. }
  188310. #endif /* PNG_READ_sPLT_SUPPORTED */
  188311. #if defined(PNG_READ_tRNS_SUPPORTED)
  188312. void /* PRIVATE */
  188313. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188314. {
  188315. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  188316. int bit_mask;
  188317. png_debug(1, "in png_handle_tRNS\n");
  188318. /* For non-indexed color, mask off any bits in the tRNS value that
  188319. * exceed the bit depth. Some creators were writing extra bits there.
  188320. * This is not needed for indexed color. */
  188321. bit_mask = (1 << png_ptr->bit_depth) - 1;
  188322. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188323. png_error(png_ptr, "Missing IHDR before tRNS");
  188324. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188325. {
  188326. png_warning(png_ptr, "Invalid tRNS after IDAT");
  188327. png_crc_finish(png_ptr, length);
  188328. return;
  188329. }
  188330. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  188331. {
  188332. png_warning(png_ptr, "Duplicate tRNS chunk");
  188333. png_crc_finish(png_ptr, length);
  188334. return;
  188335. }
  188336. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  188337. {
  188338. png_byte buf[2];
  188339. if (length != 2)
  188340. {
  188341. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188342. png_crc_finish(png_ptr, length);
  188343. return;
  188344. }
  188345. png_crc_read(png_ptr, buf, 2);
  188346. png_ptr->num_trans = 1;
  188347. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  188348. }
  188349. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  188350. {
  188351. png_byte buf[6];
  188352. if (length != 6)
  188353. {
  188354. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188355. png_crc_finish(png_ptr, length);
  188356. return;
  188357. }
  188358. png_crc_read(png_ptr, buf, (png_size_t)length);
  188359. png_ptr->num_trans = 1;
  188360. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  188361. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  188362. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  188363. }
  188364. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188365. {
  188366. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  188367. {
  188368. /* Should be an error, but we can cope with it. */
  188369. png_warning(png_ptr, "Missing PLTE before tRNS");
  188370. }
  188371. if (length > (png_uint_32)png_ptr->num_palette ||
  188372. length > PNG_MAX_PALETTE_LENGTH)
  188373. {
  188374. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188375. png_crc_finish(png_ptr, length);
  188376. return;
  188377. }
  188378. if (length == 0)
  188379. {
  188380. png_warning(png_ptr, "Zero length tRNS chunk");
  188381. png_crc_finish(png_ptr, length);
  188382. return;
  188383. }
  188384. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  188385. png_ptr->num_trans = (png_uint_16)length;
  188386. }
  188387. else
  188388. {
  188389. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  188390. png_crc_finish(png_ptr, length);
  188391. return;
  188392. }
  188393. if (png_crc_finish(png_ptr, 0))
  188394. {
  188395. png_ptr->num_trans = 0;
  188396. return;
  188397. }
  188398. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  188399. &(png_ptr->trans_values));
  188400. }
  188401. #endif
  188402. #if defined(PNG_READ_bKGD_SUPPORTED)
  188403. void /* PRIVATE */
  188404. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188405. {
  188406. png_size_t truelen;
  188407. png_byte buf[6];
  188408. png_debug(1, "in png_handle_bKGD\n");
  188409. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188410. png_error(png_ptr, "Missing IHDR before bKGD");
  188411. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188412. {
  188413. png_warning(png_ptr, "Invalid bKGD after IDAT");
  188414. png_crc_finish(png_ptr, length);
  188415. return;
  188416. }
  188417. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188418. !(png_ptr->mode & PNG_HAVE_PLTE))
  188419. {
  188420. png_warning(png_ptr, "Missing PLTE before bKGD");
  188421. png_crc_finish(png_ptr, length);
  188422. return;
  188423. }
  188424. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  188425. {
  188426. png_warning(png_ptr, "Duplicate bKGD chunk");
  188427. png_crc_finish(png_ptr, length);
  188428. return;
  188429. }
  188430. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188431. truelen = 1;
  188432. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188433. truelen = 6;
  188434. else
  188435. truelen = 2;
  188436. if (length != truelen)
  188437. {
  188438. png_warning(png_ptr, "Incorrect bKGD chunk length");
  188439. png_crc_finish(png_ptr, length);
  188440. return;
  188441. }
  188442. png_crc_read(png_ptr, buf, truelen);
  188443. if (png_crc_finish(png_ptr, 0))
  188444. return;
  188445. /* We convert the index value into RGB components so that we can allow
  188446. * arbitrary RGB values for background when we have transparency, and
  188447. * so it is easy to determine the RGB values of the background color
  188448. * from the info_ptr struct. */
  188449. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188450. {
  188451. png_ptr->background.index = buf[0];
  188452. if(info_ptr->num_palette)
  188453. {
  188454. if(buf[0] > info_ptr->num_palette)
  188455. {
  188456. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  188457. return;
  188458. }
  188459. png_ptr->background.red =
  188460. (png_uint_16)png_ptr->palette[buf[0]].red;
  188461. png_ptr->background.green =
  188462. (png_uint_16)png_ptr->palette[buf[0]].green;
  188463. png_ptr->background.blue =
  188464. (png_uint_16)png_ptr->palette[buf[0]].blue;
  188465. }
  188466. }
  188467. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  188468. {
  188469. png_ptr->background.red =
  188470. png_ptr->background.green =
  188471. png_ptr->background.blue =
  188472. png_ptr->background.gray = png_get_uint_16(buf);
  188473. }
  188474. else
  188475. {
  188476. png_ptr->background.red = png_get_uint_16(buf);
  188477. png_ptr->background.green = png_get_uint_16(buf + 2);
  188478. png_ptr->background.blue = png_get_uint_16(buf + 4);
  188479. }
  188480. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  188481. }
  188482. #endif
  188483. #if defined(PNG_READ_hIST_SUPPORTED)
  188484. void /* PRIVATE */
  188485. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188486. {
  188487. unsigned int num, i;
  188488. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  188489. png_debug(1, "in png_handle_hIST\n");
  188490. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188491. png_error(png_ptr, "Missing IHDR before hIST");
  188492. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188493. {
  188494. png_warning(png_ptr, "Invalid hIST after IDAT");
  188495. png_crc_finish(png_ptr, length);
  188496. return;
  188497. }
  188498. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  188499. {
  188500. png_warning(png_ptr, "Missing PLTE before hIST");
  188501. png_crc_finish(png_ptr, length);
  188502. return;
  188503. }
  188504. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  188505. {
  188506. png_warning(png_ptr, "Duplicate hIST chunk");
  188507. png_crc_finish(png_ptr, length);
  188508. return;
  188509. }
  188510. num = length / 2 ;
  188511. if (num != (unsigned int) png_ptr->num_palette || num >
  188512. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  188513. {
  188514. png_warning(png_ptr, "Incorrect hIST chunk length");
  188515. png_crc_finish(png_ptr, length);
  188516. return;
  188517. }
  188518. for (i = 0; i < num; i++)
  188519. {
  188520. png_byte buf[2];
  188521. png_crc_read(png_ptr, buf, 2);
  188522. readbuf[i] = png_get_uint_16(buf);
  188523. }
  188524. if (png_crc_finish(png_ptr, 0))
  188525. return;
  188526. png_set_hIST(png_ptr, info_ptr, readbuf);
  188527. }
  188528. #endif
  188529. #if defined(PNG_READ_pHYs_SUPPORTED)
  188530. void /* PRIVATE */
  188531. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188532. {
  188533. png_byte buf[9];
  188534. png_uint_32 res_x, res_y;
  188535. int unit_type;
  188536. png_debug(1, "in png_handle_pHYs\n");
  188537. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188538. png_error(png_ptr, "Missing IHDR before pHYs");
  188539. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188540. {
  188541. png_warning(png_ptr, "Invalid pHYs after IDAT");
  188542. png_crc_finish(png_ptr, length);
  188543. return;
  188544. }
  188545. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  188546. {
  188547. png_warning(png_ptr, "Duplicate pHYs chunk");
  188548. png_crc_finish(png_ptr, length);
  188549. return;
  188550. }
  188551. if (length != 9)
  188552. {
  188553. png_warning(png_ptr, "Incorrect pHYs chunk length");
  188554. png_crc_finish(png_ptr, length);
  188555. return;
  188556. }
  188557. png_crc_read(png_ptr, buf, 9);
  188558. if (png_crc_finish(png_ptr, 0))
  188559. return;
  188560. res_x = png_get_uint_32(buf);
  188561. res_y = png_get_uint_32(buf + 4);
  188562. unit_type = buf[8];
  188563. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  188564. }
  188565. #endif
  188566. #if defined(PNG_READ_oFFs_SUPPORTED)
  188567. void /* PRIVATE */
  188568. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188569. {
  188570. png_byte buf[9];
  188571. png_int_32 offset_x, offset_y;
  188572. int unit_type;
  188573. png_debug(1, "in png_handle_oFFs\n");
  188574. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188575. png_error(png_ptr, "Missing IHDR before oFFs");
  188576. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188577. {
  188578. png_warning(png_ptr, "Invalid oFFs after IDAT");
  188579. png_crc_finish(png_ptr, length);
  188580. return;
  188581. }
  188582. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  188583. {
  188584. png_warning(png_ptr, "Duplicate oFFs chunk");
  188585. png_crc_finish(png_ptr, length);
  188586. return;
  188587. }
  188588. if (length != 9)
  188589. {
  188590. png_warning(png_ptr, "Incorrect oFFs chunk length");
  188591. png_crc_finish(png_ptr, length);
  188592. return;
  188593. }
  188594. png_crc_read(png_ptr, buf, 9);
  188595. if (png_crc_finish(png_ptr, 0))
  188596. return;
  188597. offset_x = png_get_int_32(buf);
  188598. offset_y = png_get_int_32(buf + 4);
  188599. unit_type = buf[8];
  188600. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  188601. }
  188602. #endif
  188603. #if defined(PNG_READ_pCAL_SUPPORTED)
  188604. /* read the pCAL chunk (described in the PNG Extensions document) */
  188605. void /* PRIVATE */
  188606. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188607. {
  188608. png_charp purpose;
  188609. png_int_32 X0, X1;
  188610. png_byte type, nparams;
  188611. png_charp buf, units, endptr;
  188612. png_charpp params;
  188613. png_size_t slength;
  188614. int i;
  188615. png_debug(1, "in png_handle_pCAL\n");
  188616. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188617. png_error(png_ptr, "Missing IHDR before pCAL");
  188618. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188619. {
  188620. png_warning(png_ptr, "Invalid pCAL after IDAT");
  188621. png_crc_finish(png_ptr, length);
  188622. return;
  188623. }
  188624. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  188625. {
  188626. png_warning(png_ptr, "Duplicate pCAL chunk");
  188627. png_crc_finish(png_ptr, length);
  188628. return;
  188629. }
  188630. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  188631. length + 1);
  188632. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188633. if (purpose == NULL)
  188634. {
  188635. png_warning(png_ptr, "No memory for pCAL purpose.");
  188636. return;
  188637. }
  188638. slength = (png_size_t)length;
  188639. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  188640. if (png_crc_finish(png_ptr, 0))
  188641. {
  188642. png_free(png_ptr, purpose);
  188643. return;
  188644. }
  188645. purpose[slength] = 0x00; /* null terminate the last string */
  188646. png_debug(3, "Finding end of pCAL purpose string\n");
  188647. for (buf = purpose; *buf; buf++)
  188648. /* empty loop */ ;
  188649. endptr = purpose + slength;
  188650. /* We need to have at least 12 bytes after the purpose string
  188651. in order to get the parameter information. */
  188652. if (endptr <= buf + 12)
  188653. {
  188654. png_warning(png_ptr, "Invalid pCAL data");
  188655. png_free(png_ptr, purpose);
  188656. return;
  188657. }
  188658. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  188659. X0 = png_get_int_32((png_bytep)buf+1);
  188660. X1 = png_get_int_32((png_bytep)buf+5);
  188661. type = buf[9];
  188662. nparams = buf[10];
  188663. units = buf + 11;
  188664. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  188665. /* Check that we have the right number of parameters for known
  188666. equation types. */
  188667. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  188668. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  188669. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  188670. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  188671. {
  188672. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  188673. png_free(png_ptr, purpose);
  188674. return;
  188675. }
  188676. else if (type >= PNG_EQUATION_LAST)
  188677. {
  188678. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  188679. }
  188680. for (buf = units; *buf; buf++)
  188681. /* Empty loop to move past the units string. */ ;
  188682. png_debug(3, "Allocating pCAL parameters array\n");
  188683. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  188684. *png_sizeof(png_charp))) ;
  188685. if (params == NULL)
  188686. {
  188687. png_free(png_ptr, purpose);
  188688. png_warning(png_ptr, "No memory for pCAL params.");
  188689. return;
  188690. }
  188691. /* Get pointers to the start of each parameter string. */
  188692. for (i = 0; i < (int)nparams; i++)
  188693. {
  188694. buf++; /* Skip the null string terminator from previous parameter. */
  188695. png_debug1(3, "Reading pCAL parameter %d\n", i);
  188696. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  188697. /* Empty loop to move past each parameter string */ ;
  188698. /* Make sure we haven't run out of data yet */
  188699. if (buf > endptr)
  188700. {
  188701. png_warning(png_ptr, "Invalid pCAL data");
  188702. png_free(png_ptr, purpose);
  188703. png_free(png_ptr, params);
  188704. return;
  188705. }
  188706. }
  188707. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  188708. units, params);
  188709. png_free(png_ptr, purpose);
  188710. png_free(png_ptr, params);
  188711. }
  188712. #endif
  188713. #if defined(PNG_READ_sCAL_SUPPORTED)
  188714. /* read the sCAL chunk */
  188715. void /* PRIVATE */
  188716. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188717. {
  188718. png_charp buffer, ep;
  188719. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188720. double width, height;
  188721. png_charp vp;
  188722. #else
  188723. #ifdef PNG_FIXED_POINT_SUPPORTED
  188724. png_charp swidth, sheight;
  188725. #endif
  188726. #endif
  188727. png_size_t slength;
  188728. png_debug(1, "in png_handle_sCAL\n");
  188729. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188730. png_error(png_ptr, "Missing IHDR before sCAL");
  188731. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188732. {
  188733. png_warning(png_ptr, "Invalid sCAL after IDAT");
  188734. png_crc_finish(png_ptr, length);
  188735. return;
  188736. }
  188737. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  188738. {
  188739. png_warning(png_ptr, "Duplicate sCAL chunk");
  188740. png_crc_finish(png_ptr, length);
  188741. return;
  188742. }
  188743. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  188744. length + 1);
  188745. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188746. if (buffer == NULL)
  188747. {
  188748. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  188749. return;
  188750. }
  188751. slength = (png_size_t)length;
  188752. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  188753. if (png_crc_finish(png_ptr, 0))
  188754. {
  188755. png_free(png_ptr, buffer);
  188756. return;
  188757. }
  188758. buffer[slength] = 0x00; /* null terminate the last string */
  188759. ep = buffer + 1; /* skip unit byte */
  188760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188761. width = png_strtod(png_ptr, ep, &vp);
  188762. if (*vp)
  188763. {
  188764. png_warning(png_ptr, "malformed width string in sCAL chunk");
  188765. return;
  188766. }
  188767. #else
  188768. #ifdef PNG_FIXED_POINT_SUPPORTED
  188769. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  188770. if (swidth == NULL)
  188771. {
  188772. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  188773. return;
  188774. }
  188775. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  188776. #endif
  188777. #endif
  188778. for (ep = buffer; *ep; ep++)
  188779. /* empty loop */ ;
  188780. ep++;
  188781. if (buffer + slength < ep)
  188782. {
  188783. png_warning(png_ptr, "Truncated sCAL chunk");
  188784. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  188785. !defined(PNG_FLOATING_POINT_SUPPORTED)
  188786. png_free(png_ptr, swidth);
  188787. #endif
  188788. png_free(png_ptr, buffer);
  188789. return;
  188790. }
  188791. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188792. height = png_strtod(png_ptr, ep, &vp);
  188793. if (*vp)
  188794. {
  188795. png_warning(png_ptr, "malformed height string in sCAL chunk");
  188796. return;
  188797. }
  188798. #else
  188799. #ifdef PNG_FIXED_POINT_SUPPORTED
  188800. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  188801. if (swidth == NULL)
  188802. {
  188803. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  188804. return;
  188805. }
  188806. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  188807. #endif
  188808. #endif
  188809. if (buffer + slength < ep
  188810. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188811. || width <= 0. || height <= 0.
  188812. #endif
  188813. )
  188814. {
  188815. png_warning(png_ptr, "Invalid sCAL data");
  188816. png_free(png_ptr, buffer);
  188817. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  188818. png_free(png_ptr, swidth);
  188819. png_free(png_ptr, sheight);
  188820. #endif
  188821. return;
  188822. }
  188823. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188824. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  188825. #else
  188826. #ifdef PNG_FIXED_POINT_SUPPORTED
  188827. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  188828. #endif
  188829. #endif
  188830. png_free(png_ptr, buffer);
  188831. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  188832. png_free(png_ptr, swidth);
  188833. png_free(png_ptr, sheight);
  188834. #endif
  188835. }
  188836. #endif
  188837. #if defined(PNG_READ_tIME_SUPPORTED)
  188838. void /* PRIVATE */
  188839. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188840. {
  188841. png_byte buf[7];
  188842. png_time mod_time;
  188843. png_debug(1, "in png_handle_tIME\n");
  188844. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188845. png_error(png_ptr, "Out of place tIME chunk");
  188846. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  188847. {
  188848. png_warning(png_ptr, "Duplicate tIME chunk");
  188849. png_crc_finish(png_ptr, length);
  188850. return;
  188851. }
  188852. if (png_ptr->mode & PNG_HAVE_IDAT)
  188853. png_ptr->mode |= PNG_AFTER_IDAT;
  188854. if (length != 7)
  188855. {
  188856. png_warning(png_ptr, "Incorrect tIME chunk length");
  188857. png_crc_finish(png_ptr, length);
  188858. return;
  188859. }
  188860. png_crc_read(png_ptr, buf, 7);
  188861. if (png_crc_finish(png_ptr, 0))
  188862. return;
  188863. mod_time.second = buf[6];
  188864. mod_time.minute = buf[5];
  188865. mod_time.hour = buf[4];
  188866. mod_time.day = buf[3];
  188867. mod_time.month = buf[2];
  188868. mod_time.year = png_get_uint_16(buf);
  188869. png_set_tIME(png_ptr, info_ptr, &mod_time);
  188870. }
  188871. #endif
  188872. #if defined(PNG_READ_tEXt_SUPPORTED)
  188873. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188874. void /* PRIVATE */
  188875. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188876. {
  188877. png_textp text_ptr;
  188878. png_charp key;
  188879. png_charp text;
  188880. png_uint_32 skip = 0;
  188881. png_size_t slength;
  188882. int ret;
  188883. png_debug(1, "in png_handle_tEXt\n");
  188884. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188885. png_error(png_ptr, "Missing IHDR before tEXt");
  188886. if (png_ptr->mode & PNG_HAVE_IDAT)
  188887. png_ptr->mode |= PNG_AFTER_IDAT;
  188888. #ifdef PNG_MAX_MALLOC_64K
  188889. if (length > (png_uint_32)65535L)
  188890. {
  188891. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188892. skip = length - (png_uint_32)65535L;
  188893. length = (png_uint_32)65535L;
  188894. }
  188895. #endif
  188896. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188897. if (key == NULL)
  188898. {
  188899. png_warning(png_ptr, "No memory to process text chunk.");
  188900. return;
  188901. }
  188902. slength = (png_size_t)length;
  188903. png_crc_read(png_ptr, (png_bytep)key, slength);
  188904. if (png_crc_finish(png_ptr, skip))
  188905. {
  188906. png_free(png_ptr, key);
  188907. return;
  188908. }
  188909. key[slength] = 0x00;
  188910. for (text = key; *text; text++)
  188911. /* empty loop to find end of key */ ;
  188912. if (text != key + slength)
  188913. text++;
  188914. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  188915. (png_uint_32)png_sizeof(png_text));
  188916. if (text_ptr == NULL)
  188917. {
  188918. png_warning(png_ptr, "Not enough memory to process text chunk.");
  188919. png_free(png_ptr, key);
  188920. return;
  188921. }
  188922. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188923. text_ptr->key = key;
  188924. #ifdef PNG_iTXt_SUPPORTED
  188925. text_ptr->lang = NULL;
  188926. text_ptr->lang_key = NULL;
  188927. text_ptr->itxt_length = 0;
  188928. #endif
  188929. text_ptr->text = text;
  188930. text_ptr->text_length = png_strlen(text);
  188931. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188932. png_free(png_ptr, key);
  188933. png_free(png_ptr, text_ptr);
  188934. if (ret)
  188935. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  188936. }
  188937. #endif
  188938. #if defined(PNG_READ_zTXt_SUPPORTED)
  188939. /* note: this does not correctly handle chunks that are > 64K under DOS */
  188940. void /* PRIVATE */
  188941. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188942. {
  188943. png_textp text_ptr;
  188944. png_charp chunkdata;
  188945. png_charp text;
  188946. int comp_type;
  188947. int ret;
  188948. png_size_t slength, prefix_len, data_len;
  188949. png_debug(1, "in png_handle_zTXt\n");
  188950. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188951. png_error(png_ptr, "Missing IHDR before zTXt");
  188952. if (png_ptr->mode & PNG_HAVE_IDAT)
  188953. png_ptr->mode |= PNG_AFTER_IDAT;
  188954. #ifdef PNG_MAX_MALLOC_64K
  188955. /* We will no doubt have problems with chunks even half this size, but
  188956. there is no hard and fast rule to tell us where to stop. */
  188957. if (length > (png_uint_32)65535L)
  188958. {
  188959. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  188960. png_crc_finish(png_ptr, length);
  188961. return;
  188962. }
  188963. #endif
  188964. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188965. if (chunkdata == NULL)
  188966. {
  188967. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  188968. return;
  188969. }
  188970. slength = (png_size_t)length;
  188971. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188972. if (png_crc_finish(png_ptr, 0))
  188973. {
  188974. png_free(png_ptr, chunkdata);
  188975. return;
  188976. }
  188977. chunkdata[slength] = 0x00;
  188978. for (text = chunkdata; *text; text++)
  188979. /* empty loop */ ;
  188980. /* zTXt must have some text after the chunkdataword */
  188981. if (text >= chunkdata + slength - 2)
  188982. {
  188983. png_warning(png_ptr, "Truncated zTXt chunk");
  188984. png_free(png_ptr, chunkdata);
  188985. return;
  188986. }
  188987. else
  188988. {
  188989. comp_type = *(++text);
  188990. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  188991. {
  188992. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  188993. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  188994. }
  188995. text++; /* skip the compression_method byte */
  188996. }
  188997. prefix_len = text - chunkdata;
  188998. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  188999. (png_size_t)length, prefix_len, &data_len);
  189000. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189001. (png_uint_32)png_sizeof(png_text));
  189002. if (text_ptr == NULL)
  189003. {
  189004. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  189005. png_free(png_ptr, chunkdata);
  189006. return;
  189007. }
  189008. text_ptr->compression = comp_type;
  189009. text_ptr->key = chunkdata;
  189010. #ifdef PNG_iTXt_SUPPORTED
  189011. text_ptr->lang = NULL;
  189012. text_ptr->lang_key = NULL;
  189013. text_ptr->itxt_length = 0;
  189014. #endif
  189015. text_ptr->text = chunkdata + prefix_len;
  189016. text_ptr->text_length = data_len;
  189017. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189018. png_free(png_ptr, text_ptr);
  189019. png_free(png_ptr, chunkdata);
  189020. if (ret)
  189021. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  189022. }
  189023. #endif
  189024. #if defined(PNG_READ_iTXt_SUPPORTED)
  189025. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189026. void /* PRIVATE */
  189027. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189028. {
  189029. png_textp text_ptr;
  189030. png_charp chunkdata;
  189031. png_charp key, lang, text, lang_key;
  189032. int comp_flag;
  189033. int comp_type = 0;
  189034. int ret;
  189035. png_size_t slength, prefix_len, data_len;
  189036. png_debug(1, "in png_handle_iTXt\n");
  189037. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189038. png_error(png_ptr, "Missing IHDR before iTXt");
  189039. if (png_ptr->mode & PNG_HAVE_IDAT)
  189040. png_ptr->mode |= PNG_AFTER_IDAT;
  189041. #ifdef PNG_MAX_MALLOC_64K
  189042. /* We will no doubt have problems with chunks even half this size, but
  189043. there is no hard and fast rule to tell us where to stop. */
  189044. if (length > (png_uint_32)65535L)
  189045. {
  189046. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  189047. png_crc_finish(png_ptr, length);
  189048. return;
  189049. }
  189050. #endif
  189051. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189052. if (chunkdata == NULL)
  189053. {
  189054. png_warning(png_ptr, "No memory to process iTXt chunk.");
  189055. return;
  189056. }
  189057. slength = (png_size_t)length;
  189058. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189059. if (png_crc_finish(png_ptr, 0))
  189060. {
  189061. png_free(png_ptr, chunkdata);
  189062. return;
  189063. }
  189064. chunkdata[slength] = 0x00;
  189065. for (lang = chunkdata; *lang; lang++)
  189066. /* empty loop */ ;
  189067. lang++; /* skip NUL separator */
  189068. /* iTXt must have a language tag (possibly empty), two compression bytes,
  189069. translated keyword (possibly empty), and possibly some text after the
  189070. keyword */
  189071. if (lang >= chunkdata + slength - 3)
  189072. {
  189073. png_warning(png_ptr, "Truncated iTXt chunk");
  189074. png_free(png_ptr, chunkdata);
  189075. return;
  189076. }
  189077. else
  189078. {
  189079. comp_flag = *lang++;
  189080. comp_type = *lang++;
  189081. }
  189082. for (lang_key = lang; *lang_key; lang_key++)
  189083. /* empty loop */ ;
  189084. lang_key++; /* skip NUL separator */
  189085. if (lang_key >= chunkdata + slength)
  189086. {
  189087. png_warning(png_ptr, "Truncated iTXt chunk");
  189088. png_free(png_ptr, chunkdata);
  189089. return;
  189090. }
  189091. for (text = lang_key; *text; text++)
  189092. /* empty loop */ ;
  189093. text++; /* skip NUL separator */
  189094. if (text >= chunkdata + slength)
  189095. {
  189096. png_warning(png_ptr, "Malformed iTXt chunk");
  189097. png_free(png_ptr, chunkdata);
  189098. return;
  189099. }
  189100. prefix_len = text - chunkdata;
  189101. key=chunkdata;
  189102. if (comp_flag)
  189103. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189104. (size_t)length, prefix_len, &data_len);
  189105. else
  189106. data_len=png_strlen(chunkdata + prefix_len);
  189107. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189108. (png_uint_32)png_sizeof(png_text));
  189109. if (text_ptr == NULL)
  189110. {
  189111. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  189112. png_free(png_ptr, chunkdata);
  189113. return;
  189114. }
  189115. text_ptr->compression = (int)comp_flag + 1;
  189116. text_ptr->lang_key = chunkdata+(lang_key-key);
  189117. text_ptr->lang = chunkdata+(lang-key);
  189118. text_ptr->itxt_length = data_len;
  189119. text_ptr->text_length = 0;
  189120. text_ptr->key = chunkdata;
  189121. text_ptr->text = chunkdata + prefix_len;
  189122. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189123. png_free(png_ptr, text_ptr);
  189124. png_free(png_ptr, chunkdata);
  189125. if (ret)
  189126. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  189127. }
  189128. #endif
  189129. /* This function is called when we haven't found a handler for a
  189130. chunk. If there isn't a problem with the chunk itself (ie bad
  189131. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  189132. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  189133. case it will be saved away to be written out later. */
  189134. void /* PRIVATE */
  189135. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189136. {
  189137. png_uint_32 skip = 0;
  189138. png_debug(1, "in png_handle_unknown\n");
  189139. if (png_ptr->mode & PNG_HAVE_IDAT)
  189140. {
  189141. #ifdef PNG_USE_LOCAL_ARRAYS
  189142. PNG_CONST PNG_IDAT;
  189143. #endif
  189144. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  189145. png_ptr->mode |= PNG_AFTER_IDAT;
  189146. }
  189147. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189148. if (!(png_ptr->chunk_name[0] & 0x20))
  189149. {
  189150. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189151. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189152. PNG_HANDLE_CHUNK_ALWAYS
  189153. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189154. && png_ptr->read_user_chunk_fn == NULL
  189155. #endif
  189156. )
  189157. #endif
  189158. png_chunk_error(png_ptr, "unknown critical chunk");
  189159. }
  189160. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189161. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  189162. (png_ptr->read_user_chunk_fn != NULL))
  189163. {
  189164. #ifdef PNG_MAX_MALLOC_64K
  189165. if (length > (png_uint_32)65535L)
  189166. {
  189167. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189168. skip = length - (png_uint_32)65535L;
  189169. length = (png_uint_32)65535L;
  189170. }
  189171. #endif
  189172. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189173. (png_charp)png_ptr->chunk_name, 5);
  189174. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189175. png_ptr->unknown_chunk.size = (png_size_t)length;
  189176. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189177. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189178. if(png_ptr->read_user_chunk_fn != NULL)
  189179. {
  189180. /* callback to user unknown chunk handler */
  189181. int ret;
  189182. ret = (*(png_ptr->read_user_chunk_fn))
  189183. (png_ptr, &png_ptr->unknown_chunk);
  189184. if (ret < 0)
  189185. png_chunk_error(png_ptr, "error in user chunk");
  189186. if (ret == 0)
  189187. {
  189188. if (!(png_ptr->chunk_name[0] & 0x20))
  189189. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189190. PNG_HANDLE_CHUNK_ALWAYS)
  189191. png_chunk_error(png_ptr, "unknown critical chunk");
  189192. png_set_unknown_chunks(png_ptr, info_ptr,
  189193. &png_ptr->unknown_chunk, 1);
  189194. }
  189195. }
  189196. #else
  189197. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189198. #endif
  189199. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189200. png_ptr->unknown_chunk.data = NULL;
  189201. }
  189202. else
  189203. #endif
  189204. skip = length;
  189205. png_crc_finish(png_ptr, skip);
  189206. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189207. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  189208. #endif
  189209. }
  189210. /* This function is called to verify that a chunk name is valid.
  189211. This function can't have the "critical chunk check" incorporated
  189212. into it, since in the future we will need to be able to call user
  189213. functions to handle unknown critical chunks after we check that
  189214. the chunk name itself is valid. */
  189215. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  189216. void /* PRIVATE */
  189217. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  189218. {
  189219. png_debug(1, "in png_check_chunk_name\n");
  189220. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  189221. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  189222. {
  189223. png_chunk_error(png_ptr, "invalid chunk type");
  189224. }
  189225. }
  189226. /* Combines the row recently read in with the existing pixels in the
  189227. row. This routine takes care of alpha and transparency if requested.
  189228. This routine also handles the two methods of progressive display
  189229. of interlaced images, depending on the mask value.
  189230. The mask value describes which pixels are to be combined with
  189231. the row. The pattern always repeats every 8 pixels, so just 8
  189232. bits are needed. A one indicates the pixel is to be combined,
  189233. a zero indicates the pixel is to be skipped. This is in addition
  189234. to any alpha or transparency value associated with the pixel. If
  189235. you want all pixels to be combined, pass 0xff (255) in mask. */
  189236. void /* PRIVATE */
  189237. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  189238. {
  189239. png_debug(1,"in png_combine_row\n");
  189240. if (mask == 0xff)
  189241. {
  189242. png_memcpy(row, png_ptr->row_buf + 1,
  189243. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  189244. }
  189245. else
  189246. {
  189247. switch (png_ptr->row_info.pixel_depth)
  189248. {
  189249. case 1:
  189250. {
  189251. png_bytep sp = png_ptr->row_buf + 1;
  189252. png_bytep dp = row;
  189253. int s_inc, s_start, s_end;
  189254. int m = 0x80;
  189255. int shift;
  189256. png_uint_32 i;
  189257. png_uint_32 row_width = png_ptr->width;
  189258. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189259. if (png_ptr->transformations & PNG_PACKSWAP)
  189260. {
  189261. s_start = 0;
  189262. s_end = 7;
  189263. s_inc = 1;
  189264. }
  189265. else
  189266. #endif
  189267. {
  189268. s_start = 7;
  189269. s_end = 0;
  189270. s_inc = -1;
  189271. }
  189272. shift = s_start;
  189273. for (i = 0; i < row_width; i++)
  189274. {
  189275. if (m & mask)
  189276. {
  189277. int value;
  189278. value = (*sp >> shift) & 0x01;
  189279. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  189280. *dp |= (png_byte)(value << shift);
  189281. }
  189282. if (shift == s_end)
  189283. {
  189284. shift = s_start;
  189285. sp++;
  189286. dp++;
  189287. }
  189288. else
  189289. shift += s_inc;
  189290. if (m == 1)
  189291. m = 0x80;
  189292. else
  189293. m >>= 1;
  189294. }
  189295. break;
  189296. }
  189297. case 2:
  189298. {
  189299. png_bytep sp = png_ptr->row_buf + 1;
  189300. png_bytep dp = row;
  189301. int s_start, s_end, s_inc;
  189302. int m = 0x80;
  189303. int shift;
  189304. png_uint_32 i;
  189305. png_uint_32 row_width = png_ptr->width;
  189306. int value;
  189307. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189308. if (png_ptr->transformations & PNG_PACKSWAP)
  189309. {
  189310. s_start = 0;
  189311. s_end = 6;
  189312. s_inc = 2;
  189313. }
  189314. else
  189315. #endif
  189316. {
  189317. s_start = 6;
  189318. s_end = 0;
  189319. s_inc = -2;
  189320. }
  189321. shift = s_start;
  189322. for (i = 0; i < row_width; i++)
  189323. {
  189324. if (m & mask)
  189325. {
  189326. value = (*sp >> shift) & 0x03;
  189327. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189328. *dp |= (png_byte)(value << shift);
  189329. }
  189330. if (shift == s_end)
  189331. {
  189332. shift = s_start;
  189333. sp++;
  189334. dp++;
  189335. }
  189336. else
  189337. shift += s_inc;
  189338. if (m == 1)
  189339. m = 0x80;
  189340. else
  189341. m >>= 1;
  189342. }
  189343. break;
  189344. }
  189345. case 4:
  189346. {
  189347. png_bytep sp = png_ptr->row_buf + 1;
  189348. png_bytep dp = row;
  189349. int s_start, s_end, s_inc;
  189350. int m = 0x80;
  189351. int shift;
  189352. png_uint_32 i;
  189353. png_uint_32 row_width = png_ptr->width;
  189354. int value;
  189355. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189356. if (png_ptr->transformations & PNG_PACKSWAP)
  189357. {
  189358. s_start = 0;
  189359. s_end = 4;
  189360. s_inc = 4;
  189361. }
  189362. else
  189363. #endif
  189364. {
  189365. s_start = 4;
  189366. s_end = 0;
  189367. s_inc = -4;
  189368. }
  189369. shift = s_start;
  189370. for (i = 0; i < row_width; i++)
  189371. {
  189372. if (m & mask)
  189373. {
  189374. value = (*sp >> shift) & 0xf;
  189375. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189376. *dp |= (png_byte)(value << shift);
  189377. }
  189378. if (shift == s_end)
  189379. {
  189380. shift = s_start;
  189381. sp++;
  189382. dp++;
  189383. }
  189384. else
  189385. shift += s_inc;
  189386. if (m == 1)
  189387. m = 0x80;
  189388. else
  189389. m >>= 1;
  189390. }
  189391. break;
  189392. }
  189393. default:
  189394. {
  189395. png_bytep sp = png_ptr->row_buf + 1;
  189396. png_bytep dp = row;
  189397. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  189398. png_uint_32 i;
  189399. png_uint_32 row_width = png_ptr->width;
  189400. png_byte m = 0x80;
  189401. for (i = 0; i < row_width; i++)
  189402. {
  189403. if (m & mask)
  189404. {
  189405. png_memcpy(dp, sp, pixel_bytes);
  189406. }
  189407. sp += pixel_bytes;
  189408. dp += pixel_bytes;
  189409. if (m == 1)
  189410. m = 0x80;
  189411. else
  189412. m >>= 1;
  189413. }
  189414. break;
  189415. }
  189416. }
  189417. }
  189418. }
  189419. #ifdef PNG_READ_INTERLACING_SUPPORTED
  189420. /* OLD pre-1.0.9 interface:
  189421. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  189422. png_uint_32 transformations)
  189423. */
  189424. void /* PRIVATE */
  189425. png_do_read_interlace(png_structp png_ptr)
  189426. {
  189427. png_row_infop row_info = &(png_ptr->row_info);
  189428. png_bytep row = png_ptr->row_buf + 1;
  189429. int pass = png_ptr->pass;
  189430. png_uint_32 transformations = png_ptr->transformations;
  189431. #ifdef PNG_USE_LOCAL_ARRAYS
  189432. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189433. /* offset to next interlace block */
  189434. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189435. #endif
  189436. png_debug(1,"in png_do_read_interlace\n");
  189437. if (row != NULL && row_info != NULL)
  189438. {
  189439. png_uint_32 final_width;
  189440. final_width = row_info->width * png_pass_inc[pass];
  189441. switch (row_info->pixel_depth)
  189442. {
  189443. case 1:
  189444. {
  189445. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  189446. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  189447. int sshift, dshift;
  189448. int s_start, s_end, s_inc;
  189449. int jstop = png_pass_inc[pass];
  189450. png_byte v;
  189451. png_uint_32 i;
  189452. int j;
  189453. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189454. if (transformations & PNG_PACKSWAP)
  189455. {
  189456. sshift = (int)((row_info->width + 7) & 0x07);
  189457. dshift = (int)((final_width + 7) & 0x07);
  189458. s_start = 7;
  189459. s_end = 0;
  189460. s_inc = -1;
  189461. }
  189462. else
  189463. #endif
  189464. {
  189465. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  189466. dshift = 7 - (int)((final_width + 7) & 0x07);
  189467. s_start = 0;
  189468. s_end = 7;
  189469. s_inc = 1;
  189470. }
  189471. for (i = 0; i < row_info->width; i++)
  189472. {
  189473. v = (png_byte)((*sp >> sshift) & 0x01);
  189474. for (j = 0; j < jstop; j++)
  189475. {
  189476. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  189477. *dp |= (png_byte)(v << dshift);
  189478. if (dshift == s_end)
  189479. {
  189480. dshift = s_start;
  189481. dp--;
  189482. }
  189483. else
  189484. dshift += s_inc;
  189485. }
  189486. if (sshift == s_end)
  189487. {
  189488. sshift = s_start;
  189489. sp--;
  189490. }
  189491. else
  189492. sshift += s_inc;
  189493. }
  189494. break;
  189495. }
  189496. case 2:
  189497. {
  189498. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  189499. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  189500. int sshift, dshift;
  189501. int s_start, s_end, s_inc;
  189502. int jstop = png_pass_inc[pass];
  189503. png_uint_32 i;
  189504. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189505. if (transformations & PNG_PACKSWAP)
  189506. {
  189507. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  189508. dshift = (int)(((final_width + 3) & 0x03) << 1);
  189509. s_start = 6;
  189510. s_end = 0;
  189511. s_inc = -2;
  189512. }
  189513. else
  189514. #endif
  189515. {
  189516. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  189517. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  189518. s_start = 0;
  189519. s_end = 6;
  189520. s_inc = 2;
  189521. }
  189522. for (i = 0; i < row_info->width; i++)
  189523. {
  189524. png_byte v;
  189525. int j;
  189526. v = (png_byte)((*sp >> sshift) & 0x03);
  189527. for (j = 0; j < jstop; j++)
  189528. {
  189529. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  189530. *dp |= (png_byte)(v << dshift);
  189531. if (dshift == s_end)
  189532. {
  189533. dshift = s_start;
  189534. dp--;
  189535. }
  189536. else
  189537. dshift += s_inc;
  189538. }
  189539. if (sshift == s_end)
  189540. {
  189541. sshift = s_start;
  189542. sp--;
  189543. }
  189544. else
  189545. sshift += s_inc;
  189546. }
  189547. break;
  189548. }
  189549. case 4:
  189550. {
  189551. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  189552. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  189553. int sshift, dshift;
  189554. int s_start, s_end, s_inc;
  189555. png_uint_32 i;
  189556. int jstop = png_pass_inc[pass];
  189557. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189558. if (transformations & PNG_PACKSWAP)
  189559. {
  189560. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  189561. dshift = (int)(((final_width + 1) & 0x01) << 2);
  189562. s_start = 4;
  189563. s_end = 0;
  189564. s_inc = -4;
  189565. }
  189566. else
  189567. #endif
  189568. {
  189569. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  189570. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  189571. s_start = 0;
  189572. s_end = 4;
  189573. s_inc = 4;
  189574. }
  189575. for (i = 0; i < row_info->width; i++)
  189576. {
  189577. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  189578. int j;
  189579. for (j = 0; j < jstop; j++)
  189580. {
  189581. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  189582. *dp |= (png_byte)(v << dshift);
  189583. if (dshift == s_end)
  189584. {
  189585. dshift = s_start;
  189586. dp--;
  189587. }
  189588. else
  189589. dshift += s_inc;
  189590. }
  189591. if (sshift == s_end)
  189592. {
  189593. sshift = s_start;
  189594. sp--;
  189595. }
  189596. else
  189597. sshift += s_inc;
  189598. }
  189599. break;
  189600. }
  189601. default:
  189602. {
  189603. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  189604. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  189605. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  189606. int jstop = png_pass_inc[pass];
  189607. png_uint_32 i;
  189608. for (i = 0; i < row_info->width; i++)
  189609. {
  189610. png_byte v[8];
  189611. int j;
  189612. png_memcpy(v, sp, pixel_bytes);
  189613. for (j = 0; j < jstop; j++)
  189614. {
  189615. png_memcpy(dp, v, pixel_bytes);
  189616. dp -= pixel_bytes;
  189617. }
  189618. sp -= pixel_bytes;
  189619. }
  189620. break;
  189621. }
  189622. }
  189623. row_info->width = final_width;
  189624. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  189625. }
  189626. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  189627. transformations = transformations; /* silence compiler warning */
  189628. #endif
  189629. }
  189630. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  189631. void /* PRIVATE */
  189632. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  189633. png_bytep prev_row, int filter)
  189634. {
  189635. png_debug(1, "in png_read_filter_row\n");
  189636. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  189637. switch (filter)
  189638. {
  189639. case PNG_FILTER_VALUE_NONE:
  189640. break;
  189641. case PNG_FILTER_VALUE_SUB:
  189642. {
  189643. png_uint_32 i;
  189644. png_uint_32 istop = row_info->rowbytes;
  189645. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189646. png_bytep rp = row + bpp;
  189647. png_bytep lp = row;
  189648. for (i = bpp; i < istop; i++)
  189649. {
  189650. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  189651. rp++;
  189652. }
  189653. break;
  189654. }
  189655. case PNG_FILTER_VALUE_UP:
  189656. {
  189657. png_uint_32 i;
  189658. png_uint_32 istop = row_info->rowbytes;
  189659. png_bytep rp = row;
  189660. png_bytep pp = prev_row;
  189661. for (i = 0; i < istop; i++)
  189662. {
  189663. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  189664. rp++;
  189665. }
  189666. break;
  189667. }
  189668. case PNG_FILTER_VALUE_AVG:
  189669. {
  189670. png_uint_32 i;
  189671. png_bytep rp = row;
  189672. png_bytep pp = prev_row;
  189673. png_bytep lp = row;
  189674. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189675. png_uint_32 istop = row_info->rowbytes - bpp;
  189676. for (i = 0; i < bpp; i++)
  189677. {
  189678. *rp = (png_byte)(((int)(*rp) +
  189679. ((int)(*pp++) / 2 )) & 0xff);
  189680. rp++;
  189681. }
  189682. for (i = 0; i < istop; i++)
  189683. {
  189684. *rp = (png_byte)(((int)(*rp) +
  189685. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  189686. rp++;
  189687. }
  189688. break;
  189689. }
  189690. case PNG_FILTER_VALUE_PAETH:
  189691. {
  189692. png_uint_32 i;
  189693. png_bytep rp = row;
  189694. png_bytep pp = prev_row;
  189695. png_bytep lp = row;
  189696. png_bytep cp = prev_row;
  189697. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189698. png_uint_32 istop=row_info->rowbytes - bpp;
  189699. for (i = 0; i < bpp; i++)
  189700. {
  189701. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  189702. rp++;
  189703. }
  189704. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  189705. {
  189706. int a, b, c, pa, pb, pc, p;
  189707. a = *lp++;
  189708. b = *pp++;
  189709. c = *cp++;
  189710. p = b - c;
  189711. pc = a - c;
  189712. #ifdef PNG_USE_ABS
  189713. pa = abs(p);
  189714. pb = abs(pc);
  189715. pc = abs(p + pc);
  189716. #else
  189717. pa = p < 0 ? -p : p;
  189718. pb = pc < 0 ? -pc : pc;
  189719. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  189720. #endif
  189721. /*
  189722. if (pa <= pb && pa <= pc)
  189723. p = a;
  189724. else if (pb <= pc)
  189725. p = b;
  189726. else
  189727. p = c;
  189728. */
  189729. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  189730. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  189731. rp++;
  189732. }
  189733. break;
  189734. }
  189735. default:
  189736. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  189737. *row=0;
  189738. break;
  189739. }
  189740. }
  189741. void /* PRIVATE */
  189742. png_read_finish_row(png_structp png_ptr)
  189743. {
  189744. #ifdef PNG_USE_LOCAL_ARRAYS
  189745. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189746. /* start of interlace block */
  189747. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  189748. /* offset to next interlace block */
  189749. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189750. /* start of interlace block in the y direction */
  189751. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  189752. /* offset to next interlace block in the y direction */
  189753. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  189754. #endif
  189755. png_debug(1, "in png_read_finish_row\n");
  189756. png_ptr->row_number++;
  189757. if (png_ptr->row_number < png_ptr->num_rows)
  189758. return;
  189759. if (png_ptr->interlaced)
  189760. {
  189761. png_ptr->row_number = 0;
  189762. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189763. png_ptr->rowbytes + 1);
  189764. do
  189765. {
  189766. png_ptr->pass++;
  189767. if (png_ptr->pass >= 7)
  189768. break;
  189769. png_ptr->iwidth = (png_ptr->width +
  189770. png_pass_inc[png_ptr->pass] - 1 -
  189771. png_pass_start[png_ptr->pass]) /
  189772. png_pass_inc[png_ptr->pass];
  189773. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189774. png_ptr->iwidth) + 1;
  189775. if (!(png_ptr->transformations & PNG_INTERLACE))
  189776. {
  189777. png_ptr->num_rows = (png_ptr->height +
  189778. png_pass_yinc[png_ptr->pass] - 1 -
  189779. png_pass_ystart[png_ptr->pass]) /
  189780. png_pass_yinc[png_ptr->pass];
  189781. if (!(png_ptr->num_rows))
  189782. continue;
  189783. }
  189784. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  189785. break;
  189786. } while (png_ptr->iwidth == 0);
  189787. if (png_ptr->pass < 7)
  189788. return;
  189789. }
  189790. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189791. {
  189792. #ifdef PNG_USE_LOCAL_ARRAYS
  189793. PNG_CONST PNG_IDAT;
  189794. #endif
  189795. char extra;
  189796. int ret;
  189797. png_ptr->zstream.next_out = (Byte *)&extra;
  189798. png_ptr->zstream.avail_out = (uInt)1;
  189799. for(;;)
  189800. {
  189801. if (!(png_ptr->zstream.avail_in))
  189802. {
  189803. while (!png_ptr->idat_size)
  189804. {
  189805. png_byte chunk_length[4];
  189806. png_crc_finish(png_ptr, 0);
  189807. png_read_data(png_ptr, chunk_length, 4);
  189808. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  189809. png_reset_crc(png_ptr);
  189810. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189811. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189812. png_error(png_ptr, "Not enough image data");
  189813. }
  189814. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  189815. png_ptr->zstream.next_in = png_ptr->zbuf;
  189816. if (png_ptr->zbuf_size > png_ptr->idat_size)
  189817. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  189818. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  189819. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  189820. }
  189821. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189822. if (ret == Z_STREAM_END)
  189823. {
  189824. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  189825. png_ptr->idat_size)
  189826. png_warning(png_ptr, "Extra compressed data");
  189827. png_ptr->mode |= PNG_AFTER_IDAT;
  189828. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189829. break;
  189830. }
  189831. if (ret != Z_OK)
  189832. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  189833. "Decompression Error");
  189834. if (!(png_ptr->zstream.avail_out))
  189835. {
  189836. png_warning(png_ptr, "Extra compressed data.");
  189837. png_ptr->mode |= PNG_AFTER_IDAT;
  189838. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189839. break;
  189840. }
  189841. }
  189842. png_ptr->zstream.avail_out = 0;
  189843. }
  189844. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  189845. png_warning(png_ptr, "Extra compression data");
  189846. inflateReset(&png_ptr->zstream);
  189847. png_ptr->mode |= PNG_AFTER_IDAT;
  189848. }
  189849. void /* PRIVATE */
  189850. png_read_start_row(png_structp png_ptr)
  189851. {
  189852. #ifdef PNG_USE_LOCAL_ARRAYS
  189853. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189854. /* start of interlace block */
  189855. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  189856. /* offset to next interlace block */
  189857. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189858. /* start of interlace block in the y direction */
  189859. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  189860. /* offset to next interlace block in the y direction */
  189861. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  189862. #endif
  189863. int max_pixel_depth;
  189864. png_uint_32 row_bytes;
  189865. png_debug(1, "in png_read_start_row\n");
  189866. png_ptr->zstream.avail_in = 0;
  189867. png_init_read_transformations(png_ptr);
  189868. if (png_ptr->interlaced)
  189869. {
  189870. if (!(png_ptr->transformations & PNG_INTERLACE))
  189871. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  189872. png_pass_ystart[0]) / png_pass_yinc[0];
  189873. else
  189874. png_ptr->num_rows = png_ptr->height;
  189875. png_ptr->iwidth = (png_ptr->width +
  189876. png_pass_inc[png_ptr->pass] - 1 -
  189877. png_pass_start[png_ptr->pass]) /
  189878. png_pass_inc[png_ptr->pass];
  189879. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  189880. png_ptr->irowbytes = (png_size_t)row_bytes;
  189881. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  189882. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  189883. }
  189884. else
  189885. {
  189886. png_ptr->num_rows = png_ptr->height;
  189887. png_ptr->iwidth = png_ptr->width;
  189888. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  189889. }
  189890. max_pixel_depth = png_ptr->pixel_depth;
  189891. #if defined(PNG_READ_PACK_SUPPORTED)
  189892. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  189893. max_pixel_depth = 8;
  189894. #endif
  189895. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189896. if (png_ptr->transformations & PNG_EXPAND)
  189897. {
  189898. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189899. {
  189900. if (png_ptr->num_trans)
  189901. max_pixel_depth = 32;
  189902. else
  189903. max_pixel_depth = 24;
  189904. }
  189905. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189906. {
  189907. if (max_pixel_depth < 8)
  189908. max_pixel_depth = 8;
  189909. if (png_ptr->num_trans)
  189910. max_pixel_depth *= 2;
  189911. }
  189912. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189913. {
  189914. if (png_ptr->num_trans)
  189915. {
  189916. max_pixel_depth *= 4;
  189917. max_pixel_depth /= 3;
  189918. }
  189919. }
  189920. }
  189921. #endif
  189922. #if defined(PNG_READ_FILLER_SUPPORTED)
  189923. if (png_ptr->transformations & (PNG_FILLER))
  189924. {
  189925. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189926. max_pixel_depth = 32;
  189927. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189928. {
  189929. if (max_pixel_depth <= 8)
  189930. max_pixel_depth = 16;
  189931. else
  189932. max_pixel_depth = 32;
  189933. }
  189934. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189935. {
  189936. if (max_pixel_depth <= 32)
  189937. max_pixel_depth = 32;
  189938. else
  189939. max_pixel_depth = 64;
  189940. }
  189941. }
  189942. #endif
  189943. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189944. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  189945. {
  189946. if (
  189947. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189948. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  189949. #endif
  189950. #if defined(PNG_READ_FILLER_SUPPORTED)
  189951. (png_ptr->transformations & (PNG_FILLER)) ||
  189952. #endif
  189953. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  189954. {
  189955. if (max_pixel_depth <= 16)
  189956. max_pixel_depth = 32;
  189957. else
  189958. max_pixel_depth = 64;
  189959. }
  189960. else
  189961. {
  189962. if (max_pixel_depth <= 8)
  189963. {
  189964. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189965. max_pixel_depth = 32;
  189966. else
  189967. max_pixel_depth = 24;
  189968. }
  189969. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189970. max_pixel_depth = 64;
  189971. else
  189972. max_pixel_depth = 48;
  189973. }
  189974. }
  189975. #endif
  189976. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  189977. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  189978. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  189979. {
  189980. int user_pixel_depth=png_ptr->user_transform_depth*
  189981. png_ptr->user_transform_channels;
  189982. if(user_pixel_depth > max_pixel_depth)
  189983. max_pixel_depth=user_pixel_depth;
  189984. }
  189985. #endif
  189986. /* align the width on the next larger 8 pixels. Mainly used
  189987. for interlacing */
  189988. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  189989. /* calculate the maximum bytes needed, adding a byte and a pixel
  189990. for safety's sake */
  189991. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  189992. 1 + ((max_pixel_depth + 7) >> 3);
  189993. #ifdef PNG_MAX_MALLOC_64K
  189994. if (row_bytes > (png_uint_32)65536L)
  189995. png_error(png_ptr, "This image requires a row greater than 64KB");
  189996. #endif
  189997. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  189998. png_ptr->row_buf = png_ptr->big_row_buf+32;
  189999. #ifdef PNG_MAX_MALLOC_64K
  190000. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  190001. png_error(png_ptr, "This image requires a row greater than 64KB");
  190002. #endif
  190003. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  190004. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  190005. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  190006. png_ptr->rowbytes + 1));
  190007. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  190008. png_debug1(3, "width = %lu,\n", png_ptr->width);
  190009. png_debug1(3, "height = %lu,\n", png_ptr->height);
  190010. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  190011. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  190012. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  190013. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  190014. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  190015. }
  190016. #endif /* PNG_READ_SUPPORTED */
  190017. /********* End of inlined file: pngrutil.c *********/
  190018. /********* Start of inlined file: pngset.c *********/
  190019. /* pngset.c - storage of image information into info struct
  190020. *
  190021. * Last changed in libpng 1.2.21 [October 4, 2007]
  190022. * For conditions of distribution and use, see copyright notice in png.h
  190023. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190024. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190025. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190026. *
  190027. * The functions here are used during reads to store data from the file
  190028. * into the info struct, and during writes to store application data
  190029. * into the info struct for writing into the file. This abstracts the
  190030. * info struct and allows us to change the structure in the future.
  190031. */
  190032. #define PNG_INTERNAL
  190033. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  190034. #if defined(PNG_bKGD_SUPPORTED)
  190035. void PNGAPI
  190036. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  190037. {
  190038. png_debug1(1, "in %s storage function\n", "bKGD");
  190039. if (png_ptr == NULL || info_ptr == NULL)
  190040. return;
  190041. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  190042. info_ptr->valid |= PNG_INFO_bKGD;
  190043. }
  190044. #endif
  190045. #if defined(PNG_cHRM_SUPPORTED)
  190046. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190047. void PNGAPI
  190048. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  190049. double white_x, double white_y, double red_x, double red_y,
  190050. double green_x, double green_y, double blue_x, double blue_y)
  190051. {
  190052. png_debug1(1, "in %s storage function\n", "cHRM");
  190053. if (png_ptr == NULL || info_ptr == NULL)
  190054. return;
  190055. if (white_x < 0.0 || white_y < 0.0 ||
  190056. red_x < 0.0 || red_y < 0.0 ||
  190057. green_x < 0.0 || green_y < 0.0 ||
  190058. blue_x < 0.0 || blue_y < 0.0)
  190059. {
  190060. png_warning(png_ptr,
  190061. "Ignoring attempt to set negative chromaticity value");
  190062. return;
  190063. }
  190064. if (white_x > 21474.83 || white_y > 21474.83 ||
  190065. red_x > 21474.83 || red_y > 21474.83 ||
  190066. green_x > 21474.83 || green_y > 21474.83 ||
  190067. blue_x > 21474.83 || blue_y > 21474.83)
  190068. {
  190069. png_warning(png_ptr,
  190070. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190071. return;
  190072. }
  190073. info_ptr->x_white = (float)white_x;
  190074. info_ptr->y_white = (float)white_y;
  190075. info_ptr->x_red = (float)red_x;
  190076. info_ptr->y_red = (float)red_y;
  190077. info_ptr->x_green = (float)green_x;
  190078. info_ptr->y_green = (float)green_y;
  190079. info_ptr->x_blue = (float)blue_x;
  190080. info_ptr->y_blue = (float)blue_y;
  190081. #ifdef PNG_FIXED_POINT_SUPPORTED
  190082. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  190083. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  190084. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  190085. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  190086. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  190087. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  190088. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  190089. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  190090. #endif
  190091. info_ptr->valid |= PNG_INFO_cHRM;
  190092. }
  190093. #endif
  190094. #ifdef PNG_FIXED_POINT_SUPPORTED
  190095. void PNGAPI
  190096. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  190097. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  190098. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  190099. png_fixed_point blue_x, png_fixed_point blue_y)
  190100. {
  190101. png_debug1(1, "in %s storage function\n", "cHRM");
  190102. if (png_ptr == NULL || info_ptr == NULL)
  190103. return;
  190104. if (white_x < 0 || white_y < 0 ||
  190105. red_x < 0 || red_y < 0 ||
  190106. green_x < 0 || green_y < 0 ||
  190107. blue_x < 0 || blue_y < 0)
  190108. {
  190109. png_warning(png_ptr,
  190110. "Ignoring attempt to set negative chromaticity value");
  190111. return;
  190112. }
  190113. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190114. if (white_x > (double) PNG_UINT_31_MAX ||
  190115. white_y > (double) PNG_UINT_31_MAX ||
  190116. red_x > (double) PNG_UINT_31_MAX ||
  190117. red_y > (double) PNG_UINT_31_MAX ||
  190118. green_x > (double) PNG_UINT_31_MAX ||
  190119. green_y > (double) PNG_UINT_31_MAX ||
  190120. blue_x > (double) PNG_UINT_31_MAX ||
  190121. blue_y > (double) PNG_UINT_31_MAX)
  190122. #else
  190123. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190124. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190125. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190126. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190127. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190128. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190129. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190130. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  190131. #endif
  190132. {
  190133. png_warning(png_ptr,
  190134. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190135. return;
  190136. }
  190137. info_ptr->int_x_white = white_x;
  190138. info_ptr->int_y_white = white_y;
  190139. info_ptr->int_x_red = red_x;
  190140. info_ptr->int_y_red = red_y;
  190141. info_ptr->int_x_green = green_x;
  190142. info_ptr->int_y_green = green_y;
  190143. info_ptr->int_x_blue = blue_x;
  190144. info_ptr->int_y_blue = blue_y;
  190145. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190146. info_ptr->x_white = (float)(white_x/100000.);
  190147. info_ptr->y_white = (float)(white_y/100000.);
  190148. info_ptr->x_red = (float)( red_x/100000.);
  190149. info_ptr->y_red = (float)( red_y/100000.);
  190150. info_ptr->x_green = (float)(green_x/100000.);
  190151. info_ptr->y_green = (float)(green_y/100000.);
  190152. info_ptr->x_blue = (float)( blue_x/100000.);
  190153. info_ptr->y_blue = (float)( blue_y/100000.);
  190154. #endif
  190155. info_ptr->valid |= PNG_INFO_cHRM;
  190156. }
  190157. #endif
  190158. #endif
  190159. #if defined(PNG_gAMA_SUPPORTED)
  190160. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190161. void PNGAPI
  190162. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  190163. {
  190164. double gamma;
  190165. png_debug1(1, "in %s storage function\n", "gAMA");
  190166. if (png_ptr == NULL || info_ptr == NULL)
  190167. return;
  190168. /* Check for overflow */
  190169. if (file_gamma > 21474.83)
  190170. {
  190171. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190172. gamma=21474.83;
  190173. }
  190174. else
  190175. gamma=file_gamma;
  190176. info_ptr->gamma = (float)gamma;
  190177. #ifdef PNG_FIXED_POINT_SUPPORTED
  190178. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  190179. #endif
  190180. info_ptr->valid |= PNG_INFO_gAMA;
  190181. if(gamma == 0.0)
  190182. png_warning(png_ptr, "Setting gamma=0");
  190183. }
  190184. #endif
  190185. void PNGAPI
  190186. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  190187. int_gamma)
  190188. {
  190189. png_fixed_point gamma;
  190190. png_debug1(1, "in %s storage function\n", "gAMA");
  190191. if (png_ptr == NULL || info_ptr == NULL)
  190192. return;
  190193. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  190194. {
  190195. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190196. gamma=PNG_UINT_31_MAX;
  190197. }
  190198. else
  190199. {
  190200. if (int_gamma < 0)
  190201. {
  190202. png_warning(png_ptr, "Setting negative gamma to zero");
  190203. gamma=0;
  190204. }
  190205. else
  190206. gamma=int_gamma;
  190207. }
  190208. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190209. info_ptr->gamma = (float)(gamma/100000.);
  190210. #endif
  190211. #ifdef PNG_FIXED_POINT_SUPPORTED
  190212. info_ptr->int_gamma = gamma;
  190213. #endif
  190214. info_ptr->valid |= PNG_INFO_gAMA;
  190215. if(gamma == 0)
  190216. png_warning(png_ptr, "Setting gamma=0");
  190217. }
  190218. #endif
  190219. #if defined(PNG_hIST_SUPPORTED)
  190220. void PNGAPI
  190221. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  190222. {
  190223. int i;
  190224. png_debug1(1, "in %s storage function\n", "hIST");
  190225. if (png_ptr == NULL || info_ptr == NULL)
  190226. return;
  190227. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  190228. > PNG_MAX_PALETTE_LENGTH)
  190229. {
  190230. png_warning(png_ptr,
  190231. "Invalid palette size, hIST allocation skipped.");
  190232. return;
  190233. }
  190234. #ifdef PNG_FREE_ME_SUPPORTED
  190235. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  190236. #endif
  190237. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  190238. 1.2.1 */
  190239. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  190240. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  190241. if (png_ptr->hist == NULL)
  190242. {
  190243. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  190244. return;
  190245. }
  190246. for (i = 0; i < info_ptr->num_palette; i++)
  190247. png_ptr->hist[i] = hist[i];
  190248. info_ptr->hist = png_ptr->hist;
  190249. info_ptr->valid |= PNG_INFO_hIST;
  190250. #ifdef PNG_FREE_ME_SUPPORTED
  190251. info_ptr->free_me |= PNG_FREE_HIST;
  190252. #else
  190253. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  190254. #endif
  190255. }
  190256. #endif
  190257. void PNGAPI
  190258. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  190259. png_uint_32 width, png_uint_32 height, int bit_depth,
  190260. int color_type, int interlace_type, int compression_type,
  190261. int filter_type)
  190262. {
  190263. png_debug1(1, "in %s storage function\n", "IHDR");
  190264. if (png_ptr == NULL || info_ptr == NULL)
  190265. return;
  190266. /* check for width and height valid values */
  190267. if (width == 0 || height == 0)
  190268. png_error(png_ptr, "Image width or height is zero in IHDR");
  190269. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  190270. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  190271. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190272. #else
  190273. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  190274. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190275. #endif
  190276. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  190277. png_error(png_ptr, "Invalid image size in IHDR");
  190278. if ( width > (PNG_UINT_32_MAX
  190279. >> 3) /* 8-byte RGBA pixels */
  190280. - 64 /* bigrowbuf hack */
  190281. - 1 /* filter byte */
  190282. - 7*8 /* rounding of width to multiple of 8 pixels */
  190283. - 8) /* extra max_pixel_depth pad */
  190284. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  190285. /* check other values */
  190286. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  190287. bit_depth != 8 && bit_depth != 16)
  190288. png_error(png_ptr, "Invalid bit depth in IHDR");
  190289. if (color_type < 0 || color_type == 1 ||
  190290. color_type == 5 || color_type > 6)
  190291. png_error(png_ptr, "Invalid color type in IHDR");
  190292. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  190293. ((color_type == PNG_COLOR_TYPE_RGB ||
  190294. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  190295. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  190296. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  190297. if (interlace_type >= PNG_INTERLACE_LAST)
  190298. png_error(png_ptr, "Unknown interlace method in IHDR");
  190299. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  190300. png_error(png_ptr, "Unknown compression method in IHDR");
  190301. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190302. /* Accept filter_method 64 (intrapixel differencing) only if
  190303. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  190304. * 2. Libpng did not read a PNG signature (this filter_method is only
  190305. * used in PNG datastreams that are embedded in MNG datastreams) and
  190306. * 3. The application called png_permit_mng_features with a mask that
  190307. * included PNG_FLAG_MNG_FILTER_64 and
  190308. * 4. The filter_method is 64 and
  190309. * 5. The color_type is RGB or RGBA
  190310. */
  190311. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  190312. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  190313. if(filter_type != PNG_FILTER_TYPE_BASE)
  190314. {
  190315. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  190316. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  190317. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  190318. (color_type == PNG_COLOR_TYPE_RGB ||
  190319. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  190320. png_error(png_ptr, "Unknown filter method in IHDR");
  190321. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  190322. png_warning(png_ptr, "Invalid filter method in IHDR");
  190323. }
  190324. #else
  190325. if(filter_type != PNG_FILTER_TYPE_BASE)
  190326. png_error(png_ptr, "Unknown filter method in IHDR");
  190327. #endif
  190328. info_ptr->width = width;
  190329. info_ptr->height = height;
  190330. info_ptr->bit_depth = (png_byte)bit_depth;
  190331. info_ptr->color_type =(png_byte) color_type;
  190332. info_ptr->compression_type = (png_byte)compression_type;
  190333. info_ptr->filter_type = (png_byte)filter_type;
  190334. info_ptr->interlace_type = (png_byte)interlace_type;
  190335. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190336. info_ptr->channels = 1;
  190337. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190338. info_ptr->channels = 3;
  190339. else
  190340. info_ptr->channels = 1;
  190341. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190342. info_ptr->channels++;
  190343. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  190344. /* check for potential overflow */
  190345. if (width > (PNG_UINT_32_MAX
  190346. >> 3) /* 8-byte RGBA pixels */
  190347. - 64 /* bigrowbuf hack */
  190348. - 1 /* filter byte */
  190349. - 7*8 /* rounding of width to multiple of 8 pixels */
  190350. - 8) /* extra max_pixel_depth pad */
  190351. info_ptr->rowbytes = (png_size_t)0;
  190352. else
  190353. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  190354. }
  190355. #if defined(PNG_oFFs_SUPPORTED)
  190356. void PNGAPI
  190357. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  190358. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  190359. {
  190360. png_debug1(1, "in %s storage function\n", "oFFs");
  190361. if (png_ptr == NULL || info_ptr == NULL)
  190362. return;
  190363. info_ptr->x_offset = offset_x;
  190364. info_ptr->y_offset = offset_y;
  190365. info_ptr->offset_unit_type = (png_byte)unit_type;
  190366. info_ptr->valid |= PNG_INFO_oFFs;
  190367. }
  190368. #endif
  190369. #if defined(PNG_pCAL_SUPPORTED)
  190370. void PNGAPI
  190371. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  190372. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  190373. png_charp units, png_charpp params)
  190374. {
  190375. png_uint_32 length;
  190376. int i;
  190377. png_debug1(1, "in %s storage function\n", "pCAL");
  190378. if (png_ptr == NULL || info_ptr == NULL)
  190379. return;
  190380. length = png_strlen(purpose) + 1;
  190381. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  190382. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  190383. if (info_ptr->pcal_purpose == NULL)
  190384. {
  190385. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  190386. return;
  190387. }
  190388. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  190389. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  190390. info_ptr->pcal_X0 = X0;
  190391. info_ptr->pcal_X1 = X1;
  190392. info_ptr->pcal_type = (png_byte)type;
  190393. info_ptr->pcal_nparams = (png_byte)nparams;
  190394. length = png_strlen(units) + 1;
  190395. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  190396. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  190397. if (info_ptr->pcal_units == NULL)
  190398. {
  190399. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  190400. return;
  190401. }
  190402. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  190403. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  190404. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  190405. if (info_ptr->pcal_params == NULL)
  190406. {
  190407. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  190408. return;
  190409. }
  190410. info_ptr->pcal_params[nparams] = NULL;
  190411. for (i = 0; i < nparams; i++)
  190412. {
  190413. length = png_strlen(params[i]) + 1;
  190414. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  190415. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  190416. if (info_ptr->pcal_params[i] == NULL)
  190417. {
  190418. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  190419. return;
  190420. }
  190421. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  190422. }
  190423. info_ptr->valid |= PNG_INFO_pCAL;
  190424. #ifdef PNG_FREE_ME_SUPPORTED
  190425. info_ptr->free_me |= PNG_FREE_PCAL;
  190426. #endif
  190427. }
  190428. #endif
  190429. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  190430. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190431. void PNGAPI
  190432. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  190433. int unit, double width, double height)
  190434. {
  190435. png_debug1(1, "in %s storage function\n", "sCAL");
  190436. if (png_ptr == NULL || info_ptr == NULL)
  190437. return;
  190438. info_ptr->scal_unit = (png_byte)unit;
  190439. info_ptr->scal_pixel_width = width;
  190440. info_ptr->scal_pixel_height = height;
  190441. info_ptr->valid |= PNG_INFO_sCAL;
  190442. }
  190443. #else
  190444. #ifdef PNG_FIXED_POINT_SUPPORTED
  190445. void PNGAPI
  190446. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  190447. int unit, png_charp swidth, png_charp sheight)
  190448. {
  190449. png_uint_32 length;
  190450. png_debug1(1, "in %s storage function\n", "sCAL");
  190451. if (png_ptr == NULL || info_ptr == NULL)
  190452. return;
  190453. info_ptr->scal_unit = (png_byte)unit;
  190454. length = png_strlen(swidth) + 1;
  190455. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  190456. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  190457. if (info_ptr->scal_s_width == NULL)
  190458. {
  190459. png_warning(png_ptr,
  190460. "Memory allocation failed while processing sCAL.");
  190461. }
  190462. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  190463. length = png_strlen(sheight) + 1;
  190464. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  190465. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  190466. if (info_ptr->scal_s_height == NULL)
  190467. {
  190468. png_free (png_ptr, info_ptr->scal_s_width);
  190469. png_warning(png_ptr,
  190470. "Memory allocation failed while processing sCAL.");
  190471. }
  190472. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  190473. info_ptr->valid |= PNG_INFO_sCAL;
  190474. #ifdef PNG_FREE_ME_SUPPORTED
  190475. info_ptr->free_me |= PNG_FREE_SCAL;
  190476. #endif
  190477. }
  190478. #endif
  190479. #endif
  190480. #endif
  190481. #if defined(PNG_pHYs_SUPPORTED)
  190482. void PNGAPI
  190483. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  190484. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  190485. {
  190486. png_debug1(1, "in %s storage function\n", "pHYs");
  190487. if (png_ptr == NULL || info_ptr == NULL)
  190488. return;
  190489. info_ptr->x_pixels_per_unit = res_x;
  190490. info_ptr->y_pixels_per_unit = res_y;
  190491. info_ptr->phys_unit_type = (png_byte)unit_type;
  190492. info_ptr->valid |= PNG_INFO_pHYs;
  190493. }
  190494. #endif
  190495. void PNGAPI
  190496. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  190497. png_colorp palette, int num_palette)
  190498. {
  190499. png_debug1(1, "in %s storage function\n", "PLTE");
  190500. if (png_ptr == NULL || info_ptr == NULL)
  190501. return;
  190502. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  190503. {
  190504. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190505. png_error(png_ptr, "Invalid palette length");
  190506. else
  190507. {
  190508. png_warning(png_ptr, "Invalid palette length");
  190509. return;
  190510. }
  190511. }
  190512. /*
  190513. * It may not actually be necessary to set png_ptr->palette here;
  190514. * we do it for backward compatibility with the way the png_handle_tRNS
  190515. * function used to do the allocation.
  190516. */
  190517. #ifdef PNG_FREE_ME_SUPPORTED
  190518. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  190519. #endif
  190520. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  190521. of num_palette entries,
  190522. in case of an invalid PNG file that has too-large sample values. */
  190523. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  190524. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  190525. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  190526. png_sizeof(png_color));
  190527. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  190528. info_ptr->palette = png_ptr->palette;
  190529. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  190530. #ifdef PNG_FREE_ME_SUPPORTED
  190531. info_ptr->free_me |= PNG_FREE_PLTE;
  190532. #else
  190533. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  190534. #endif
  190535. info_ptr->valid |= PNG_INFO_PLTE;
  190536. }
  190537. #if defined(PNG_sBIT_SUPPORTED)
  190538. void PNGAPI
  190539. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  190540. png_color_8p sig_bit)
  190541. {
  190542. png_debug1(1, "in %s storage function\n", "sBIT");
  190543. if (png_ptr == NULL || info_ptr == NULL)
  190544. return;
  190545. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  190546. info_ptr->valid |= PNG_INFO_sBIT;
  190547. }
  190548. #endif
  190549. #if defined(PNG_sRGB_SUPPORTED)
  190550. void PNGAPI
  190551. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  190552. {
  190553. png_debug1(1, "in %s storage function\n", "sRGB");
  190554. if (png_ptr == NULL || info_ptr == NULL)
  190555. return;
  190556. info_ptr->srgb_intent = (png_byte)intent;
  190557. info_ptr->valid |= PNG_INFO_sRGB;
  190558. }
  190559. void PNGAPI
  190560. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  190561. int intent)
  190562. {
  190563. #if defined(PNG_gAMA_SUPPORTED)
  190564. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190565. float file_gamma;
  190566. #endif
  190567. #ifdef PNG_FIXED_POINT_SUPPORTED
  190568. png_fixed_point int_file_gamma;
  190569. #endif
  190570. #endif
  190571. #if defined(PNG_cHRM_SUPPORTED)
  190572. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190573. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190574. #endif
  190575. #ifdef PNG_FIXED_POINT_SUPPORTED
  190576. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  190577. int_green_y, int_blue_x, int_blue_y;
  190578. #endif
  190579. #endif
  190580. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  190581. if (png_ptr == NULL || info_ptr == NULL)
  190582. return;
  190583. png_set_sRGB(png_ptr, info_ptr, intent);
  190584. #if defined(PNG_gAMA_SUPPORTED)
  190585. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190586. file_gamma = (float).45455;
  190587. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190588. #endif
  190589. #ifdef PNG_FIXED_POINT_SUPPORTED
  190590. int_file_gamma = 45455L;
  190591. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  190592. #endif
  190593. #endif
  190594. #if defined(PNG_cHRM_SUPPORTED)
  190595. #ifdef PNG_FIXED_POINT_SUPPORTED
  190596. int_white_x = 31270L;
  190597. int_white_y = 32900L;
  190598. int_red_x = 64000L;
  190599. int_red_y = 33000L;
  190600. int_green_x = 30000L;
  190601. int_green_y = 60000L;
  190602. int_blue_x = 15000L;
  190603. int_blue_y = 6000L;
  190604. png_set_cHRM_fixed(png_ptr, info_ptr,
  190605. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  190606. int_blue_x, int_blue_y);
  190607. #endif
  190608. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190609. white_x = (float).3127;
  190610. white_y = (float).3290;
  190611. red_x = (float).64;
  190612. red_y = (float).33;
  190613. green_x = (float).30;
  190614. green_y = (float).60;
  190615. blue_x = (float).15;
  190616. blue_y = (float).06;
  190617. png_set_cHRM(png_ptr, info_ptr,
  190618. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190619. #endif
  190620. #endif
  190621. }
  190622. #endif
  190623. #if defined(PNG_iCCP_SUPPORTED)
  190624. void PNGAPI
  190625. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  190626. png_charp name, int compression_type,
  190627. png_charp profile, png_uint_32 proflen)
  190628. {
  190629. png_charp new_iccp_name;
  190630. png_charp new_iccp_profile;
  190631. png_debug1(1, "in %s storage function\n", "iCCP");
  190632. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  190633. return;
  190634. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  190635. if (new_iccp_name == NULL)
  190636. {
  190637. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  190638. return;
  190639. }
  190640. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  190641. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  190642. if (new_iccp_profile == NULL)
  190643. {
  190644. png_free (png_ptr, new_iccp_name);
  190645. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  190646. return;
  190647. }
  190648. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  190649. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  190650. info_ptr->iccp_proflen = proflen;
  190651. info_ptr->iccp_name = new_iccp_name;
  190652. info_ptr->iccp_profile = new_iccp_profile;
  190653. /* Compression is always zero but is here so the API and info structure
  190654. * does not have to change if we introduce multiple compression types */
  190655. info_ptr->iccp_compression = (png_byte)compression_type;
  190656. #ifdef PNG_FREE_ME_SUPPORTED
  190657. info_ptr->free_me |= PNG_FREE_ICCP;
  190658. #endif
  190659. info_ptr->valid |= PNG_INFO_iCCP;
  190660. }
  190661. #endif
  190662. #if defined(PNG_TEXT_SUPPORTED)
  190663. void PNGAPI
  190664. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  190665. int num_text)
  190666. {
  190667. int ret;
  190668. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  190669. if (ret)
  190670. png_error(png_ptr, "Insufficient memory to store text");
  190671. }
  190672. int /* PRIVATE */
  190673. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  190674. int num_text)
  190675. {
  190676. int i;
  190677. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  190678. "text" : (png_const_charp)png_ptr->chunk_name));
  190679. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  190680. return(0);
  190681. /* Make sure we have enough space in the "text" array in info_struct
  190682. * to hold all of the incoming text_ptr objects.
  190683. */
  190684. if (info_ptr->num_text + num_text > info_ptr->max_text)
  190685. {
  190686. if (info_ptr->text != NULL)
  190687. {
  190688. png_textp old_text;
  190689. int old_max;
  190690. old_max = info_ptr->max_text;
  190691. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  190692. old_text = info_ptr->text;
  190693. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  190694. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  190695. if (info_ptr->text == NULL)
  190696. {
  190697. png_free(png_ptr, old_text);
  190698. return(1);
  190699. }
  190700. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  190701. png_sizeof(png_text)));
  190702. png_free(png_ptr, old_text);
  190703. }
  190704. else
  190705. {
  190706. info_ptr->max_text = num_text + 8;
  190707. info_ptr->num_text = 0;
  190708. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  190709. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  190710. if (info_ptr->text == NULL)
  190711. return(1);
  190712. #ifdef PNG_FREE_ME_SUPPORTED
  190713. info_ptr->free_me |= PNG_FREE_TEXT;
  190714. #endif
  190715. }
  190716. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  190717. info_ptr->max_text);
  190718. }
  190719. for (i = 0; i < num_text; i++)
  190720. {
  190721. png_size_t text_length,key_len;
  190722. png_size_t lang_len,lang_key_len;
  190723. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  190724. if (text_ptr[i].key == NULL)
  190725. continue;
  190726. key_len = png_strlen(text_ptr[i].key);
  190727. if(text_ptr[i].compression <= 0)
  190728. {
  190729. lang_len = 0;
  190730. lang_key_len = 0;
  190731. }
  190732. else
  190733. #ifdef PNG_iTXt_SUPPORTED
  190734. {
  190735. /* set iTXt data */
  190736. if (text_ptr[i].lang != NULL)
  190737. lang_len = png_strlen(text_ptr[i].lang);
  190738. else
  190739. lang_len = 0;
  190740. if (text_ptr[i].lang_key != NULL)
  190741. lang_key_len = png_strlen(text_ptr[i].lang_key);
  190742. else
  190743. lang_key_len = 0;
  190744. }
  190745. #else
  190746. {
  190747. png_warning(png_ptr, "iTXt chunk not supported.");
  190748. continue;
  190749. }
  190750. #endif
  190751. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  190752. {
  190753. text_length = 0;
  190754. #ifdef PNG_iTXt_SUPPORTED
  190755. if(text_ptr[i].compression > 0)
  190756. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  190757. else
  190758. #endif
  190759. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  190760. }
  190761. else
  190762. {
  190763. text_length = png_strlen(text_ptr[i].text);
  190764. textp->compression = text_ptr[i].compression;
  190765. }
  190766. textp->key = (png_charp)png_malloc_warn(png_ptr,
  190767. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  190768. if (textp->key == NULL)
  190769. return(1);
  190770. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  190771. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  190772. (int)textp->key);
  190773. png_memcpy(textp->key, text_ptr[i].key,
  190774. (png_size_t)(key_len));
  190775. *(textp->key+key_len) = '\0';
  190776. #ifdef PNG_iTXt_SUPPORTED
  190777. if (text_ptr[i].compression > 0)
  190778. {
  190779. textp->lang=textp->key + key_len + 1;
  190780. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  190781. *(textp->lang+lang_len) = '\0';
  190782. textp->lang_key=textp->lang + lang_len + 1;
  190783. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  190784. *(textp->lang_key+lang_key_len) = '\0';
  190785. textp->text=textp->lang_key + lang_key_len + 1;
  190786. }
  190787. else
  190788. #endif
  190789. {
  190790. #ifdef PNG_iTXt_SUPPORTED
  190791. textp->lang=NULL;
  190792. textp->lang_key=NULL;
  190793. #endif
  190794. textp->text=textp->key + key_len + 1;
  190795. }
  190796. if(text_length)
  190797. png_memcpy(textp->text, text_ptr[i].text,
  190798. (png_size_t)(text_length));
  190799. *(textp->text+text_length) = '\0';
  190800. #ifdef PNG_iTXt_SUPPORTED
  190801. if(textp->compression > 0)
  190802. {
  190803. textp->text_length = 0;
  190804. textp->itxt_length = text_length;
  190805. }
  190806. else
  190807. #endif
  190808. {
  190809. textp->text_length = text_length;
  190810. #ifdef PNG_iTXt_SUPPORTED
  190811. textp->itxt_length = 0;
  190812. #endif
  190813. }
  190814. info_ptr->num_text++;
  190815. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  190816. }
  190817. return(0);
  190818. }
  190819. #endif
  190820. #if defined(PNG_tIME_SUPPORTED)
  190821. void PNGAPI
  190822. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  190823. {
  190824. png_debug1(1, "in %s storage function\n", "tIME");
  190825. if (png_ptr == NULL || info_ptr == NULL ||
  190826. (png_ptr->mode & PNG_WROTE_tIME))
  190827. return;
  190828. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  190829. info_ptr->valid |= PNG_INFO_tIME;
  190830. }
  190831. #endif
  190832. #if defined(PNG_tRNS_SUPPORTED)
  190833. void PNGAPI
  190834. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  190835. png_bytep trans, int num_trans, png_color_16p trans_values)
  190836. {
  190837. png_debug1(1, "in %s storage function\n", "tRNS");
  190838. if (png_ptr == NULL || info_ptr == NULL)
  190839. return;
  190840. if (trans != NULL)
  190841. {
  190842. /*
  190843. * It may not actually be necessary to set png_ptr->trans here;
  190844. * we do it for backward compatibility with the way the png_handle_tRNS
  190845. * function used to do the allocation.
  190846. */
  190847. #ifdef PNG_FREE_ME_SUPPORTED
  190848. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  190849. #endif
  190850. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  190851. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  190852. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  190853. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  190854. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  190855. #ifdef PNG_FREE_ME_SUPPORTED
  190856. info_ptr->free_me |= PNG_FREE_TRNS;
  190857. #else
  190858. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  190859. #endif
  190860. }
  190861. if (trans_values != NULL)
  190862. {
  190863. png_memcpy(&(info_ptr->trans_values), trans_values,
  190864. png_sizeof(png_color_16));
  190865. if (num_trans == 0)
  190866. num_trans = 1;
  190867. }
  190868. info_ptr->num_trans = (png_uint_16)num_trans;
  190869. info_ptr->valid |= PNG_INFO_tRNS;
  190870. }
  190871. #endif
  190872. #if defined(PNG_sPLT_SUPPORTED)
  190873. void PNGAPI
  190874. png_set_sPLT(png_structp png_ptr,
  190875. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  190876. {
  190877. png_sPLT_tp np;
  190878. int i;
  190879. if (png_ptr == NULL || info_ptr == NULL)
  190880. return;
  190881. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  190882. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  190883. if (np == NULL)
  190884. {
  190885. png_warning(png_ptr, "No memory for sPLT palettes.");
  190886. return;
  190887. }
  190888. png_memcpy(np, info_ptr->splt_palettes,
  190889. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  190890. png_free(png_ptr, info_ptr->splt_palettes);
  190891. info_ptr->splt_palettes=NULL;
  190892. for (i = 0; i < nentries; i++)
  190893. {
  190894. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  190895. png_sPLT_tp from = entries + i;
  190896. to->name = (png_charp)png_malloc_warn(png_ptr,
  190897. png_strlen(from->name) + 1);
  190898. if (to->name == NULL)
  190899. {
  190900. png_warning(png_ptr,
  190901. "Out of memory while processing sPLT chunk");
  190902. }
  190903. /* TODO: use png_malloc_warn */
  190904. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  190905. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  190906. from->nentries * png_sizeof(png_sPLT_entry));
  190907. /* TODO: use png_malloc_warn */
  190908. png_memcpy(to->entries, from->entries,
  190909. from->nentries * png_sizeof(png_sPLT_entry));
  190910. if (to->entries == NULL)
  190911. {
  190912. png_warning(png_ptr,
  190913. "Out of memory while processing sPLT chunk");
  190914. png_free(png_ptr,to->name);
  190915. to->name = NULL;
  190916. }
  190917. to->nentries = from->nentries;
  190918. to->depth = from->depth;
  190919. }
  190920. info_ptr->splt_palettes = np;
  190921. info_ptr->splt_palettes_num += nentries;
  190922. info_ptr->valid |= PNG_INFO_sPLT;
  190923. #ifdef PNG_FREE_ME_SUPPORTED
  190924. info_ptr->free_me |= PNG_FREE_SPLT;
  190925. #endif
  190926. }
  190927. #endif /* PNG_sPLT_SUPPORTED */
  190928. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  190929. void PNGAPI
  190930. png_set_unknown_chunks(png_structp png_ptr,
  190931. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  190932. {
  190933. png_unknown_chunkp np;
  190934. int i;
  190935. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  190936. return;
  190937. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  190938. (info_ptr->unknown_chunks_num + num_unknowns) *
  190939. png_sizeof(png_unknown_chunk));
  190940. if (np == NULL)
  190941. {
  190942. png_warning(png_ptr,
  190943. "Out of memory while processing unknown chunk.");
  190944. return;
  190945. }
  190946. png_memcpy(np, info_ptr->unknown_chunks,
  190947. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  190948. png_free(png_ptr, info_ptr->unknown_chunks);
  190949. info_ptr->unknown_chunks=NULL;
  190950. for (i = 0; i < num_unknowns; i++)
  190951. {
  190952. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  190953. png_unknown_chunkp from = unknowns + i;
  190954. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  190955. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  190956. if (to->data == NULL)
  190957. {
  190958. png_warning(png_ptr,
  190959. "Out of memory while processing unknown chunk.");
  190960. }
  190961. else
  190962. {
  190963. png_memcpy(to->data, from->data, from->size);
  190964. to->size = from->size;
  190965. /* note our location in the read or write sequence */
  190966. to->location = (png_byte)(png_ptr->mode & 0xff);
  190967. }
  190968. }
  190969. info_ptr->unknown_chunks = np;
  190970. info_ptr->unknown_chunks_num += num_unknowns;
  190971. #ifdef PNG_FREE_ME_SUPPORTED
  190972. info_ptr->free_me |= PNG_FREE_UNKN;
  190973. #endif
  190974. }
  190975. void PNGAPI
  190976. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  190977. int chunk, int location)
  190978. {
  190979. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  190980. (int)info_ptr->unknown_chunks_num)
  190981. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  190982. }
  190983. #endif
  190984. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190985. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  190986. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  190987. void PNGAPI
  190988. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  190989. {
  190990. /* This function is deprecated in favor of png_permit_mng_features()
  190991. and will be removed from libpng-1.3.0 */
  190992. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  190993. if (png_ptr == NULL)
  190994. return;
  190995. png_ptr->mng_features_permitted = (png_byte)
  190996. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  190997. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  190998. }
  190999. #endif
  191000. #endif
  191001. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191002. png_uint_32 PNGAPI
  191003. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  191004. {
  191005. png_debug(1, "in png_permit_mng_features\n");
  191006. if (png_ptr == NULL)
  191007. return (png_uint_32)0;
  191008. png_ptr->mng_features_permitted =
  191009. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  191010. return (png_uint_32)png_ptr->mng_features_permitted;
  191011. }
  191012. #endif
  191013. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191014. void PNGAPI
  191015. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  191016. chunk_list, int num_chunks)
  191017. {
  191018. png_bytep new_list, p;
  191019. int i, old_num_chunks;
  191020. if (png_ptr == NULL)
  191021. return;
  191022. if (num_chunks == 0)
  191023. {
  191024. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  191025. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191026. else
  191027. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191028. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  191029. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191030. else
  191031. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191032. return;
  191033. }
  191034. if (chunk_list == NULL)
  191035. return;
  191036. old_num_chunks=png_ptr->num_chunk_list;
  191037. new_list=(png_bytep)png_malloc(png_ptr,
  191038. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  191039. if(png_ptr->chunk_list != NULL)
  191040. {
  191041. png_memcpy(new_list, png_ptr->chunk_list,
  191042. (png_size_t)(5*old_num_chunks));
  191043. png_free(png_ptr, png_ptr->chunk_list);
  191044. png_ptr->chunk_list=NULL;
  191045. }
  191046. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  191047. (png_size_t)(5*num_chunks));
  191048. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  191049. *p=(png_byte)keep;
  191050. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  191051. png_ptr->chunk_list=new_list;
  191052. #ifdef PNG_FREE_ME_SUPPORTED
  191053. png_ptr->free_me |= PNG_FREE_LIST;
  191054. #endif
  191055. }
  191056. #endif
  191057. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191058. void PNGAPI
  191059. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  191060. png_user_chunk_ptr read_user_chunk_fn)
  191061. {
  191062. png_debug(1, "in png_set_read_user_chunk_fn\n");
  191063. if (png_ptr == NULL)
  191064. return;
  191065. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  191066. png_ptr->user_chunk_ptr = user_chunk_ptr;
  191067. }
  191068. #endif
  191069. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  191070. void PNGAPI
  191071. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  191072. {
  191073. png_debug1(1, "in %s storage function\n", "rows");
  191074. if (png_ptr == NULL || info_ptr == NULL)
  191075. return;
  191076. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  191077. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  191078. info_ptr->row_pointers = row_pointers;
  191079. if(row_pointers)
  191080. info_ptr->valid |= PNG_INFO_IDAT;
  191081. }
  191082. #endif
  191083. #ifdef PNG_WRITE_SUPPORTED
  191084. void PNGAPI
  191085. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  191086. {
  191087. if (png_ptr == NULL)
  191088. return;
  191089. if(png_ptr->zbuf)
  191090. png_free(png_ptr, png_ptr->zbuf);
  191091. png_ptr->zbuf_size = (png_size_t)size;
  191092. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  191093. png_ptr->zstream.next_out = png_ptr->zbuf;
  191094. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191095. }
  191096. #endif
  191097. void PNGAPI
  191098. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  191099. {
  191100. if (png_ptr && info_ptr)
  191101. info_ptr->valid &= ~(mask);
  191102. }
  191103. #ifndef PNG_1_0_X
  191104. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  191105. /* function was added to libpng 1.2.0 and should always exist by default */
  191106. void PNGAPI
  191107. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  191108. {
  191109. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191110. if (png_ptr != NULL)
  191111. png_ptr->asm_flags = 0;
  191112. }
  191113. /* this function was added to libpng 1.2.0 */
  191114. void PNGAPI
  191115. png_set_mmx_thresholds (png_structp png_ptr,
  191116. png_byte mmx_bitdepth_threshold,
  191117. png_uint_32 mmx_rowbytes_threshold)
  191118. {
  191119. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191120. if (png_ptr == NULL)
  191121. return;
  191122. }
  191123. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  191124. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191125. /* this function was added to libpng 1.2.6 */
  191126. void PNGAPI
  191127. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  191128. png_uint_32 user_height_max)
  191129. {
  191130. /* Images with dimensions larger than these limits will be
  191131. * rejected by png_set_IHDR(). To accept any PNG datastream
  191132. * regardless of dimensions, set both limits to 0x7ffffffL.
  191133. */
  191134. if(png_ptr == NULL) return;
  191135. png_ptr->user_width_max = user_width_max;
  191136. png_ptr->user_height_max = user_height_max;
  191137. }
  191138. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  191139. #endif /* ?PNG_1_0_X */
  191140. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191141. /********* End of inlined file: pngset.c *********/
  191142. /********* Start of inlined file: pngtrans.c *********/
  191143. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  191144. *
  191145. * Last changed in libpng 1.2.17 May 15, 2007
  191146. * For conditions of distribution and use, see copyright notice in png.h
  191147. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191148. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191149. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191150. */
  191151. #define PNG_INTERNAL
  191152. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191153. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191154. /* turn on BGR-to-RGB mapping */
  191155. void PNGAPI
  191156. png_set_bgr(png_structp png_ptr)
  191157. {
  191158. png_debug(1, "in png_set_bgr\n");
  191159. if(png_ptr == NULL) return;
  191160. png_ptr->transformations |= PNG_BGR;
  191161. }
  191162. #endif
  191163. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191164. /* turn on 16 bit byte swapping */
  191165. void PNGAPI
  191166. png_set_swap(png_structp png_ptr)
  191167. {
  191168. png_debug(1, "in png_set_swap\n");
  191169. if(png_ptr == NULL) return;
  191170. if (png_ptr->bit_depth == 16)
  191171. png_ptr->transformations |= PNG_SWAP_BYTES;
  191172. }
  191173. #endif
  191174. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  191175. /* turn on pixel packing */
  191176. void PNGAPI
  191177. png_set_packing(png_structp png_ptr)
  191178. {
  191179. png_debug(1, "in png_set_packing\n");
  191180. if(png_ptr == NULL) return;
  191181. if (png_ptr->bit_depth < 8)
  191182. {
  191183. png_ptr->transformations |= PNG_PACK;
  191184. png_ptr->usr_bit_depth = 8;
  191185. }
  191186. }
  191187. #endif
  191188. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191189. /* turn on packed pixel swapping */
  191190. void PNGAPI
  191191. png_set_packswap(png_structp png_ptr)
  191192. {
  191193. png_debug(1, "in png_set_packswap\n");
  191194. if(png_ptr == NULL) return;
  191195. if (png_ptr->bit_depth < 8)
  191196. png_ptr->transformations |= PNG_PACKSWAP;
  191197. }
  191198. #endif
  191199. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  191200. void PNGAPI
  191201. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  191202. {
  191203. png_debug(1, "in png_set_shift\n");
  191204. if(png_ptr == NULL) return;
  191205. png_ptr->transformations |= PNG_SHIFT;
  191206. png_ptr->shift = *true_bits;
  191207. }
  191208. #endif
  191209. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  191210. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  191211. int PNGAPI
  191212. png_set_interlace_handling(png_structp png_ptr)
  191213. {
  191214. png_debug(1, "in png_set_interlace handling\n");
  191215. if (png_ptr && png_ptr->interlaced)
  191216. {
  191217. png_ptr->transformations |= PNG_INTERLACE;
  191218. return (7);
  191219. }
  191220. return (1);
  191221. }
  191222. #endif
  191223. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  191224. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  191225. * The filler type has changed in v0.95 to allow future 2-byte fillers
  191226. * for 48-bit input data, as well as to avoid problems with some compilers
  191227. * that don't like bytes as parameters.
  191228. */
  191229. void PNGAPI
  191230. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191231. {
  191232. png_debug(1, "in png_set_filler\n");
  191233. if(png_ptr == NULL) return;
  191234. png_ptr->transformations |= PNG_FILLER;
  191235. png_ptr->filler = (png_byte)filler;
  191236. if (filler_loc == PNG_FILLER_AFTER)
  191237. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  191238. else
  191239. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  191240. /* This should probably go in the "do_read_filler" routine.
  191241. * I attempted to do that in libpng-1.0.1a but that caused problems
  191242. * so I restored it in libpng-1.0.2a
  191243. */
  191244. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191245. {
  191246. png_ptr->usr_channels = 4;
  191247. }
  191248. /* Also I added this in libpng-1.0.2a (what happens when we expand
  191249. * a less-than-8-bit grayscale to GA? */
  191250. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  191251. {
  191252. png_ptr->usr_channels = 2;
  191253. }
  191254. }
  191255. #if !defined(PNG_1_0_X)
  191256. /* Added to libpng-1.2.7 */
  191257. void PNGAPI
  191258. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191259. {
  191260. png_debug(1, "in png_set_add_alpha\n");
  191261. if(png_ptr == NULL) return;
  191262. png_set_filler(png_ptr, filler, filler_loc);
  191263. png_ptr->transformations |= PNG_ADD_ALPHA;
  191264. }
  191265. #endif
  191266. #endif
  191267. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  191268. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  191269. void PNGAPI
  191270. png_set_swap_alpha(png_structp png_ptr)
  191271. {
  191272. png_debug(1, "in png_set_swap_alpha\n");
  191273. if(png_ptr == NULL) return;
  191274. png_ptr->transformations |= PNG_SWAP_ALPHA;
  191275. }
  191276. #endif
  191277. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  191278. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  191279. void PNGAPI
  191280. png_set_invert_alpha(png_structp png_ptr)
  191281. {
  191282. png_debug(1, "in png_set_invert_alpha\n");
  191283. if(png_ptr == NULL) return;
  191284. png_ptr->transformations |= PNG_INVERT_ALPHA;
  191285. }
  191286. #endif
  191287. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  191288. void PNGAPI
  191289. png_set_invert_mono(png_structp png_ptr)
  191290. {
  191291. png_debug(1, "in png_set_invert_mono\n");
  191292. if(png_ptr == NULL) return;
  191293. png_ptr->transformations |= PNG_INVERT_MONO;
  191294. }
  191295. /* invert monochrome grayscale data */
  191296. void /* PRIVATE */
  191297. png_do_invert(png_row_infop row_info, png_bytep row)
  191298. {
  191299. png_debug(1, "in png_do_invert\n");
  191300. /* This test removed from libpng version 1.0.13 and 1.2.0:
  191301. * if (row_info->bit_depth == 1 &&
  191302. */
  191303. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191304. if (row == NULL || row_info == NULL)
  191305. return;
  191306. #endif
  191307. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191308. {
  191309. png_bytep rp = row;
  191310. png_uint_32 i;
  191311. png_uint_32 istop = row_info->rowbytes;
  191312. for (i = 0; i < istop; i++)
  191313. {
  191314. *rp = (png_byte)(~(*rp));
  191315. rp++;
  191316. }
  191317. }
  191318. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191319. row_info->bit_depth == 8)
  191320. {
  191321. png_bytep rp = row;
  191322. png_uint_32 i;
  191323. png_uint_32 istop = row_info->rowbytes;
  191324. for (i = 0; i < istop; i+=2)
  191325. {
  191326. *rp = (png_byte)(~(*rp));
  191327. rp+=2;
  191328. }
  191329. }
  191330. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191331. row_info->bit_depth == 16)
  191332. {
  191333. png_bytep rp = row;
  191334. png_uint_32 i;
  191335. png_uint_32 istop = row_info->rowbytes;
  191336. for (i = 0; i < istop; i+=4)
  191337. {
  191338. *rp = (png_byte)(~(*rp));
  191339. *(rp+1) = (png_byte)(~(*(rp+1)));
  191340. rp+=4;
  191341. }
  191342. }
  191343. }
  191344. #endif
  191345. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191346. /* swaps byte order on 16 bit depth images */
  191347. void /* PRIVATE */
  191348. png_do_swap(png_row_infop row_info, png_bytep row)
  191349. {
  191350. png_debug(1, "in png_do_swap\n");
  191351. if (
  191352. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191353. row != NULL && row_info != NULL &&
  191354. #endif
  191355. row_info->bit_depth == 16)
  191356. {
  191357. png_bytep rp = row;
  191358. png_uint_32 i;
  191359. png_uint_32 istop= row_info->width * row_info->channels;
  191360. for (i = 0; i < istop; i++, rp += 2)
  191361. {
  191362. png_byte t = *rp;
  191363. *rp = *(rp + 1);
  191364. *(rp + 1) = t;
  191365. }
  191366. }
  191367. }
  191368. #endif
  191369. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191370. static PNG_CONST png_byte onebppswaptable[256] = {
  191371. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  191372. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  191373. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  191374. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  191375. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  191376. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  191377. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  191378. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  191379. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  191380. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  191381. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  191382. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  191383. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  191384. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  191385. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  191386. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  191387. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  191388. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  191389. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  191390. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  191391. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  191392. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  191393. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  191394. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  191395. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  191396. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  191397. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  191398. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  191399. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  191400. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  191401. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  191402. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  191403. };
  191404. static PNG_CONST png_byte twobppswaptable[256] = {
  191405. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  191406. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  191407. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  191408. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  191409. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  191410. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  191411. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  191412. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  191413. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  191414. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  191415. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  191416. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  191417. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  191418. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  191419. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  191420. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  191421. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  191422. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  191423. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  191424. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  191425. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  191426. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  191427. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  191428. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  191429. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  191430. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  191431. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  191432. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  191433. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  191434. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  191435. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  191436. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  191437. };
  191438. static PNG_CONST png_byte fourbppswaptable[256] = {
  191439. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  191440. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  191441. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  191442. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  191443. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  191444. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  191445. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  191446. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  191447. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  191448. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  191449. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  191450. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  191451. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  191452. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  191453. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  191454. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  191455. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  191456. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  191457. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  191458. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  191459. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  191460. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  191461. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  191462. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  191463. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  191464. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  191465. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  191466. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  191467. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  191468. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  191469. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  191470. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  191471. };
  191472. /* swaps pixel packing order within bytes */
  191473. void /* PRIVATE */
  191474. png_do_packswap(png_row_infop row_info, png_bytep row)
  191475. {
  191476. png_debug(1, "in png_do_packswap\n");
  191477. if (
  191478. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191479. row != NULL && row_info != NULL &&
  191480. #endif
  191481. row_info->bit_depth < 8)
  191482. {
  191483. png_bytep rp, end, table;
  191484. end = row + row_info->rowbytes;
  191485. if (row_info->bit_depth == 1)
  191486. table = (png_bytep)onebppswaptable;
  191487. else if (row_info->bit_depth == 2)
  191488. table = (png_bytep)twobppswaptable;
  191489. else if (row_info->bit_depth == 4)
  191490. table = (png_bytep)fourbppswaptable;
  191491. else
  191492. return;
  191493. for (rp = row; rp < end; rp++)
  191494. *rp = table[*rp];
  191495. }
  191496. }
  191497. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  191498. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  191499. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191500. /* remove filler or alpha byte(s) */
  191501. void /* PRIVATE */
  191502. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  191503. {
  191504. png_debug(1, "in png_do_strip_filler\n");
  191505. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191506. if (row != NULL && row_info != NULL)
  191507. #endif
  191508. {
  191509. png_bytep sp=row;
  191510. png_bytep dp=row;
  191511. png_uint_32 row_width=row_info->width;
  191512. png_uint_32 i;
  191513. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  191514. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  191515. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  191516. row_info->channels == 4)
  191517. {
  191518. if (row_info->bit_depth == 8)
  191519. {
  191520. /* This converts from RGBX or RGBA to RGB */
  191521. if (flags & PNG_FLAG_FILLER_AFTER)
  191522. {
  191523. dp+=3; sp+=4;
  191524. for (i = 1; i < row_width; i++)
  191525. {
  191526. *dp++ = *sp++;
  191527. *dp++ = *sp++;
  191528. *dp++ = *sp++;
  191529. sp++;
  191530. }
  191531. }
  191532. /* This converts from XRGB or ARGB to RGB */
  191533. else
  191534. {
  191535. for (i = 0; i < row_width; i++)
  191536. {
  191537. sp++;
  191538. *dp++ = *sp++;
  191539. *dp++ = *sp++;
  191540. *dp++ = *sp++;
  191541. }
  191542. }
  191543. row_info->pixel_depth = 24;
  191544. row_info->rowbytes = row_width * 3;
  191545. }
  191546. else /* if (row_info->bit_depth == 16) */
  191547. {
  191548. if (flags & PNG_FLAG_FILLER_AFTER)
  191549. {
  191550. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  191551. sp += 8; dp += 6;
  191552. for (i = 1; i < row_width; i++)
  191553. {
  191554. /* This could be (although png_memcpy is probably slower):
  191555. png_memcpy(dp, sp, 6);
  191556. sp += 8;
  191557. dp += 6;
  191558. */
  191559. *dp++ = *sp++;
  191560. *dp++ = *sp++;
  191561. *dp++ = *sp++;
  191562. *dp++ = *sp++;
  191563. *dp++ = *sp++;
  191564. *dp++ = *sp++;
  191565. sp += 2;
  191566. }
  191567. }
  191568. else
  191569. {
  191570. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  191571. for (i = 0; i < row_width; i++)
  191572. {
  191573. /* This could be (although png_memcpy is probably slower):
  191574. png_memcpy(dp, sp, 6);
  191575. sp += 8;
  191576. dp += 6;
  191577. */
  191578. sp+=2;
  191579. *dp++ = *sp++;
  191580. *dp++ = *sp++;
  191581. *dp++ = *sp++;
  191582. *dp++ = *sp++;
  191583. *dp++ = *sp++;
  191584. *dp++ = *sp++;
  191585. }
  191586. }
  191587. row_info->pixel_depth = 48;
  191588. row_info->rowbytes = row_width * 6;
  191589. }
  191590. row_info->channels = 3;
  191591. }
  191592. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  191593. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191594. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  191595. row_info->channels == 2)
  191596. {
  191597. if (row_info->bit_depth == 8)
  191598. {
  191599. /* This converts from GX or GA to G */
  191600. if (flags & PNG_FLAG_FILLER_AFTER)
  191601. {
  191602. for (i = 0; i < row_width; i++)
  191603. {
  191604. *dp++ = *sp++;
  191605. sp++;
  191606. }
  191607. }
  191608. /* This converts from XG or AG to G */
  191609. else
  191610. {
  191611. for (i = 0; i < row_width; i++)
  191612. {
  191613. sp++;
  191614. *dp++ = *sp++;
  191615. }
  191616. }
  191617. row_info->pixel_depth = 8;
  191618. row_info->rowbytes = row_width;
  191619. }
  191620. else /* if (row_info->bit_depth == 16) */
  191621. {
  191622. if (flags & PNG_FLAG_FILLER_AFTER)
  191623. {
  191624. /* This converts from GGXX or GGAA to GG */
  191625. sp += 4; dp += 2;
  191626. for (i = 1; i < row_width; i++)
  191627. {
  191628. *dp++ = *sp++;
  191629. *dp++ = *sp++;
  191630. sp += 2;
  191631. }
  191632. }
  191633. else
  191634. {
  191635. /* This converts from XXGG or AAGG to GG */
  191636. for (i = 0; i < row_width; i++)
  191637. {
  191638. sp += 2;
  191639. *dp++ = *sp++;
  191640. *dp++ = *sp++;
  191641. }
  191642. }
  191643. row_info->pixel_depth = 16;
  191644. row_info->rowbytes = row_width * 2;
  191645. }
  191646. row_info->channels = 1;
  191647. }
  191648. if (flags & PNG_FLAG_STRIP_ALPHA)
  191649. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191650. }
  191651. }
  191652. #endif
  191653. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191654. /* swaps red and blue bytes within a pixel */
  191655. void /* PRIVATE */
  191656. png_do_bgr(png_row_infop row_info, png_bytep row)
  191657. {
  191658. png_debug(1, "in png_do_bgr\n");
  191659. if (
  191660. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191661. row != NULL && row_info != NULL &&
  191662. #endif
  191663. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191664. {
  191665. png_uint_32 row_width = row_info->width;
  191666. if (row_info->bit_depth == 8)
  191667. {
  191668. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191669. {
  191670. png_bytep rp;
  191671. png_uint_32 i;
  191672. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  191673. {
  191674. png_byte save = *rp;
  191675. *rp = *(rp + 2);
  191676. *(rp + 2) = save;
  191677. }
  191678. }
  191679. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191680. {
  191681. png_bytep rp;
  191682. png_uint_32 i;
  191683. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  191684. {
  191685. png_byte save = *rp;
  191686. *rp = *(rp + 2);
  191687. *(rp + 2) = save;
  191688. }
  191689. }
  191690. }
  191691. else if (row_info->bit_depth == 16)
  191692. {
  191693. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191694. {
  191695. png_bytep rp;
  191696. png_uint_32 i;
  191697. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  191698. {
  191699. png_byte save = *rp;
  191700. *rp = *(rp + 4);
  191701. *(rp + 4) = save;
  191702. save = *(rp + 1);
  191703. *(rp + 1) = *(rp + 5);
  191704. *(rp + 5) = save;
  191705. }
  191706. }
  191707. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191708. {
  191709. png_bytep rp;
  191710. png_uint_32 i;
  191711. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  191712. {
  191713. png_byte save = *rp;
  191714. *rp = *(rp + 4);
  191715. *(rp + 4) = save;
  191716. save = *(rp + 1);
  191717. *(rp + 1) = *(rp + 5);
  191718. *(rp + 5) = save;
  191719. }
  191720. }
  191721. }
  191722. }
  191723. }
  191724. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  191725. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  191726. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  191727. defined(PNG_LEGACY_SUPPORTED)
  191728. void PNGAPI
  191729. png_set_user_transform_info(png_structp png_ptr, png_voidp
  191730. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  191731. {
  191732. png_debug(1, "in png_set_user_transform_info\n");
  191733. if(png_ptr == NULL) return;
  191734. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191735. png_ptr->user_transform_ptr = user_transform_ptr;
  191736. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  191737. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  191738. #else
  191739. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  191740. png_warning(png_ptr,
  191741. "This version of libpng does not support user transform info");
  191742. #endif
  191743. }
  191744. #endif
  191745. /* This function returns a pointer to the user_transform_ptr associated with
  191746. * the user transform functions. The application should free any memory
  191747. * associated with this pointer before png_write_destroy and png_read_destroy
  191748. * are called.
  191749. */
  191750. png_voidp PNGAPI
  191751. png_get_user_transform_ptr(png_structp png_ptr)
  191752. {
  191753. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191754. if (png_ptr == NULL) return (NULL);
  191755. return ((png_voidp)png_ptr->user_transform_ptr);
  191756. #else
  191757. return (NULL);
  191758. #endif
  191759. }
  191760. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191761. /********* End of inlined file: pngtrans.c *********/
  191762. /********* Start of inlined file: pngwio.c *********/
  191763. /* pngwio.c - functions for data output
  191764. *
  191765. * Last changed in libpng 1.2.13 November 13, 2006
  191766. * For conditions of distribution and use, see copyright notice in png.h
  191767. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  191768. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191769. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191770. *
  191771. * This file provides a location for all output. Users who need
  191772. * special handling are expected to write functions that have the same
  191773. * arguments as these and perform similar functions, but that possibly
  191774. * use different output methods. Note that you shouldn't change these
  191775. * functions, but rather write replacement functions and then change
  191776. * them at run time with png_set_write_fn(...).
  191777. */
  191778. #define PNG_INTERNAL
  191779. #ifdef PNG_WRITE_SUPPORTED
  191780. /* Write the data to whatever output you are using. The default routine
  191781. writes to a file pointer. Note that this routine sometimes gets called
  191782. with very small lengths, so you should implement some kind of simple
  191783. buffering if you are using unbuffered writes. This should never be asked
  191784. to write more than 64K on a 16 bit machine. */
  191785. void /* PRIVATE */
  191786. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191787. {
  191788. if (png_ptr->write_data_fn != NULL )
  191789. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  191790. else
  191791. png_error(png_ptr, "Call to NULL write function");
  191792. }
  191793. #if !defined(PNG_NO_STDIO)
  191794. /* This is the function that does the actual writing of data. If you are
  191795. not writing to a standard C stream, you should create a replacement
  191796. write_data function and use it at run time with png_set_write_fn(), rather
  191797. than changing the library. */
  191798. #ifndef USE_FAR_KEYWORD
  191799. void PNGAPI
  191800. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191801. {
  191802. png_uint_32 check;
  191803. if(png_ptr == NULL) return;
  191804. #if defined(_WIN32_WCE)
  191805. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  191806. check = 0;
  191807. #else
  191808. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  191809. #endif
  191810. if (check != length)
  191811. png_error(png_ptr, "Write Error");
  191812. }
  191813. #else
  191814. /* this is the model-independent version. Since the standard I/O library
  191815. can't handle far buffers in the medium and small models, we have to copy
  191816. the data.
  191817. */
  191818. #define NEAR_BUF_SIZE 1024
  191819. #define MIN(a,b) (a <= b ? a : b)
  191820. void PNGAPI
  191821. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191822. {
  191823. png_uint_32 check;
  191824. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  191825. png_FILE_p io_ptr;
  191826. if(png_ptr == NULL) return;
  191827. /* Check if data really is near. If so, use usual code. */
  191828. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  191829. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  191830. if ((png_bytep)near_data == data)
  191831. {
  191832. #if defined(_WIN32_WCE)
  191833. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  191834. check = 0;
  191835. #else
  191836. check = fwrite(near_data, 1, length, io_ptr);
  191837. #endif
  191838. }
  191839. else
  191840. {
  191841. png_byte buf[NEAR_BUF_SIZE];
  191842. png_size_t written, remaining, err;
  191843. check = 0;
  191844. remaining = length;
  191845. do
  191846. {
  191847. written = MIN(NEAR_BUF_SIZE, remaining);
  191848. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  191849. #if defined(_WIN32_WCE)
  191850. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  191851. err = 0;
  191852. #else
  191853. err = fwrite(buf, 1, written, io_ptr);
  191854. #endif
  191855. if (err != written)
  191856. break;
  191857. else
  191858. check += err;
  191859. data += written;
  191860. remaining -= written;
  191861. }
  191862. while (remaining != 0);
  191863. }
  191864. if (check != length)
  191865. png_error(png_ptr, "Write Error");
  191866. }
  191867. #endif
  191868. #endif
  191869. /* This function is called to output any data pending writing (normally
  191870. to disk). After png_flush is called, there should be no data pending
  191871. writing in any buffers. */
  191872. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  191873. void /* PRIVATE */
  191874. png_flush(png_structp png_ptr)
  191875. {
  191876. if (png_ptr->output_flush_fn != NULL)
  191877. (*(png_ptr->output_flush_fn))(png_ptr);
  191878. }
  191879. #if !defined(PNG_NO_STDIO)
  191880. void PNGAPI
  191881. png_default_flush(png_structp png_ptr)
  191882. {
  191883. #if !defined(_WIN32_WCE)
  191884. png_FILE_p io_ptr;
  191885. #endif
  191886. if(png_ptr == NULL) return;
  191887. #if !defined(_WIN32_WCE)
  191888. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  191889. if (io_ptr != NULL)
  191890. fflush(io_ptr);
  191891. #endif
  191892. }
  191893. #endif
  191894. #endif
  191895. /* This function allows the application to supply new output functions for
  191896. libpng if standard C streams aren't being used.
  191897. This function takes as its arguments:
  191898. png_ptr - pointer to a png output data structure
  191899. io_ptr - pointer to user supplied structure containing info about
  191900. the output functions. May be NULL.
  191901. write_data_fn - pointer to a new output function that takes as its
  191902. arguments a pointer to a png_struct, a pointer to
  191903. data to be written, and a 32-bit unsigned int that is
  191904. the number of bytes to be written. The new write
  191905. function should call png_error(png_ptr, "Error msg")
  191906. to exit and output any fatal error messages.
  191907. flush_data_fn - pointer to a new flush function that takes as its
  191908. arguments a pointer to a png_struct. After a call to
  191909. the flush function, there should be no data in any buffers
  191910. or pending transmission. If the output method doesn't do
  191911. any buffering of ouput, a function prototype must still be
  191912. supplied although it doesn't have to do anything. If
  191913. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  191914. time, output_flush_fn will be ignored, although it must be
  191915. supplied for compatibility. */
  191916. void PNGAPI
  191917. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  191918. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  191919. {
  191920. if(png_ptr == NULL) return;
  191921. png_ptr->io_ptr = io_ptr;
  191922. #if !defined(PNG_NO_STDIO)
  191923. if (write_data_fn != NULL)
  191924. png_ptr->write_data_fn = write_data_fn;
  191925. else
  191926. png_ptr->write_data_fn = png_default_write_data;
  191927. #else
  191928. png_ptr->write_data_fn = write_data_fn;
  191929. #endif
  191930. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  191931. #if !defined(PNG_NO_STDIO)
  191932. if (output_flush_fn != NULL)
  191933. png_ptr->output_flush_fn = output_flush_fn;
  191934. else
  191935. png_ptr->output_flush_fn = png_default_flush;
  191936. #else
  191937. png_ptr->output_flush_fn = output_flush_fn;
  191938. #endif
  191939. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  191940. /* It is an error to read while writing a png file */
  191941. if (png_ptr->read_data_fn != NULL)
  191942. {
  191943. png_ptr->read_data_fn = NULL;
  191944. png_warning(png_ptr,
  191945. "Attempted to set both read_data_fn and write_data_fn in");
  191946. png_warning(png_ptr,
  191947. "the same structure. Resetting read_data_fn to NULL.");
  191948. }
  191949. }
  191950. #if defined(USE_FAR_KEYWORD)
  191951. #if defined(_MSC_VER)
  191952. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  191953. {
  191954. void *near_ptr;
  191955. void FAR *far_ptr;
  191956. FP_OFF(near_ptr) = FP_OFF(ptr);
  191957. far_ptr = (void FAR *)near_ptr;
  191958. if(check != 0)
  191959. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  191960. png_error(png_ptr,"segment lost in conversion");
  191961. return(near_ptr);
  191962. }
  191963. # else
  191964. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  191965. {
  191966. void *near_ptr;
  191967. void FAR *far_ptr;
  191968. near_ptr = (void FAR *)ptr;
  191969. far_ptr = (void FAR *)near_ptr;
  191970. if(check != 0)
  191971. if(far_ptr != ptr)
  191972. png_error(png_ptr,"segment lost in conversion");
  191973. return(near_ptr);
  191974. }
  191975. # endif
  191976. # endif
  191977. #endif /* PNG_WRITE_SUPPORTED */
  191978. /********* End of inlined file: pngwio.c *********/
  191979. /********* Start of inlined file: pngwrite.c *********/
  191980. /* pngwrite.c - general routines to write a PNG file
  191981. *
  191982. * Last changed in libpng 1.2.15 January 5, 2007
  191983. * For conditions of distribution and use, see copyright notice in png.h
  191984. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191985. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191986. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191987. */
  191988. /* get internal access to png.h */
  191989. #define PNG_INTERNAL
  191990. #ifdef PNG_WRITE_SUPPORTED
  191991. /* Writes all the PNG information. This is the suggested way to use the
  191992. * library. If you have a new chunk to add, make a function to write it,
  191993. * and put it in the correct location here. If you want the chunk written
  191994. * after the image data, put it in png_write_end(). I strongly encourage
  191995. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  191996. * the chunk, as that will keep the code from breaking if you want to just
  191997. * write a plain PNG file. If you have long comments, I suggest writing
  191998. * them in png_write_end(), and compressing them.
  191999. */
  192000. void PNGAPI
  192001. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  192002. {
  192003. png_debug(1, "in png_write_info_before_PLTE\n");
  192004. if (png_ptr == NULL || info_ptr == NULL)
  192005. return;
  192006. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192007. {
  192008. png_write_sig(png_ptr); /* write PNG signature */
  192009. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192010. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  192011. {
  192012. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192013. png_ptr->mng_features_permitted=0;
  192014. }
  192015. #endif
  192016. /* write IHDR information. */
  192017. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  192018. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  192019. info_ptr->filter_type,
  192020. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192021. info_ptr->interlace_type);
  192022. #else
  192023. 0);
  192024. #endif
  192025. /* the rest of these check to see if the valid field has the appropriate
  192026. flag set, and if it does, writes the chunk. */
  192027. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  192028. if (info_ptr->valid & PNG_INFO_gAMA)
  192029. {
  192030. # ifdef PNG_FLOATING_POINT_SUPPORTED
  192031. png_write_gAMA(png_ptr, info_ptr->gamma);
  192032. #else
  192033. #ifdef PNG_FIXED_POINT_SUPPORTED
  192034. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  192035. # endif
  192036. #endif
  192037. }
  192038. #endif
  192039. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  192040. if (info_ptr->valid & PNG_INFO_sRGB)
  192041. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  192042. #endif
  192043. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  192044. if (info_ptr->valid & PNG_INFO_iCCP)
  192045. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  192046. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  192047. #endif
  192048. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  192049. if (info_ptr->valid & PNG_INFO_sBIT)
  192050. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  192051. #endif
  192052. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  192053. if (info_ptr->valid & PNG_INFO_cHRM)
  192054. {
  192055. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192056. png_write_cHRM(png_ptr,
  192057. info_ptr->x_white, info_ptr->y_white,
  192058. info_ptr->x_red, info_ptr->y_red,
  192059. info_ptr->x_green, info_ptr->y_green,
  192060. info_ptr->x_blue, info_ptr->y_blue);
  192061. #else
  192062. # ifdef PNG_FIXED_POINT_SUPPORTED
  192063. png_write_cHRM_fixed(png_ptr,
  192064. info_ptr->int_x_white, info_ptr->int_y_white,
  192065. info_ptr->int_x_red, info_ptr->int_y_red,
  192066. info_ptr->int_x_green, info_ptr->int_y_green,
  192067. info_ptr->int_x_blue, info_ptr->int_y_blue);
  192068. # endif
  192069. #endif
  192070. }
  192071. #endif
  192072. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192073. if (info_ptr->unknown_chunks_num)
  192074. {
  192075. png_unknown_chunk *up;
  192076. png_debug(5, "writing extra chunks\n");
  192077. for (up = info_ptr->unknown_chunks;
  192078. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192079. up++)
  192080. {
  192081. int keep=png_handle_as_unknown(png_ptr, up->name);
  192082. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192083. up->location && !(up->location & PNG_HAVE_PLTE) &&
  192084. !(up->location & PNG_HAVE_IDAT) &&
  192085. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192086. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192087. {
  192088. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192089. }
  192090. }
  192091. }
  192092. #endif
  192093. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  192094. }
  192095. }
  192096. void PNGAPI
  192097. png_write_info(png_structp png_ptr, png_infop info_ptr)
  192098. {
  192099. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  192100. int i;
  192101. #endif
  192102. png_debug(1, "in png_write_info\n");
  192103. if (png_ptr == NULL || info_ptr == NULL)
  192104. return;
  192105. png_write_info_before_PLTE(png_ptr, info_ptr);
  192106. if (info_ptr->valid & PNG_INFO_PLTE)
  192107. png_write_PLTE(png_ptr, info_ptr->palette,
  192108. (png_uint_32)info_ptr->num_palette);
  192109. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192110. png_error(png_ptr, "Valid palette required for paletted images");
  192111. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  192112. if (info_ptr->valid & PNG_INFO_tRNS)
  192113. {
  192114. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192115. /* invert the alpha channel (in tRNS) */
  192116. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  192117. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192118. {
  192119. int j;
  192120. for (j=0; j<(int)info_ptr->num_trans; j++)
  192121. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  192122. }
  192123. #endif
  192124. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  192125. info_ptr->num_trans, info_ptr->color_type);
  192126. }
  192127. #endif
  192128. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  192129. if (info_ptr->valid & PNG_INFO_bKGD)
  192130. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  192131. #endif
  192132. #if defined(PNG_WRITE_hIST_SUPPORTED)
  192133. if (info_ptr->valid & PNG_INFO_hIST)
  192134. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  192135. #endif
  192136. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  192137. if (info_ptr->valid & PNG_INFO_oFFs)
  192138. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  192139. info_ptr->offset_unit_type);
  192140. #endif
  192141. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  192142. if (info_ptr->valid & PNG_INFO_pCAL)
  192143. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  192144. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  192145. info_ptr->pcal_units, info_ptr->pcal_params);
  192146. #endif
  192147. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  192148. if (info_ptr->valid & PNG_INFO_sCAL)
  192149. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  192150. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  192151. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  192152. #else
  192153. #ifdef PNG_FIXED_POINT_SUPPORTED
  192154. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  192155. info_ptr->scal_s_width, info_ptr->scal_s_height);
  192156. #else
  192157. png_warning(png_ptr,
  192158. "png_write_sCAL not supported; sCAL chunk not written.");
  192159. #endif
  192160. #endif
  192161. #endif
  192162. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  192163. if (info_ptr->valid & PNG_INFO_pHYs)
  192164. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  192165. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  192166. #endif
  192167. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192168. if (info_ptr->valid & PNG_INFO_tIME)
  192169. {
  192170. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192171. png_ptr->mode |= PNG_WROTE_tIME;
  192172. }
  192173. #endif
  192174. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  192175. if (info_ptr->valid & PNG_INFO_sPLT)
  192176. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  192177. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  192178. #endif
  192179. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192180. /* Check to see if we need to write text chunks */
  192181. for (i = 0; i < info_ptr->num_text; i++)
  192182. {
  192183. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  192184. info_ptr->text[i].compression);
  192185. /* an internationalized chunk? */
  192186. if (info_ptr->text[i].compression > 0)
  192187. {
  192188. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192189. /* write international chunk */
  192190. png_write_iTXt(png_ptr,
  192191. info_ptr->text[i].compression,
  192192. info_ptr->text[i].key,
  192193. info_ptr->text[i].lang,
  192194. info_ptr->text[i].lang_key,
  192195. info_ptr->text[i].text);
  192196. #else
  192197. png_warning(png_ptr, "Unable to write international text");
  192198. #endif
  192199. /* Mark this chunk as written */
  192200. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192201. }
  192202. /* If we want a compressed text chunk */
  192203. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  192204. {
  192205. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192206. /* write compressed chunk */
  192207. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192208. info_ptr->text[i].text, 0,
  192209. info_ptr->text[i].compression);
  192210. #else
  192211. png_warning(png_ptr, "Unable to write compressed text");
  192212. #endif
  192213. /* Mark this chunk as written */
  192214. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192215. }
  192216. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192217. {
  192218. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192219. /* write uncompressed chunk */
  192220. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192221. info_ptr->text[i].text,
  192222. 0);
  192223. #else
  192224. png_warning(png_ptr, "Unable to write uncompressed text");
  192225. #endif
  192226. /* Mark this chunk as written */
  192227. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192228. }
  192229. }
  192230. #endif
  192231. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192232. if (info_ptr->unknown_chunks_num)
  192233. {
  192234. png_unknown_chunk *up;
  192235. png_debug(5, "writing extra chunks\n");
  192236. for (up = info_ptr->unknown_chunks;
  192237. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192238. up++)
  192239. {
  192240. int keep=png_handle_as_unknown(png_ptr, up->name);
  192241. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192242. up->location && (up->location & PNG_HAVE_PLTE) &&
  192243. !(up->location & PNG_HAVE_IDAT) &&
  192244. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192245. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192246. {
  192247. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192248. }
  192249. }
  192250. }
  192251. #endif
  192252. }
  192253. /* Writes the end of the PNG file. If you don't want to write comments or
  192254. * time information, you can pass NULL for info. If you already wrote these
  192255. * in png_write_info(), do not write them again here. If you have long
  192256. * comments, I suggest writing them here, and compressing them.
  192257. */
  192258. void PNGAPI
  192259. png_write_end(png_structp png_ptr, png_infop info_ptr)
  192260. {
  192261. png_debug(1, "in png_write_end\n");
  192262. if (png_ptr == NULL)
  192263. return;
  192264. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  192265. png_error(png_ptr, "No IDATs written into file");
  192266. /* see if user wants us to write information chunks */
  192267. if (info_ptr != NULL)
  192268. {
  192269. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192270. int i; /* local index variable */
  192271. #endif
  192272. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192273. /* check to see if user has supplied a time chunk */
  192274. if ((info_ptr->valid & PNG_INFO_tIME) &&
  192275. !(png_ptr->mode & PNG_WROTE_tIME))
  192276. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192277. #endif
  192278. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192279. /* loop through comment chunks */
  192280. for (i = 0; i < info_ptr->num_text; i++)
  192281. {
  192282. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  192283. info_ptr->text[i].compression);
  192284. /* an internationalized chunk? */
  192285. if (info_ptr->text[i].compression > 0)
  192286. {
  192287. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192288. /* write international chunk */
  192289. png_write_iTXt(png_ptr,
  192290. info_ptr->text[i].compression,
  192291. info_ptr->text[i].key,
  192292. info_ptr->text[i].lang,
  192293. info_ptr->text[i].lang_key,
  192294. info_ptr->text[i].text);
  192295. #else
  192296. png_warning(png_ptr, "Unable to write international text");
  192297. #endif
  192298. /* Mark this chunk as written */
  192299. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192300. }
  192301. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  192302. {
  192303. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192304. /* write compressed chunk */
  192305. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192306. info_ptr->text[i].text, 0,
  192307. info_ptr->text[i].compression);
  192308. #else
  192309. png_warning(png_ptr, "Unable to write compressed text");
  192310. #endif
  192311. /* Mark this chunk as written */
  192312. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192313. }
  192314. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192315. {
  192316. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192317. /* write uncompressed chunk */
  192318. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192319. info_ptr->text[i].text, 0);
  192320. #else
  192321. png_warning(png_ptr, "Unable to write uncompressed text");
  192322. #endif
  192323. /* Mark this chunk as written */
  192324. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192325. }
  192326. }
  192327. #endif
  192328. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192329. if (info_ptr->unknown_chunks_num)
  192330. {
  192331. png_unknown_chunk *up;
  192332. png_debug(5, "writing extra chunks\n");
  192333. for (up = info_ptr->unknown_chunks;
  192334. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192335. up++)
  192336. {
  192337. int keep=png_handle_as_unknown(png_ptr, up->name);
  192338. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192339. up->location && (up->location & PNG_AFTER_IDAT) &&
  192340. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192341. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192342. {
  192343. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192344. }
  192345. }
  192346. }
  192347. #endif
  192348. }
  192349. png_ptr->mode |= PNG_AFTER_IDAT;
  192350. /* write end of PNG file */
  192351. png_write_IEND(png_ptr);
  192352. }
  192353. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192354. #if !defined(_WIN32_WCE)
  192355. /* "time.h" functions are not supported on WindowsCE */
  192356. void PNGAPI
  192357. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  192358. {
  192359. png_debug(1, "in png_convert_from_struct_tm\n");
  192360. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  192361. ptime->month = (png_byte)(ttime->tm_mon + 1);
  192362. ptime->day = (png_byte)ttime->tm_mday;
  192363. ptime->hour = (png_byte)ttime->tm_hour;
  192364. ptime->minute = (png_byte)ttime->tm_min;
  192365. ptime->second = (png_byte)ttime->tm_sec;
  192366. }
  192367. void PNGAPI
  192368. png_convert_from_time_t(png_timep ptime, time_t ttime)
  192369. {
  192370. struct tm *tbuf;
  192371. png_debug(1, "in png_convert_from_time_t\n");
  192372. tbuf = gmtime(&ttime);
  192373. png_convert_from_struct_tm(ptime, tbuf);
  192374. }
  192375. #endif
  192376. #endif
  192377. /* Initialize png_ptr structure, and allocate any memory needed */
  192378. png_structp PNGAPI
  192379. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  192380. png_error_ptr error_fn, png_error_ptr warn_fn)
  192381. {
  192382. #ifdef PNG_USER_MEM_SUPPORTED
  192383. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  192384. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  192385. }
  192386. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  192387. png_structp PNGAPI
  192388. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  192389. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  192390. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  192391. {
  192392. #endif /* PNG_USER_MEM_SUPPORTED */
  192393. png_structp png_ptr;
  192394. #ifdef PNG_SETJMP_SUPPORTED
  192395. #ifdef USE_FAR_KEYWORD
  192396. jmp_buf jmpbuf;
  192397. #endif
  192398. #endif
  192399. int i;
  192400. png_debug(1, "in png_create_write_struct\n");
  192401. #ifdef PNG_USER_MEM_SUPPORTED
  192402. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  192403. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  192404. #else
  192405. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  192406. #endif /* PNG_USER_MEM_SUPPORTED */
  192407. if (png_ptr == NULL)
  192408. return (NULL);
  192409. /* added at libpng-1.2.6 */
  192410. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192411. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  192412. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  192413. #endif
  192414. #ifdef PNG_SETJMP_SUPPORTED
  192415. #ifdef USE_FAR_KEYWORD
  192416. if (setjmp(jmpbuf))
  192417. #else
  192418. if (setjmp(png_ptr->jmpbuf))
  192419. #endif
  192420. {
  192421. png_free(png_ptr, png_ptr->zbuf);
  192422. png_ptr->zbuf=NULL;
  192423. png_destroy_struct(png_ptr);
  192424. return (NULL);
  192425. }
  192426. #ifdef USE_FAR_KEYWORD
  192427. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  192428. #endif
  192429. #endif
  192430. #ifdef PNG_USER_MEM_SUPPORTED
  192431. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  192432. #endif /* PNG_USER_MEM_SUPPORTED */
  192433. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  192434. i=0;
  192435. do
  192436. {
  192437. if(user_png_ver[i] != png_libpng_ver[i])
  192438. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  192439. } while (png_libpng_ver[i++]);
  192440. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  192441. {
  192442. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  192443. * we must recompile any applications that use any older library version.
  192444. * For versions after libpng 1.0, we will be compatible, so we need
  192445. * only check the first digit.
  192446. */
  192447. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  192448. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  192449. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  192450. {
  192451. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  192452. char msg[80];
  192453. if (user_png_ver)
  192454. {
  192455. png_snprintf(msg, 80,
  192456. "Application was compiled with png.h from libpng-%.20s",
  192457. user_png_ver);
  192458. png_warning(png_ptr, msg);
  192459. }
  192460. png_snprintf(msg, 80,
  192461. "Application is running with png.c from libpng-%.20s",
  192462. png_libpng_ver);
  192463. png_warning(png_ptr, msg);
  192464. #endif
  192465. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192466. png_ptr->flags=0;
  192467. #endif
  192468. png_error(png_ptr,
  192469. "Incompatible libpng version in application and library");
  192470. }
  192471. }
  192472. /* initialize zbuf - compression buffer */
  192473. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  192474. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  192475. (png_uint_32)png_ptr->zbuf_size);
  192476. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  192477. png_flush_ptr_NULL);
  192478. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192479. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  192480. 1, png_doublep_NULL, png_doublep_NULL);
  192481. #endif
  192482. #ifdef PNG_SETJMP_SUPPORTED
  192483. /* Applications that neglect to set up their own setjmp() and then encounter
  192484. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  192485. abort instead of returning. */
  192486. #ifdef USE_FAR_KEYWORD
  192487. if (setjmp(jmpbuf))
  192488. PNG_ABORT();
  192489. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  192490. #else
  192491. if (setjmp(png_ptr->jmpbuf))
  192492. PNG_ABORT();
  192493. #endif
  192494. #endif
  192495. return (png_ptr);
  192496. }
  192497. /* Initialize png_ptr structure, and allocate any memory needed */
  192498. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  192499. /* Deprecated. */
  192500. #undef png_write_init
  192501. void PNGAPI
  192502. png_write_init(png_structp png_ptr)
  192503. {
  192504. /* We only come here via pre-1.0.7-compiled applications */
  192505. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  192506. }
  192507. void PNGAPI
  192508. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  192509. png_size_t png_struct_size, png_size_t png_info_size)
  192510. {
  192511. /* We only come here via pre-1.0.12-compiled applications */
  192512. if(png_ptr == NULL) return;
  192513. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  192514. if(png_sizeof(png_struct) > png_struct_size ||
  192515. png_sizeof(png_info) > png_info_size)
  192516. {
  192517. char msg[80];
  192518. png_ptr->warning_fn=NULL;
  192519. if (user_png_ver)
  192520. {
  192521. png_snprintf(msg, 80,
  192522. "Application was compiled with png.h from libpng-%.20s",
  192523. user_png_ver);
  192524. png_warning(png_ptr, msg);
  192525. }
  192526. png_snprintf(msg, 80,
  192527. "Application is running with png.c from libpng-%.20s",
  192528. png_libpng_ver);
  192529. png_warning(png_ptr, msg);
  192530. }
  192531. #endif
  192532. if(png_sizeof(png_struct) > png_struct_size)
  192533. {
  192534. png_ptr->error_fn=NULL;
  192535. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192536. png_ptr->flags=0;
  192537. #endif
  192538. png_error(png_ptr,
  192539. "The png struct allocated by the application for writing is too small.");
  192540. }
  192541. if(png_sizeof(png_info) > png_info_size)
  192542. {
  192543. png_ptr->error_fn=NULL;
  192544. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192545. png_ptr->flags=0;
  192546. #endif
  192547. png_error(png_ptr,
  192548. "The info struct allocated by the application for writing is too small.");
  192549. }
  192550. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  192551. }
  192552. #endif /* PNG_1_0_X || PNG_1_2_X */
  192553. void PNGAPI
  192554. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  192555. png_size_t png_struct_size)
  192556. {
  192557. png_structp png_ptr=*ptr_ptr;
  192558. #ifdef PNG_SETJMP_SUPPORTED
  192559. jmp_buf tmp_jmp; /* to save current jump buffer */
  192560. #endif
  192561. int i = 0;
  192562. if (png_ptr == NULL)
  192563. return;
  192564. do
  192565. {
  192566. if (user_png_ver[i] != png_libpng_ver[i])
  192567. {
  192568. #ifdef PNG_LEGACY_SUPPORTED
  192569. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  192570. #else
  192571. png_ptr->warning_fn=NULL;
  192572. png_warning(png_ptr,
  192573. "Application uses deprecated png_write_init() and should be recompiled.");
  192574. break;
  192575. #endif
  192576. }
  192577. } while (png_libpng_ver[i++]);
  192578. png_debug(1, "in png_write_init_3\n");
  192579. #ifdef PNG_SETJMP_SUPPORTED
  192580. /* save jump buffer and error functions */
  192581. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  192582. #endif
  192583. if (png_sizeof(png_struct) > png_struct_size)
  192584. {
  192585. png_destroy_struct(png_ptr);
  192586. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  192587. *ptr_ptr = png_ptr;
  192588. }
  192589. /* reset all variables to 0 */
  192590. png_memset(png_ptr, 0, png_sizeof (png_struct));
  192591. /* added at libpng-1.2.6 */
  192592. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192593. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  192594. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  192595. #endif
  192596. #ifdef PNG_SETJMP_SUPPORTED
  192597. /* restore jump buffer */
  192598. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  192599. #endif
  192600. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  192601. png_flush_ptr_NULL);
  192602. /* initialize zbuf - compression buffer */
  192603. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  192604. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  192605. (png_uint_32)png_ptr->zbuf_size);
  192606. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192607. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  192608. 1, png_doublep_NULL, png_doublep_NULL);
  192609. #endif
  192610. }
  192611. /* Write a few rows of image data. If the image is interlaced,
  192612. * either you will have to write the 7 sub images, or, if you
  192613. * have called png_set_interlace_handling(), you will have to
  192614. * "write" the image seven times.
  192615. */
  192616. void PNGAPI
  192617. png_write_rows(png_structp png_ptr, png_bytepp row,
  192618. png_uint_32 num_rows)
  192619. {
  192620. png_uint_32 i; /* row counter */
  192621. png_bytepp rp; /* row pointer */
  192622. png_debug(1, "in png_write_rows\n");
  192623. if (png_ptr == NULL)
  192624. return;
  192625. /* loop through the rows */
  192626. for (i = 0, rp = row; i < num_rows; i++, rp++)
  192627. {
  192628. png_write_row(png_ptr, *rp);
  192629. }
  192630. }
  192631. /* Write the image. You only need to call this function once, even
  192632. * if you are writing an interlaced image.
  192633. */
  192634. void PNGAPI
  192635. png_write_image(png_structp png_ptr, png_bytepp image)
  192636. {
  192637. png_uint_32 i; /* row index */
  192638. int pass, num_pass; /* pass variables */
  192639. png_bytepp rp; /* points to current row */
  192640. if (png_ptr == NULL)
  192641. return;
  192642. png_debug(1, "in png_write_image\n");
  192643. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192644. /* intialize interlace handling. If image is not interlaced,
  192645. this will set pass to 1 */
  192646. num_pass = png_set_interlace_handling(png_ptr);
  192647. #else
  192648. num_pass = 1;
  192649. #endif
  192650. /* loop through passes */
  192651. for (pass = 0; pass < num_pass; pass++)
  192652. {
  192653. /* loop through image */
  192654. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  192655. {
  192656. png_write_row(png_ptr, *rp);
  192657. }
  192658. }
  192659. }
  192660. /* called by user to write a row of image data */
  192661. void PNGAPI
  192662. png_write_row(png_structp png_ptr, png_bytep row)
  192663. {
  192664. if (png_ptr == NULL)
  192665. return;
  192666. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  192667. png_ptr->row_number, png_ptr->pass);
  192668. /* initialize transformations and other stuff if first time */
  192669. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  192670. {
  192671. /* make sure we wrote the header info */
  192672. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192673. png_error(png_ptr,
  192674. "png_write_info was never called before png_write_row.");
  192675. /* check for transforms that have been set but were defined out */
  192676. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  192677. if (png_ptr->transformations & PNG_INVERT_MONO)
  192678. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  192679. #endif
  192680. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  192681. if (png_ptr->transformations & PNG_FILLER)
  192682. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  192683. #endif
  192684. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  192685. if (png_ptr->transformations & PNG_PACKSWAP)
  192686. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  192687. #endif
  192688. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  192689. if (png_ptr->transformations & PNG_PACK)
  192690. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  192691. #endif
  192692. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  192693. if (png_ptr->transformations & PNG_SHIFT)
  192694. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  192695. #endif
  192696. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  192697. if (png_ptr->transformations & PNG_BGR)
  192698. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  192699. #endif
  192700. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  192701. if (png_ptr->transformations & PNG_SWAP_BYTES)
  192702. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  192703. #endif
  192704. png_write_start_row(png_ptr);
  192705. }
  192706. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192707. /* if interlaced and not interested in row, return */
  192708. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  192709. {
  192710. switch (png_ptr->pass)
  192711. {
  192712. case 0:
  192713. if (png_ptr->row_number & 0x07)
  192714. {
  192715. png_write_finish_row(png_ptr);
  192716. return;
  192717. }
  192718. break;
  192719. case 1:
  192720. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  192721. {
  192722. png_write_finish_row(png_ptr);
  192723. return;
  192724. }
  192725. break;
  192726. case 2:
  192727. if ((png_ptr->row_number & 0x07) != 4)
  192728. {
  192729. png_write_finish_row(png_ptr);
  192730. return;
  192731. }
  192732. break;
  192733. case 3:
  192734. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  192735. {
  192736. png_write_finish_row(png_ptr);
  192737. return;
  192738. }
  192739. break;
  192740. case 4:
  192741. if ((png_ptr->row_number & 0x03) != 2)
  192742. {
  192743. png_write_finish_row(png_ptr);
  192744. return;
  192745. }
  192746. break;
  192747. case 5:
  192748. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  192749. {
  192750. png_write_finish_row(png_ptr);
  192751. return;
  192752. }
  192753. break;
  192754. case 6:
  192755. if (!(png_ptr->row_number & 0x01))
  192756. {
  192757. png_write_finish_row(png_ptr);
  192758. return;
  192759. }
  192760. break;
  192761. }
  192762. }
  192763. #endif
  192764. /* set up row info for transformations */
  192765. png_ptr->row_info.color_type = png_ptr->color_type;
  192766. png_ptr->row_info.width = png_ptr->usr_width;
  192767. png_ptr->row_info.channels = png_ptr->usr_channels;
  192768. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  192769. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  192770. png_ptr->row_info.channels);
  192771. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  192772. png_ptr->row_info.width);
  192773. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  192774. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  192775. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  192776. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  192777. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  192778. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  192779. /* Copy user's row into buffer, leaving room for filter byte. */
  192780. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  192781. png_ptr->row_info.rowbytes);
  192782. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192783. /* handle interlacing */
  192784. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  192785. (png_ptr->transformations & PNG_INTERLACE))
  192786. {
  192787. png_do_write_interlace(&(png_ptr->row_info),
  192788. png_ptr->row_buf + 1, png_ptr->pass);
  192789. /* this should always get caught above, but still ... */
  192790. if (!(png_ptr->row_info.width))
  192791. {
  192792. png_write_finish_row(png_ptr);
  192793. return;
  192794. }
  192795. }
  192796. #endif
  192797. /* handle other transformations */
  192798. if (png_ptr->transformations)
  192799. png_do_write_transformations(png_ptr);
  192800. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192801. /* Write filter_method 64 (intrapixel differencing) only if
  192802. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192803. * 2. Libpng did not write a PNG signature (this filter_method is only
  192804. * used in PNG datastreams that are embedded in MNG datastreams) and
  192805. * 3. The application called png_permit_mng_features with a mask that
  192806. * included PNG_FLAG_MNG_FILTER_64 and
  192807. * 4. The filter_method is 64 and
  192808. * 5. The color_type is RGB or RGBA
  192809. */
  192810. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192811. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  192812. {
  192813. /* Intrapixel differencing */
  192814. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192815. }
  192816. #endif
  192817. /* Find a filter if necessary, filter the row and write it out. */
  192818. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  192819. if (png_ptr->write_row_fn != NULL)
  192820. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  192821. }
  192822. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192823. /* Set the automatic flush interval or 0 to turn flushing off */
  192824. void PNGAPI
  192825. png_set_flush(png_structp png_ptr, int nrows)
  192826. {
  192827. png_debug(1, "in png_set_flush\n");
  192828. if (png_ptr == NULL)
  192829. return;
  192830. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  192831. }
  192832. /* flush the current output buffers now */
  192833. void PNGAPI
  192834. png_write_flush(png_structp png_ptr)
  192835. {
  192836. int wrote_IDAT;
  192837. png_debug(1, "in png_write_flush\n");
  192838. if (png_ptr == NULL)
  192839. return;
  192840. /* We have already written out all of the data */
  192841. if (png_ptr->row_number >= png_ptr->num_rows)
  192842. return;
  192843. do
  192844. {
  192845. int ret;
  192846. /* compress the data */
  192847. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  192848. wrote_IDAT = 0;
  192849. /* check for compression errors */
  192850. if (ret != Z_OK)
  192851. {
  192852. if (png_ptr->zstream.msg != NULL)
  192853. png_error(png_ptr, png_ptr->zstream.msg);
  192854. else
  192855. png_error(png_ptr, "zlib error");
  192856. }
  192857. if (!(png_ptr->zstream.avail_out))
  192858. {
  192859. /* write the IDAT and reset the zlib output buffer */
  192860. png_write_IDAT(png_ptr, png_ptr->zbuf,
  192861. png_ptr->zbuf_size);
  192862. png_ptr->zstream.next_out = png_ptr->zbuf;
  192863. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192864. wrote_IDAT = 1;
  192865. }
  192866. } while(wrote_IDAT == 1);
  192867. /* If there is any data left to be output, write it into a new IDAT */
  192868. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  192869. {
  192870. /* write the IDAT and reset the zlib output buffer */
  192871. png_write_IDAT(png_ptr, png_ptr->zbuf,
  192872. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  192873. png_ptr->zstream.next_out = png_ptr->zbuf;
  192874. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192875. }
  192876. png_ptr->flush_rows = 0;
  192877. png_flush(png_ptr);
  192878. }
  192879. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  192880. /* free all memory used by the write */
  192881. void PNGAPI
  192882. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  192883. {
  192884. png_structp png_ptr = NULL;
  192885. png_infop info_ptr = NULL;
  192886. #ifdef PNG_USER_MEM_SUPPORTED
  192887. png_free_ptr free_fn = NULL;
  192888. png_voidp mem_ptr = NULL;
  192889. #endif
  192890. png_debug(1, "in png_destroy_write_struct\n");
  192891. if (png_ptr_ptr != NULL)
  192892. {
  192893. png_ptr = *png_ptr_ptr;
  192894. #ifdef PNG_USER_MEM_SUPPORTED
  192895. free_fn = png_ptr->free_fn;
  192896. mem_ptr = png_ptr->mem_ptr;
  192897. #endif
  192898. }
  192899. if (info_ptr_ptr != NULL)
  192900. info_ptr = *info_ptr_ptr;
  192901. if (info_ptr != NULL)
  192902. {
  192903. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  192904. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192905. if (png_ptr->num_chunk_list)
  192906. {
  192907. png_free(png_ptr, png_ptr->chunk_list);
  192908. png_ptr->chunk_list=NULL;
  192909. png_ptr->num_chunk_list=0;
  192910. }
  192911. #endif
  192912. #ifdef PNG_USER_MEM_SUPPORTED
  192913. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  192914. (png_voidp)mem_ptr);
  192915. #else
  192916. png_destroy_struct((png_voidp)info_ptr);
  192917. #endif
  192918. *info_ptr_ptr = NULL;
  192919. }
  192920. if (png_ptr != NULL)
  192921. {
  192922. png_write_destroy(png_ptr);
  192923. #ifdef PNG_USER_MEM_SUPPORTED
  192924. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  192925. (png_voidp)mem_ptr);
  192926. #else
  192927. png_destroy_struct((png_voidp)png_ptr);
  192928. #endif
  192929. *png_ptr_ptr = NULL;
  192930. }
  192931. }
  192932. /* Free any memory used in png_ptr struct (old method) */
  192933. void /* PRIVATE */
  192934. png_write_destroy(png_structp png_ptr)
  192935. {
  192936. #ifdef PNG_SETJMP_SUPPORTED
  192937. jmp_buf tmp_jmp; /* save jump buffer */
  192938. #endif
  192939. png_error_ptr error_fn;
  192940. png_error_ptr warning_fn;
  192941. png_voidp error_ptr;
  192942. #ifdef PNG_USER_MEM_SUPPORTED
  192943. png_free_ptr free_fn;
  192944. #endif
  192945. png_debug(1, "in png_write_destroy\n");
  192946. /* free any memory zlib uses */
  192947. deflateEnd(&png_ptr->zstream);
  192948. /* free our memory. png_free checks NULL for us. */
  192949. png_free(png_ptr, png_ptr->zbuf);
  192950. png_free(png_ptr, png_ptr->row_buf);
  192951. png_free(png_ptr, png_ptr->prev_row);
  192952. png_free(png_ptr, png_ptr->sub_row);
  192953. png_free(png_ptr, png_ptr->up_row);
  192954. png_free(png_ptr, png_ptr->avg_row);
  192955. png_free(png_ptr, png_ptr->paeth_row);
  192956. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  192957. png_free(png_ptr, png_ptr->time_buffer);
  192958. #endif
  192959. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192960. png_free(png_ptr, png_ptr->prev_filters);
  192961. png_free(png_ptr, png_ptr->filter_weights);
  192962. png_free(png_ptr, png_ptr->inv_filter_weights);
  192963. png_free(png_ptr, png_ptr->filter_costs);
  192964. png_free(png_ptr, png_ptr->inv_filter_costs);
  192965. #endif
  192966. #ifdef PNG_SETJMP_SUPPORTED
  192967. /* reset structure */
  192968. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  192969. #endif
  192970. error_fn = png_ptr->error_fn;
  192971. warning_fn = png_ptr->warning_fn;
  192972. error_ptr = png_ptr->error_ptr;
  192973. #ifdef PNG_USER_MEM_SUPPORTED
  192974. free_fn = png_ptr->free_fn;
  192975. #endif
  192976. png_memset(png_ptr, 0, png_sizeof (png_struct));
  192977. png_ptr->error_fn = error_fn;
  192978. png_ptr->warning_fn = warning_fn;
  192979. png_ptr->error_ptr = error_ptr;
  192980. #ifdef PNG_USER_MEM_SUPPORTED
  192981. png_ptr->free_fn = free_fn;
  192982. #endif
  192983. #ifdef PNG_SETJMP_SUPPORTED
  192984. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  192985. #endif
  192986. }
  192987. /* Allow the application to select one or more row filters to use. */
  192988. void PNGAPI
  192989. png_set_filter(png_structp png_ptr, int method, int filters)
  192990. {
  192991. png_debug(1, "in png_set_filter\n");
  192992. if (png_ptr == NULL)
  192993. return;
  192994. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192995. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192996. (method == PNG_INTRAPIXEL_DIFFERENCING))
  192997. method = PNG_FILTER_TYPE_BASE;
  192998. #endif
  192999. if (method == PNG_FILTER_TYPE_BASE)
  193000. {
  193001. switch (filters & (PNG_ALL_FILTERS | 0x07))
  193002. {
  193003. #ifndef PNG_NO_WRITE_FILTER
  193004. case 5:
  193005. case 6:
  193006. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  193007. #endif /* PNG_NO_WRITE_FILTER */
  193008. case PNG_FILTER_VALUE_NONE:
  193009. png_ptr->do_filter=PNG_FILTER_NONE; break;
  193010. #ifndef PNG_NO_WRITE_FILTER
  193011. case PNG_FILTER_VALUE_SUB:
  193012. png_ptr->do_filter=PNG_FILTER_SUB; break;
  193013. case PNG_FILTER_VALUE_UP:
  193014. png_ptr->do_filter=PNG_FILTER_UP; break;
  193015. case PNG_FILTER_VALUE_AVG:
  193016. png_ptr->do_filter=PNG_FILTER_AVG; break;
  193017. case PNG_FILTER_VALUE_PAETH:
  193018. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  193019. default: png_ptr->do_filter = (png_byte)filters; break;
  193020. #else
  193021. default: png_warning(png_ptr, "Unknown row filter for method 0");
  193022. #endif /* PNG_NO_WRITE_FILTER */
  193023. }
  193024. /* If we have allocated the row_buf, this means we have already started
  193025. * with the image and we should have allocated all of the filter buffers
  193026. * that have been selected. If prev_row isn't already allocated, then
  193027. * it is too late to start using the filters that need it, since we
  193028. * will be missing the data in the previous row. If an application
  193029. * wants to start and stop using particular filters during compression,
  193030. * it should start out with all of the filters, and then add and
  193031. * remove them after the start of compression.
  193032. */
  193033. if (png_ptr->row_buf != NULL)
  193034. {
  193035. #ifndef PNG_NO_WRITE_FILTER
  193036. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  193037. {
  193038. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  193039. (png_ptr->rowbytes + 1));
  193040. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  193041. }
  193042. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  193043. {
  193044. if (png_ptr->prev_row == NULL)
  193045. {
  193046. png_warning(png_ptr, "Can't add Up filter after starting");
  193047. png_ptr->do_filter &= ~PNG_FILTER_UP;
  193048. }
  193049. else
  193050. {
  193051. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  193052. (png_ptr->rowbytes + 1));
  193053. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  193054. }
  193055. }
  193056. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  193057. {
  193058. if (png_ptr->prev_row == NULL)
  193059. {
  193060. png_warning(png_ptr, "Can't add Average filter after starting");
  193061. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  193062. }
  193063. else
  193064. {
  193065. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  193066. (png_ptr->rowbytes + 1));
  193067. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  193068. }
  193069. }
  193070. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  193071. png_ptr->paeth_row == NULL)
  193072. {
  193073. if (png_ptr->prev_row == NULL)
  193074. {
  193075. png_warning(png_ptr, "Can't add Paeth filter after starting");
  193076. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  193077. }
  193078. else
  193079. {
  193080. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  193081. (png_ptr->rowbytes + 1));
  193082. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  193083. }
  193084. }
  193085. if (png_ptr->do_filter == PNG_NO_FILTERS)
  193086. #endif /* PNG_NO_WRITE_FILTER */
  193087. png_ptr->do_filter = PNG_FILTER_NONE;
  193088. }
  193089. }
  193090. else
  193091. png_error(png_ptr, "Unknown custom filter method");
  193092. }
  193093. /* This allows us to influence the way in which libpng chooses the "best"
  193094. * filter for the current scanline. While the "minimum-sum-of-absolute-
  193095. * differences metric is relatively fast and effective, there is some
  193096. * question as to whether it can be improved upon by trying to keep the
  193097. * filtered data going to zlib more consistent, hopefully resulting in
  193098. * better compression.
  193099. */
  193100. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  193101. void PNGAPI
  193102. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  193103. int num_weights, png_doublep filter_weights,
  193104. png_doublep filter_costs)
  193105. {
  193106. int i;
  193107. png_debug(1, "in png_set_filter_heuristics\n");
  193108. if (png_ptr == NULL)
  193109. return;
  193110. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  193111. {
  193112. png_warning(png_ptr, "Unknown filter heuristic method");
  193113. return;
  193114. }
  193115. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  193116. {
  193117. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  193118. }
  193119. if (num_weights < 0 || filter_weights == NULL ||
  193120. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  193121. {
  193122. num_weights = 0;
  193123. }
  193124. png_ptr->num_prev_filters = (png_byte)num_weights;
  193125. png_ptr->heuristic_method = (png_byte)heuristic_method;
  193126. if (num_weights > 0)
  193127. {
  193128. if (png_ptr->prev_filters == NULL)
  193129. {
  193130. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  193131. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  193132. /* To make sure that the weighting starts out fairly */
  193133. for (i = 0; i < num_weights; i++)
  193134. {
  193135. png_ptr->prev_filters[i] = 255;
  193136. }
  193137. }
  193138. if (png_ptr->filter_weights == NULL)
  193139. {
  193140. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193141. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193142. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193143. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193144. for (i = 0; i < num_weights; i++)
  193145. {
  193146. png_ptr->inv_filter_weights[i] =
  193147. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193148. }
  193149. }
  193150. for (i = 0; i < num_weights; i++)
  193151. {
  193152. if (filter_weights[i] < 0.0)
  193153. {
  193154. png_ptr->inv_filter_weights[i] =
  193155. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193156. }
  193157. else
  193158. {
  193159. png_ptr->inv_filter_weights[i] =
  193160. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  193161. png_ptr->filter_weights[i] =
  193162. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  193163. }
  193164. }
  193165. }
  193166. /* If, in the future, there are other filter methods, this would
  193167. * need to be based on png_ptr->filter.
  193168. */
  193169. if (png_ptr->filter_costs == NULL)
  193170. {
  193171. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193172. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193173. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193174. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193175. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193176. {
  193177. png_ptr->inv_filter_costs[i] =
  193178. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193179. }
  193180. }
  193181. /* Here is where we set the relative costs of the different filters. We
  193182. * should take the desired compression level into account when setting
  193183. * the costs, so that Paeth, for instance, has a high relative cost at low
  193184. * compression levels, while it has a lower relative cost at higher
  193185. * compression settings. The filter types are in order of increasing
  193186. * relative cost, so it would be possible to do this with an algorithm.
  193187. */
  193188. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193189. {
  193190. if (filter_costs == NULL || filter_costs[i] < 0.0)
  193191. {
  193192. png_ptr->inv_filter_costs[i] =
  193193. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193194. }
  193195. else if (filter_costs[i] >= 1.0)
  193196. {
  193197. png_ptr->inv_filter_costs[i] =
  193198. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  193199. png_ptr->filter_costs[i] =
  193200. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  193201. }
  193202. }
  193203. }
  193204. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  193205. void PNGAPI
  193206. png_set_compression_level(png_structp png_ptr, int level)
  193207. {
  193208. png_debug(1, "in png_set_compression_level\n");
  193209. if (png_ptr == NULL)
  193210. return;
  193211. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  193212. png_ptr->zlib_level = level;
  193213. }
  193214. void PNGAPI
  193215. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  193216. {
  193217. png_debug(1, "in png_set_compression_mem_level\n");
  193218. if (png_ptr == NULL)
  193219. return;
  193220. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  193221. png_ptr->zlib_mem_level = mem_level;
  193222. }
  193223. void PNGAPI
  193224. png_set_compression_strategy(png_structp png_ptr, int strategy)
  193225. {
  193226. png_debug(1, "in png_set_compression_strategy\n");
  193227. if (png_ptr == NULL)
  193228. return;
  193229. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  193230. png_ptr->zlib_strategy = strategy;
  193231. }
  193232. void PNGAPI
  193233. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  193234. {
  193235. if (png_ptr == NULL)
  193236. return;
  193237. if (window_bits > 15)
  193238. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  193239. else if (window_bits < 8)
  193240. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  193241. #ifndef WBITS_8_OK
  193242. /* avoid libpng bug with 256-byte windows */
  193243. if (window_bits == 8)
  193244. {
  193245. png_warning(png_ptr, "Compression window is being reset to 512");
  193246. window_bits=9;
  193247. }
  193248. #endif
  193249. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  193250. png_ptr->zlib_window_bits = window_bits;
  193251. }
  193252. void PNGAPI
  193253. png_set_compression_method(png_structp png_ptr, int method)
  193254. {
  193255. png_debug(1, "in png_set_compression_method\n");
  193256. if (png_ptr == NULL)
  193257. return;
  193258. if (method != 8)
  193259. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  193260. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  193261. png_ptr->zlib_method = method;
  193262. }
  193263. void PNGAPI
  193264. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  193265. {
  193266. if (png_ptr == NULL)
  193267. return;
  193268. png_ptr->write_row_fn = write_row_fn;
  193269. }
  193270. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193271. void PNGAPI
  193272. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  193273. write_user_transform_fn)
  193274. {
  193275. png_debug(1, "in png_set_write_user_transform_fn\n");
  193276. if (png_ptr == NULL)
  193277. return;
  193278. png_ptr->transformations |= PNG_USER_TRANSFORM;
  193279. png_ptr->write_user_transform_fn = write_user_transform_fn;
  193280. }
  193281. #endif
  193282. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193283. void PNGAPI
  193284. png_write_png(png_structp png_ptr, png_infop info_ptr,
  193285. int transforms, voidp params)
  193286. {
  193287. if (png_ptr == NULL || info_ptr == NULL)
  193288. return;
  193289. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193290. /* invert the alpha channel from opacity to transparency */
  193291. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  193292. png_set_invert_alpha(png_ptr);
  193293. #endif
  193294. /* Write the file header information. */
  193295. png_write_info(png_ptr, info_ptr);
  193296. /* ------ these transformations don't touch the info structure ------- */
  193297. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  193298. /* invert monochrome pixels */
  193299. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  193300. png_set_invert_mono(png_ptr);
  193301. #endif
  193302. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193303. /* Shift the pixels up to a legal bit depth and fill in
  193304. * as appropriate to correctly scale the image.
  193305. */
  193306. if ((transforms & PNG_TRANSFORM_SHIFT)
  193307. && (info_ptr->valid & PNG_INFO_sBIT))
  193308. png_set_shift(png_ptr, &info_ptr->sig_bit);
  193309. #endif
  193310. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193311. /* pack pixels into bytes */
  193312. if (transforms & PNG_TRANSFORM_PACKING)
  193313. png_set_packing(png_ptr);
  193314. #endif
  193315. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193316. /* swap location of alpha bytes from ARGB to RGBA */
  193317. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  193318. png_set_swap_alpha(png_ptr);
  193319. #endif
  193320. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  193321. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  193322. * RGB (4 channels -> 3 channels). The second parameter is not used.
  193323. */
  193324. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  193325. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  193326. #endif
  193327. #if defined(PNG_WRITE_BGR_SUPPORTED)
  193328. /* flip BGR pixels to RGB */
  193329. if (transforms & PNG_TRANSFORM_BGR)
  193330. png_set_bgr(png_ptr);
  193331. #endif
  193332. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  193333. /* swap bytes of 16-bit files to most significant byte first */
  193334. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  193335. png_set_swap(png_ptr);
  193336. #endif
  193337. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193338. /* swap bits of 1, 2, 4 bit packed pixel formats */
  193339. if (transforms & PNG_TRANSFORM_PACKSWAP)
  193340. png_set_packswap(png_ptr);
  193341. #endif
  193342. /* ----------------------- end of transformations ------------------- */
  193343. /* write the bits */
  193344. if (info_ptr->valid & PNG_INFO_IDAT)
  193345. png_write_image(png_ptr, info_ptr->row_pointers);
  193346. /* It is REQUIRED to call this to finish writing the rest of the file */
  193347. png_write_end(png_ptr, info_ptr);
  193348. transforms = transforms; /* quiet compiler warnings */
  193349. params = params;
  193350. }
  193351. #endif
  193352. #endif /* PNG_WRITE_SUPPORTED */
  193353. /********* End of inlined file: pngwrite.c *********/
  193354. /********* Start of inlined file: pngwtran.c *********/
  193355. /* pngwtran.c - transforms the data in a row for PNG writers
  193356. *
  193357. * Last changed in libpng 1.2.9 April 14, 2006
  193358. * For conditions of distribution and use, see copyright notice in png.h
  193359. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  193360. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193361. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193362. */
  193363. #define PNG_INTERNAL
  193364. #ifdef PNG_WRITE_SUPPORTED
  193365. /* Transform the data according to the user's wishes. The order of
  193366. * transformations is significant.
  193367. */
  193368. void /* PRIVATE */
  193369. png_do_write_transformations(png_structp png_ptr)
  193370. {
  193371. png_debug(1, "in png_do_write_transformations\n");
  193372. if (png_ptr == NULL)
  193373. return;
  193374. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193375. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  193376. if(png_ptr->write_user_transform_fn != NULL)
  193377. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  193378. (png_ptr, /* png_ptr */
  193379. &(png_ptr->row_info), /* row_info: */
  193380. /* png_uint_32 width; width of row */
  193381. /* png_uint_32 rowbytes; number of bytes in row */
  193382. /* png_byte color_type; color type of pixels */
  193383. /* png_byte bit_depth; bit depth of samples */
  193384. /* png_byte channels; number of channels (1-4) */
  193385. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  193386. png_ptr->row_buf + 1); /* start of pixel data for row */
  193387. #endif
  193388. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  193389. if (png_ptr->transformations & PNG_FILLER)
  193390. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193391. png_ptr->flags);
  193392. #endif
  193393. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193394. if (png_ptr->transformations & PNG_PACKSWAP)
  193395. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193396. #endif
  193397. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193398. if (png_ptr->transformations & PNG_PACK)
  193399. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193400. (png_uint_32)png_ptr->bit_depth);
  193401. #endif
  193402. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  193403. if (png_ptr->transformations & PNG_SWAP_BYTES)
  193404. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193405. #endif
  193406. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193407. if (png_ptr->transformations & PNG_SHIFT)
  193408. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193409. &(png_ptr->shift));
  193410. #endif
  193411. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193412. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  193413. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193414. #endif
  193415. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193416. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  193417. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193418. #endif
  193419. #if defined(PNG_WRITE_BGR_SUPPORTED)
  193420. if (png_ptr->transformations & PNG_BGR)
  193421. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193422. #endif
  193423. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  193424. if (png_ptr->transformations & PNG_INVERT_MONO)
  193425. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193426. #endif
  193427. }
  193428. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193429. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  193430. * row_info bit depth should be 8 (one pixel per byte). The channels
  193431. * should be 1 (this only happens on grayscale and paletted images).
  193432. */
  193433. void /* PRIVATE */
  193434. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  193435. {
  193436. png_debug(1, "in png_do_pack\n");
  193437. if (row_info->bit_depth == 8 &&
  193438. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193439. row != NULL && row_info != NULL &&
  193440. #endif
  193441. row_info->channels == 1)
  193442. {
  193443. switch ((int)bit_depth)
  193444. {
  193445. case 1:
  193446. {
  193447. png_bytep sp, dp;
  193448. int mask, v;
  193449. png_uint_32 i;
  193450. png_uint_32 row_width = row_info->width;
  193451. sp = row;
  193452. dp = row;
  193453. mask = 0x80;
  193454. v = 0;
  193455. for (i = 0; i < row_width; i++)
  193456. {
  193457. if (*sp != 0)
  193458. v |= mask;
  193459. sp++;
  193460. if (mask > 1)
  193461. mask >>= 1;
  193462. else
  193463. {
  193464. mask = 0x80;
  193465. *dp = (png_byte)v;
  193466. dp++;
  193467. v = 0;
  193468. }
  193469. }
  193470. if (mask != 0x80)
  193471. *dp = (png_byte)v;
  193472. break;
  193473. }
  193474. case 2:
  193475. {
  193476. png_bytep sp, dp;
  193477. int shift, v;
  193478. png_uint_32 i;
  193479. png_uint_32 row_width = row_info->width;
  193480. sp = row;
  193481. dp = row;
  193482. shift = 6;
  193483. v = 0;
  193484. for (i = 0; i < row_width; i++)
  193485. {
  193486. png_byte value;
  193487. value = (png_byte)(*sp & 0x03);
  193488. v |= (value << shift);
  193489. if (shift == 0)
  193490. {
  193491. shift = 6;
  193492. *dp = (png_byte)v;
  193493. dp++;
  193494. v = 0;
  193495. }
  193496. else
  193497. shift -= 2;
  193498. sp++;
  193499. }
  193500. if (shift != 6)
  193501. *dp = (png_byte)v;
  193502. break;
  193503. }
  193504. case 4:
  193505. {
  193506. png_bytep sp, dp;
  193507. int shift, v;
  193508. png_uint_32 i;
  193509. png_uint_32 row_width = row_info->width;
  193510. sp = row;
  193511. dp = row;
  193512. shift = 4;
  193513. v = 0;
  193514. for (i = 0; i < row_width; i++)
  193515. {
  193516. png_byte value;
  193517. value = (png_byte)(*sp & 0x0f);
  193518. v |= (value << shift);
  193519. if (shift == 0)
  193520. {
  193521. shift = 4;
  193522. *dp = (png_byte)v;
  193523. dp++;
  193524. v = 0;
  193525. }
  193526. else
  193527. shift -= 4;
  193528. sp++;
  193529. }
  193530. if (shift != 4)
  193531. *dp = (png_byte)v;
  193532. break;
  193533. }
  193534. }
  193535. row_info->bit_depth = (png_byte)bit_depth;
  193536. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  193537. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193538. row_info->width);
  193539. }
  193540. }
  193541. #endif
  193542. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193543. /* Shift pixel values to take advantage of whole range. Pass the
  193544. * true number of bits in bit_depth. The row should be packed
  193545. * according to row_info->bit_depth. Thus, if you had a row of
  193546. * bit depth 4, but the pixels only had values from 0 to 7, you
  193547. * would pass 3 as bit_depth, and this routine would translate the
  193548. * data to 0 to 15.
  193549. */
  193550. void /* PRIVATE */
  193551. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  193552. {
  193553. png_debug(1, "in png_do_shift\n");
  193554. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193555. if (row != NULL && row_info != NULL &&
  193556. #else
  193557. if (
  193558. #endif
  193559. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  193560. {
  193561. int shift_start[4], shift_dec[4];
  193562. int channels = 0;
  193563. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  193564. {
  193565. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  193566. shift_dec[channels] = bit_depth->red;
  193567. channels++;
  193568. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  193569. shift_dec[channels] = bit_depth->green;
  193570. channels++;
  193571. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  193572. shift_dec[channels] = bit_depth->blue;
  193573. channels++;
  193574. }
  193575. else
  193576. {
  193577. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  193578. shift_dec[channels] = bit_depth->gray;
  193579. channels++;
  193580. }
  193581. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193582. {
  193583. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  193584. shift_dec[channels] = bit_depth->alpha;
  193585. channels++;
  193586. }
  193587. /* with low row depths, could only be grayscale, so one channel */
  193588. if (row_info->bit_depth < 8)
  193589. {
  193590. png_bytep bp = row;
  193591. png_uint_32 i;
  193592. png_byte mask;
  193593. png_uint_32 row_bytes = row_info->rowbytes;
  193594. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  193595. mask = 0x55;
  193596. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  193597. mask = 0x11;
  193598. else
  193599. mask = 0xff;
  193600. for (i = 0; i < row_bytes; i++, bp++)
  193601. {
  193602. png_uint_16 v;
  193603. int j;
  193604. v = *bp;
  193605. *bp = 0;
  193606. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  193607. {
  193608. if (j > 0)
  193609. *bp |= (png_byte)((v << j) & 0xff);
  193610. else
  193611. *bp |= (png_byte)((v >> (-j)) & mask);
  193612. }
  193613. }
  193614. }
  193615. else if (row_info->bit_depth == 8)
  193616. {
  193617. png_bytep bp = row;
  193618. png_uint_32 i;
  193619. png_uint_32 istop = channels * row_info->width;
  193620. for (i = 0; i < istop; i++, bp++)
  193621. {
  193622. png_uint_16 v;
  193623. int j;
  193624. int c = (int)(i%channels);
  193625. v = *bp;
  193626. *bp = 0;
  193627. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  193628. {
  193629. if (j > 0)
  193630. *bp |= (png_byte)((v << j) & 0xff);
  193631. else
  193632. *bp |= (png_byte)((v >> (-j)) & 0xff);
  193633. }
  193634. }
  193635. }
  193636. else
  193637. {
  193638. png_bytep bp;
  193639. png_uint_32 i;
  193640. png_uint_32 istop = channels * row_info->width;
  193641. for (bp = row, i = 0; i < istop; i++)
  193642. {
  193643. int c = (int)(i%channels);
  193644. png_uint_16 value, v;
  193645. int j;
  193646. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  193647. value = 0;
  193648. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  193649. {
  193650. if (j > 0)
  193651. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  193652. else
  193653. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  193654. }
  193655. *bp++ = (png_byte)(value >> 8);
  193656. *bp++ = (png_byte)(value & 0xff);
  193657. }
  193658. }
  193659. }
  193660. }
  193661. #endif
  193662. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193663. void /* PRIVATE */
  193664. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  193665. {
  193666. png_debug(1, "in png_do_write_swap_alpha\n");
  193667. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193668. if (row != NULL && row_info != NULL)
  193669. #endif
  193670. {
  193671. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193672. {
  193673. /* This converts from ARGB to RGBA */
  193674. if (row_info->bit_depth == 8)
  193675. {
  193676. png_bytep sp, dp;
  193677. png_uint_32 i;
  193678. png_uint_32 row_width = row_info->width;
  193679. for (i = 0, sp = dp = row; i < row_width; i++)
  193680. {
  193681. png_byte save = *(sp++);
  193682. *(dp++) = *(sp++);
  193683. *(dp++) = *(sp++);
  193684. *(dp++) = *(sp++);
  193685. *(dp++) = save;
  193686. }
  193687. }
  193688. /* This converts from AARRGGBB to RRGGBBAA */
  193689. else
  193690. {
  193691. png_bytep sp, dp;
  193692. png_uint_32 i;
  193693. png_uint_32 row_width = row_info->width;
  193694. for (i = 0, sp = dp = row; i < row_width; i++)
  193695. {
  193696. png_byte save[2];
  193697. save[0] = *(sp++);
  193698. save[1] = *(sp++);
  193699. *(dp++) = *(sp++);
  193700. *(dp++) = *(sp++);
  193701. *(dp++) = *(sp++);
  193702. *(dp++) = *(sp++);
  193703. *(dp++) = *(sp++);
  193704. *(dp++) = *(sp++);
  193705. *(dp++) = save[0];
  193706. *(dp++) = save[1];
  193707. }
  193708. }
  193709. }
  193710. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193711. {
  193712. /* This converts from AG to GA */
  193713. if (row_info->bit_depth == 8)
  193714. {
  193715. png_bytep sp, dp;
  193716. png_uint_32 i;
  193717. png_uint_32 row_width = row_info->width;
  193718. for (i = 0, sp = dp = row; i < row_width; i++)
  193719. {
  193720. png_byte save = *(sp++);
  193721. *(dp++) = *(sp++);
  193722. *(dp++) = save;
  193723. }
  193724. }
  193725. /* This converts from AAGG to GGAA */
  193726. else
  193727. {
  193728. png_bytep sp, dp;
  193729. png_uint_32 i;
  193730. png_uint_32 row_width = row_info->width;
  193731. for (i = 0, sp = dp = row; i < row_width; i++)
  193732. {
  193733. png_byte save[2];
  193734. save[0] = *(sp++);
  193735. save[1] = *(sp++);
  193736. *(dp++) = *(sp++);
  193737. *(dp++) = *(sp++);
  193738. *(dp++) = save[0];
  193739. *(dp++) = save[1];
  193740. }
  193741. }
  193742. }
  193743. }
  193744. }
  193745. #endif
  193746. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193747. void /* PRIVATE */
  193748. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  193749. {
  193750. png_debug(1, "in png_do_write_invert_alpha\n");
  193751. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193752. if (row != NULL && row_info != NULL)
  193753. #endif
  193754. {
  193755. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193756. {
  193757. /* This inverts the alpha channel in RGBA */
  193758. if (row_info->bit_depth == 8)
  193759. {
  193760. png_bytep sp, dp;
  193761. png_uint_32 i;
  193762. png_uint_32 row_width = row_info->width;
  193763. for (i = 0, sp = dp = row; i < row_width; i++)
  193764. {
  193765. /* does nothing
  193766. *(dp++) = *(sp++);
  193767. *(dp++) = *(sp++);
  193768. *(dp++) = *(sp++);
  193769. */
  193770. sp+=3; dp = sp;
  193771. *(dp++) = (png_byte)(255 - *(sp++));
  193772. }
  193773. }
  193774. /* This inverts the alpha channel in RRGGBBAA */
  193775. else
  193776. {
  193777. png_bytep sp, dp;
  193778. png_uint_32 i;
  193779. png_uint_32 row_width = row_info->width;
  193780. for (i = 0, sp = dp = row; i < row_width; i++)
  193781. {
  193782. /* does nothing
  193783. *(dp++) = *(sp++);
  193784. *(dp++) = *(sp++);
  193785. *(dp++) = *(sp++);
  193786. *(dp++) = *(sp++);
  193787. *(dp++) = *(sp++);
  193788. *(dp++) = *(sp++);
  193789. */
  193790. sp+=6; dp = sp;
  193791. *(dp++) = (png_byte)(255 - *(sp++));
  193792. *(dp++) = (png_byte)(255 - *(sp++));
  193793. }
  193794. }
  193795. }
  193796. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193797. {
  193798. /* This inverts the alpha channel in GA */
  193799. if (row_info->bit_depth == 8)
  193800. {
  193801. png_bytep sp, dp;
  193802. png_uint_32 i;
  193803. png_uint_32 row_width = row_info->width;
  193804. for (i = 0, sp = dp = row; i < row_width; i++)
  193805. {
  193806. *(dp++) = *(sp++);
  193807. *(dp++) = (png_byte)(255 - *(sp++));
  193808. }
  193809. }
  193810. /* This inverts the alpha channel in GGAA */
  193811. else
  193812. {
  193813. png_bytep sp, dp;
  193814. png_uint_32 i;
  193815. png_uint_32 row_width = row_info->width;
  193816. for (i = 0, sp = dp = row; i < row_width; i++)
  193817. {
  193818. /* does nothing
  193819. *(dp++) = *(sp++);
  193820. *(dp++) = *(sp++);
  193821. */
  193822. sp+=2; dp = sp;
  193823. *(dp++) = (png_byte)(255 - *(sp++));
  193824. *(dp++) = (png_byte)(255 - *(sp++));
  193825. }
  193826. }
  193827. }
  193828. }
  193829. }
  193830. #endif
  193831. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193832. /* undoes intrapixel differencing */
  193833. void /* PRIVATE */
  193834. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  193835. {
  193836. png_debug(1, "in png_do_write_intrapixel\n");
  193837. if (
  193838. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193839. row != NULL && row_info != NULL &&
  193840. #endif
  193841. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193842. {
  193843. int bytes_per_pixel;
  193844. png_uint_32 row_width = row_info->width;
  193845. if (row_info->bit_depth == 8)
  193846. {
  193847. png_bytep rp;
  193848. png_uint_32 i;
  193849. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193850. bytes_per_pixel = 3;
  193851. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193852. bytes_per_pixel = 4;
  193853. else
  193854. return;
  193855. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193856. {
  193857. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  193858. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  193859. }
  193860. }
  193861. else if (row_info->bit_depth == 16)
  193862. {
  193863. png_bytep rp;
  193864. png_uint_32 i;
  193865. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193866. bytes_per_pixel = 6;
  193867. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193868. bytes_per_pixel = 8;
  193869. else
  193870. return;
  193871. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193872. {
  193873. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193874. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193875. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193876. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  193877. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  193878. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193879. *(rp+1) = (png_byte)(red & 0xff);
  193880. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193881. *(rp+5) = (png_byte)(blue & 0xff);
  193882. }
  193883. }
  193884. }
  193885. }
  193886. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193887. #endif /* PNG_WRITE_SUPPORTED */
  193888. /********* End of inlined file: pngwtran.c *********/
  193889. /********* Start of inlined file: pngwutil.c *********/
  193890. /* pngwutil.c - utilities to write a PNG file
  193891. *
  193892. * Last changed in libpng 1.2.20 Septhember 3, 2007
  193893. * For conditions of distribution and use, see copyright notice in png.h
  193894. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193895. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193896. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193897. */
  193898. #define PNG_INTERNAL
  193899. #ifdef PNG_WRITE_SUPPORTED
  193900. /* Place a 32-bit number into a buffer in PNG byte order. We work
  193901. * with unsigned numbers for convenience, although one supported
  193902. * ancillary chunk uses signed (two's complement) numbers.
  193903. */
  193904. void PNGAPI
  193905. png_save_uint_32(png_bytep buf, png_uint_32 i)
  193906. {
  193907. buf[0] = (png_byte)((i >> 24) & 0xff);
  193908. buf[1] = (png_byte)((i >> 16) & 0xff);
  193909. buf[2] = (png_byte)((i >> 8) & 0xff);
  193910. buf[3] = (png_byte)(i & 0xff);
  193911. }
  193912. /* The png_save_int_32 function assumes integers are stored in two's
  193913. * complement format. If this isn't the case, then this routine needs to
  193914. * be modified to write data in two's complement format.
  193915. */
  193916. void PNGAPI
  193917. png_save_int_32(png_bytep buf, png_int_32 i)
  193918. {
  193919. buf[0] = (png_byte)((i >> 24) & 0xff);
  193920. buf[1] = (png_byte)((i >> 16) & 0xff);
  193921. buf[2] = (png_byte)((i >> 8) & 0xff);
  193922. buf[3] = (png_byte)(i & 0xff);
  193923. }
  193924. /* Place a 16-bit number into a buffer in PNG byte order.
  193925. * The parameter is declared unsigned int, not png_uint_16,
  193926. * just to avoid potential problems on pre-ANSI C compilers.
  193927. */
  193928. void PNGAPI
  193929. png_save_uint_16(png_bytep buf, unsigned int i)
  193930. {
  193931. buf[0] = (png_byte)((i >> 8) & 0xff);
  193932. buf[1] = (png_byte)(i & 0xff);
  193933. }
  193934. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  193935. * representing the chunk name. The array must be at least 4 bytes in
  193936. * length, and does not need to be null terminated. To be safe, pass the
  193937. * pre-defined chunk names here, and if you need a new one, define it
  193938. * where the others are defined. The length is the length of the data.
  193939. * All the data must be present. If that is not possible, use the
  193940. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  193941. * functions instead.
  193942. */
  193943. void PNGAPI
  193944. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  193945. png_bytep data, png_size_t length)
  193946. {
  193947. if(png_ptr == NULL) return;
  193948. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  193949. png_write_chunk_data(png_ptr, data, length);
  193950. png_write_chunk_end(png_ptr);
  193951. }
  193952. /* Write the start of a PNG chunk. The type is the chunk type.
  193953. * The total_length is the sum of the lengths of all the data you will be
  193954. * passing in png_write_chunk_data().
  193955. */
  193956. void PNGAPI
  193957. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  193958. png_uint_32 length)
  193959. {
  193960. png_byte buf[4];
  193961. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  193962. if(png_ptr == NULL) return;
  193963. /* write the length */
  193964. png_save_uint_32(buf, length);
  193965. png_write_data(png_ptr, buf, (png_size_t)4);
  193966. /* write the chunk name */
  193967. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  193968. /* reset the crc and run it over the chunk name */
  193969. png_reset_crc(png_ptr);
  193970. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  193971. }
  193972. /* Write the data of a PNG chunk started with png_write_chunk_start().
  193973. * Note that multiple calls to this function are allowed, and that the
  193974. * sum of the lengths from these calls *must* add up to the total_length
  193975. * given to png_write_chunk_start().
  193976. */
  193977. void PNGAPI
  193978. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193979. {
  193980. /* write the data, and run the CRC over it */
  193981. if(png_ptr == NULL) return;
  193982. if (data != NULL && length > 0)
  193983. {
  193984. png_calculate_crc(png_ptr, data, length);
  193985. png_write_data(png_ptr, data, length);
  193986. }
  193987. }
  193988. /* Finish a chunk started with png_write_chunk_start(). */
  193989. void PNGAPI
  193990. png_write_chunk_end(png_structp png_ptr)
  193991. {
  193992. png_byte buf[4];
  193993. if(png_ptr == NULL) return;
  193994. /* write the crc */
  193995. png_save_uint_32(buf, png_ptr->crc);
  193996. png_write_data(png_ptr, buf, (png_size_t)4);
  193997. }
  193998. /* Simple function to write the signature. If we have already written
  193999. * the magic bytes of the signature, or more likely, the PNG stream is
  194000. * being embedded into another stream and doesn't need its own signature,
  194001. * we should call png_set_sig_bytes() to tell libpng how many of the
  194002. * bytes have already been written.
  194003. */
  194004. void /* PRIVATE */
  194005. png_write_sig(png_structp png_ptr)
  194006. {
  194007. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  194008. /* write the rest of the 8 byte signature */
  194009. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  194010. (png_size_t)8 - png_ptr->sig_bytes);
  194011. if(png_ptr->sig_bytes < 3)
  194012. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  194013. }
  194014. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  194015. /*
  194016. * This pair of functions encapsulates the operation of (a) compressing a
  194017. * text string, and (b) issuing it later as a series of chunk data writes.
  194018. * The compression_state structure is shared context for these functions
  194019. * set up by the caller in order to make the whole mess thread-safe.
  194020. */
  194021. typedef struct
  194022. {
  194023. char *input; /* the uncompressed input data */
  194024. int input_len; /* its length */
  194025. int num_output_ptr; /* number of output pointers used */
  194026. int max_output_ptr; /* size of output_ptr */
  194027. png_charpp output_ptr; /* array of pointers to output */
  194028. } compression_state;
  194029. /* compress given text into storage in the png_ptr structure */
  194030. static int /* PRIVATE */
  194031. png_text_compress(png_structp png_ptr,
  194032. png_charp text, png_size_t text_len, int compression,
  194033. compression_state *comp)
  194034. {
  194035. int ret;
  194036. comp->num_output_ptr = 0;
  194037. comp->max_output_ptr = 0;
  194038. comp->output_ptr = NULL;
  194039. comp->input = NULL;
  194040. comp->input_len = 0;
  194041. /* we may just want to pass the text right through */
  194042. if (compression == PNG_TEXT_COMPRESSION_NONE)
  194043. {
  194044. comp->input = text;
  194045. comp->input_len = text_len;
  194046. return((int)text_len);
  194047. }
  194048. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  194049. {
  194050. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194051. char msg[50];
  194052. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  194053. png_warning(png_ptr, msg);
  194054. #else
  194055. png_warning(png_ptr, "Unknown compression type");
  194056. #endif
  194057. }
  194058. /* We can't write the chunk until we find out how much data we have,
  194059. * which means we need to run the compressor first and save the
  194060. * output. This shouldn't be a problem, as the vast majority of
  194061. * comments should be reasonable, but we will set up an array of
  194062. * malloc'd pointers to be sure.
  194063. *
  194064. * If we knew the application was well behaved, we could simplify this
  194065. * greatly by assuming we can always malloc an output buffer large
  194066. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  194067. * and malloc this directly. The only time this would be a bad idea is
  194068. * if we can't malloc more than 64K and we have 64K of random input
  194069. * data, or if the input string is incredibly large (although this
  194070. * wouldn't cause a failure, just a slowdown due to swapping).
  194071. */
  194072. /* set up the compression buffers */
  194073. png_ptr->zstream.avail_in = (uInt)text_len;
  194074. png_ptr->zstream.next_in = (Bytef *)text;
  194075. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194076. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  194077. /* this is the same compression loop as in png_write_row() */
  194078. do
  194079. {
  194080. /* compress the data */
  194081. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  194082. if (ret != Z_OK)
  194083. {
  194084. /* error */
  194085. if (png_ptr->zstream.msg != NULL)
  194086. png_error(png_ptr, png_ptr->zstream.msg);
  194087. else
  194088. png_error(png_ptr, "zlib error");
  194089. }
  194090. /* check to see if we need more room */
  194091. if (!(png_ptr->zstream.avail_out))
  194092. {
  194093. /* make sure the output array has room */
  194094. if (comp->num_output_ptr >= comp->max_output_ptr)
  194095. {
  194096. int old_max;
  194097. old_max = comp->max_output_ptr;
  194098. comp->max_output_ptr = comp->num_output_ptr + 4;
  194099. if (comp->output_ptr != NULL)
  194100. {
  194101. png_charpp old_ptr;
  194102. old_ptr = comp->output_ptr;
  194103. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194104. (png_uint_32)(comp->max_output_ptr *
  194105. png_sizeof (png_charpp)));
  194106. png_memcpy(comp->output_ptr, old_ptr, old_max
  194107. * png_sizeof (png_charp));
  194108. png_free(png_ptr, old_ptr);
  194109. }
  194110. else
  194111. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194112. (png_uint_32)(comp->max_output_ptr *
  194113. png_sizeof (png_charp)));
  194114. }
  194115. /* save the data */
  194116. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  194117. (png_uint_32)png_ptr->zbuf_size);
  194118. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194119. png_ptr->zbuf_size);
  194120. comp->num_output_ptr++;
  194121. /* and reset the buffer */
  194122. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194123. png_ptr->zstream.next_out = png_ptr->zbuf;
  194124. }
  194125. /* continue until we don't have any more to compress */
  194126. } while (png_ptr->zstream.avail_in);
  194127. /* finish the compression */
  194128. do
  194129. {
  194130. /* tell zlib we are finished */
  194131. ret = deflate(&png_ptr->zstream, Z_FINISH);
  194132. if (ret == Z_OK)
  194133. {
  194134. /* check to see if we need more room */
  194135. if (!(png_ptr->zstream.avail_out))
  194136. {
  194137. /* check to make sure our output array has room */
  194138. if (comp->num_output_ptr >= comp->max_output_ptr)
  194139. {
  194140. int old_max;
  194141. old_max = comp->max_output_ptr;
  194142. comp->max_output_ptr = comp->num_output_ptr + 4;
  194143. if (comp->output_ptr != NULL)
  194144. {
  194145. png_charpp old_ptr;
  194146. old_ptr = comp->output_ptr;
  194147. /* This could be optimized to realloc() */
  194148. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194149. (png_uint_32)(comp->max_output_ptr *
  194150. png_sizeof (png_charpp)));
  194151. png_memcpy(comp->output_ptr, old_ptr,
  194152. old_max * png_sizeof (png_charp));
  194153. png_free(png_ptr, old_ptr);
  194154. }
  194155. else
  194156. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194157. (png_uint_32)(comp->max_output_ptr *
  194158. png_sizeof (png_charp)));
  194159. }
  194160. /* save off the data */
  194161. comp->output_ptr[comp->num_output_ptr] =
  194162. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  194163. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194164. png_ptr->zbuf_size);
  194165. comp->num_output_ptr++;
  194166. /* and reset the buffer pointers */
  194167. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194168. png_ptr->zstream.next_out = png_ptr->zbuf;
  194169. }
  194170. }
  194171. else if (ret != Z_STREAM_END)
  194172. {
  194173. /* we got an error */
  194174. if (png_ptr->zstream.msg != NULL)
  194175. png_error(png_ptr, png_ptr->zstream.msg);
  194176. else
  194177. png_error(png_ptr, "zlib error");
  194178. }
  194179. } while (ret != Z_STREAM_END);
  194180. /* text length is number of buffers plus last buffer */
  194181. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  194182. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  194183. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  194184. return((int)text_len);
  194185. }
  194186. /* ship the compressed text out via chunk writes */
  194187. static void /* PRIVATE */
  194188. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  194189. {
  194190. int i;
  194191. /* handle the no-compression case */
  194192. if (comp->input)
  194193. {
  194194. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  194195. (png_size_t)comp->input_len);
  194196. return;
  194197. }
  194198. /* write saved output buffers, if any */
  194199. for (i = 0; i < comp->num_output_ptr; i++)
  194200. {
  194201. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  194202. png_ptr->zbuf_size);
  194203. png_free(png_ptr, comp->output_ptr[i]);
  194204. comp->output_ptr[i]=NULL;
  194205. }
  194206. if (comp->max_output_ptr != 0)
  194207. png_free(png_ptr, comp->output_ptr);
  194208. comp->output_ptr=NULL;
  194209. /* write anything left in zbuf */
  194210. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  194211. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  194212. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194213. /* reset zlib for another zTXt/iTXt or image data */
  194214. deflateReset(&png_ptr->zstream);
  194215. png_ptr->zstream.data_type = Z_BINARY;
  194216. }
  194217. #endif
  194218. /* Write the IHDR chunk, and update the png_struct with the necessary
  194219. * information. Note that the rest of this code depends upon this
  194220. * information being correct.
  194221. */
  194222. void /* PRIVATE */
  194223. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  194224. int bit_depth, int color_type, int compression_type, int filter_type,
  194225. int interlace_type)
  194226. {
  194227. #ifdef PNG_USE_LOCAL_ARRAYS
  194228. PNG_IHDR;
  194229. #endif
  194230. png_byte buf[13]; /* buffer to store the IHDR info */
  194231. png_debug(1, "in png_write_IHDR\n");
  194232. /* Check that we have valid input data from the application info */
  194233. switch (color_type)
  194234. {
  194235. case PNG_COLOR_TYPE_GRAY:
  194236. switch (bit_depth)
  194237. {
  194238. case 1:
  194239. case 2:
  194240. case 4:
  194241. case 8:
  194242. case 16: png_ptr->channels = 1; break;
  194243. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  194244. }
  194245. break;
  194246. case PNG_COLOR_TYPE_RGB:
  194247. if (bit_depth != 8 && bit_depth != 16)
  194248. png_error(png_ptr, "Invalid bit depth for RGB image");
  194249. png_ptr->channels = 3;
  194250. break;
  194251. case PNG_COLOR_TYPE_PALETTE:
  194252. switch (bit_depth)
  194253. {
  194254. case 1:
  194255. case 2:
  194256. case 4:
  194257. case 8: png_ptr->channels = 1; break;
  194258. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  194259. }
  194260. break;
  194261. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194262. if (bit_depth != 8 && bit_depth != 16)
  194263. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  194264. png_ptr->channels = 2;
  194265. break;
  194266. case PNG_COLOR_TYPE_RGB_ALPHA:
  194267. if (bit_depth != 8 && bit_depth != 16)
  194268. png_error(png_ptr, "Invalid bit depth for RGBA image");
  194269. png_ptr->channels = 4;
  194270. break;
  194271. default:
  194272. png_error(png_ptr, "Invalid image color type specified");
  194273. }
  194274. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194275. {
  194276. png_warning(png_ptr, "Invalid compression type specified");
  194277. compression_type = PNG_COMPRESSION_TYPE_BASE;
  194278. }
  194279. /* Write filter_method 64 (intrapixel differencing) only if
  194280. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194281. * 2. Libpng did not write a PNG signature (this filter_method is only
  194282. * used in PNG datastreams that are embedded in MNG datastreams) and
  194283. * 3. The application called png_permit_mng_features with a mask that
  194284. * included PNG_FLAG_MNG_FILTER_64 and
  194285. * 4. The filter_method is 64 and
  194286. * 5. The color_type is RGB or RGBA
  194287. */
  194288. if (
  194289. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194290. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194291. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  194292. (color_type == PNG_COLOR_TYPE_RGB ||
  194293. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  194294. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  194295. #endif
  194296. filter_type != PNG_FILTER_TYPE_BASE)
  194297. {
  194298. png_warning(png_ptr, "Invalid filter type specified");
  194299. filter_type = PNG_FILTER_TYPE_BASE;
  194300. }
  194301. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  194302. if (interlace_type != PNG_INTERLACE_NONE &&
  194303. interlace_type != PNG_INTERLACE_ADAM7)
  194304. {
  194305. png_warning(png_ptr, "Invalid interlace type specified");
  194306. interlace_type = PNG_INTERLACE_ADAM7;
  194307. }
  194308. #else
  194309. interlace_type=PNG_INTERLACE_NONE;
  194310. #endif
  194311. /* save off the relevent information */
  194312. png_ptr->bit_depth = (png_byte)bit_depth;
  194313. png_ptr->color_type = (png_byte)color_type;
  194314. png_ptr->interlaced = (png_byte)interlace_type;
  194315. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194316. png_ptr->filter_type = (png_byte)filter_type;
  194317. #endif
  194318. png_ptr->compression_type = (png_byte)compression_type;
  194319. png_ptr->width = width;
  194320. png_ptr->height = height;
  194321. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  194322. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  194323. /* set the usr info, so any transformations can modify it */
  194324. png_ptr->usr_width = png_ptr->width;
  194325. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  194326. png_ptr->usr_channels = png_ptr->channels;
  194327. /* pack the header information into the buffer */
  194328. png_save_uint_32(buf, width);
  194329. png_save_uint_32(buf + 4, height);
  194330. buf[8] = (png_byte)bit_depth;
  194331. buf[9] = (png_byte)color_type;
  194332. buf[10] = (png_byte)compression_type;
  194333. buf[11] = (png_byte)filter_type;
  194334. buf[12] = (png_byte)interlace_type;
  194335. /* write the chunk */
  194336. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  194337. /* initialize zlib with PNG info */
  194338. png_ptr->zstream.zalloc = png_zalloc;
  194339. png_ptr->zstream.zfree = png_zfree;
  194340. png_ptr->zstream.opaque = (voidpf)png_ptr;
  194341. if (!(png_ptr->do_filter))
  194342. {
  194343. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  194344. png_ptr->bit_depth < 8)
  194345. png_ptr->do_filter = PNG_FILTER_NONE;
  194346. else
  194347. png_ptr->do_filter = PNG_ALL_FILTERS;
  194348. }
  194349. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  194350. {
  194351. if (png_ptr->do_filter != PNG_FILTER_NONE)
  194352. png_ptr->zlib_strategy = Z_FILTERED;
  194353. else
  194354. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  194355. }
  194356. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  194357. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  194358. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  194359. png_ptr->zlib_mem_level = 8;
  194360. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  194361. png_ptr->zlib_window_bits = 15;
  194362. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  194363. png_ptr->zlib_method = 8;
  194364. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  194365. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  194366. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  194367. png_error(png_ptr, "zlib failed to initialize compressor");
  194368. png_ptr->zstream.next_out = png_ptr->zbuf;
  194369. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194370. /* libpng is not interested in zstream.data_type */
  194371. /* set it to a predefined value, to avoid its evaluation inside zlib */
  194372. png_ptr->zstream.data_type = Z_BINARY;
  194373. png_ptr->mode = PNG_HAVE_IHDR;
  194374. }
  194375. /* write the palette. We are careful not to trust png_color to be in the
  194376. * correct order for PNG, so people can redefine it to any convenient
  194377. * structure.
  194378. */
  194379. void /* PRIVATE */
  194380. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  194381. {
  194382. #ifdef PNG_USE_LOCAL_ARRAYS
  194383. PNG_PLTE;
  194384. #endif
  194385. png_uint_32 i;
  194386. png_colorp pal_ptr;
  194387. png_byte buf[3];
  194388. png_debug(1, "in png_write_PLTE\n");
  194389. if ((
  194390. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194391. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  194392. #endif
  194393. num_pal == 0) || num_pal > 256)
  194394. {
  194395. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194396. {
  194397. png_error(png_ptr, "Invalid number of colors in palette");
  194398. }
  194399. else
  194400. {
  194401. png_warning(png_ptr, "Invalid number of colors in palette");
  194402. return;
  194403. }
  194404. }
  194405. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194406. {
  194407. png_warning(png_ptr,
  194408. "Ignoring request to write a PLTE chunk in grayscale PNG");
  194409. return;
  194410. }
  194411. png_ptr->num_palette = (png_uint_16)num_pal;
  194412. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  194413. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  194414. #ifndef PNG_NO_POINTER_INDEXING
  194415. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  194416. {
  194417. buf[0] = pal_ptr->red;
  194418. buf[1] = pal_ptr->green;
  194419. buf[2] = pal_ptr->blue;
  194420. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  194421. }
  194422. #else
  194423. /* This is a little slower but some buggy compilers need to do this instead */
  194424. pal_ptr=palette;
  194425. for (i = 0; i < num_pal; i++)
  194426. {
  194427. buf[0] = pal_ptr[i].red;
  194428. buf[1] = pal_ptr[i].green;
  194429. buf[2] = pal_ptr[i].blue;
  194430. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  194431. }
  194432. #endif
  194433. png_write_chunk_end(png_ptr);
  194434. png_ptr->mode |= PNG_HAVE_PLTE;
  194435. }
  194436. /* write an IDAT chunk */
  194437. void /* PRIVATE */
  194438. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  194439. {
  194440. #ifdef PNG_USE_LOCAL_ARRAYS
  194441. PNG_IDAT;
  194442. #endif
  194443. png_debug(1, "in png_write_IDAT\n");
  194444. /* Optimize the CMF field in the zlib stream. */
  194445. /* This hack of the zlib stream is compliant to the stream specification. */
  194446. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  194447. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  194448. {
  194449. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  194450. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  194451. {
  194452. /* Avoid memory underflows and multiplication overflows. */
  194453. /* The conditions below are practically always satisfied;
  194454. however, they still must be checked. */
  194455. if (length >= 2 &&
  194456. png_ptr->height < 16384 && png_ptr->width < 16384)
  194457. {
  194458. png_uint_32 uncompressed_idat_size = png_ptr->height *
  194459. ((png_ptr->width *
  194460. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  194461. unsigned int z_cinfo = z_cmf >> 4;
  194462. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  194463. while (uncompressed_idat_size <= half_z_window_size &&
  194464. half_z_window_size >= 256)
  194465. {
  194466. z_cinfo--;
  194467. half_z_window_size >>= 1;
  194468. }
  194469. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  194470. if (data[0] != (png_byte)z_cmf)
  194471. {
  194472. data[0] = (png_byte)z_cmf;
  194473. data[1] &= 0xe0;
  194474. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  194475. }
  194476. }
  194477. }
  194478. else
  194479. png_error(png_ptr,
  194480. "Invalid zlib compression method or flags in IDAT");
  194481. }
  194482. png_write_chunk(png_ptr, png_IDAT, data, length);
  194483. png_ptr->mode |= PNG_HAVE_IDAT;
  194484. }
  194485. /* write an IEND chunk */
  194486. void /* PRIVATE */
  194487. png_write_IEND(png_structp png_ptr)
  194488. {
  194489. #ifdef PNG_USE_LOCAL_ARRAYS
  194490. PNG_IEND;
  194491. #endif
  194492. png_debug(1, "in png_write_IEND\n");
  194493. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  194494. (png_size_t)0);
  194495. png_ptr->mode |= PNG_HAVE_IEND;
  194496. }
  194497. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194498. /* write a gAMA chunk */
  194499. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194500. void /* PRIVATE */
  194501. png_write_gAMA(png_structp png_ptr, double file_gamma)
  194502. {
  194503. #ifdef PNG_USE_LOCAL_ARRAYS
  194504. PNG_gAMA;
  194505. #endif
  194506. png_uint_32 igamma;
  194507. png_byte buf[4];
  194508. png_debug(1, "in png_write_gAMA\n");
  194509. /* file_gamma is saved in 1/100,000ths */
  194510. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  194511. png_save_uint_32(buf, igamma);
  194512. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  194513. }
  194514. #endif
  194515. #ifdef PNG_FIXED_POINT_SUPPORTED
  194516. void /* PRIVATE */
  194517. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  194518. {
  194519. #ifdef PNG_USE_LOCAL_ARRAYS
  194520. PNG_gAMA;
  194521. #endif
  194522. png_byte buf[4];
  194523. png_debug(1, "in png_write_gAMA\n");
  194524. /* file_gamma is saved in 1/100,000ths */
  194525. png_save_uint_32(buf, (png_uint_32)file_gamma);
  194526. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  194527. }
  194528. #endif
  194529. #endif
  194530. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194531. /* write a sRGB chunk */
  194532. void /* PRIVATE */
  194533. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  194534. {
  194535. #ifdef PNG_USE_LOCAL_ARRAYS
  194536. PNG_sRGB;
  194537. #endif
  194538. png_byte buf[1];
  194539. png_debug(1, "in png_write_sRGB\n");
  194540. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  194541. png_warning(png_ptr,
  194542. "Invalid sRGB rendering intent specified");
  194543. buf[0]=(png_byte)srgb_intent;
  194544. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  194545. }
  194546. #endif
  194547. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194548. /* write an iCCP chunk */
  194549. void /* PRIVATE */
  194550. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  194551. png_charp profile, int profile_len)
  194552. {
  194553. #ifdef PNG_USE_LOCAL_ARRAYS
  194554. PNG_iCCP;
  194555. #endif
  194556. png_size_t name_len;
  194557. png_charp new_name;
  194558. compression_state comp;
  194559. int embedded_profile_len = 0;
  194560. png_debug(1, "in png_write_iCCP\n");
  194561. comp.num_output_ptr = 0;
  194562. comp.max_output_ptr = 0;
  194563. comp.output_ptr = NULL;
  194564. comp.input = NULL;
  194565. comp.input_len = 0;
  194566. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  194567. &new_name)) == 0)
  194568. {
  194569. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  194570. return;
  194571. }
  194572. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194573. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  194574. if (profile == NULL)
  194575. profile_len = 0;
  194576. if (profile_len > 3)
  194577. embedded_profile_len =
  194578. ((*( (png_bytep)profile ))<<24) |
  194579. ((*( (png_bytep)profile+1))<<16) |
  194580. ((*( (png_bytep)profile+2))<< 8) |
  194581. ((*( (png_bytep)profile+3)) );
  194582. if (profile_len < embedded_profile_len)
  194583. {
  194584. png_warning(png_ptr,
  194585. "Embedded profile length too large in iCCP chunk");
  194586. return;
  194587. }
  194588. if (profile_len > embedded_profile_len)
  194589. {
  194590. png_warning(png_ptr,
  194591. "Truncating profile to actual length in iCCP chunk");
  194592. profile_len = embedded_profile_len;
  194593. }
  194594. if (profile_len)
  194595. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  194596. PNG_COMPRESSION_TYPE_BASE, &comp);
  194597. /* make sure we include the NULL after the name and the compression type */
  194598. png_write_chunk_start(png_ptr, png_iCCP,
  194599. (png_uint_32)name_len+profile_len+2);
  194600. new_name[name_len+1]=0x00;
  194601. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  194602. if (profile_len)
  194603. png_write_compressed_data_out(png_ptr, &comp);
  194604. png_write_chunk_end(png_ptr);
  194605. png_free(png_ptr, new_name);
  194606. }
  194607. #endif
  194608. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194609. /* write a sPLT chunk */
  194610. void /* PRIVATE */
  194611. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  194612. {
  194613. #ifdef PNG_USE_LOCAL_ARRAYS
  194614. PNG_sPLT;
  194615. #endif
  194616. png_size_t name_len;
  194617. png_charp new_name;
  194618. png_byte entrybuf[10];
  194619. int entry_size = (spalette->depth == 8 ? 6 : 10);
  194620. int palette_size = entry_size * spalette->nentries;
  194621. png_sPLT_entryp ep;
  194622. #ifdef PNG_NO_POINTER_INDEXING
  194623. int i;
  194624. #endif
  194625. png_debug(1, "in png_write_sPLT\n");
  194626. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  194627. spalette->name, &new_name))==0)
  194628. {
  194629. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  194630. return;
  194631. }
  194632. /* make sure we include the NULL after the name */
  194633. png_write_chunk_start(png_ptr, png_sPLT,
  194634. (png_uint_32)(name_len + 2 + palette_size));
  194635. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  194636. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  194637. /* loop through each palette entry, writing appropriately */
  194638. #ifndef PNG_NO_POINTER_INDEXING
  194639. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  194640. {
  194641. if (spalette->depth == 8)
  194642. {
  194643. entrybuf[0] = (png_byte)ep->red;
  194644. entrybuf[1] = (png_byte)ep->green;
  194645. entrybuf[2] = (png_byte)ep->blue;
  194646. entrybuf[3] = (png_byte)ep->alpha;
  194647. png_save_uint_16(entrybuf + 4, ep->frequency);
  194648. }
  194649. else
  194650. {
  194651. png_save_uint_16(entrybuf + 0, ep->red);
  194652. png_save_uint_16(entrybuf + 2, ep->green);
  194653. png_save_uint_16(entrybuf + 4, ep->blue);
  194654. png_save_uint_16(entrybuf + 6, ep->alpha);
  194655. png_save_uint_16(entrybuf + 8, ep->frequency);
  194656. }
  194657. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  194658. }
  194659. #else
  194660. ep=spalette->entries;
  194661. for (i=0; i>spalette->nentries; i++)
  194662. {
  194663. if (spalette->depth == 8)
  194664. {
  194665. entrybuf[0] = (png_byte)ep[i].red;
  194666. entrybuf[1] = (png_byte)ep[i].green;
  194667. entrybuf[2] = (png_byte)ep[i].blue;
  194668. entrybuf[3] = (png_byte)ep[i].alpha;
  194669. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  194670. }
  194671. else
  194672. {
  194673. png_save_uint_16(entrybuf + 0, ep[i].red);
  194674. png_save_uint_16(entrybuf + 2, ep[i].green);
  194675. png_save_uint_16(entrybuf + 4, ep[i].blue);
  194676. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  194677. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  194678. }
  194679. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  194680. }
  194681. #endif
  194682. png_write_chunk_end(png_ptr);
  194683. png_free(png_ptr, new_name);
  194684. }
  194685. #endif
  194686. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194687. /* write the sBIT chunk */
  194688. void /* PRIVATE */
  194689. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  194690. {
  194691. #ifdef PNG_USE_LOCAL_ARRAYS
  194692. PNG_sBIT;
  194693. #endif
  194694. png_byte buf[4];
  194695. png_size_t size;
  194696. png_debug(1, "in png_write_sBIT\n");
  194697. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  194698. if (color_type & PNG_COLOR_MASK_COLOR)
  194699. {
  194700. png_byte maxbits;
  194701. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  194702. png_ptr->usr_bit_depth);
  194703. if (sbit->red == 0 || sbit->red > maxbits ||
  194704. sbit->green == 0 || sbit->green > maxbits ||
  194705. sbit->blue == 0 || sbit->blue > maxbits)
  194706. {
  194707. png_warning(png_ptr, "Invalid sBIT depth specified");
  194708. return;
  194709. }
  194710. buf[0] = sbit->red;
  194711. buf[1] = sbit->green;
  194712. buf[2] = sbit->blue;
  194713. size = 3;
  194714. }
  194715. else
  194716. {
  194717. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  194718. {
  194719. png_warning(png_ptr, "Invalid sBIT depth specified");
  194720. return;
  194721. }
  194722. buf[0] = sbit->gray;
  194723. size = 1;
  194724. }
  194725. if (color_type & PNG_COLOR_MASK_ALPHA)
  194726. {
  194727. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  194728. {
  194729. png_warning(png_ptr, "Invalid sBIT depth specified");
  194730. return;
  194731. }
  194732. buf[size++] = sbit->alpha;
  194733. }
  194734. png_write_chunk(png_ptr, png_sBIT, buf, size);
  194735. }
  194736. #endif
  194737. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194738. /* write the cHRM chunk */
  194739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194740. void /* PRIVATE */
  194741. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  194742. double red_x, double red_y, double green_x, double green_y,
  194743. double blue_x, double blue_y)
  194744. {
  194745. #ifdef PNG_USE_LOCAL_ARRAYS
  194746. PNG_cHRM;
  194747. #endif
  194748. png_byte buf[32];
  194749. png_uint_32 itemp;
  194750. png_debug(1, "in png_write_cHRM\n");
  194751. /* each value is saved in 1/100,000ths */
  194752. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  194753. white_x + white_y > 1.0)
  194754. {
  194755. png_warning(png_ptr, "Invalid cHRM white point specified");
  194756. #if !defined(PNG_NO_CONSOLE_IO)
  194757. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  194758. #endif
  194759. return;
  194760. }
  194761. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  194762. png_save_uint_32(buf, itemp);
  194763. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  194764. png_save_uint_32(buf + 4, itemp);
  194765. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  194766. {
  194767. png_warning(png_ptr, "Invalid cHRM red point specified");
  194768. return;
  194769. }
  194770. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  194771. png_save_uint_32(buf + 8, itemp);
  194772. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  194773. png_save_uint_32(buf + 12, itemp);
  194774. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  194775. {
  194776. png_warning(png_ptr, "Invalid cHRM green point specified");
  194777. return;
  194778. }
  194779. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  194780. png_save_uint_32(buf + 16, itemp);
  194781. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  194782. png_save_uint_32(buf + 20, itemp);
  194783. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  194784. {
  194785. png_warning(png_ptr, "Invalid cHRM blue point specified");
  194786. return;
  194787. }
  194788. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  194789. png_save_uint_32(buf + 24, itemp);
  194790. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  194791. png_save_uint_32(buf + 28, itemp);
  194792. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  194793. }
  194794. #endif
  194795. #ifdef PNG_FIXED_POINT_SUPPORTED
  194796. void /* PRIVATE */
  194797. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  194798. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  194799. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  194800. png_fixed_point blue_y)
  194801. {
  194802. #ifdef PNG_USE_LOCAL_ARRAYS
  194803. PNG_cHRM;
  194804. #endif
  194805. png_byte buf[32];
  194806. png_debug(1, "in png_write_cHRM\n");
  194807. /* each value is saved in 1/100,000ths */
  194808. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  194809. {
  194810. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  194811. #if !defined(PNG_NO_CONSOLE_IO)
  194812. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  194813. #endif
  194814. return;
  194815. }
  194816. png_save_uint_32(buf, (png_uint_32)white_x);
  194817. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  194818. if (red_x + red_y > 100000L)
  194819. {
  194820. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  194821. return;
  194822. }
  194823. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  194824. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  194825. if (green_x + green_y > 100000L)
  194826. {
  194827. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  194828. return;
  194829. }
  194830. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  194831. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  194832. if (blue_x + blue_y > 100000L)
  194833. {
  194834. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  194835. return;
  194836. }
  194837. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  194838. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  194839. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  194840. }
  194841. #endif
  194842. #endif
  194843. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194844. /* write the tRNS chunk */
  194845. void /* PRIVATE */
  194846. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  194847. int num_trans, int color_type)
  194848. {
  194849. #ifdef PNG_USE_LOCAL_ARRAYS
  194850. PNG_tRNS;
  194851. #endif
  194852. png_byte buf[6];
  194853. png_debug(1, "in png_write_tRNS\n");
  194854. if (color_type == PNG_COLOR_TYPE_PALETTE)
  194855. {
  194856. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  194857. {
  194858. png_warning(png_ptr,"Invalid number of transparent colors specified");
  194859. return;
  194860. }
  194861. /* write the chunk out as it is */
  194862. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  194863. }
  194864. else if (color_type == PNG_COLOR_TYPE_GRAY)
  194865. {
  194866. /* one 16 bit value */
  194867. if(tran->gray >= (1 << png_ptr->bit_depth))
  194868. {
  194869. png_warning(png_ptr,
  194870. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  194871. return;
  194872. }
  194873. png_save_uint_16(buf, tran->gray);
  194874. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  194875. }
  194876. else if (color_type == PNG_COLOR_TYPE_RGB)
  194877. {
  194878. /* three 16 bit values */
  194879. png_save_uint_16(buf, tran->red);
  194880. png_save_uint_16(buf + 2, tran->green);
  194881. png_save_uint_16(buf + 4, tran->blue);
  194882. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  194883. {
  194884. png_warning(png_ptr,
  194885. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  194886. return;
  194887. }
  194888. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  194889. }
  194890. else
  194891. {
  194892. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  194893. }
  194894. }
  194895. #endif
  194896. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194897. /* write the background chunk */
  194898. void /* PRIVATE */
  194899. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  194900. {
  194901. #ifdef PNG_USE_LOCAL_ARRAYS
  194902. PNG_bKGD;
  194903. #endif
  194904. png_byte buf[6];
  194905. png_debug(1, "in png_write_bKGD\n");
  194906. if (color_type == PNG_COLOR_TYPE_PALETTE)
  194907. {
  194908. if (
  194909. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194910. (png_ptr->num_palette ||
  194911. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  194912. #endif
  194913. back->index > png_ptr->num_palette)
  194914. {
  194915. png_warning(png_ptr, "Invalid background palette index");
  194916. return;
  194917. }
  194918. buf[0] = back->index;
  194919. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  194920. }
  194921. else if (color_type & PNG_COLOR_MASK_COLOR)
  194922. {
  194923. png_save_uint_16(buf, back->red);
  194924. png_save_uint_16(buf + 2, back->green);
  194925. png_save_uint_16(buf + 4, back->blue);
  194926. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  194927. {
  194928. png_warning(png_ptr,
  194929. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  194930. return;
  194931. }
  194932. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  194933. }
  194934. else
  194935. {
  194936. if(back->gray >= (1 << png_ptr->bit_depth))
  194937. {
  194938. png_warning(png_ptr,
  194939. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  194940. return;
  194941. }
  194942. png_save_uint_16(buf, back->gray);
  194943. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  194944. }
  194945. }
  194946. #endif
  194947. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194948. /* write the histogram */
  194949. void /* PRIVATE */
  194950. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  194951. {
  194952. #ifdef PNG_USE_LOCAL_ARRAYS
  194953. PNG_hIST;
  194954. #endif
  194955. int i;
  194956. png_byte buf[3];
  194957. png_debug(1, "in png_write_hIST\n");
  194958. if (num_hist > (int)png_ptr->num_palette)
  194959. {
  194960. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  194961. png_ptr->num_palette);
  194962. png_warning(png_ptr, "Invalid number of histogram entries specified");
  194963. return;
  194964. }
  194965. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  194966. for (i = 0; i < num_hist; i++)
  194967. {
  194968. png_save_uint_16(buf, hist[i]);
  194969. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  194970. }
  194971. png_write_chunk_end(png_ptr);
  194972. }
  194973. #endif
  194974. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  194975. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194976. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  194977. * and if invalid, correct the keyword rather than discarding the entire
  194978. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  194979. * length, forbids leading or trailing whitespace, multiple internal spaces,
  194980. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  194981. *
  194982. * The new_key is allocated to hold the corrected keyword and must be freed
  194983. * by the calling routine. This avoids problems with trying to write to
  194984. * static keywords without having to have duplicate copies of the strings.
  194985. */
  194986. png_size_t /* PRIVATE */
  194987. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  194988. {
  194989. png_size_t key_len;
  194990. png_charp kp, dp;
  194991. int kflag;
  194992. int kwarn=0;
  194993. png_debug(1, "in png_check_keyword\n");
  194994. *new_key = NULL;
  194995. if (key == NULL || (key_len = png_strlen(key)) == 0)
  194996. {
  194997. png_warning(png_ptr, "zero length keyword");
  194998. return ((png_size_t)0);
  194999. }
  195000. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  195001. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  195002. if (*new_key == NULL)
  195003. {
  195004. png_warning(png_ptr, "Out of memory while procesing keyword");
  195005. return ((png_size_t)0);
  195006. }
  195007. /* Replace non-printing characters with a blank and print a warning */
  195008. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  195009. {
  195010. if ((png_byte)*kp < 0x20 ||
  195011. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  195012. {
  195013. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195014. char msg[40];
  195015. png_snprintf(msg, 40,
  195016. "invalid keyword character 0x%02X", (png_byte)*kp);
  195017. png_warning(png_ptr, msg);
  195018. #else
  195019. png_warning(png_ptr, "invalid character in keyword");
  195020. #endif
  195021. *dp = ' ';
  195022. }
  195023. else
  195024. {
  195025. *dp = *kp;
  195026. }
  195027. }
  195028. *dp = '\0';
  195029. /* Remove any trailing white space. */
  195030. kp = *new_key + key_len - 1;
  195031. if (*kp == ' ')
  195032. {
  195033. png_warning(png_ptr, "trailing spaces removed from keyword");
  195034. while (*kp == ' ')
  195035. {
  195036. *(kp--) = '\0';
  195037. key_len--;
  195038. }
  195039. }
  195040. /* Remove any leading white space. */
  195041. kp = *new_key;
  195042. if (*kp == ' ')
  195043. {
  195044. png_warning(png_ptr, "leading spaces removed from keyword");
  195045. while (*kp == ' ')
  195046. {
  195047. kp++;
  195048. key_len--;
  195049. }
  195050. }
  195051. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  195052. /* Remove multiple internal spaces. */
  195053. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  195054. {
  195055. if (*kp == ' ' && kflag == 0)
  195056. {
  195057. *(dp++) = *kp;
  195058. kflag = 1;
  195059. }
  195060. else if (*kp == ' ')
  195061. {
  195062. key_len--;
  195063. kwarn=1;
  195064. }
  195065. else
  195066. {
  195067. *(dp++) = *kp;
  195068. kflag = 0;
  195069. }
  195070. }
  195071. *dp = '\0';
  195072. if(kwarn)
  195073. png_warning(png_ptr, "extra interior spaces removed from keyword");
  195074. if (key_len == 0)
  195075. {
  195076. png_free(png_ptr, *new_key);
  195077. *new_key=NULL;
  195078. png_warning(png_ptr, "Zero length keyword");
  195079. }
  195080. if (key_len > 79)
  195081. {
  195082. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  195083. new_key[79] = '\0';
  195084. key_len = 79;
  195085. }
  195086. return (key_len);
  195087. }
  195088. #endif
  195089. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195090. /* write a tEXt chunk */
  195091. void /* PRIVATE */
  195092. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  195093. png_size_t text_len)
  195094. {
  195095. #ifdef PNG_USE_LOCAL_ARRAYS
  195096. PNG_tEXt;
  195097. #endif
  195098. png_size_t key_len;
  195099. png_charp new_key;
  195100. png_debug(1, "in png_write_tEXt\n");
  195101. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195102. {
  195103. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  195104. return;
  195105. }
  195106. if (text == NULL || *text == '\0')
  195107. text_len = 0;
  195108. else
  195109. text_len = png_strlen(text);
  195110. /* make sure we include the 0 after the key */
  195111. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  195112. /*
  195113. * We leave it to the application to meet PNG-1.0 requirements on the
  195114. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195115. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195116. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195117. */
  195118. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195119. if (text_len)
  195120. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  195121. png_write_chunk_end(png_ptr);
  195122. png_free(png_ptr, new_key);
  195123. }
  195124. #endif
  195125. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195126. /* write a compressed text chunk */
  195127. void /* PRIVATE */
  195128. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  195129. png_size_t text_len, int compression)
  195130. {
  195131. #ifdef PNG_USE_LOCAL_ARRAYS
  195132. PNG_zTXt;
  195133. #endif
  195134. png_size_t key_len;
  195135. char buf[1];
  195136. png_charp new_key;
  195137. compression_state comp;
  195138. png_debug(1, "in png_write_zTXt\n");
  195139. comp.num_output_ptr = 0;
  195140. comp.max_output_ptr = 0;
  195141. comp.output_ptr = NULL;
  195142. comp.input = NULL;
  195143. comp.input_len = 0;
  195144. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195145. {
  195146. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  195147. return;
  195148. }
  195149. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  195150. {
  195151. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  195152. png_free(png_ptr, new_key);
  195153. return;
  195154. }
  195155. text_len = png_strlen(text);
  195156. /* compute the compressed data; do it now for the length */
  195157. text_len = png_text_compress(png_ptr, text, text_len, compression,
  195158. &comp);
  195159. /* write start of chunk */
  195160. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  195161. (key_len+text_len+2));
  195162. /* write key */
  195163. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195164. png_free(png_ptr, new_key);
  195165. buf[0] = (png_byte)compression;
  195166. /* write compression */
  195167. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  195168. /* write the compressed data */
  195169. png_write_compressed_data_out(png_ptr, &comp);
  195170. /* close the chunk */
  195171. png_write_chunk_end(png_ptr);
  195172. }
  195173. #endif
  195174. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195175. /* write an iTXt chunk */
  195176. void /* PRIVATE */
  195177. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  195178. png_charp lang, png_charp lang_key, png_charp text)
  195179. {
  195180. #ifdef PNG_USE_LOCAL_ARRAYS
  195181. PNG_iTXt;
  195182. #endif
  195183. png_size_t lang_len, key_len, lang_key_len, text_len;
  195184. png_charp new_lang, new_key;
  195185. png_byte cbuf[2];
  195186. compression_state comp;
  195187. png_debug(1, "in png_write_iTXt\n");
  195188. comp.num_output_ptr = 0;
  195189. comp.max_output_ptr = 0;
  195190. comp.output_ptr = NULL;
  195191. comp.input = NULL;
  195192. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195193. {
  195194. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  195195. return;
  195196. }
  195197. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  195198. {
  195199. png_warning(png_ptr, "Empty language field in iTXt chunk");
  195200. new_lang = NULL;
  195201. lang_len = 0;
  195202. }
  195203. if (lang_key == NULL)
  195204. lang_key_len = 0;
  195205. else
  195206. lang_key_len = png_strlen(lang_key);
  195207. if (text == NULL)
  195208. text_len = 0;
  195209. else
  195210. text_len = png_strlen(text);
  195211. /* compute the compressed data; do it now for the length */
  195212. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  195213. &comp);
  195214. /* make sure we include the compression flag, the compression byte,
  195215. * and the NULs after the key, lang, and lang_key parts */
  195216. png_write_chunk_start(png_ptr, png_iTXt,
  195217. (png_uint_32)(
  195218. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  195219. + key_len
  195220. + lang_len
  195221. + lang_key_len
  195222. + text_len));
  195223. /*
  195224. * We leave it to the application to meet PNG-1.0 requirements on the
  195225. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195226. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195227. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195228. */
  195229. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195230. /* set the compression flag */
  195231. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  195232. compression == PNG_TEXT_COMPRESSION_NONE)
  195233. cbuf[0] = 0;
  195234. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  195235. cbuf[0] = 1;
  195236. /* set the compression method */
  195237. cbuf[1] = 0;
  195238. png_write_chunk_data(png_ptr, cbuf, 2);
  195239. cbuf[0] = 0;
  195240. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  195241. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  195242. png_write_compressed_data_out(png_ptr, &comp);
  195243. png_write_chunk_end(png_ptr);
  195244. png_free(png_ptr, new_key);
  195245. if (new_lang)
  195246. png_free(png_ptr, new_lang);
  195247. }
  195248. #endif
  195249. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195250. /* write the oFFs chunk */
  195251. void /* PRIVATE */
  195252. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  195253. int unit_type)
  195254. {
  195255. #ifdef PNG_USE_LOCAL_ARRAYS
  195256. PNG_oFFs;
  195257. #endif
  195258. png_byte buf[9];
  195259. png_debug(1, "in png_write_oFFs\n");
  195260. if (unit_type >= PNG_OFFSET_LAST)
  195261. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  195262. png_save_int_32(buf, x_offset);
  195263. png_save_int_32(buf + 4, y_offset);
  195264. buf[8] = (png_byte)unit_type;
  195265. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  195266. }
  195267. #endif
  195268. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195269. /* write the pCAL chunk (described in the PNG extensions document) */
  195270. void /* PRIVATE */
  195271. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  195272. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  195273. {
  195274. #ifdef PNG_USE_LOCAL_ARRAYS
  195275. PNG_pCAL;
  195276. #endif
  195277. png_size_t purpose_len, units_len, total_len;
  195278. png_uint_32p params_len;
  195279. png_byte buf[10];
  195280. png_charp new_purpose;
  195281. int i;
  195282. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  195283. if (type >= PNG_EQUATION_LAST)
  195284. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195285. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  195286. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  195287. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  195288. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  195289. total_len = purpose_len + units_len + 10;
  195290. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  195291. *png_sizeof(png_uint_32)));
  195292. /* Find the length of each parameter, making sure we don't count the
  195293. null terminator for the last parameter. */
  195294. for (i = 0; i < nparams; i++)
  195295. {
  195296. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  195297. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  195298. total_len += (png_size_t)params_len[i];
  195299. }
  195300. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  195301. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  195302. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  195303. png_save_int_32(buf, X0);
  195304. png_save_int_32(buf + 4, X1);
  195305. buf[8] = (png_byte)type;
  195306. buf[9] = (png_byte)nparams;
  195307. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  195308. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  195309. png_free(png_ptr, new_purpose);
  195310. for (i = 0; i < nparams; i++)
  195311. {
  195312. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  195313. (png_size_t)params_len[i]);
  195314. }
  195315. png_free(png_ptr, params_len);
  195316. png_write_chunk_end(png_ptr);
  195317. }
  195318. #endif
  195319. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  195320. /* write the sCAL chunk */
  195321. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  195322. void /* PRIVATE */
  195323. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  195324. {
  195325. #ifdef PNG_USE_LOCAL_ARRAYS
  195326. PNG_sCAL;
  195327. #endif
  195328. char buf[64];
  195329. png_size_t total_len;
  195330. png_debug(1, "in png_write_sCAL\n");
  195331. buf[0] = (char)unit;
  195332. #if defined(_WIN32_WCE)
  195333. /* sprintf() function is not supported on WindowsCE */
  195334. {
  195335. wchar_t wc_buf[32];
  195336. size_t wc_len;
  195337. swprintf(wc_buf, TEXT("%12.12e"), width);
  195338. wc_len = wcslen(wc_buf);
  195339. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  195340. total_len = wc_len + 2;
  195341. swprintf(wc_buf, TEXT("%12.12e"), height);
  195342. wc_len = wcslen(wc_buf);
  195343. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  195344. NULL, NULL);
  195345. total_len += wc_len;
  195346. }
  195347. #else
  195348. png_snprintf(buf + 1, 63, "%12.12e", width);
  195349. total_len = 1 + png_strlen(buf + 1) + 1;
  195350. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  195351. total_len += png_strlen(buf + total_len);
  195352. #endif
  195353. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  195354. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  195355. }
  195356. #else
  195357. #ifdef PNG_FIXED_POINT_SUPPORTED
  195358. void /* PRIVATE */
  195359. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  195360. png_charp height)
  195361. {
  195362. #ifdef PNG_USE_LOCAL_ARRAYS
  195363. PNG_sCAL;
  195364. #endif
  195365. png_byte buf[64];
  195366. png_size_t wlen, hlen, total_len;
  195367. png_debug(1, "in png_write_sCAL_s\n");
  195368. wlen = png_strlen(width);
  195369. hlen = png_strlen(height);
  195370. total_len = wlen + hlen + 2;
  195371. if (total_len > 64)
  195372. {
  195373. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  195374. return;
  195375. }
  195376. buf[0] = (png_byte)unit;
  195377. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  195378. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  195379. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  195380. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  195381. }
  195382. #endif
  195383. #endif
  195384. #endif
  195385. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  195386. /* write the pHYs chunk */
  195387. void /* PRIVATE */
  195388. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  195389. png_uint_32 y_pixels_per_unit,
  195390. int unit_type)
  195391. {
  195392. #ifdef PNG_USE_LOCAL_ARRAYS
  195393. PNG_pHYs;
  195394. #endif
  195395. png_byte buf[9];
  195396. png_debug(1, "in png_write_pHYs\n");
  195397. if (unit_type >= PNG_RESOLUTION_LAST)
  195398. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  195399. png_save_uint_32(buf, x_pixels_per_unit);
  195400. png_save_uint_32(buf + 4, y_pixels_per_unit);
  195401. buf[8] = (png_byte)unit_type;
  195402. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  195403. }
  195404. #endif
  195405. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195406. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  195407. * or png_convert_from_time_t(), or fill in the structure yourself.
  195408. */
  195409. void /* PRIVATE */
  195410. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  195411. {
  195412. #ifdef PNG_USE_LOCAL_ARRAYS
  195413. PNG_tIME;
  195414. #endif
  195415. png_byte buf[7];
  195416. png_debug(1, "in png_write_tIME\n");
  195417. if (mod_time->month > 12 || mod_time->month < 1 ||
  195418. mod_time->day > 31 || mod_time->day < 1 ||
  195419. mod_time->hour > 23 || mod_time->second > 60)
  195420. {
  195421. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  195422. return;
  195423. }
  195424. png_save_uint_16(buf, mod_time->year);
  195425. buf[2] = mod_time->month;
  195426. buf[3] = mod_time->day;
  195427. buf[4] = mod_time->hour;
  195428. buf[5] = mod_time->minute;
  195429. buf[6] = mod_time->second;
  195430. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  195431. }
  195432. #endif
  195433. /* initializes the row writing capability of libpng */
  195434. void /* PRIVATE */
  195435. png_write_start_row(png_structp png_ptr)
  195436. {
  195437. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195438. #ifdef PNG_USE_LOCAL_ARRAYS
  195439. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195440. /* start of interlace block */
  195441. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195442. /* offset to next interlace block */
  195443. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195444. /* start of interlace block in the y direction */
  195445. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195446. /* offset to next interlace block in the y direction */
  195447. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195448. #endif
  195449. #endif
  195450. png_size_t buf_size;
  195451. png_debug(1, "in png_write_start_row\n");
  195452. buf_size = (png_size_t)(PNG_ROWBYTES(
  195453. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  195454. /* set up row buffer */
  195455. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  195456. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  195457. #ifndef PNG_NO_WRITE_FILTERING
  195458. /* set up filtering buffer, if using this filter */
  195459. if (png_ptr->do_filter & PNG_FILTER_SUB)
  195460. {
  195461. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195462. (png_ptr->rowbytes + 1));
  195463. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195464. }
  195465. /* We only need to keep the previous row if we are using one of these. */
  195466. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  195467. {
  195468. /* set up previous row buffer */
  195469. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  195470. png_memset(png_ptr->prev_row, 0, buf_size);
  195471. if (png_ptr->do_filter & PNG_FILTER_UP)
  195472. {
  195473. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195474. (png_ptr->rowbytes + 1));
  195475. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195476. }
  195477. if (png_ptr->do_filter & PNG_FILTER_AVG)
  195478. {
  195479. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195480. (png_ptr->rowbytes + 1));
  195481. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195482. }
  195483. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  195484. {
  195485. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195486. (png_ptr->rowbytes + 1));
  195487. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195488. }
  195489. #endif /* PNG_NO_WRITE_FILTERING */
  195490. }
  195491. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195492. /* if interlaced, we need to set up width and height of pass */
  195493. if (png_ptr->interlaced)
  195494. {
  195495. if (!(png_ptr->transformations & PNG_INTERLACE))
  195496. {
  195497. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195498. png_pass_ystart[0]) / png_pass_yinc[0];
  195499. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  195500. png_pass_start[0]) / png_pass_inc[0];
  195501. }
  195502. else
  195503. {
  195504. png_ptr->num_rows = png_ptr->height;
  195505. png_ptr->usr_width = png_ptr->width;
  195506. }
  195507. }
  195508. else
  195509. #endif
  195510. {
  195511. png_ptr->num_rows = png_ptr->height;
  195512. png_ptr->usr_width = png_ptr->width;
  195513. }
  195514. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195515. png_ptr->zstream.next_out = png_ptr->zbuf;
  195516. }
  195517. /* Internal use only. Called when finished processing a row of data. */
  195518. void /* PRIVATE */
  195519. png_write_finish_row(png_structp png_ptr)
  195520. {
  195521. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195522. #ifdef PNG_USE_LOCAL_ARRAYS
  195523. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195524. /* start of interlace block */
  195525. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195526. /* offset to next interlace block */
  195527. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195528. /* start of interlace block in the y direction */
  195529. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195530. /* offset to next interlace block in the y direction */
  195531. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195532. #endif
  195533. #endif
  195534. int ret;
  195535. png_debug(1, "in png_write_finish_row\n");
  195536. /* next row */
  195537. png_ptr->row_number++;
  195538. /* see if we are done */
  195539. if (png_ptr->row_number < png_ptr->num_rows)
  195540. return;
  195541. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195542. /* if interlaced, go to next pass */
  195543. if (png_ptr->interlaced)
  195544. {
  195545. png_ptr->row_number = 0;
  195546. if (png_ptr->transformations & PNG_INTERLACE)
  195547. {
  195548. png_ptr->pass++;
  195549. }
  195550. else
  195551. {
  195552. /* loop until we find a non-zero width or height pass */
  195553. do
  195554. {
  195555. png_ptr->pass++;
  195556. if (png_ptr->pass >= 7)
  195557. break;
  195558. png_ptr->usr_width = (png_ptr->width +
  195559. png_pass_inc[png_ptr->pass] - 1 -
  195560. png_pass_start[png_ptr->pass]) /
  195561. png_pass_inc[png_ptr->pass];
  195562. png_ptr->num_rows = (png_ptr->height +
  195563. png_pass_yinc[png_ptr->pass] - 1 -
  195564. png_pass_ystart[png_ptr->pass]) /
  195565. png_pass_yinc[png_ptr->pass];
  195566. if (png_ptr->transformations & PNG_INTERLACE)
  195567. break;
  195568. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  195569. }
  195570. /* reset the row above the image for the next pass */
  195571. if (png_ptr->pass < 7)
  195572. {
  195573. if (png_ptr->prev_row != NULL)
  195574. png_memset(png_ptr->prev_row, 0,
  195575. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  195576. png_ptr->usr_bit_depth,png_ptr->width))+1);
  195577. return;
  195578. }
  195579. }
  195580. #endif
  195581. /* if we get here, we've just written the last row, so we need
  195582. to flush the compressor */
  195583. do
  195584. {
  195585. /* tell the compressor we are done */
  195586. ret = deflate(&png_ptr->zstream, Z_FINISH);
  195587. /* check for an error */
  195588. if (ret == Z_OK)
  195589. {
  195590. /* check to see if we need more room */
  195591. if (!(png_ptr->zstream.avail_out))
  195592. {
  195593. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  195594. png_ptr->zstream.next_out = png_ptr->zbuf;
  195595. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195596. }
  195597. }
  195598. else if (ret != Z_STREAM_END)
  195599. {
  195600. if (png_ptr->zstream.msg != NULL)
  195601. png_error(png_ptr, png_ptr->zstream.msg);
  195602. else
  195603. png_error(png_ptr, "zlib error");
  195604. }
  195605. } while (ret != Z_STREAM_END);
  195606. /* write any extra space */
  195607. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  195608. {
  195609. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  195610. png_ptr->zstream.avail_out);
  195611. }
  195612. deflateReset(&png_ptr->zstream);
  195613. png_ptr->zstream.data_type = Z_BINARY;
  195614. }
  195615. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195616. /* Pick out the correct pixels for the interlace pass.
  195617. * The basic idea here is to go through the row with a source
  195618. * pointer and a destination pointer (sp and dp), and copy the
  195619. * correct pixels for the pass. As the row gets compacted,
  195620. * sp will always be >= dp, so we should never overwrite anything.
  195621. * See the default: case for the easiest code to understand.
  195622. */
  195623. void /* PRIVATE */
  195624. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  195625. {
  195626. #ifdef PNG_USE_LOCAL_ARRAYS
  195627. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195628. /* start of interlace block */
  195629. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195630. /* offset to next interlace block */
  195631. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195632. #endif
  195633. png_debug(1, "in png_do_write_interlace\n");
  195634. /* we don't have to do anything on the last pass (6) */
  195635. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195636. if (row != NULL && row_info != NULL && pass < 6)
  195637. #else
  195638. if (pass < 6)
  195639. #endif
  195640. {
  195641. /* each pixel depth is handled separately */
  195642. switch (row_info->pixel_depth)
  195643. {
  195644. case 1:
  195645. {
  195646. png_bytep sp;
  195647. png_bytep dp;
  195648. int shift;
  195649. int d;
  195650. int value;
  195651. png_uint_32 i;
  195652. png_uint_32 row_width = row_info->width;
  195653. dp = row;
  195654. d = 0;
  195655. shift = 7;
  195656. for (i = png_pass_start[pass]; i < row_width;
  195657. i += png_pass_inc[pass])
  195658. {
  195659. sp = row + (png_size_t)(i >> 3);
  195660. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  195661. d |= (value << shift);
  195662. if (shift == 0)
  195663. {
  195664. shift = 7;
  195665. *dp++ = (png_byte)d;
  195666. d = 0;
  195667. }
  195668. else
  195669. shift--;
  195670. }
  195671. if (shift != 7)
  195672. *dp = (png_byte)d;
  195673. break;
  195674. }
  195675. case 2:
  195676. {
  195677. png_bytep sp;
  195678. png_bytep dp;
  195679. int shift;
  195680. int d;
  195681. int value;
  195682. png_uint_32 i;
  195683. png_uint_32 row_width = row_info->width;
  195684. dp = row;
  195685. shift = 6;
  195686. d = 0;
  195687. for (i = png_pass_start[pass]; i < row_width;
  195688. i += png_pass_inc[pass])
  195689. {
  195690. sp = row + (png_size_t)(i >> 2);
  195691. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  195692. d |= (value << shift);
  195693. if (shift == 0)
  195694. {
  195695. shift = 6;
  195696. *dp++ = (png_byte)d;
  195697. d = 0;
  195698. }
  195699. else
  195700. shift -= 2;
  195701. }
  195702. if (shift != 6)
  195703. *dp = (png_byte)d;
  195704. break;
  195705. }
  195706. case 4:
  195707. {
  195708. png_bytep sp;
  195709. png_bytep dp;
  195710. int shift;
  195711. int d;
  195712. int value;
  195713. png_uint_32 i;
  195714. png_uint_32 row_width = row_info->width;
  195715. dp = row;
  195716. shift = 4;
  195717. d = 0;
  195718. for (i = png_pass_start[pass]; i < row_width;
  195719. i += png_pass_inc[pass])
  195720. {
  195721. sp = row + (png_size_t)(i >> 1);
  195722. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  195723. d |= (value << shift);
  195724. if (shift == 0)
  195725. {
  195726. shift = 4;
  195727. *dp++ = (png_byte)d;
  195728. d = 0;
  195729. }
  195730. else
  195731. shift -= 4;
  195732. }
  195733. if (shift != 4)
  195734. *dp = (png_byte)d;
  195735. break;
  195736. }
  195737. default:
  195738. {
  195739. png_bytep sp;
  195740. png_bytep dp;
  195741. png_uint_32 i;
  195742. png_uint_32 row_width = row_info->width;
  195743. png_size_t pixel_bytes;
  195744. /* start at the beginning */
  195745. dp = row;
  195746. /* find out how many bytes each pixel takes up */
  195747. pixel_bytes = (row_info->pixel_depth >> 3);
  195748. /* loop through the row, only looking at the pixels that
  195749. matter */
  195750. for (i = png_pass_start[pass]; i < row_width;
  195751. i += png_pass_inc[pass])
  195752. {
  195753. /* find out where the original pixel is */
  195754. sp = row + (png_size_t)i * pixel_bytes;
  195755. /* move the pixel */
  195756. if (dp != sp)
  195757. png_memcpy(dp, sp, pixel_bytes);
  195758. /* next pixel */
  195759. dp += pixel_bytes;
  195760. }
  195761. break;
  195762. }
  195763. }
  195764. /* set new row width */
  195765. row_info->width = (row_info->width +
  195766. png_pass_inc[pass] - 1 -
  195767. png_pass_start[pass]) /
  195768. png_pass_inc[pass];
  195769. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195770. row_info->width);
  195771. }
  195772. }
  195773. #endif
  195774. /* This filters the row, chooses which filter to use, if it has not already
  195775. * been specified by the application, and then writes the row out with the
  195776. * chosen filter.
  195777. */
  195778. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  195779. #define PNG_HISHIFT 10
  195780. #define PNG_LOMASK ((png_uint_32)0xffffL)
  195781. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  195782. void /* PRIVATE */
  195783. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  195784. {
  195785. png_bytep best_row;
  195786. #ifndef PNG_NO_WRITE_FILTER
  195787. png_bytep prev_row, row_buf;
  195788. png_uint_32 mins, bpp;
  195789. png_byte filter_to_do = png_ptr->do_filter;
  195790. png_uint_32 row_bytes = row_info->rowbytes;
  195791. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195792. int num_p_filters = (int)png_ptr->num_prev_filters;
  195793. #endif
  195794. png_debug(1, "in png_write_find_filter\n");
  195795. /* find out how many bytes offset each pixel is */
  195796. bpp = (row_info->pixel_depth + 7) >> 3;
  195797. prev_row = png_ptr->prev_row;
  195798. #endif
  195799. best_row = png_ptr->row_buf;
  195800. #ifndef PNG_NO_WRITE_FILTER
  195801. row_buf = best_row;
  195802. mins = PNG_MAXSUM;
  195803. /* The prediction method we use is to find which method provides the
  195804. * smallest value when summing the absolute values of the distances
  195805. * from zero, using anything >= 128 as negative numbers. This is known
  195806. * as the "minimum sum of absolute differences" heuristic. Other
  195807. * heuristics are the "weighted minimum sum of absolute differences"
  195808. * (experimental and can in theory improve compression), and the "zlib
  195809. * predictive" method (not implemented yet), which does test compressions
  195810. * of lines using different filter methods, and then chooses the
  195811. * (series of) filter(s) that give minimum compressed data size (VERY
  195812. * computationally expensive).
  195813. *
  195814. * GRR 980525: consider also
  195815. * (1) minimum sum of absolute differences from running average (i.e.,
  195816. * keep running sum of non-absolute differences & count of bytes)
  195817. * [track dispersion, too? restart average if dispersion too large?]
  195818. * (1b) minimum sum of absolute differences from sliding average, probably
  195819. * with window size <= deflate window (usually 32K)
  195820. * (2) minimum sum of squared differences from zero or running average
  195821. * (i.e., ~ root-mean-square approach)
  195822. */
  195823. /* We don't need to test the 'no filter' case if this is the only filter
  195824. * that has been chosen, as it doesn't actually do anything to the data.
  195825. */
  195826. if ((filter_to_do & PNG_FILTER_NONE) &&
  195827. filter_to_do != PNG_FILTER_NONE)
  195828. {
  195829. png_bytep rp;
  195830. png_uint_32 sum = 0;
  195831. png_uint_32 i;
  195832. int v;
  195833. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  195834. {
  195835. v = *rp;
  195836. sum += (v < 128) ? v : 256 - v;
  195837. }
  195838. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195839. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195840. {
  195841. png_uint_32 sumhi, sumlo;
  195842. int j;
  195843. sumlo = sum & PNG_LOMASK;
  195844. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  195845. /* Reduce the sum if we match any of the previous rows */
  195846. for (j = 0; j < num_p_filters; j++)
  195847. {
  195848. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  195849. {
  195850. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  195851. PNG_WEIGHT_SHIFT;
  195852. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  195853. PNG_WEIGHT_SHIFT;
  195854. }
  195855. }
  195856. /* Factor in the cost of this filter (this is here for completeness,
  195857. * but it makes no sense to have a "cost" for the NONE filter, as
  195858. * it has the minimum possible computational cost - none).
  195859. */
  195860. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  195861. PNG_COST_SHIFT;
  195862. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  195863. PNG_COST_SHIFT;
  195864. if (sumhi > PNG_HIMASK)
  195865. sum = PNG_MAXSUM;
  195866. else
  195867. sum = (sumhi << PNG_HISHIFT) + sumlo;
  195868. }
  195869. #endif
  195870. mins = sum;
  195871. }
  195872. /* sub filter */
  195873. if (filter_to_do == PNG_FILTER_SUB)
  195874. /* it's the only filter so no testing is needed */
  195875. {
  195876. png_bytep rp, lp, dp;
  195877. png_uint_32 i;
  195878. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  195879. i++, rp++, dp++)
  195880. {
  195881. *dp = *rp;
  195882. }
  195883. for (lp = row_buf + 1; i < row_bytes;
  195884. i++, rp++, lp++, dp++)
  195885. {
  195886. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  195887. }
  195888. best_row = png_ptr->sub_row;
  195889. }
  195890. else if (filter_to_do & PNG_FILTER_SUB)
  195891. {
  195892. png_bytep rp, dp, lp;
  195893. png_uint_32 sum = 0, lmins = mins;
  195894. png_uint_32 i;
  195895. int v;
  195896. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195897. /* We temporarily increase the "minimum sum" by the factor we
  195898. * would reduce the sum of this filter, so that we can do the
  195899. * early exit comparison without scaling the sum each time.
  195900. */
  195901. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195902. {
  195903. int j;
  195904. png_uint_32 lmhi, lmlo;
  195905. lmlo = lmins & PNG_LOMASK;
  195906. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  195907. for (j = 0; j < num_p_filters; j++)
  195908. {
  195909. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  195910. {
  195911. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  195912. PNG_WEIGHT_SHIFT;
  195913. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  195914. PNG_WEIGHT_SHIFT;
  195915. }
  195916. }
  195917. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195918. PNG_COST_SHIFT;
  195919. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195920. PNG_COST_SHIFT;
  195921. if (lmhi > PNG_HIMASK)
  195922. lmins = PNG_MAXSUM;
  195923. else
  195924. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  195925. }
  195926. #endif
  195927. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  195928. i++, rp++, dp++)
  195929. {
  195930. v = *dp = *rp;
  195931. sum += (v < 128) ? v : 256 - v;
  195932. }
  195933. for (lp = row_buf + 1; i < row_bytes;
  195934. i++, rp++, lp++, dp++)
  195935. {
  195936. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  195937. sum += (v < 128) ? v : 256 - v;
  195938. if (sum > lmins) /* We are already worse, don't continue. */
  195939. break;
  195940. }
  195941. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195942. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195943. {
  195944. int j;
  195945. png_uint_32 sumhi, sumlo;
  195946. sumlo = sum & PNG_LOMASK;
  195947. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  195948. for (j = 0; j < num_p_filters; j++)
  195949. {
  195950. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  195951. {
  195952. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  195953. PNG_WEIGHT_SHIFT;
  195954. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  195955. PNG_WEIGHT_SHIFT;
  195956. }
  195957. }
  195958. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195959. PNG_COST_SHIFT;
  195960. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195961. PNG_COST_SHIFT;
  195962. if (sumhi > PNG_HIMASK)
  195963. sum = PNG_MAXSUM;
  195964. else
  195965. sum = (sumhi << PNG_HISHIFT) + sumlo;
  195966. }
  195967. #endif
  195968. if (sum < mins)
  195969. {
  195970. mins = sum;
  195971. best_row = png_ptr->sub_row;
  195972. }
  195973. }
  195974. /* up filter */
  195975. if (filter_to_do == PNG_FILTER_UP)
  195976. {
  195977. png_bytep rp, dp, pp;
  195978. png_uint_32 i;
  195979. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  195980. pp = prev_row + 1; i < row_bytes;
  195981. i++, rp++, pp++, dp++)
  195982. {
  195983. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  195984. }
  195985. best_row = png_ptr->up_row;
  195986. }
  195987. else if (filter_to_do & PNG_FILTER_UP)
  195988. {
  195989. png_bytep rp, dp, pp;
  195990. png_uint_32 sum = 0, lmins = mins;
  195991. png_uint_32 i;
  195992. int v;
  195993. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195994. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195995. {
  195996. int j;
  195997. png_uint_32 lmhi, lmlo;
  195998. lmlo = lmins & PNG_LOMASK;
  195999. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196000. for (j = 0; j < num_p_filters; j++)
  196001. {
  196002. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196003. {
  196004. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196005. PNG_WEIGHT_SHIFT;
  196006. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196007. PNG_WEIGHT_SHIFT;
  196008. }
  196009. }
  196010. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196011. PNG_COST_SHIFT;
  196012. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196013. PNG_COST_SHIFT;
  196014. if (lmhi > PNG_HIMASK)
  196015. lmins = PNG_MAXSUM;
  196016. else
  196017. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196018. }
  196019. #endif
  196020. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196021. pp = prev_row + 1; i < row_bytes; i++)
  196022. {
  196023. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196024. sum += (v < 128) ? v : 256 - v;
  196025. if (sum > lmins) /* We are already worse, don't continue. */
  196026. break;
  196027. }
  196028. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196029. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196030. {
  196031. int j;
  196032. png_uint_32 sumhi, sumlo;
  196033. sumlo = sum & PNG_LOMASK;
  196034. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196035. for (j = 0; j < num_p_filters; j++)
  196036. {
  196037. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196038. {
  196039. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196040. PNG_WEIGHT_SHIFT;
  196041. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196042. PNG_WEIGHT_SHIFT;
  196043. }
  196044. }
  196045. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196046. PNG_COST_SHIFT;
  196047. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196048. PNG_COST_SHIFT;
  196049. if (sumhi > PNG_HIMASK)
  196050. sum = PNG_MAXSUM;
  196051. else
  196052. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196053. }
  196054. #endif
  196055. if (sum < mins)
  196056. {
  196057. mins = sum;
  196058. best_row = png_ptr->up_row;
  196059. }
  196060. }
  196061. /* avg filter */
  196062. if (filter_to_do == PNG_FILTER_AVG)
  196063. {
  196064. png_bytep rp, dp, pp, lp;
  196065. png_uint_32 i;
  196066. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196067. pp = prev_row + 1; i < bpp; i++)
  196068. {
  196069. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196070. }
  196071. for (lp = row_buf + 1; i < row_bytes; i++)
  196072. {
  196073. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  196074. & 0xff);
  196075. }
  196076. best_row = png_ptr->avg_row;
  196077. }
  196078. else if (filter_to_do & PNG_FILTER_AVG)
  196079. {
  196080. png_bytep rp, dp, pp, lp;
  196081. png_uint_32 sum = 0, lmins = mins;
  196082. png_uint_32 i;
  196083. int v;
  196084. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196085. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196086. {
  196087. int j;
  196088. png_uint_32 lmhi, lmlo;
  196089. lmlo = lmins & PNG_LOMASK;
  196090. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196091. for (j = 0; j < num_p_filters; j++)
  196092. {
  196093. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  196094. {
  196095. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196096. PNG_WEIGHT_SHIFT;
  196097. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196098. PNG_WEIGHT_SHIFT;
  196099. }
  196100. }
  196101. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196102. PNG_COST_SHIFT;
  196103. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196104. PNG_COST_SHIFT;
  196105. if (lmhi > PNG_HIMASK)
  196106. lmins = PNG_MAXSUM;
  196107. else
  196108. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196109. }
  196110. #endif
  196111. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196112. pp = prev_row + 1; i < bpp; i++)
  196113. {
  196114. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196115. sum += (v < 128) ? v : 256 - v;
  196116. }
  196117. for (lp = row_buf + 1; i < row_bytes; i++)
  196118. {
  196119. v = *dp++ =
  196120. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  196121. sum += (v < 128) ? v : 256 - v;
  196122. if (sum > lmins) /* We are already worse, don't continue. */
  196123. break;
  196124. }
  196125. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196126. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196127. {
  196128. int j;
  196129. png_uint_32 sumhi, sumlo;
  196130. sumlo = sum & PNG_LOMASK;
  196131. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196132. for (j = 0; j < num_p_filters; j++)
  196133. {
  196134. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196135. {
  196136. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196137. PNG_WEIGHT_SHIFT;
  196138. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196139. PNG_WEIGHT_SHIFT;
  196140. }
  196141. }
  196142. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196143. PNG_COST_SHIFT;
  196144. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196145. PNG_COST_SHIFT;
  196146. if (sumhi > PNG_HIMASK)
  196147. sum = PNG_MAXSUM;
  196148. else
  196149. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196150. }
  196151. #endif
  196152. if (sum < mins)
  196153. {
  196154. mins = sum;
  196155. best_row = png_ptr->avg_row;
  196156. }
  196157. }
  196158. /* Paeth filter */
  196159. if (filter_to_do == PNG_FILTER_PAETH)
  196160. {
  196161. png_bytep rp, dp, pp, cp, lp;
  196162. png_uint_32 i;
  196163. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196164. pp = prev_row + 1; i < bpp; i++)
  196165. {
  196166. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196167. }
  196168. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196169. {
  196170. int a, b, c, pa, pb, pc, p;
  196171. b = *pp++;
  196172. c = *cp++;
  196173. a = *lp++;
  196174. p = b - c;
  196175. pc = a - c;
  196176. #ifdef PNG_USE_ABS
  196177. pa = abs(p);
  196178. pb = abs(pc);
  196179. pc = abs(p + pc);
  196180. #else
  196181. pa = p < 0 ? -p : p;
  196182. pb = pc < 0 ? -pc : pc;
  196183. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196184. #endif
  196185. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196186. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196187. }
  196188. best_row = png_ptr->paeth_row;
  196189. }
  196190. else if (filter_to_do & PNG_FILTER_PAETH)
  196191. {
  196192. png_bytep rp, dp, pp, cp, lp;
  196193. png_uint_32 sum = 0, lmins = mins;
  196194. png_uint_32 i;
  196195. int v;
  196196. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196197. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196198. {
  196199. int j;
  196200. png_uint_32 lmhi, lmlo;
  196201. lmlo = lmins & PNG_LOMASK;
  196202. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196203. for (j = 0; j < num_p_filters; j++)
  196204. {
  196205. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196206. {
  196207. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196208. PNG_WEIGHT_SHIFT;
  196209. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196210. PNG_WEIGHT_SHIFT;
  196211. }
  196212. }
  196213. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196214. PNG_COST_SHIFT;
  196215. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196216. PNG_COST_SHIFT;
  196217. if (lmhi > PNG_HIMASK)
  196218. lmins = PNG_MAXSUM;
  196219. else
  196220. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196221. }
  196222. #endif
  196223. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196224. pp = prev_row + 1; i < bpp; i++)
  196225. {
  196226. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196227. sum += (v < 128) ? v : 256 - v;
  196228. }
  196229. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196230. {
  196231. int a, b, c, pa, pb, pc, p;
  196232. b = *pp++;
  196233. c = *cp++;
  196234. a = *lp++;
  196235. #ifndef PNG_SLOW_PAETH
  196236. p = b - c;
  196237. pc = a - c;
  196238. #ifdef PNG_USE_ABS
  196239. pa = abs(p);
  196240. pb = abs(pc);
  196241. pc = abs(p + pc);
  196242. #else
  196243. pa = p < 0 ? -p : p;
  196244. pb = pc < 0 ? -pc : pc;
  196245. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196246. #endif
  196247. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196248. #else /* PNG_SLOW_PAETH */
  196249. p = a + b - c;
  196250. pa = abs(p - a);
  196251. pb = abs(p - b);
  196252. pc = abs(p - c);
  196253. if (pa <= pb && pa <= pc)
  196254. p = a;
  196255. else if (pb <= pc)
  196256. p = b;
  196257. else
  196258. p = c;
  196259. #endif /* PNG_SLOW_PAETH */
  196260. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196261. sum += (v < 128) ? v : 256 - v;
  196262. if (sum > lmins) /* We are already worse, don't continue. */
  196263. break;
  196264. }
  196265. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196266. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196267. {
  196268. int j;
  196269. png_uint_32 sumhi, sumlo;
  196270. sumlo = sum & PNG_LOMASK;
  196271. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196272. for (j = 0; j < num_p_filters; j++)
  196273. {
  196274. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196275. {
  196276. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196277. PNG_WEIGHT_SHIFT;
  196278. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196279. PNG_WEIGHT_SHIFT;
  196280. }
  196281. }
  196282. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196283. PNG_COST_SHIFT;
  196284. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196285. PNG_COST_SHIFT;
  196286. if (sumhi > PNG_HIMASK)
  196287. sum = PNG_MAXSUM;
  196288. else
  196289. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196290. }
  196291. #endif
  196292. if (sum < mins)
  196293. {
  196294. best_row = png_ptr->paeth_row;
  196295. }
  196296. }
  196297. #endif /* PNG_NO_WRITE_FILTER */
  196298. /* Do the actual writing of the filtered row data from the chosen filter. */
  196299. png_write_filtered_row(png_ptr, best_row);
  196300. #ifndef PNG_NO_WRITE_FILTER
  196301. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196302. /* Save the type of filter we picked this time for future calculations */
  196303. if (png_ptr->num_prev_filters > 0)
  196304. {
  196305. int j;
  196306. for (j = 1; j < num_p_filters; j++)
  196307. {
  196308. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  196309. }
  196310. png_ptr->prev_filters[j] = best_row[0];
  196311. }
  196312. #endif
  196313. #endif /* PNG_NO_WRITE_FILTER */
  196314. }
  196315. /* Do the actual writing of a previously filtered row. */
  196316. void /* PRIVATE */
  196317. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  196318. {
  196319. png_debug(1, "in png_write_filtered_row\n");
  196320. png_debug1(2, "filter = %d\n", filtered_row[0]);
  196321. /* set up the zlib input buffer */
  196322. png_ptr->zstream.next_in = filtered_row;
  196323. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  196324. /* repeat until we have compressed all the data */
  196325. do
  196326. {
  196327. int ret; /* return of zlib */
  196328. /* compress the data */
  196329. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196330. /* check for compression errors */
  196331. if (ret != Z_OK)
  196332. {
  196333. if (png_ptr->zstream.msg != NULL)
  196334. png_error(png_ptr, png_ptr->zstream.msg);
  196335. else
  196336. png_error(png_ptr, "zlib error");
  196337. }
  196338. /* see if it is time to write another IDAT */
  196339. if (!(png_ptr->zstream.avail_out))
  196340. {
  196341. /* write the IDAT and reset the zlib output buffer */
  196342. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  196343. png_ptr->zstream.next_out = png_ptr->zbuf;
  196344. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196345. }
  196346. /* repeat until all data has been compressed */
  196347. } while (png_ptr->zstream.avail_in);
  196348. /* swap the current and previous rows */
  196349. if (png_ptr->prev_row != NULL)
  196350. {
  196351. png_bytep tptr;
  196352. tptr = png_ptr->prev_row;
  196353. png_ptr->prev_row = png_ptr->row_buf;
  196354. png_ptr->row_buf = tptr;
  196355. }
  196356. /* finish row - updates counters and flushes zlib if last row */
  196357. png_write_finish_row(png_ptr);
  196358. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196359. png_ptr->flush_rows++;
  196360. if (png_ptr->flush_dist > 0 &&
  196361. png_ptr->flush_rows >= png_ptr->flush_dist)
  196362. {
  196363. png_write_flush(png_ptr);
  196364. }
  196365. #endif
  196366. }
  196367. #endif /* PNG_WRITE_SUPPORTED */
  196368. /********* End of inlined file: pngwutil.c *********/
  196369. }
  196370. }
  196371. #ifdef _MSC_VER
  196372. #pragma warning (pop)
  196373. #endif
  196374. BEGIN_JUCE_NAMESPACE
  196375. using namespace pnglibNamespace;
  196376. using ::malloc;
  196377. using ::free;
  196378. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  196379. {
  196380. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  196381. in->read (data, (int) length);
  196382. }
  196383. struct PNGErrorStruct {};
  196384. static void pngErrorCallback (png_structp, png_const_charp)
  196385. {
  196386. throw PNGErrorStruct();
  196387. }
  196388. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  196389. {
  196390. Image* image = 0;
  196391. png_structp pngReadStruct;
  196392. png_infop pngInfoStruct;
  196393. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  196394. if (pngReadStruct != 0)
  196395. {
  196396. pngInfoStruct = png_create_info_struct (pngReadStruct);
  196397. if (pngInfoStruct == 0)
  196398. {
  196399. png_destroy_read_struct (&pngReadStruct, 0, 0);
  196400. return 0;
  196401. }
  196402. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  196403. // read the header..
  196404. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  196405. png_uint_32 width, height;
  196406. int bitDepth, colorType, interlaceType;
  196407. try
  196408. {
  196409. png_read_info (pngReadStruct, pngInfoStruct);
  196410. png_get_IHDR (pngReadStruct, pngInfoStruct,
  196411. &width, &height,
  196412. &bitDepth, &colorType,
  196413. &interlaceType, 0, 0);
  196414. }
  196415. catch (...)
  196416. {
  196417. png_destroy_read_struct (&pngReadStruct, 0, 0);
  196418. return 0;
  196419. }
  196420. if (bitDepth == 16)
  196421. png_set_strip_16 (pngReadStruct);
  196422. if (colorType == PNG_COLOR_TYPE_PALETTE)
  196423. png_set_expand (pngReadStruct);
  196424. if (bitDepth < 8)
  196425. png_set_expand (pngReadStruct);
  196426. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  196427. png_set_expand (pngReadStruct);
  196428. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  196429. png_set_gray_to_rgb (pngReadStruct);
  196430. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  196431. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  196432. || pngInfoStruct->num_trans > 0;
  196433. // Load the image into a temp buffer in the pnglib format..
  196434. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  196435. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  196436. int y;
  196437. for (y = (int) height; --y >= 0;)
  196438. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  196439. bool crashed = false;
  196440. try
  196441. {
  196442. png_read_image (pngReadStruct, rows);
  196443. png_read_end (pngReadStruct, pngInfoStruct);
  196444. }
  196445. catch (...)
  196446. {
  196447. crashed = true;
  196448. }
  196449. juce_free (rows);
  196450. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  196451. if (crashed)
  196452. return 0;
  196453. // now convert the data to a juce image format..
  196454. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  196455. width, height, hasAlphaChan);
  196456. int stride, pixelStride;
  196457. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  196458. uint8* srcRow = tempBuffer;
  196459. uint8* destRow = pixels;
  196460. for (y = 0; y < (int) height; ++y)
  196461. {
  196462. const uint8* src = srcRow;
  196463. srcRow += (width << 2);
  196464. uint8* dest = destRow;
  196465. destRow += stride;
  196466. if (hasAlphaChan)
  196467. {
  196468. for (int i = width; --i >= 0;)
  196469. {
  196470. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  196471. ((PixelARGB*) dest)->premultiply();
  196472. dest += pixelStride;
  196473. src += 4;
  196474. }
  196475. }
  196476. else
  196477. {
  196478. for (int i = width; --i >= 0;)
  196479. {
  196480. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  196481. dest += pixelStride;
  196482. src += 4;
  196483. }
  196484. }
  196485. }
  196486. image->releasePixelDataReadWrite (pixels);
  196487. juce_free (tempBuffer);
  196488. }
  196489. return image;
  196490. }
  196491. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  196492. {
  196493. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  196494. const bool ok = out->write (data, length);
  196495. (void) ok;
  196496. jassert (ok);
  196497. }
  196498. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  196499. {
  196500. const int width = image.getWidth();
  196501. const int height = image.getHeight();
  196502. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  196503. if (pngWriteStruct == 0)
  196504. return false;
  196505. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  196506. if (pngInfoStruct == 0)
  196507. {
  196508. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  196509. return false;
  196510. }
  196511. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  196512. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  196513. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  196514. : PNG_COLOR_TYPE_RGB,
  196515. PNG_INTERLACE_NONE,
  196516. PNG_COMPRESSION_TYPE_BASE,
  196517. PNG_FILTER_TYPE_BASE);
  196518. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  196519. png_color_8 sig_bit;
  196520. sig_bit.red = 8;
  196521. sig_bit.green = 8;
  196522. sig_bit.blue = 8;
  196523. sig_bit.alpha = 8;
  196524. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  196525. png_write_info (pngWriteStruct, pngInfoStruct);
  196526. png_set_shift (pngWriteStruct, &sig_bit);
  196527. png_set_packing (pngWriteStruct);
  196528. for (int y = 0; y < height; ++y)
  196529. {
  196530. uint8* dst = (uint8*) rowData;
  196531. int stride, pixelStride;
  196532. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  196533. const uint8* src = pixels;
  196534. if (image.hasAlphaChannel())
  196535. {
  196536. for (int i = width; --i >= 0;)
  196537. {
  196538. PixelARGB p (*(const PixelARGB*) src);
  196539. p.unpremultiply();
  196540. *dst++ = p.getRed();
  196541. *dst++ = p.getGreen();
  196542. *dst++ = p.getBlue();
  196543. *dst++ = p.getAlpha();
  196544. src += pixelStride;
  196545. }
  196546. }
  196547. else
  196548. {
  196549. for (int i = width; --i >= 0;)
  196550. {
  196551. *dst++ = ((const PixelRGB*) src)->getRed();
  196552. *dst++ = ((const PixelRGB*) src)->getGreen();
  196553. *dst++ = ((const PixelRGB*) src)->getBlue();
  196554. src += pixelStride;
  196555. }
  196556. }
  196557. png_write_rows (pngWriteStruct, &rowData, 1);
  196558. image.releasePixelDataReadOnly (pixels);
  196559. }
  196560. juce_free (rowData);
  196561. png_write_end (pngWriteStruct, pngInfoStruct);
  196562. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  196563. out.flush();
  196564. return true;
  196565. }
  196566. END_JUCE_NAMESPACE
  196567. /********* End of inlined file: juce_PNGLoader.cpp *********/
  196568. #endif
  196569. //==============================================================================
  196570. #if JUCE_WIN32
  196571. /********* Start of inlined file: juce_win32_Files.cpp *********/
  196572. #ifdef _MSC_VER
  196573. #pragma warning (disable: 4514)
  196574. #pragma warning (push)
  196575. #endif
  196576. #include <ctime>
  196577. #ifndef _WIN32_IE
  196578. #define _WIN32_IE 0x0400
  196579. #endif
  196580. #include <shlobj.h>
  196581. #ifndef CSIDL_MYMUSIC
  196582. #define CSIDL_MYMUSIC 0x000d
  196583. #endif
  196584. #ifndef CSIDL_MYVIDEO
  196585. #define CSIDL_MYVIDEO 0x000e
  196586. #endif
  196587. BEGIN_JUCE_NAMESPACE
  196588. #ifdef _MSC_VER
  196589. #pragma warning (pop)
  196590. #endif
  196591. const tchar File::separator = T('\\');
  196592. const tchar* File::separatorString = T("\\");
  196593. bool juce_fileExists (const String& fileName,
  196594. const bool dontCountDirectories) throw()
  196595. {
  196596. if (fileName.isEmpty())
  196597. return false;
  196598. const DWORD attr = GetFileAttributes (fileName);
  196599. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  196600. : (attr != 0xffffffff);
  196601. }
  196602. bool juce_isDirectory (const String& fileName) throw()
  196603. {
  196604. const DWORD attr = GetFileAttributes (fileName);
  196605. return (attr != 0xffffffff)
  196606. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  196607. }
  196608. bool juce_canWriteToFile (const String& fileName) throw()
  196609. {
  196610. const DWORD attr = GetFileAttributes (fileName);
  196611. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  196612. }
  196613. bool juce_setFileReadOnly (const String& fileName,
  196614. bool isReadOnly)
  196615. {
  196616. DWORD attr = GetFileAttributes (fileName);
  196617. if (attr == 0xffffffff)
  196618. return false;
  196619. if (isReadOnly != juce_canWriteToFile (fileName))
  196620. return true;
  196621. if (isReadOnly)
  196622. attr |= FILE_ATTRIBUTE_READONLY;
  196623. else
  196624. attr &= ~FILE_ATTRIBUTE_READONLY;
  196625. return SetFileAttributes (fileName, attr) != FALSE;
  196626. }
  196627. bool File::isHidden() const throw()
  196628. {
  196629. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  196630. }
  196631. bool juce_deleteFile (const String& fileName) throw()
  196632. {
  196633. if (juce_isDirectory (fileName))
  196634. return RemoveDirectory (fileName) != 0;
  196635. return DeleteFile (fileName) != 0;
  196636. }
  196637. bool juce_moveFile (const String& source, const String& dest) throw()
  196638. {
  196639. return MoveFile (source, dest) != 0;
  196640. }
  196641. bool juce_copyFile (const String& source, const String& dest) throw()
  196642. {
  196643. return CopyFile (source, dest, false) != 0;
  196644. }
  196645. void juce_createDirectory (const String& fileName) throw()
  196646. {
  196647. if (! juce_fileExists (fileName, true))
  196648. {
  196649. CreateDirectory (fileName, 0);
  196650. }
  196651. }
  196652. // return 0 if not possible
  196653. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  196654. {
  196655. HANDLE h;
  196656. if (forWriting)
  196657. {
  196658. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  196659. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  196660. if (h != INVALID_HANDLE_VALUE)
  196661. SetFilePointer (h, 0, 0, FILE_END);
  196662. else
  196663. h = 0;
  196664. }
  196665. else
  196666. {
  196667. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  196668. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  196669. if (h == INVALID_HANDLE_VALUE)
  196670. h = 0;
  196671. }
  196672. return (void*) h;
  196673. }
  196674. void juce_fileClose (void* handle) throw()
  196675. {
  196676. CloseHandle (handle);
  196677. }
  196678. int juce_fileRead (void* handle, void* buffer, int size) throw()
  196679. {
  196680. DWORD num = 0;
  196681. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  196682. return num;
  196683. }
  196684. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  196685. {
  196686. DWORD num;
  196687. WriteFile ((HANDLE) handle,
  196688. buffer, size,
  196689. &num, 0);
  196690. return num;
  196691. }
  196692. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  196693. {
  196694. LARGE_INTEGER li;
  196695. li.QuadPart = pos;
  196696. li.LowPart = SetFilePointer ((HANDLE) handle,
  196697. li.LowPart,
  196698. &li.HighPart,
  196699. FILE_BEGIN); // (returns -1 if it fails)
  196700. return li.QuadPart;
  196701. }
  196702. int64 juce_fileGetPosition (void* handle) throw()
  196703. {
  196704. LARGE_INTEGER li;
  196705. li.QuadPart = 0;
  196706. li.LowPart = SetFilePointer ((HANDLE) handle,
  196707. 0, &li.HighPart,
  196708. FILE_CURRENT); // (returns -1 if it fails)
  196709. return jmax ((int64) 0, li.QuadPart);
  196710. }
  196711. void juce_fileFlush (void* handle) throw()
  196712. {
  196713. FlushFileBuffers ((HANDLE) handle);
  196714. }
  196715. int64 juce_getFileSize (const String& fileName) throw()
  196716. {
  196717. WIN32_FILE_ATTRIBUTE_DATA attributes;
  196718. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  196719. {
  196720. return (((int64) attributes.nFileSizeHigh) << 32)
  196721. | attributes.nFileSizeLow;
  196722. }
  196723. return 0;
  196724. }
  196725. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  196726. {
  196727. // tell me if this fails!
  196728. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  196729. #if JUCE_GCC
  196730. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  196731. #else
  196732. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  196733. #endif
  196734. }
  196735. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  196736. {
  196737. #if JUCE_GCC
  196738. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  196739. #else
  196740. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  196741. #endif
  196742. }
  196743. void juce_getFileTimes (const String& fileName,
  196744. int64& modificationTime,
  196745. int64& accessTime,
  196746. int64& creationTime) throw()
  196747. {
  196748. WIN32_FILE_ATTRIBUTE_DATA attributes;
  196749. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  196750. {
  196751. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  196752. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  196753. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  196754. }
  196755. else
  196756. {
  196757. creationTime = accessTime = modificationTime = 0;
  196758. }
  196759. }
  196760. bool juce_setFileTimes (const String& fileName,
  196761. int64 modificationTime,
  196762. int64 accessTime,
  196763. int64 creationTime) throw()
  196764. {
  196765. FILETIME m, a, c;
  196766. if (modificationTime > 0)
  196767. timeToFileTime (modificationTime, &m);
  196768. if (accessTime > 0)
  196769. timeToFileTime (accessTime, &a);
  196770. if (creationTime > 0)
  196771. timeToFileTime (creationTime, &c);
  196772. void* const h = juce_fileOpen (fileName, true);
  196773. bool ok = false;
  196774. if (h != 0)
  196775. {
  196776. ok = SetFileTime ((HANDLE) h,
  196777. (creationTime > 0) ? &c : 0,
  196778. (accessTime > 0) ? &a : 0,
  196779. (modificationTime > 0) ? &m : 0) != 0;
  196780. juce_fileClose (h);
  196781. }
  196782. return ok;
  196783. }
  196784. // return '\0' separated list of strings
  196785. const StringArray juce_getFileSystemRoots() throw()
  196786. {
  196787. TCHAR buffer [2048];
  196788. buffer[0] = 0;
  196789. buffer[1] = 0;
  196790. GetLogicalDriveStrings (2048, buffer);
  196791. TCHAR* n = buffer;
  196792. StringArray roots;
  196793. while (*n != 0)
  196794. {
  196795. roots.add (String (n));
  196796. while (*n++ != 0)
  196797. {
  196798. }
  196799. }
  196800. roots.sort (true);
  196801. return roots;
  196802. }
  196803. const String juce_getVolumeLabel (const String& filenameOnVolume,
  196804. int& volumeSerialNumber) throw()
  196805. {
  196806. TCHAR n [4];
  196807. n[0] = *(const TCHAR*) filenameOnVolume;
  196808. n[1] = L':';
  196809. n[2] = L'\\';
  196810. n[3] = 0;
  196811. TCHAR dest [64];
  196812. DWORD serialNum;
  196813. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  196814. {
  196815. dest[0] = 0;
  196816. serialNum = 0;
  196817. }
  196818. volumeSerialNumber = serialNum;
  196819. return String (dest);
  196820. }
  196821. int64 File::getBytesFreeOnVolume() const throw()
  196822. {
  196823. String fn (getFullPathName());
  196824. if (fn[1] == T(':'))
  196825. fn = fn.substring (0, 2) + T("\\");
  196826. ULARGE_INTEGER spc;
  196827. ULARGE_INTEGER tot;
  196828. ULARGE_INTEGER totFree;
  196829. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  196830. return (int64)(spc.QuadPart);
  196831. return 0;
  196832. }
  196833. static unsigned int getWindowsDriveType (const String& fileName) throw()
  196834. {
  196835. TCHAR n[4];
  196836. n[0] = *(const TCHAR*) fileName;
  196837. n[1] = L':';
  196838. n[2] = L'\\';
  196839. n[3] = 0;
  196840. return GetDriveType (n);
  196841. }
  196842. bool File::isOnCDRomDrive() const throw()
  196843. {
  196844. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  196845. }
  196846. bool File::isOnHardDisk() const throw()
  196847. {
  196848. if (fullPath.isEmpty())
  196849. return false;
  196850. const unsigned int n = getWindowsDriveType (getFullPathName());
  196851. if (fullPath.toLowerCase()[0] <= 'b'
  196852. && fullPath[1] == T(':'))
  196853. {
  196854. return n != DRIVE_REMOVABLE;
  196855. }
  196856. else
  196857. {
  196858. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  196859. }
  196860. }
  196861. bool File::isOnRemovableDrive() const throw()
  196862. {
  196863. if (fullPath.isEmpty())
  196864. return false;
  196865. const unsigned int n = getWindowsDriveType (getFullPathName());
  196866. return n == DRIVE_CDROM
  196867. || n == DRIVE_REMOTE
  196868. || n == DRIVE_REMOVABLE
  196869. || n == DRIVE_RAMDISK;
  196870. }
  196871. #define MAX_PATH_CHARS (MAX_PATH + 256)
  196872. static const File juce_getSpecialFolderPath (int type) throw()
  196873. {
  196874. WCHAR path [MAX_PATH_CHARS];
  196875. if (SHGetSpecialFolderPath (0, path, type, 0))
  196876. return File (String (path));
  196877. return File::nonexistent;
  196878. }
  196879. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  196880. {
  196881. int csidlType = 0;
  196882. switch (type)
  196883. {
  196884. case userHomeDirectory:
  196885. case userDocumentsDirectory:
  196886. csidlType = CSIDL_PERSONAL;
  196887. break;
  196888. case userDesktopDirectory:
  196889. csidlType = CSIDL_DESKTOP;
  196890. break;
  196891. case userApplicationDataDirectory:
  196892. csidlType = CSIDL_APPDATA;
  196893. break;
  196894. case commonApplicationDataDirectory:
  196895. csidlType = CSIDL_COMMON_APPDATA;
  196896. break;
  196897. case globalApplicationsDirectory:
  196898. csidlType = CSIDL_PROGRAM_FILES;
  196899. break;
  196900. case userMusicDirectory:
  196901. csidlType = CSIDL_MYMUSIC;
  196902. break;
  196903. case userMoviesDirectory:
  196904. csidlType = CSIDL_MYVIDEO;
  196905. break;
  196906. case tempDirectory:
  196907. {
  196908. WCHAR dest [2048];
  196909. dest[0] = 0;
  196910. GetTempPath (2048, dest);
  196911. return File (String (dest));
  196912. }
  196913. case currentExecutableFile:
  196914. case currentApplicationFile:
  196915. {
  196916. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  196917. WCHAR dest [MAX_PATH_CHARS];
  196918. dest[0] = 0;
  196919. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  196920. return File (String (dest));
  196921. }
  196922. break;
  196923. default:
  196924. jassertfalse // unknown type?
  196925. return File::nonexistent;
  196926. }
  196927. return juce_getSpecialFolderPath (csidlType);
  196928. }
  196929. void juce_setCurrentExecutableFileName (const String&) throw()
  196930. {
  196931. // n/a on windows
  196932. }
  196933. const File File::getCurrentWorkingDirectory() throw()
  196934. {
  196935. WCHAR dest [MAX_PATH_CHARS];
  196936. dest[0] = 0;
  196937. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  196938. return File (String (dest));
  196939. }
  196940. bool File::setAsCurrentWorkingDirectory() const throw()
  196941. {
  196942. return SetCurrentDirectory (getFullPathName()) != FALSE;
  196943. }
  196944. template <class FindDataType>
  196945. static void getFindFileInfo (FindDataType& findData,
  196946. String& filename, bool* const isDir, bool* const isHidden,
  196947. int64* const fileSize, Time* const modTime, Time* const creationTime,
  196948. bool* const isReadOnly) throw()
  196949. {
  196950. filename = findData.cFileName;
  196951. if (isDir != 0)
  196952. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  196953. if (isHidden != 0)
  196954. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  196955. if (fileSize != 0)
  196956. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  196957. if (modTime != 0)
  196958. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  196959. if (creationTime != 0)
  196960. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  196961. if (isReadOnly != 0)
  196962. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  196963. }
  196964. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  196965. bool* isDir, bool* isHidden, int64* fileSize,
  196966. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  196967. {
  196968. String wc (directory);
  196969. if (! wc.endsWithChar (File::separator))
  196970. wc += File::separator;
  196971. wc += wildCard;
  196972. WIN32_FIND_DATA findData;
  196973. HANDLE h = FindFirstFile (wc, &findData);
  196974. if (h != INVALID_HANDLE_VALUE)
  196975. {
  196976. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  196977. modTime, creationTime, isReadOnly);
  196978. return h;
  196979. }
  196980. firstResult = String::empty;
  196981. return 0;
  196982. }
  196983. bool juce_findFileNext (void* handle, String& resultFile,
  196984. bool* isDir, bool* isHidden, int64* fileSize,
  196985. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  196986. {
  196987. WIN32_FIND_DATA findData;
  196988. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  196989. {
  196990. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  196991. modTime, creationTime, isReadOnly);
  196992. return true;
  196993. }
  196994. resultFile = String::empty;
  196995. return false;
  196996. }
  196997. void juce_findFileClose (void* handle) throw()
  196998. {
  196999. FindClose (handle);
  197000. }
  197001. bool juce_launchFile (const String& fileName,
  197002. const String& parameters) throw()
  197003. {
  197004. HINSTANCE hInstance = 0;
  197005. JUCE_TRY
  197006. {
  197007. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  197008. }
  197009. JUCE_CATCH_ALL
  197010. return hInstance > (HINSTANCE) 32;
  197011. }
  197012. struct NamedPipeInternal
  197013. {
  197014. HANDLE pipeH;
  197015. HANDLE cancelEvent;
  197016. bool connected, createdPipe;
  197017. NamedPipeInternal()
  197018. : pipeH (0),
  197019. cancelEvent (0),
  197020. connected (false),
  197021. createdPipe (false)
  197022. {
  197023. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  197024. }
  197025. ~NamedPipeInternal()
  197026. {
  197027. disconnect();
  197028. if (pipeH != 0)
  197029. CloseHandle (pipeH);
  197030. CloseHandle (cancelEvent);
  197031. }
  197032. bool connect (const int timeOutMs)
  197033. {
  197034. if (! createdPipe)
  197035. return true;
  197036. if (! connected)
  197037. {
  197038. OVERLAPPED over;
  197039. zerostruct (over);
  197040. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197041. if (ConnectNamedPipe (pipeH, &over))
  197042. {
  197043. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  197044. }
  197045. else
  197046. {
  197047. const int err = GetLastError();
  197048. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  197049. {
  197050. HANDLE handles[] = { over.hEvent, cancelEvent };
  197051. if (WaitForMultipleObjects (2, handles, FALSE,
  197052. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  197053. connected = true;
  197054. }
  197055. else if (err == ERROR_PIPE_CONNECTED)
  197056. {
  197057. connected = true;
  197058. }
  197059. }
  197060. CloseHandle (over.hEvent);
  197061. }
  197062. return connected;
  197063. }
  197064. void disconnect()
  197065. {
  197066. if (connected)
  197067. {
  197068. DisconnectNamedPipe (pipeH);
  197069. connected = false;
  197070. }
  197071. }
  197072. };
  197073. void NamedPipe::close()
  197074. {
  197075. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197076. delete intern;
  197077. internal = 0;
  197078. }
  197079. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  197080. {
  197081. close();
  197082. NamedPipeInternal* const intern = new NamedPipeInternal();
  197083. String file ("\\\\.\\pipe\\");
  197084. file += pipeName;
  197085. intern->createdPipe = createPipe;
  197086. if (createPipe)
  197087. {
  197088. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  197089. 1, 64, 64, 0, NULL);
  197090. }
  197091. else
  197092. {
  197093. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  197094. FILE_FLAG_OVERLAPPED, 0);
  197095. }
  197096. if (intern->pipeH != INVALID_HANDLE_VALUE)
  197097. {
  197098. internal = intern;
  197099. return true;
  197100. }
  197101. delete intern;
  197102. return false;
  197103. }
  197104. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  197105. {
  197106. int bytesRead = -1;
  197107. bool waitAgain = true;
  197108. while (waitAgain && internal != 0)
  197109. {
  197110. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197111. waitAgain = false;
  197112. if (! intern->connect (timeOutMilliseconds))
  197113. break;
  197114. if (maxBytesToRead <= 0)
  197115. return 0;
  197116. OVERLAPPED over;
  197117. zerostruct (over);
  197118. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197119. unsigned long numRead;
  197120. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  197121. {
  197122. bytesRead = (int) numRead;
  197123. }
  197124. else if (GetLastError() == ERROR_IO_PENDING)
  197125. {
  197126. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197127. if (WaitForMultipleObjects (2, handles, FALSE,
  197128. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197129. : INFINITE) == WAIT_OBJECT_0)
  197130. {
  197131. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  197132. {
  197133. bytesRead = (int) numRead;
  197134. }
  197135. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197136. {
  197137. intern->disconnect();
  197138. waitAgain = true;
  197139. }
  197140. }
  197141. }
  197142. else
  197143. {
  197144. waitAgain = internal != 0;
  197145. Sleep (5);
  197146. }
  197147. CloseHandle (over.hEvent);
  197148. }
  197149. return bytesRead;
  197150. }
  197151. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  197152. {
  197153. int bytesWritten = -1;
  197154. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197155. if (intern != 0 && intern->connect (timeOutMilliseconds))
  197156. {
  197157. if (numBytesToWrite <= 0)
  197158. return 0;
  197159. OVERLAPPED over;
  197160. zerostruct (over);
  197161. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197162. unsigned long numWritten;
  197163. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  197164. {
  197165. bytesWritten = (int) numWritten;
  197166. }
  197167. else if (GetLastError() == ERROR_IO_PENDING)
  197168. {
  197169. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197170. if (WaitForMultipleObjects (2, handles, FALSE, timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197171. : INFINITE) == WAIT_OBJECT_0)
  197172. {
  197173. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  197174. {
  197175. bytesWritten = (int) numWritten;
  197176. }
  197177. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197178. {
  197179. intern->disconnect();
  197180. }
  197181. }
  197182. }
  197183. CloseHandle (over.hEvent);
  197184. }
  197185. return bytesWritten;
  197186. }
  197187. void NamedPipe::cancelPendingReads()
  197188. {
  197189. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197190. if (intern != 0)
  197191. SetEvent (intern->cancelEvent);
  197192. }
  197193. END_JUCE_NAMESPACE
  197194. /********* End of inlined file: juce_win32_Files.cpp *********/
  197195. /********* Start of inlined file: juce_win32_Network.cpp *********/
  197196. #ifdef _MSC_VER
  197197. #pragma warning (disable: 4514)
  197198. #pragma warning (push)
  197199. #endif
  197200. #include <wininet.h>
  197201. #include <nb30.h>
  197202. #include <iphlpapi.h>
  197203. #include <mapi.h>
  197204. BEGIN_JUCE_NAMESPACE
  197205. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197206. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197207. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197208. #ifndef DOXYGEN
  197209. // use with DynamicLibraryLoader to simplify importing functions
  197210. //
  197211. // functionName: function to import
  197212. // localFunctionName: name you want to use to actually call it (must be different)
  197213. // returnType: the return type
  197214. // object: the DynamicLibraryLoader to use
  197215. // params: list of params (bracketed)
  197216. //
  197217. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  197218. typedef returnType (WINAPI *type##localFunctionName) params; \
  197219. type##localFunctionName localFunctionName \
  197220. = (type##localFunctionName)object.findProcAddress (#functionName);
  197221. // loads and unloads a DLL automatically
  197222. class JUCE_API DynamicLibraryLoader
  197223. {
  197224. public:
  197225. DynamicLibraryLoader (const String& name);
  197226. ~DynamicLibraryLoader();
  197227. void* findProcAddress (const String& functionName);
  197228. private:
  197229. void* libHandle;
  197230. };
  197231. #endif
  197232. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197233. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197234. #ifndef INTERNET_FLAG_NEED_FILE
  197235. #define INTERNET_FLAG_NEED_FILE 0x00000010
  197236. #endif
  197237. #ifdef _MSC_VER
  197238. #pragma warning (pop)
  197239. #endif
  197240. bool juce_isOnLine()
  197241. {
  197242. DWORD connectionType;
  197243. return InternetGetConnectedState (&connectionType, 0) != 0
  197244. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  197245. }
  197246. struct ConnectionAndRequestStruct
  197247. {
  197248. HINTERNET connection, request;
  197249. };
  197250. static HINTERNET sessionHandle = 0;
  197251. void* juce_openInternetFile (const String& url,
  197252. const String& headers,
  197253. const MemoryBlock& postData,
  197254. const bool isPost,
  197255. URL::OpenStreamProgressCallback* callback,
  197256. void* callbackContext)
  197257. {
  197258. if (sessionHandle == 0)
  197259. sessionHandle = InternetOpen (_T("juce"),
  197260. INTERNET_OPEN_TYPE_PRECONFIG,
  197261. 0, 0, 0);
  197262. if (sessionHandle != 0)
  197263. {
  197264. // break up the url..
  197265. TCHAR file[1024], server[1024];
  197266. URL_COMPONENTS uc;
  197267. zerostruct (uc);
  197268. uc.dwStructSize = sizeof (uc);
  197269. uc.dwUrlPathLength = sizeof (file);
  197270. uc.dwHostNameLength = sizeof (server);
  197271. uc.lpszUrlPath = file;
  197272. uc.lpszHostName = server;
  197273. if (InternetCrackUrl (url, 0, 0, &uc))
  197274. {
  197275. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  197276. HINTERNET connection = InternetConnect (sessionHandle,
  197277. uc.lpszHostName,
  197278. uc.nPort,
  197279. _T(""), _T(""),
  197280. isFtp ? INTERNET_SERVICE_FTP
  197281. : INTERNET_SERVICE_HTTP,
  197282. 0, 0);
  197283. if (connection != 0)
  197284. {
  197285. if (isFtp)
  197286. {
  197287. HINTERNET request = FtpOpenFile (connection,
  197288. uc.lpszUrlPath,
  197289. GENERIC_READ,
  197290. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  197291. 0);
  197292. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  197293. result->connection = connection;
  197294. result->request = request;
  197295. return result;
  197296. }
  197297. else
  197298. {
  197299. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  197300. HINTERNET request = HttpOpenRequest (connection,
  197301. isPost ? _T("POST")
  197302. : _T("GET"),
  197303. uc.lpszUrlPath,
  197304. 0, 0, mimeTypes,
  197305. INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE,
  197306. 0);
  197307. if (request != 0)
  197308. {
  197309. INTERNET_BUFFERS buffers;
  197310. zerostruct (buffers);
  197311. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  197312. buffers.lpcszHeader = (LPCTSTR) headers;
  197313. buffers.dwHeadersLength = headers.length();
  197314. buffers.dwBufferTotal = (DWORD) postData.getSize();
  197315. ConnectionAndRequestStruct* result = 0;
  197316. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  197317. {
  197318. int bytesSent = 0;
  197319. for (;;)
  197320. {
  197321. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  197322. DWORD bytesDone = 0;
  197323. if (bytesToDo > 0
  197324. && ! InternetWriteFile (request,
  197325. ((const char*) postData.getData()) + bytesSent,
  197326. bytesToDo, &bytesDone))
  197327. {
  197328. break;
  197329. }
  197330. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  197331. {
  197332. result = new ConnectionAndRequestStruct();
  197333. result->connection = connection;
  197334. result->request = request;
  197335. HttpEndRequest (request, 0, 0, 0);
  197336. return result;
  197337. }
  197338. bytesSent += bytesDone;
  197339. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  197340. break;
  197341. }
  197342. }
  197343. InternetCloseHandle (request);
  197344. }
  197345. InternetCloseHandle (connection);
  197346. }
  197347. }
  197348. }
  197349. }
  197350. return 0;
  197351. }
  197352. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  197353. {
  197354. DWORD bytesRead = 0;
  197355. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  197356. if (crs != 0)
  197357. InternetReadFile (crs->request,
  197358. buffer, bytesToRead,
  197359. &bytesRead);
  197360. return bytesRead;
  197361. }
  197362. int juce_seekInInternetFile (void* handle, int newPosition)
  197363. {
  197364. if (handle != 0)
  197365. {
  197366. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  197367. return InternetSetFilePointer (crs->request,
  197368. newPosition, 0,
  197369. FILE_BEGIN, 0);
  197370. }
  197371. else
  197372. {
  197373. return -1;
  197374. }
  197375. }
  197376. void juce_closeInternetFile (void* handle)
  197377. {
  197378. if (handle != 0)
  197379. {
  197380. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  197381. InternetCloseHandle (crs->request);
  197382. InternetCloseHandle (crs->connection);
  197383. delete crs;
  197384. }
  197385. }
  197386. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  197387. {
  197388. int numFound = 0;
  197389. DynamicLibraryLoader dll ("iphlpapi.dll");
  197390. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  197391. if (getAdaptersInfo != 0)
  197392. {
  197393. ULONG len = sizeof (IP_ADAPTER_INFO);
  197394. MemoryBlock mb;
  197395. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  197396. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  197397. {
  197398. mb.setSize (len);
  197399. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  197400. }
  197401. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  197402. {
  197403. PIP_ADAPTER_INFO adapter = adapterInfo;
  197404. while (adapter != 0)
  197405. {
  197406. int64 mac = 0;
  197407. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  197408. mac = (mac << 8) | adapter->Address[i];
  197409. if (littleEndian)
  197410. mac = (int64) swapByteOrder ((uint64) mac);
  197411. if (numFound < maxNum && mac != 0)
  197412. addresses [numFound++] = mac;
  197413. adapter = adapter->Next;
  197414. }
  197415. }
  197416. }
  197417. return numFound;
  197418. }
  197419. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  197420. {
  197421. int numFound = 0;
  197422. DynamicLibraryLoader dll ("netapi32.dll");
  197423. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  197424. if (NetbiosCall != 0)
  197425. {
  197426. NCB ncb;
  197427. zerostruct (ncb);
  197428. typedef struct _ASTAT_
  197429. {
  197430. ADAPTER_STATUS adapt;
  197431. NAME_BUFFER NameBuff [30];
  197432. } ASTAT;
  197433. ASTAT astat;
  197434. zerostruct (astat);
  197435. LANA_ENUM enums;
  197436. zerostruct (enums);
  197437. ncb.ncb_command = NCBENUM;
  197438. ncb.ncb_buffer = (unsigned char*) &enums;
  197439. ncb.ncb_length = sizeof (LANA_ENUM);
  197440. NetbiosCall (&ncb);
  197441. for (int i = 0; i < enums.length; ++i)
  197442. {
  197443. zerostruct (ncb);
  197444. ncb.ncb_command = NCBRESET;
  197445. ncb.ncb_lana_num = enums.lana[i];
  197446. if (NetbiosCall (&ncb) == 0)
  197447. {
  197448. zerostruct (ncb);
  197449. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  197450. ncb.ncb_command = NCBASTAT;
  197451. ncb.ncb_lana_num = enums.lana[i];
  197452. ncb.ncb_buffer = (unsigned char*) &astat;
  197453. ncb.ncb_length = sizeof (ASTAT);
  197454. if (NetbiosCall (&ncb) == 0)
  197455. {
  197456. if (astat.adapt.adapter_type == 0xfe)
  197457. {
  197458. int64 mac = 0;
  197459. for (unsigned int i = 0; i < 6; ++i)
  197460. mac = (mac << 8) | astat.adapt.adapter_address[i];
  197461. if (littleEndian)
  197462. mac = (int64) swapByteOrder ((uint64) mac);
  197463. if (numFound < maxNum && mac != 0)
  197464. addresses [numFound++] = mac;
  197465. }
  197466. }
  197467. }
  197468. }
  197469. }
  197470. return numFound;
  197471. }
  197472. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  197473. {
  197474. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  197475. if (numFound == 0)
  197476. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  197477. return numFound;
  197478. }
  197479. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  197480. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  197481. const String& emailSubject,
  197482. const String& bodyText,
  197483. const StringArray& filesToAttach)
  197484. {
  197485. HMODULE h = LoadLibraryA ("MAPI32.dll");
  197486. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  197487. bool ok = false;
  197488. if (mapiSendMail != 0)
  197489. {
  197490. MapiMessage message;
  197491. zerostruct (message);
  197492. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  197493. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  197494. MapiRecipDesc recip;
  197495. zerostruct (recip);
  197496. recip.ulRecipClass = MAPI_TO;
  197497. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  197498. message.nRecipCount = 1;
  197499. message.lpRecips = &recip;
  197500. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  197501. mb.fillWith (0);
  197502. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  197503. message.nFileCount = filesToAttach.size();
  197504. message.lpFiles = files;
  197505. for (int i = 0; i < filesToAttach.size(); ++i)
  197506. {
  197507. files[i].nPosition = (ULONG) -1;
  197508. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  197509. }
  197510. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  197511. }
  197512. FreeLibrary (h);
  197513. return ok;
  197514. }
  197515. END_JUCE_NAMESPACE
  197516. /********* End of inlined file: juce_win32_Network.cpp *********/
  197517. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  197518. BEGIN_JUCE_NAMESPACE
  197519. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  197520. bool AlertWindow::showNativeDialogBox (const String& title,
  197521. const String& bodyText,
  197522. bool isOkCancel)
  197523. {
  197524. return MessageBox (0, bodyText, title,
  197525. (isOkCancel) ? MB_OKCANCEL
  197526. : MB_OK) == IDOK;
  197527. }
  197528. #endif
  197529. void PlatformUtilities::beep()
  197530. {
  197531. MessageBeep (MB_OK);
  197532. }
  197533. #if JUCE_MSVC
  197534. #pragma warning (disable : 4127) // "Conditional expression is constant" warning
  197535. #endif
  197536. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  197537. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  197538. {
  197539. if (OpenClipboard (0) != 0)
  197540. {
  197541. if (EmptyClipboard() != 0)
  197542. {
  197543. const int len = text.length();
  197544. if (len > 0)
  197545. {
  197546. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  197547. (len + 1) * sizeof (wchar_t));
  197548. if (bufH != 0)
  197549. {
  197550. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  197551. text.copyToBuffer (data, len);
  197552. GlobalUnlock (bufH);
  197553. SetClipboardData (CF_UNICODETEXT, bufH);
  197554. }
  197555. }
  197556. }
  197557. CloseClipboard();
  197558. }
  197559. }
  197560. const String SystemClipboard::getTextFromClipboard() throw()
  197561. {
  197562. String result;
  197563. if (OpenClipboard (0) != 0)
  197564. {
  197565. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  197566. if (bufH != 0)
  197567. {
  197568. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  197569. if (data != 0)
  197570. {
  197571. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  197572. GlobalUnlock (bufH);
  197573. }
  197574. }
  197575. CloseClipboard();
  197576. }
  197577. return result;
  197578. }
  197579. #endif
  197580. END_JUCE_NAMESPACE
  197581. /********* End of inlined file: juce_win32_Misc.cpp *********/
  197582. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  197583. #ifdef _MSC_VER
  197584. #pragma warning (disable: 4514)
  197585. #pragma warning (push)
  197586. #endif
  197587. #include <float.h>
  197588. BEGIN_JUCE_NAMESPACE
  197589. #ifdef _MSC_VER
  197590. #pragma warning (pop)
  197591. #endif
  197592. static HKEY findKeyForPath (String name,
  197593. const bool createForWriting,
  197594. String& valueName) throw()
  197595. {
  197596. HKEY rootKey = 0;
  197597. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  197598. rootKey = HKEY_CURRENT_USER;
  197599. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  197600. rootKey = HKEY_LOCAL_MACHINE;
  197601. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  197602. rootKey = HKEY_CLASSES_ROOT;
  197603. if (rootKey != 0)
  197604. {
  197605. name = name.substring (name.indexOfChar (T('\\')) + 1);
  197606. const int lastSlash = name.lastIndexOfChar (T('\\'));
  197607. valueName = name.substring (lastSlash + 1);
  197608. name = name.substring (0, lastSlash);
  197609. HKEY key;
  197610. DWORD result;
  197611. if (createForWriting)
  197612. {
  197613. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  197614. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  197615. return key;
  197616. }
  197617. else
  197618. {
  197619. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  197620. return key;
  197621. }
  197622. }
  197623. return 0;
  197624. }
  197625. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  197626. const String& defaultValue)
  197627. {
  197628. String valueName, s;
  197629. HKEY k = findKeyForPath (regValuePath, false, valueName);
  197630. if (k != 0)
  197631. {
  197632. WCHAR buffer [2048];
  197633. unsigned long bufferSize = sizeof (buffer);
  197634. DWORD type = REG_SZ;
  197635. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  197636. s = buffer;
  197637. else
  197638. s = defaultValue;
  197639. RegCloseKey (k);
  197640. }
  197641. return s;
  197642. }
  197643. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  197644. const String& value)
  197645. {
  197646. String valueName;
  197647. HKEY k = findKeyForPath (regValuePath, true, valueName);
  197648. if (k != 0)
  197649. {
  197650. RegSetValueEx (k, valueName, 0, REG_SZ,
  197651. (const BYTE*) (const WCHAR*) value,
  197652. sizeof (WCHAR) * (value.length() + 1));
  197653. RegCloseKey (k);
  197654. }
  197655. }
  197656. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  197657. {
  197658. bool exists = false;
  197659. String valueName;
  197660. HKEY k = findKeyForPath (regValuePath, false, valueName);
  197661. if (k != 0)
  197662. {
  197663. unsigned char buffer [2048];
  197664. unsigned long bufferSize = sizeof (buffer);
  197665. DWORD type = 0;
  197666. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  197667. exists = true;
  197668. RegCloseKey (k);
  197669. }
  197670. return exists;
  197671. }
  197672. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  197673. {
  197674. String valueName;
  197675. HKEY k = findKeyForPath (regValuePath, true, valueName);
  197676. if (k != 0)
  197677. {
  197678. RegDeleteValue (k, valueName);
  197679. RegCloseKey (k);
  197680. }
  197681. }
  197682. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  197683. {
  197684. String valueName;
  197685. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  197686. if (k != 0)
  197687. {
  197688. RegDeleteKey (k, valueName);
  197689. RegCloseKey (k);
  197690. }
  197691. }
  197692. bool juce_IsRunningInWine() throw()
  197693. {
  197694. HKEY key;
  197695. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  197696. {
  197697. RegCloseKey (key);
  197698. return true;
  197699. }
  197700. return false;
  197701. }
  197702. static void* currentModuleHandle = 0;
  197703. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  197704. {
  197705. if (currentModuleHandle == 0)
  197706. currentModuleHandle = GetModuleHandle (0);
  197707. return currentModuleHandle;
  197708. }
  197709. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  197710. {
  197711. currentModuleHandle = newHandle;
  197712. }
  197713. void PlatformUtilities::fpuReset()
  197714. {
  197715. #if JUCE_MSVC
  197716. _clearfp();
  197717. #endif
  197718. }
  197719. END_JUCE_NAMESPACE
  197720. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  197721. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  197722. // Auto-link the other win32 libs that are needed by library calls..
  197723. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  197724. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  197725. // Auto-links to various win32 libs that are needed by library calls..
  197726. #pragma comment(lib, "kernel32.lib")
  197727. #pragma comment(lib, "user32.lib")
  197728. #pragma comment(lib, "shell32.lib")
  197729. #pragma comment(lib, "gdi32.lib")
  197730. #pragma comment(lib, "vfw32.lib")
  197731. #pragma comment(lib, "comdlg32.lib")
  197732. #pragma comment(lib, "winmm.lib")
  197733. #pragma comment(lib, "wininet.lib")
  197734. #pragma comment(lib, "ole32.lib")
  197735. #pragma comment(lib, "advapi32.lib")
  197736. #pragma comment(lib, "ws2_32.lib")
  197737. #pragma comment(lib, "comsupp.lib")
  197738. #if JUCE_OPENGL
  197739. #pragma comment(lib, "OpenGL32.Lib")
  197740. #pragma comment(lib, "GlU32.Lib")
  197741. #endif
  197742. #if JUCE_QUICKTIME
  197743. #pragma comment (lib, "QTMLClient.lib")
  197744. #endif
  197745. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  197746. #endif
  197747. BEGIN_JUCE_NAMESPACE
  197748. extern void juce_updateMultiMonitorInfo() throw();
  197749. extern void juce_initialiseThreadEvents() throw();
  197750. void Logger::outputDebugString (const String& text) throw()
  197751. {
  197752. OutputDebugString (text + T("\n"));
  197753. }
  197754. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  197755. {
  197756. String text;
  197757. va_list args;
  197758. va_start (args, format);
  197759. text.vprintf(format, args);
  197760. outputDebugString (text);
  197761. }
  197762. static int64 hiResTicksPerSecond;
  197763. static double hiResTicksScaleFactor;
  197764. #if JUCE_USE_INTRINSICS
  197765. // CPU info functions using intrinsics...
  197766. #pragma intrinsic (__cpuid)
  197767. #pragma intrinsic (__rdtsc)
  197768. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  197769. {
  197770. int info [4];
  197771. __cpuid (info, 1);
  197772. if (familyModel != 0)
  197773. *familyModel = info [0];
  197774. if (extFeatures != 0)
  197775. *extFeatures = info[1];
  197776. return info[3];
  197777. }*/
  197778. const String SystemStats::getCpuVendor() throw()
  197779. {
  197780. int info [4];
  197781. __cpuid (info, 0);
  197782. char v [12];
  197783. memcpy (v, info + 1, 4);
  197784. memcpy (v + 4, info + 3, 4);
  197785. memcpy (v + 8, info + 2, 4);
  197786. return String (v, 12);
  197787. }
  197788. #else
  197789. // CPU info functions using old fashioned inline asm...
  197790. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  197791. {
  197792. unsigned int cpu = 0;
  197793. unsigned int ext = 0;
  197794. unsigned int family = 0;
  197795. #if JUCE_GCC
  197796. unsigned int dummy = 0;
  197797. #endif
  197798. #ifndef __MINGW32__
  197799. __try
  197800. #endif
  197801. {
  197802. #if JUCE_GCC
  197803. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  197804. #else
  197805. __asm
  197806. {
  197807. mov eax, 1
  197808. cpuid
  197809. mov cpu, edx
  197810. mov family, eax
  197811. mov ext, ebx
  197812. }
  197813. #endif
  197814. }
  197815. #ifndef __MINGW32__
  197816. __except (EXCEPTION_EXECUTE_HANDLER)
  197817. {
  197818. return 0;
  197819. }
  197820. #endif
  197821. if (familyModel != 0)
  197822. *familyModel = family;
  197823. if (extFeatures != 0)
  197824. *extFeatures = ext;
  197825. return cpu;
  197826. }*/
  197827. static void juce_getCpuVendor (char* const v)
  197828. {
  197829. int vendor[4];
  197830. zeromem (vendor, 16);
  197831. #ifdef JUCE_64BIT
  197832. #else
  197833. #ifndef __MINGW32__
  197834. __try
  197835. #endif
  197836. {
  197837. #if JUCE_GCC
  197838. unsigned int dummy = 0;
  197839. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  197840. #else
  197841. __asm
  197842. {
  197843. mov eax, 0
  197844. cpuid
  197845. mov [vendor], ebx
  197846. mov [vendor + 4], edx
  197847. mov [vendor + 8], ecx
  197848. }
  197849. #endif
  197850. }
  197851. #ifndef __MINGW32__
  197852. __except (EXCEPTION_EXECUTE_HANDLER)
  197853. {
  197854. *v = 0;
  197855. }
  197856. #endif
  197857. #endif
  197858. memcpy (v, vendor, 16);
  197859. }
  197860. const String SystemStats::getCpuVendor() throw()
  197861. {
  197862. char v [16];
  197863. juce_getCpuVendor (v);
  197864. return String (v, 16);
  197865. }
  197866. #endif
  197867. struct CPUFlags
  197868. {
  197869. bool hasMMX : 1;
  197870. bool hasSSE : 1;
  197871. bool hasSSE2 : 1;
  197872. bool has3DNow : 1;
  197873. };
  197874. static CPUFlags cpuFlags;
  197875. bool SystemStats::hasMMX() throw()
  197876. {
  197877. return cpuFlags.hasMMX;
  197878. }
  197879. bool SystemStats::hasSSE() throw()
  197880. {
  197881. return cpuFlags.hasSSE;
  197882. }
  197883. bool SystemStats::hasSSE2() throw()
  197884. {
  197885. return cpuFlags.hasSSE2;
  197886. }
  197887. bool SystemStats::has3DNow() throw()
  197888. {
  197889. return cpuFlags.has3DNow;
  197890. }
  197891. void SystemStats::initialiseStats() throw()
  197892. {
  197893. juce_initialiseThreadEvents();
  197894. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  197895. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  197896. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  197897. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  197898. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  197899. #else
  197900. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  197901. #endif
  197902. LARGE_INTEGER f;
  197903. QueryPerformanceFrequency (&f);
  197904. hiResTicksPerSecond = f.QuadPart;
  197905. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  197906. String s (SystemStats::getJUCEVersion());
  197907. #ifdef JUCE_DEBUG
  197908. const MMRESULT res = timeBeginPeriod (1);
  197909. jassert (res == TIMERR_NOERROR);
  197910. #else
  197911. timeBeginPeriod (1);
  197912. #endif
  197913. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  197914. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  197915. #endif
  197916. }
  197917. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  197918. {
  197919. OSVERSIONINFO info;
  197920. info.dwOSVersionInfoSize = sizeof (info);
  197921. GetVersionEx (&info);
  197922. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  197923. {
  197924. switch (info.dwMajorVersion)
  197925. {
  197926. case 5:
  197927. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  197928. case 6:
  197929. return WinVista;
  197930. default:
  197931. jassertfalse // !! not a supported OS!
  197932. break;
  197933. }
  197934. }
  197935. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  197936. {
  197937. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  197938. return Win98;
  197939. }
  197940. return UnknownOS;
  197941. }
  197942. const String SystemStats::getOperatingSystemName() throw()
  197943. {
  197944. const char* name = "Unknown OS";
  197945. switch (getOperatingSystemType())
  197946. {
  197947. case WinVista:
  197948. name = "Windows Vista";
  197949. break;
  197950. case WinXP:
  197951. name = "Windows XP";
  197952. break;
  197953. case Win2000:
  197954. name = "Windows 2000";
  197955. break;
  197956. case Win98:
  197957. name = "Windows 98";
  197958. break;
  197959. default:
  197960. jassertfalse // !! new type of OS?
  197961. break;
  197962. }
  197963. return name;
  197964. }
  197965. bool SystemStats::isOperatingSystem64Bit() throw()
  197966. {
  197967. #ifdef _WIN64
  197968. return true;
  197969. #else
  197970. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  197971. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  197972. BOOL isWow64 = FALSE;
  197973. return (fnIsWow64Process != 0)
  197974. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  197975. && (isWow64 != FALSE);
  197976. #endif
  197977. }
  197978. int SystemStats::getMemorySizeInMegabytes() throw()
  197979. {
  197980. MEMORYSTATUS mem;
  197981. GlobalMemoryStatus (&mem);
  197982. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  197983. }
  197984. int SystemStats::getNumCpus() throw()
  197985. {
  197986. SYSTEM_INFO systemInfo;
  197987. GetSystemInfo (&systemInfo);
  197988. return systemInfo.dwNumberOfProcessors;
  197989. }
  197990. uint32 juce_millisecondsSinceStartup() throw()
  197991. {
  197992. return (uint32) GetTickCount();
  197993. }
  197994. int64 Time::getHighResolutionTicks() throw()
  197995. {
  197996. LARGE_INTEGER ticks;
  197997. QueryPerformanceCounter (&ticks);
  197998. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  197999. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198000. // fix for a very obscure PCI hardware bug that can make the counter
  198001. // sometimes jump forwards by a few seconds..
  198002. static int64 hiResTicksOffset = 0;
  198003. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198004. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198005. hiResTicksOffset = newOffset;
  198006. return ticks.QuadPart + hiResTicksOffset;
  198007. }
  198008. double Time::getMillisecondCounterHiRes() throw()
  198009. {
  198010. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198011. }
  198012. int64 Time::getHighResolutionTicksPerSecond() throw()
  198013. {
  198014. return hiResTicksPerSecond;
  198015. }
  198016. int64 SystemStats::getClockCycleCounter() throw()
  198017. {
  198018. #if JUCE_USE_INTRINSICS
  198019. // MS intrinsics version...
  198020. return __rdtsc();
  198021. #elif JUCE_GCC
  198022. // GNU inline asm version...
  198023. unsigned int hi = 0, lo = 0;
  198024. __asm__ __volatile__ (
  198025. "xor %%eax, %%eax \n\
  198026. xor %%edx, %%edx \n\
  198027. rdtsc \n\
  198028. movl %%eax, %[lo] \n\
  198029. movl %%edx, %[hi]"
  198030. :
  198031. : [hi] "m" (hi),
  198032. [lo] "m" (lo)
  198033. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198034. return (int64) ((((uint64) hi) << 32) | lo);
  198035. #else
  198036. // MSVC inline asm version...
  198037. unsigned int hi = 0, lo = 0;
  198038. __asm
  198039. {
  198040. xor eax, eax
  198041. xor edx, edx
  198042. rdtsc
  198043. mov lo, eax
  198044. mov hi, edx
  198045. }
  198046. return (int64) ((((uint64) hi) << 32) | lo);
  198047. #endif
  198048. }
  198049. int SystemStats::getCpuSpeedInMegaherz() throw()
  198050. {
  198051. const int64 cycles = SystemStats::getClockCycleCounter();
  198052. const uint32 millis = Time::getMillisecondCounter();
  198053. int lastResult = 0;
  198054. for (;;)
  198055. {
  198056. int n = 1000000;
  198057. while (--n > 0) {}
  198058. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198059. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198060. if (millisElapsed > 80)
  198061. {
  198062. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198063. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198064. return newResult;
  198065. lastResult = newResult;
  198066. }
  198067. }
  198068. }
  198069. bool Time::setSystemTimeToThisTime() const throw()
  198070. {
  198071. SYSTEMTIME st;
  198072. st.wDayOfWeek = 0;
  198073. st.wYear = (WORD) getYear();
  198074. st.wMonth = (WORD) (getMonth() + 1);
  198075. st.wDay = (WORD) getDayOfMonth();
  198076. st.wHour = (WORD) getHours();
  198077. st.wMinute = (WORD) getMinutes();
  198078. st.wSecond = (WORD) getSeconds();
  198079. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198080. // do this twice because of daylight saving conversion problems - the
  198081. // first one sets it up, the second one kicks it in.
  198082. return SetLocalTime (&st) != 0
  198083. && SetLocalTime (&st) != 0;
  198084. }
  198085. int SystemStats::getPageSize() throw()
  198086. {
  198087. SYSTEM_INFO systemInfo;
  198088. GetSystemInfo (&systemInfo);
  198089. return systemInfo.dwPageSize;
  198090. }
  198091. END_JUCE_NAMESPACE
  198092. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198093. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198094. #ifdef _MSC_VER
  198095. #pragma warning (disable: 4514)
  198096. #pragma warning (push)
  198097. #include <crtdbg.h>
  198098. #endif
  198099. #include <process.h>
  198100. BEGIN_JUCE_NAMESPACE
  198101. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198102. extern HWND juce_messageWindowHandle;
  198103. #endif
  198104. #ifdef _MSC_VER
  198105. #pragma warning (pop)
  198106. #endif
  198107. CriticalSection::CriticalSection() throw()
  198108. {
  198109. // (just to check the MS haven't changed this structure and broken things...)
  198110. #if _MSC_VER >= 1400
  198111. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198112. #else
  198113. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198114. #endif
  198115. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198116. }
  198117. CriticalSection::~CriticalSection() throw()
  198118. {
  198119. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198120. }
  198121. void CriticalSection::enter() const throw()
  198122. {
  198123. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198124. }
  198125. bool CriticalSection::tryEnter() const throw()
  198126. {
  198127. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198128. }
  198129. void CriticalSection::exit() const throw()
  198130. {
  198131. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198132. }
  198133. WaitableEvent::WaitableEvent() throw()
  198134. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198135. {
  198136. }
  198137. WaitableEvent::~WaitableEvent() throw()
  198138. {
  198139. CloseHandle (internal);
  198140. }
  198141. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198142. {
  198143. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198144. }
  198145. void WaitableEvent::signal() const throw()
  198146. {
  198147. SetEvent (internal);
  198148. }
  198149. void WaitableEvent::reset() const throw()
  198150. {
  198151. ResetEvent (internal);
  198152. }
  198153. void JUCE_API juce_threadEntryPoint (void*);
  198154. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198155. {
  198156. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198157. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198158. GetCurrentThreadId(), TRUE);
  198159. #endif
  198160. juce_threadEntryPoint (userData);
  198161. _endthreadex(0);
  198162. return 0;
  198163. }
  198164. void juce_CloseThreadHandle (void* handle) throw()
  198165. {
  198166. CloseHandle ((HANDLE) handle);
  198167. }
  198168. void* juce_createThread (void* userData) throw()
  198169. {
  198170. unsigned int threadId;
  198171. return (void*) _beginthreadex (0, 0,
  198172. &threadEntryProc,
  198173. userData,
  198174. 0, &threadId);
  198175. }
  198176. void juce_killThread (void* handle) throw()
  198177. {
  198178. if (handle != 0)
  198179. {
  198180. #ifdef JUCE_DEBUG
  198181. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198182. #endif
  198183. TerminateThread (handle, 0);
  198184. }
  198185. }
  198186. void juce_setCurrentThreadName (const String& name) throw()
  198187. {
  198188. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198189. struct
  198190. {
  198191. DWORD dwType;
  198192. LPCSTR szName;
  198193. DWORD dwThreadID;
  198194. DWORD dwFlags;
  198195. } info;
  198196. info.dwType = 0x1000;
  198197. info.szName = name;
  198198. info.dwThreadID = GetCurrentThreadId();
  198199. info.dwFlags = 0;
  198200. #define MS_VC_EXCEPTION 0x406d1388
  198201. __try
  198202. {
  198203. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198204. }
  198205. __except (EXCEPTION_CONTINUE_EXECUTION)
  198206. {}
  198207. #else
  198208. (void) name;
  198209. #endif
  198210. }
  198211. int Thread::getCurrentThreadId() throw()
  198212. {
  198213. return (int) GetCurrentThreadId();
  198214. }
  198215. // priority 1 to 10 where 5=normal, 1=low
  198216. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  198217. {
  198218. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198219. if (priority < 1)
  198220. pri = THREAD_PRIORITY_IDLE;
  198221. else if (priority < 2)
  198222. pri = THREAD_PRIORITY_LOWEST;
  198223. else if (priority < 5)
  198224. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198225. else if (priority < 7)
  198226. pri = THREAD_PRIORITY_NORMAL;
  198227. else if (priority < 9)
  198228. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198229. else if (priority < 10)
  198230. pri = THREAD_PRIORITY_HIGHEST;
  198231. if (threadHandle == 0)
  198232. threadHandle = GetCurrentThread();
  198233. SetThreadPriority (threadHandle, pri);
  198234. }
  198235. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198236. {
  198237. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198238. }
  198239. static HANDLE sleepEvent = 0;
  198240. void juce_initialiseThreadEvents() throw()
  198241. {
  198242. if (sleepEvent == 0)
  198243. #ifdef JUCE_DEBUG
  198244. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198245. #else
  198246. sleepEvent = CreateEvent (0, 0, 0, 0);
  198247. #endif
  198248. }
  198249. void Thread::yield() throw()
  198250. {
  198251. Sleep (0);
  198252. }
  198253. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198254. {
  198255. if (millisecs >= 10)
  198256. {
  198257. Sleep (millisecs);
  198258. }
  198259. else
  198260. {
  198261. jassert (sleepEvent != 0);
  198262. // unlike Sleep() this is guaranteed to return to the current thread after
  198263. // the time expires, so we'll use this for short waits, which are more likely
  198264. // to need to be accurate
  198265. WaitForSingleObject (sleepEvent, millisecs);
  198266. }
  198267. }
  198268. static int lastProcessPriority = -1;
  198269. // called by WindowDriver because Windows does wierd things to process priority
  198270. // when you swap apps, and this forces an update when the app is brought to the front.
  198271. void juce_repeatLastProcessPriority() throw()
  198272. {
  198273. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  198274. {
  198275. DWORD p;
  198276. switch (lastProcessPriority)
  198277. {
  198278. case Process::LowPriority:
  198279. p = IDLE_PRIORITY_CLASS;
  198280. break;
  198281. case Process::NormalPriority:
  198282. p = NORMAL_PRIORITY_CLASS;
  198283. break;
  198284. case Process::HighPriority:
  198285. p = HIGH_PRIORITY_CLASS;
  198286. break;
  198287. case Process::RealtimePriority:
  198288. p = REALTIME_PRIORITY_CLASS;
  198289. break;
  198290. default:
  198291. jassertfalse // bad priority value
  198292. return;
  198293. }
  198294. SetPriorityClass (GetCurrentProcess(), p);
  198295. }
  198296. }
  198297. void Process::setPriority (ProcessPriority prior)
  198298. {
  198299. if (lastProcessPriority != (int) prior)
  198300. {
  198301. lastProcessPriority = (int) prior;
  198302. juce_repeatLastProcessPriority();
  198303. }
  198304. }
  198305. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  198306. {
  198307. return IsDebuggerPresent() != FALSE;
  198308. }
  198309. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  198310. {
  198311. return juce_isRunningUnderDebugger();
  198312. }
  198313. void Process::raisePrivilege()
  198314. {
  198315. jassertfalse // xxx not implemented
  198316. }
  198317. void Process::lowerPrivilege()
  198318. {
  198319. jassertfalse // xxx not implemented
  198320. }
  198321. void Process::terminate()
  198322. {
  198323. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198324. _CrtDumpMemoryLeaks();
  198325. #endif
  198326. // bullet in the head in case there's a problem shutting down..
  198327. ExitProcess (0);
  198328. }
  198329. void* Process::loadDynamicLibrary (const String& name)
  198330. {
  198331. void* result = 0;
  198332. JUCE_TRY
  198333. {
  198334. result = (void*) LoadLibrary (name);
  198335. }
  198336. JUCE_CATCH_ALL
  198337. return result;
  198338. }
  198339. void Process::freeDynamicLibrary (void* h)
  198340. {
  198341. JUCE_TRY
  198342. {
  198343. if (h != 0)
  198344. FreeLibrary ((HMODULE) h);
  198345. }
  198346. JUCE_CATCH_ALL
  198347. }
  198348. void* Process::getProcedureEntryPoint (void* h, const String& name)
  198349. {
  198350. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  198351. : 0;
  198352. }
  198353. InterProcessLock::InterProcessLock (const String& name_) throw()
  198354. : internal (0),
  198355. name (name_),
  198356. reentrancyLevel (0)
  198357. {
  198358. }
  198359. InterProcessLock::~InterProcessLock() throw()
  198360. {
  198361. exit();
  198362. }
  198363. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  198364. {
  198365. if (reentrancyLevel++ == 0)
  198366. {
  198367. internal = CreateMutex (0, TRUE, name);
  198368. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  198369. {
  198370. if (timeOutMillisecs == 0
  198371. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  198372. == WAIT_TIMEOUT)
  198373. {
  198374. ReleaseMutex (internal);
  198375. CloseHandle (internal);
  198376. internal = 0;
  198377. }
  198378. }
  198379. }
  198380. return (internal != 0);
  198381. }
  198382. void InterProcessLock::exit() throw()
  198383. {
  198384. if (--reentrancyLevel == 0 && internal != 0)
  198385. {
  198386. ReleaseMutex (internal);
  198387. CloseHandle (internal);
  198388. internal = 0;
  198389. }
  198390. }
  198391. END_JUCE_NAMESPACE
  198392. /********* End of inlined file: juce_win32_Threads.cpp *********/
  198393. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198394. BEGIN_JUCE_NAMESPACE
  198395. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198396. {
  198397. libHandle = LoadLibrary (name);
  198398. }
  198399. DynamicLibraryLoader::~DynamicLibraryLoader()
  198400. {
  198401. FreeLibrary ((HMODULE) libHandle);
  198402. }
  198403. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198404. {
  198405. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198406. }
  198407. END_JUCE_NAMESPACE
  198408. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198409. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198410. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  198411. #undef WINDOWS
  198412. #if JUCE_ASIO
  198413. /*
  198414. This is very frustrating - we only need to use a handful of definitions from
  198415. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  198416. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  198417. implementation...
  198418. ..unfortunately that would break Steinberg's license agreement for use of
  198419. their SDK, so I'm not allowed to do this.
  198420. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  198421. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  198422. (see www.steinberg.net/Steinberg/Developers.asp).
  198423. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  198424. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  198425. if you prefer). Make sure that your header search path will find the
  198426. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  198427. files are actually needed - so to simplify things, you could just copy
  198428. these into your JUCE directory).
  198429. */
  198430. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  198431. // you don't have the ASIO SDK installed, you can disable ASIO
  198432. // support by commenting-out the "#define JUCE_ASIO" line in
  198433. // juce_Config.h
  198434. BEGIN_JUCE_NAMESPACE
  198435. // #define ASIO_DEBUGGING
  198436. #ifdef ASIO_DEBUGGING
  198437. #define log(a) { Logger::writeToLog (a); DBG (a) }
  198438. #else
  198439. #define log(a) {}
  198440. #endif
  198441. #ifdef ASIO_DEBUGGING
  198442. static void logError (const String& context, long error)
  198443. {
  198444. String err ("unknown error");
  198445. if (error == ASE_NotPresent)
  198446. err = "Not Present";
  198447. else if (error == ASE_HWMalfunction)
  198448. err = "Hardware Malfunction";
  198449. else if (error == ASE_InvalidParameter)
  198450. err = "Invalid Parameter";
  198451. else if (error == ASE_InvalidMode)
  198452. err = "Invalid Mode";
  198453. else if (error == ASE_SPNotAdvancing)
  198454. err = "Sample position not advancing";
  198455. else if (error == ASE_NoClock)
  198456. err = "No Clock";
  198457. else if (error == ASE_NoMemory)
  198458. err = "Out of memory";
  198459. log (T("!!error: ") + context + T(" - ") + err);
  198460. }
  198461. #else
  198462. #define logError(a, b) {}
  198463. #endif
  198464. class ASIOAudioIODevice;
  198465. static ASIOAudioIODevice* volatile currentASIODev = 0;
  198466. static IASIO* volatile asioObject = 0;
  198467. static const int maxASIOChannels = 160;
  198468. static ASIOCallbacks callbacks;
  198469. static ASIOBufferInfo bufferInfos[64];
  198470. static bool volatile insideControlPanelModalLoop = false;
  198471. static bool volatile shouldUsePreferredSize = false;
  198472. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  198473. private Thread,
  198474. private Timer
  198475. {
  198476. public:
  198477. Component ourWindow;
  198478. ASIOAudioIODevice (const String& name_, CLSID classId_)
  198479. : AudioIODevice (name_, T("ASIO")),
  198480. Thread ("Juce ASIO"),
  198481. classId (classId_),
  198482. currentBitDepth (16),
  198483. currentSampleRate (0),
  198484. tempBuffer (0),
  198485. isOpen_ (false),
  198486. isStarted (false),
  198487. postOutput (true)
  198488. {
  198489. name = name_;
  198490. ourWindow.addToDesktop (0);
  198491. windowHandle = ourWindow.getWindowHandle();
  198492. jassert (currentASIODev == 0);
  198493. currentASIODev = this;
  198494. shouldUseThread = false;
  198495. openDevice();
  198496. }
  198497. ~ASIOAudioIODevice()
  198498. {
  198499. jassert (currentASIODev == this);
  198500. if (currentASIODev == this)
  198501. currentASIODev = 0;
  198502. close();
  198503. log ("ASIO - exiting");
  198504. removeCurrentDriver();
  198505. juce_free (tempBuffer);
  198506. if (isUsingThread)
  198507. {
  198508. signalThreadShouldExit();
  198509. event1.signal();
  198510. stopThread (3000);
  198511. }
  198512. }
  198513. void updateSampleRates()
  198514. {
  198515. // find a list of sample rates..
  198516. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  198517. sampleRates.clear();
  198518. if (asioObject != 0)
  198519. {
  198520. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  198521. {
  198522. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  198523. if (err == 0)
  198524. {
  198525. sampleRates.add ((int) possibleSampleRates[index]);
  198526. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  198527. }
  198528. else if (err != ASE_NoClock)
  198529. {
  198530. logError (T("CanSampleRate"), err);
  198531. }
  198532. }
  198533. if (sampleRates.size() == 0)
  198534. {
  198535. double cr = 0;
  198536. const long err = asioObject->getSampleRate (&cr);
  198537. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  198538. if (err == 0)
  198539. sampleRates.add ((int) cr);
  198540. }
  198541. }
  198542. }
  198543. const StringArray getOutputChannelNames()
  198544. {
  198545. return outputChannelNames;
  198546. }
  198547. const StringArray getInputChannelNames()
  198548. {
  198549. return inputChannelNames;
  198550. }
  198551. int getNumSampleRates()
  198552. {
  198553. return sampleRates.size();
  198554. }
  198555. double getSampleRate (int index)
  198556. {
  198557. return sampleRates [index];
  198558. }
  198559. int getNumBufferSizesAvailable()
  198560. {
  198561. return bufferSizes.size();
  198562. }
  198563. int getBufferSizeSamples (int index)
  198564. {
  198565. return bufferSizes [index];
  198566. }
  198567. int getDefaultBufferSize()
  198568. {
  198569. return preferredSize;
  198570. }
  198571. const String open (const BitArray& inputChannels,
  198572. const BitArray& outputChannels,
  198573. double sr,
  198574. int bufferSizeSamples)
  198575. {
  198576. close();
  198577. currentCallback = 0;
  198578. if (bufferSizeSamples <= 0)
  198579. shouldUsePreferredSize = true;
  198580. if (asioObject == 0 || ! isASIOOpen)
  198581. {
  198582. log ("Warning: device not open");
  198583. const String err (openDevice());
  198584. if (asioObject == 0 || ! isASIOOpen)
  198585. return err;
  198586. }
  198587. isStarted = false;
  198588. bufferIndex = -1;
  198589. long err = 0;
  198590. long newPreferredSize = 0;
  198591. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  198592. minSize = 0;
  198593. maxSize = 0;
  198594. newPreferredSize = 0;
  198595. granularity = 0;
  198596. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  198597. {
  198598. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  198599. shouldUsePreferredSize = true;
  198600. preferredSize = newPreferredSize;
  198601. }
  198602. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  198603. // dynamic changes to the buffer size...
  198604. shouldUsePreferredSize = shouldUsePreferredSize
  198605. || getName().containsIgnoreCase (T("Digidesign"));
  198606. if (shouldUsePreferredSize)
  198607. {
  198608. log ("Using preferred size for buffer..");
  198609. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  198610. {
  198611. bufferSizeSamples = preferredSize;
  198612. }
  198613. else
  198614. {
  198615. bufferSizeSamples = 1024;
  198616. logError ("GetBufferSize1", err);
  198617. }
  198618. shouldUsePreferredSize = false;
  198619. }
  198620. int sampleRate = roundDoubleToInt (sr);
  198621. currentSampleRate = sampleRate;
  198622. currentBlockSizeSamples = bufferSizeSamples;
  198623. currentChansOut.clear();
  198624. currentChansIn.clear();
  198625. updateSampleRates();
  198626. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  198627. sampleRate = sampleRates[0];
  198628. jassert (sampleRate != 0);
  198629. if (sampleRate == 0)
  198630. sampleRate = 44100;
  198631. long numSources = 32;
  198632. ASIOClockSource clocks[32];
  198633. zeromem (clocks, sizeof (clocks));
  198634. asioObject->getClockSources (clocks, &numSources);
  198635. bool isSourceSet = false;
  198636. // careful not to remove this loop because it does more than just logging!
  198637. int i;
  198638. for (i = 0; i < numSources; ++i)
  198639. {
  198640. String s ("clock: ");
  198641. s += clocks[i].name;
  198642. if (clocks[i].isCurrentSource)
  198643. {
  198644. isSourceSet = true;
  198645. s << " (cur)";
  198646. }
  198647. log (s);
  198648. }
  198649. if (numSources > 1 && ! isSourceSet)
  198650. {
  198651. log ("setting clock source");
  198652. asioObject->setClockSource (clocks[0].index);
  198653. Thread::sleep (20);
  198654. }
  198655. else
  198656. {
  198657. if (numSources == 0)
  198658. {
  198659. log ("ASIO - no clock sources!");
  198660. }
  198661. }
  198662. double cr = 0;
  198663. err = asioObject->getSampleRate (&cr);
  198664. if (err == 0)
  198665. {
  198666. currentSampleRate = cr;
  198667. }
  198668. else
  198669. {
  198670. logError ("GetSampleRate", err);
  198671. currentSampleRate = 0;
  198672. }
  198673. error = String::empty;
  198674. needToReset = false;
  198675. isReSync = false;
  198676. err = 0;
  198677. bool buffersCreated = false;
  198678. if (currentSampleRate != sampleRate)
  198679. {
  198680. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  198681. err = asioObject->setSampleRate (sampleRate);
  198682. if (err == ASE_NoClock && numSources > 0)
  198683. {
  198684. log ("trying to set a clock source..");
  198685. Thread::sleep (10);
  198686. err = asioObject->setClockSource (clocks[0].index);
  198687. if (err != 0)
  198688. {
  198689. logError ("SetClock", err);
  198690. }
  198691. Thread::sleep (10);
  198692. err = asioObject->setSampleRate (sampleRate);
  198693. }
  198694. }
  198695. if (err == 0)
  198696. {
  198697. currentSampleRate = sampleRate;
  198698. if (needToReset)
  198699. {
  198700. if (isReSync)
  198701. {
  198702. log ("Resync request");
  198703. }
  198704. log ("! Resetting ASIO after sample rate change");
  198705. removeCurrentDriver();
  198706. loadDriver();
  198707. const String error (initDriver());
  198708. if (error.isNotEmpty())
  198709. {
  198710. log (T("ASIOInit: ") + error);
  198711. }
  198712. needToReset = false;
  198713. isReSync = false;
  198714. }
  198715. numActiveInputChans = 0;
  198716. numActiveOutputChans = 0;
  198717. ASIOBufferInfo* info = bufferInfos;
  198718. int i;
  198719. for (i = 0; i < numInputs; ++i)
  198720. {
  198721. if (inputChannels[i])
  198722. {
  198723. currentChansIn.setBit (i);
  198724. info->isInput = 1;
  198725. info->channelNum = i;
  198726. info->buffers[0] = info->buffers[1] = 0;
  198727. ++info;
  198728. ++numActiveInputChans;
  198729. }
  198730. }
  198731. for (i = 0; i < numOutputs; ++i)
  198732. {
  198733. if (outputChannels[i])
  198734. {
  198735. currentChansOut.setBit (i);
  198736. info->isInput = 0;
  198737. info->channelNum = i;
  198738. info->buffers[0] = info->buffers[1] = 0;
  198739. ++info;
  198740. ++numActiveOutputChans;
  198741. }
  198742. }
  198743. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  198744. callbacks.bufferSwitch = &bufferSwitchCallback;
  198745. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  198746. callbacks.asioMessage = &asioMessagesCallback;
  198747. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  198748. log ("disposing buffers");
  198749. err = asioObject->disposeBuffers();
  198750. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  198751. err = asioObject->createBuffers (bufferInfos,
  198752. totalBuffers,
  198753. currentBlockSizeSamples,
  198754. &callbacks);
  198755. if (err != 0)
  198756. {
  198757. currentBlockSizeSamples = preferredSize;
  198758. logError ("create buffers 2", err);
  198759. asioObject->disposeBuffers();
  198760. err = asioObject->createBuffers (bufferInfos,
  198761. totalBuffers,
  198762. currentBlockSizeSamples,
  198763. &callbacks);
  198764. }
  198765. if (err == 0)
  198766. {
  198767. buffersCreated = true;
  198768. jassert (! isThreadRunning());
  198769. juce_free (tempBuffer);
  198770. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  198771. int n = 0;
  198772. Array <int> types;
  198773. currentBitDepth = 16;
  198774. for (i = 0; i < jmin (numInputs, maxASIOChannels); ++i)
  198775. {
  198776. if (inputChannels[i])
  198777. {
  198778. inBuffers[i] = tempBuffer + (currentBlockSizeSamples * n++);
  198779. ASIOChannelInfo channelInfo;
  198780. zerostruct (channelInfo);
  198781. channelInfo.channel = i;
  198782. channelInfo.isInput = 1;
  198783. asioObject->getChannelInfo (&channelInfo);
  198784. types.addIfNotAlreadyThere (channelInfo.type);
  198785. typeToFormatParameters (channelInfo.type,
  198786. inputChannelBitDepths[i],
  198787. inputChannelBytesPerSample[i],
  198788. inputChannelIsFloat[i],
  198789. inputChannelLittleEndian[i]);
  198790. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[i]);
  198791. }
  198792. else
  198793. {
  198794. inBuffers[i] = 0;
  198795. }
  198796. }
  198797. for (i = 0; i < jmin (numOutputs, maxASIOChannels); ++i)
  198798. {
  198799. if (outputChannels[i])
  198800. {
  198801. outBuffers[i] = tempBuffer + (currentBlockSizeSamples * n++);
  198802. ASIOChannelInfo channelInfo;
  198803. zerostruct (channelInfo);
  198804. channelInfo.channel = i;
  198805. channelInfo.isInput = 0;
  198806. asioObject->getChannelInfo (&channelInfo);
  198807. types.addIfNotAlreadyThere (channelInfo.type);
  198808. typeToFormatParameters (channelInfo.type,
  198809. outputChannelBitDepths[i],
  198810. outputChannelBytesPerSample[i],
  198811. outputChannelIsFloat[i],
  198812. outputChannelLittleEndian[i]);
  198813. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[i]);
  198814. }
  198815. else
  198816. {
  198817. outBuffers[i] = 0;
  198818. }
  198819. }
  198820. for (i = types.size(); --i >= 0;)
  198821. {
  198822. log (T("channel format: ") + String (types[i]));
  198823. }
  198824. jassert (n <= totalBuffers);
  198825. n = numActiveInputChans;
  198826. for (i = 0; i < numOutputs; ++i)
  198827. {
  198828. if (outputChannels[i])
  198829. {
  198830. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  198831. if (bufferInfos[n].buffers[0] == 0
  198832. || bufferInfos[n].buffers[1] == 0)
  198833. {
  198834. log ("!! Null buffers");
  198835. }
  198836. else
  198837. {
  198838. zeromem (bufferInfos[n].buffers[0], size);
  198839. zeromem (bufferInfos[n].buffers[1], size);
  198840. }
  198841. ++n;
  198842. }
  198843. }
  198844. jassert (n <= totalBuffers);
  198845. inputLatency = outputLatency = 0;
  198846. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  198847. {
  198848. log ("ASIO - no latencies");
  198849. }
  198850. else
  198851. {
  198852. log (T("ASIO latencies: ")
  198853. + String ((int) outputLatency)
  198854. + T(", ")
  198855. + String ((int) inputLatency));
  198856. }
  198857. isOpen_ = true;
  198858. isThreadReady = false;
  198859. if (isUsingThread)
  198860. {
  198861. event1.wait (1); // reset the event in case it was flipped by a callback from the ASIO->start call in openDevice()
  198862. startThread (8);
  198863. int count = 5000;
  198864. while (--count > 0 && ! isThreadReady)
  198865. sleep (1);
  198866. }
  198867. if (isUsingThread && ! isThreadRunning())
  198868. {
  198869. error = "Can't start thread!";
  198870. }
  198871. else
  198872. {
  198873. log ("starting ASIO");
  198874. calledback = false;
  198875. err = asioObject->start();
  198876. if (err != 0)
  198877. {
  198878. if (isUsingThread)
  198879. {
  198880. signalThreadShouldExit();
  198881. event1.signal();
  198882. stopThread (3000);
  198883. }
  198884. isOpen_ = false;
  198885. log ("ASIO - stop on failure");
  198886. Thread::sleep (10);
  198887. asioObject->stop();
  198888. error = "Can't start device";
  198889. Thread::sleep (10);
  198890. }
  198891. else
  198892. {
  198893. int count = 300;
  198894. while (--count > 0 && ! calledback)
  198895. Thread::sleep (10);
  198896. isStarted = true;
  198897. if (! calledback)
  198898. {
  198899. error = "Device didn't start correctly";
  198900. log ("ASIO didn't callback - stopping..");
  198901. asioObject->stop();
  198902. }
  198903. }
  198904. }
  198905. }
  198906. else
  198907. {
  198908. error = "Can't create i/o buffers";
  198909. }
  198910. }
  198911. else
  198912. {
  198913. error = "Can't set sample rate: ";
  198914. error << sampleRate;
  198915. }
  198916. if (error.isNotEmpty())
  198917. {
  198918. logError (error, err);
  198919. if (asioObject != 0 && buffersCreated)
  198920. asioObject->disposeBuffers();
  198921. Thread::sleep (20);
  198922. isStarted = false;
  198923. isOpen_ = false;
  198924. close();
  198925. }
  198926. needToReset = false;
  198927. isReSync = false;
  198928. return error;
  198929. }
  198930. void close()
  198931. {
  198932. error = String::empty;
  198933. stopTimer();
  198934. stop();
  198935. if (isASIOOpen && isOpen_)
  198936. {
  198937. const ScopedLock sl (callbackLock);
  198938. if (isUsingThread)
  198939. {
  198940. signalThreadShouldExit();
  198941. event1.signal();
  198942. stopThread (3000);
  198943. }
  198944. isOpen_ = false;
  198945. isStarted = false;
  198946. needToReset = false;
  198947. isReSync = false;
  198948. log ("ASIO - stopping");
  198949. if (asioObject != 0)
  198950. {
  198951. Thread::sleep (20);
  198952. asioObject->stop();
  198953. Thread::sleep (10);
  198954. asioObject->disposeBuffers();
  198955. }
  198956. Thread::sleep (10);
  198957. }
  198958. }
  198959. bool isOpen()
  198960. {
  198961. return isOpen_ || insideControlPanelModalLoop;
  198962. }
  198963. int getCurrentBufferSizeSamples()
  198964. {
  198965. return currentBlockSizeSamples;
  198966. }
  198967. double getCurrentSampleRate()
  198968. {
  198969. return currentSampleRate;
  198970. }
  198971. const BitArray getActiveOutputChannels() const
  198972. {
  198973. return currentChansOut;
  198974. }
  198975. const BitArray getActiveInputChannels() const
  198976. {
  198977. return currentChansIn;
  198978. }
  198979. int getCurrentBitDepth()
  198980. {
  198981. return currentBitDepth;
  198982. }
  198983. int getOutputLatencyInSamples()
  198984. {
  198985. return outputLatency + currentBlockSizeSamples / 4;
  198986. }
  198987. int getInputLatencyInSamples()
  198988. {
  198989. return inputLatency + currentBlockSizeSamples / 4;
  198990. }
  198991. void start (AudioIODeviceCallback* callback)
  198992. {
  198993. if (callback != 0)
  198994. {
  198995. callback->audioDeviceAboutToStart (this);
  198996. const ScopedLock sl (callbackLock);
  198997. currentCallback = callback;
  198998. }
  198999. }
  199000. void stop()
  199001. {
  199002. AudioIODeviceCallback* const lastCallback = currentCallback;
  199003. {
  199004. const ScopedLock sl (callbackLock);
  199005. currentCallback = 0;
  199006. }
  199007. if (lastCallback != 0)
  199008. lastCallback->audioDeviceStopped();
  199009. }
  199010. bool isPlaying()
  199011. {
  199012. return isASIOOpen
  199013. && (isThreadRunning() || ! isUsingThread)
  199014. && (currentCallback != 0);
  199015. }
  199016. const String getLastError()
  199017. {
  199018. return error;
  199019. }
  199020. void setUsingThread (bool b)
  199021. {
  199022. shouldUseThread = b;
  199023. }
  199024. bool hasControlPanel() const
  199025. {
  199026. return true;
  199027. }
  199028. bool showControlPanel()
  199029. {
  199030. log ("ASIO - showing control panel");
  199031. Component modalWindow (String::empty);
  199032. modalWindow.setOpaque (true);
  199033. modalWindow.addToDesktop (0);
  199034. modalWindow.enterModalState();
  199035. bool done = false;
  199036. JUCE_TRY
  199037. {
  199038. close();
  199039. insideControlPanelModalLoop = true;
  199040. const uint32 started = Time::getMillisecondCounter();
  199041. if (asioObject != 0)
  199042. {
  199043. asioObject->controlPanel();
  199044. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  199045. log (T("spent: ") + String (spent));
  199046. if (spent > 300)
  199047. {
  199048. shouldUsePreferredSize = true;
  199049. done = true;
  199050. }
  199051. }
  199052. }
  199053. JUCE_CATCH_ALL
  199054. insideControlPanelModalLoop = false;
  199055. return done;
  199056. }
  199057. void run()
  199058. {
  199059. isThreadReady = true;
  199060. for (;;)
  199061. {
  199062. event1.wait();
  199063. if (threadShouldExit())
  199064. break;
  199065. processBuffer();
  199066. }
  199067. if (bufferIndex < 0)
  199068. {
  199069. log ("! ASIO callback never called");
  199070. }
  199071. }
  199072. void resetRequest() throw()
  199073. {
  199074. needToReset = true;
  199075. }
  199076. void resyncRequest() throw()
  199077. {
  199078. needToReset = true;
  199079. isReSync = true;
  199080. }
  199081. void timerCallback()
  199082. {
  199083. if (! insideControlPanelModalLoop)
  199084. {
  199085. stopTimer();
  199086. // used to cause a reset
  199087. log ("! ASIO restart request!");
  199088. if (isOpen_)
  199089. {
  199090. AudioIODeviceCallback* const oldCallback = currentCallback;
  199091. close();
  199092. open (currentChansIn, currentChansOut,
  199093. currentSampleRate, currentBlockSizeSamples);
  199094. if (oldCallback != 0)
  199095. start (oldCallback);
  199096. }
  199097. }
  199098. else
  199099. {
  199100. startTimer (100);
  199101. }
  199102. }
  199103. juce_UseDebuggingNewOperator
  199104. private:
  199105. void* windowHandle;
  199106. CLSID classId;
  199107. String error;
  199108. long numInputs, numOutputs;
  199109. StringArray outputChannelNames, inputChannelNames;
  199110. Array<int> sampleRates, bufferSizes;
  199111. long inputLatency, outputLatency;
  199112. long minSize, maxSize, preferredSize, granularity;
  199113. int volatile currentBlockSizeSamples;
  199114. int volatile currentBitDepth;
  199115. double volatile currentSampleRate;
  199116. BitArray currentChansOut, currentChansIn;
  199117. AudioIODeviceCallback* volatile currentCallback;
  199118. CriticalSection callbackLock;
  199119. float* inBuffers[maxASIOChannels];
  199120. float* outBuffers[maxASIOChannels];
  199121. int inputChannelBitDepths[maxASIOChannels];
  199122. int outputChannelBitDepths[maxASIOChannels];
  199123. int inputChannelBytesPerSample[maxASIOChannels];
  199124. int outputChannelBytesPerSample[maxASIOChannels];
  199125. bool inputChannelIsFloat[maxASIOChannels];
  199126. bool outputChannelIsFloat[maxASIOChannels];
  199127. bool inputChannelLittleEndian[maxASIOChannels];
  199128. bool outputChannelLittleEndian[maxASIOChannels];
  199129. WaitableEvent event1;
  199130. float* tempBuffer;
  199131. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  199132. bool isOpen_, isStarted;
  199133. bool isUsingThread, shouldUseThread;
  199134. bool volatile isASIOOpen;
  199135. bool volatile calledback;
  199136. bool volatile littleEndian, postOutput, needToReset, isReSync, isThreadReady;
  199137. static void removeCurrentDriver()
  199138. {
  199139. if (asioObject != 0)
  199140. {
  199141. asioObject->Release();
  199142. asioObject = 0;
  199143. }
  199144. }
  199145. bool loadDriver()
  199146. {
  199147. removeCurrentDriver();
  199148. JUCE_TRY
  199149. {
  199150. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  199151. classId, (void**) &asioObject) == S_OK)
  199152. {
  199153. return true;
  199154. }
  199155. }
  199156. JUCE_CATCH_ALL
  199157. asioObject = 0;
  199158. return false;
  199159. }
  199160. const String initDriver()
  199161. {
  199162. if (asioObject != 0)
  199163. {
  199164. char buffer [256];
  199165. zeromem (buffer, sizeof (buffer));
  199166. if (! asioObject->init (windowHandle))
  199167. {
  199168. asioObject->getErrorMessage (buffer);
  199169. return String (buffer, sizeof (buffer) - 1);
  199170. }
  199171. // just in case any daft drivers expect this to be called..
  199172. asioObject->getDriverName (buffer);
  199173. return String::empty;
  199174. }
  199175. return "No Driver";
  199176. }
  199177. const String openDevice()
  199178. {
  199179. // use this in case the driver starts opening dialog boxes..
  199180. Component modalWindow (String::empty);
  199181. modalWindow.setOpaque (true);
  199182. modalWindow.addToDesktop (0);
  199183. modalWindow.enterModalState();
  199184. isUsingThread = shouldUseThread;
  199185. // open the device and get its info..
  199186. log (T("opening ASIO device: ") + getName());
  199187. needToReset = false;
  199188. isReSync = false;
  199189. outputChannelNames.clear();
  199190. inputChannelNames.clear();
  199191. bufferSizes.clear();
  199192. sampleRates.clear();
  199193. isASIOOpen = false;
  199194. isOpen_ = false;
  199195. numInputs = 0;
  199196. numOutputs = 0;
  199197. currentCallback = 0;
  199198. error = String::empty;
  199199. if (getName().isEmpty())
  199200. return error;
  199201. long err = 0;
  199202. if (loadDriver())
  199203. {
  199204. String driverName;
  199205. if ((error = initDriver()).isEmpty())
  199206. {
  199207. numInputs = 0;
  199208. numOutputs = 0;
  199209. if (asioObject != 0
  199210. && (err = asioObject->getChannels (&numInputs, &numOutputs)) == 0)
  199211. {
  199212. log (String ((int) numInputs) + T(" in, ") + String ((int) numOutputs) + T(" out"));
  199213. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199214. {
  199215. // find a list of buffer sizes..
  199216. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  199217. if (granularity >= 0)
  199218. {
  199219. granularity = jmax (1, (int) granularity);
  199220. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  199221. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  199222. }
  199223. else if (granularity < 0)
  199224. {
  199225. for (int i = 0; i < 18; ++i)
  199226. {
  199227. const int s = (1 << i);
  199228. if (s >= minSize && s <= maxSize)
  199229. bufferSizes.add (s);
  199230. }
  199231. }
  199232. if (! bufferSizes.contains (preferredSize))
  199233. bufferSizes.insert (0, preferredSize);
  199234. double currentRate = 0;
  199235. asioObject->getSampleRate (&currentRate);
  199236. if (currentRate <= 0.0 || currentRate > 192001.0)
  199237. {
  199238. log ("setting sample rate");
  199239. err = asioObject->setSampleRate (44100.0);
  199240. if (err != 0)
  199241. {
  199242. logError ("setting sample rate", err);
  199243. }
  199244. asioObject->getSampleRate (&currentRate);
  199245. }
  199246. currentSampleRate = currentRate;
  199247. postOutput = (asioObject->outputReady() == 0);
  199248. if (postOutput)
  199249. {
  199250. log ("ASIO outputReady = ok");
  199251. }
  199252. updateSampleRates();
  199253. // ..because cubase does it at this point
  199254. inputLatency = outputLatency = 0;
  199255. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199256. {
  199257. log ("ASIO - no latencies");
  199258. }
  199259. log (String ("latencies: ")
  199260. + String ((int) inputLatency)
  199261. + T(", ") + String ((int) outputLatency));
  199262. // create some dummy buffers now.. because cubase does..
  199263. numActiveInputChans = 0;
  199264. numActiveOutputChans = 0;
  199265. ASIOBufferInfo* info = bufferInfos;
  199266. int i, numChans = 0;
  199267. for (i = 0; i < jmin (2, numInputs); ++i)
  199268. {
  199269. info->isInput = 1;
  199270. info->channelNum = i;
  199271. info->buffers[0] = info->buffers[1] = 0;
  199272. ++info;
  199273. ++numChans;
  199274. }
  199275. const int outputBufferIndex = numChans;
  199276. for (i = 0; i < jmin (2, numOutputs); ++i)
  199277. {
  199278. info->isInput = 0;
  199279. info->channelNum = i;
  199280. info->buffers[0] = info->buffers[1] = 0;
  199281. ++info;
  199282. ++numChans;
  199283. }
  199284. callbacks.bufferSwitch = &bufferSwitchCallback;
  199285. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199286. callbacks.asioMessage = &asioMessagesCallback;
  199287. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  199288. log (T("creating buffers (dummy): ") + String (numChans)
  199289. + T(", ") + String ((int) preferredSize));
  199290. if (preferredSize > 0)
  199291. {
  199292. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  199293. if (err != 0)
  199294. {
  199295. logError ("dummy buffers", err);
  199296. }
  199297. }
  199298. long newInps = 0, newOuts = 0;
  199299. asioObject->getChannels (&newInps, &newOuts);
  199300. if (numInputs != newInps || numOutputs != newOuts)
  199301. {
  199302. numInputs = newInps;
  199303. numOutputs = newOuts;
  199304. log (String ((int) numInputs) + T(" in; ")
  199305. + String ((int) numOutputs) + T(" out"));
  199306. }
  199307. updateSampleRates();
  199308. ASIOChannelInfo channelInfo;
  199309. channelInfo.type = 0;
  199310. for (i = 0; i < numInputs; ++i)
  199311. {
  199312. zerostruct (channelInfo);
  199313. channelInfo.channel = i;
  199314. channelInfo.isInput = 1;
  199315. asioObject->getChannelInfo (&channelInfo);
  199316. inputChannelNames.add (String (channelInfo.name));
  199317. }
  199318. for (i = 0; i < numOutputs; ++i)
  199319. {
  199320. zerostruct (channelInfo);
  199321. channelInfo.channel = i;
  199322. channelInfo.isInput = 0;
  199323. asioObject->getChannelInfo (&channelInfo);
  199324. outputChannelNames.add (String (channelInfo.name));
  199325. typeToFormatParameters (channelInfo.type,
  199326. outputChannelBitDepths[i],
  199327. outputChannelBytesPerSample[i],
  199328. outputChannelIsFloat[i],
  199329. outputChannelLittleEndian[i]);
  199330. if (i < 2)
  199331. {
  199332. // clear the channels that are used with the dummy stuff
  199333. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  199334. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  199335. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  199336. }
  199337. }
  199338. outputChannelNames.trim();
  199339. inputChannelNames.trim();
  199340. outputChannelNames.appendNumbersToDuplicates (false, true);
  199341. inputChannelNames.appendNumbersToDuplicates (false, true);
  199342. // start and stop because cubase does it..
  199343. asioObject->getLatencies (&inputLatency, &outputLatency);
  199344. if ((err = asioObject->start()) != 0)
  199345. {
  199346. // ignore an error here, as it might start later after setting other stuff up
  199347. logError ("ASIO start", err);
  199348. }
  199349. Thread::sleep (100);
  199350. asioObject->stop();
  199351. }
  199352. else
  199353. {
  199354. error = "Can't detect buffer sizes";
  199355. }
  199356. }
  199357. else
  199358. {
  199359. error = "Can't detect asio channels";
  199360. }
  199361. }
  199362. }
  199363. else
  199364. {
  199365. error = "No such device";
  199366. }
  199367. if (error.isNotEmpty())
  199368. {
  199369. logError (error, err);
  199370. if (asioObject != 0)
  199371. asioObject->disposeBuffers();
  199372. removeCurrentDriver();
  199373. isASIOOpen = false;
  199374. }
  199375. else
  199376. {
  199377. isASIOOpen = true;
  199378. log ("ASIO device open");
  199379. }
  199380. isOpen_ = false;
  199381. needToReset = false;
  199382. isReSync = false;
  199383. return error;
  199384. }
  199385. void callback (const long index) throw()
  199386. {
  199387. if (isStarted)
  199388. {
  199389. bufferIndex = index;
  199390. if (isUsingThread) // if not started, just use processBuffer() to clear the buffers directly
  199391. {
  199392. event1.signal();
  199393. if (postOutput && (! isThreadRunning()) && asioObject != 0)
  199394. asioObject->outputReady();
  199395. }
  199396. else
  199397. {
  199398. processBuffer();
  199399. }
  199400. }
  199401. else
  199402. {
  199403. if (postOutput && (asioObject != 0))
  199404. asioObject->outputReady();
  199405. }
  199406. calledback = true;
  199407. }
  199408. void processBuffer() throw()
  199409. {
  199410. const ASIOBufferInfo* const infos = bufferInfos;
  199411. const int bi = bufferIndex;
  199412. const ScopedLock sl (callbackLock);
  199413. if (needToReset)
  199414. {
  199415. needToReset = false;
  199416. if (isReSync)
  199417. {
  199418. log ("! ASIO resync");
  199419. isReSync = false;
  199420. }
  199421. else
  199422. {
  199423. startTimer (20);
  199424. }
  199425. }
  199426. if (bi >= 0)
  199427. {
  199428. const int samps = currentBlockSizeSamples;
  199429. if (currentCallback != 0)
  199430. {
  199431. int n = 0;
  199432. int i;
  199433. for (i = 0; i < numInputs; ++i)
  199434. {
  199435. float* const dst = inBuffers[i];
  199436. if (dst != 0)
  199437. {
  199438. const char* const src = (const char*) (infos[n].buffers[bi]);
  199439. if (inputChannelIsFloat[i])
  199440. {
  199441. memcpy (dst, src, samps * sizeof (float));
  199442. }
  199443. else
  199444. {
  199445. jassert (dst == tempBuffer + (samps * n));
  199446. switch (inputChannelBitDepths[i])
  199447. {
  199448. case 16:
  199449. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  199450. samps, inputChannelLittleEndian[i]);
  199451. break;
  199452. case 24:
  199453. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  199454. samps, inputChannelLittleEndian[i]);
  199455. break;
  199456. case 32:
  199457. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  199458. samps, inputChannelLittleEndian[i]);
  199459. break;
  199460. case 64:
  199461. jassertfalse
  199462. break;
  199463. }
  199464. }
  199465. ++n;
  199466. }
  199467. }
  199468. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  199469. numInputs,
  199470. outBuffers,
  199471. numOutputs,
  199472. samps);
  199473. for (i = 0; i < numOutputs; ++i)
  199474. {
  199475. float* const src = outBuffers[i];
  199476. if (src != 0)
  199477. {
  199478. char* const dst = (char*) (infos[n].buffers[bi]);
  199479. if (outputChannelIsFloat[i])
  199480. {
  199481. memcpy (dst, src, samps * sizeof (float));
  199482. }
  199483. else
  199484. {
  199485. jassert (src == tempBuffer + (samps * n));
  199486. switch (outputChannelBitDepths[i])
  199487. {
  199488. case 16:
  199489. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  199490. samps, outputChannelLittleEndian[i]);
  199491. break;
  199492. case 24:
  199493. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  199494. samps, outputChannelLittleEndian[i]);
  199495. break;
  199496. case 32:
  199497. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  199498. samps, outputChannelLittleEndian[i]);
  199499. break;
  199500. case 64:
  199501. jassertfalse
  199502. break;
  199503. }
  199504. }
  199505. ++n;
  199506. }
  199507. }
  199508. }
  199509. else
  199510. {
  199511. int n = 0;
  199512. int i;
  199513. for (i = 0; i < numInputs; ++i)
  199514. if (inBuffers[i] != 0)
  199515. ++n;
  199516. for (i = 0; i < numOutputs; ++i)
  199517. {
  199518. if (outBuffers[i] != 0)
  199519. {
  199520. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  199521. zeromem (infos[n].buffers[bi], bytesPerBuffer);
  199522. ++n;
  199523. }
  199524. }
  199525. }
  199526. }
  199527. if (postOutput)
  199528. asioObject->outputReady();
  199529. }
  199530. static ASIOTime* bufferSwitchTimeInfoCallback (ASIOTime*, long index, long) throw()
  199531. {
  199532. if (currentASIODev != 0)
  199533. currentASIODev->callback (index);
  199534. return 0;
  199535. }
  199536. static void bufferSwitchCallback (long index, long) throw()
  199537. {
  199538. if (currentASIODev != 0)
  199539. currentASIODev->callback (index);
  199540. }
  199541. static long asioMessagesCallback (long selector, long value, void*, double*) throw()
  199542. {
  199543. switch (selector)
  199544. {
  199545. case kAsioSelectorSupported:
  199546. if (value == kAsioResetRequest
  199547. || value == kAsioEngineVersion
  199548. || value == kAsioResyncRequest
  199549. || value == kAsioLatenciesChanged
  199550. || value == kAsioSupportsInputMonitor)
  199551. return 1;
  199552. break;
  199553. case kAsioBufferSizeChange:
  199554. break;
  199555. case kAsioResetRequest:
  199556. if (currentASIODev != 0)
  199557. currentASIODev->resetRequest();
  199558. return 1;
  199559. case kAsioResyncRequest:
  199560. if (currentASIODev != 0)
  199561. currentASIODev->resyncRequest();
  199562. return 1;
  199563. case kAsioLatenciesChanged:
  199564. return 1;
  199565. case kAsioEngineVersion:
  199566. return 2;
  199567. case kAsioSupportsTimeInfo:
  199568. case kAsioSupportsTimeCode:
  199569. return 0;
  199570. }
  199571. return 0;
  199572. }
  199573. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  199574. {
  199575. }
  199576. static void convertInt16ToFloat (const char* src,
  199577. float* dest,
  199578. const int srcStrideBytes,
  199579. int numSamples,
  199580. const bool littleEndian) throw()
  199581. {
  199582. const double g = 1.0 / 32768.0;
  199583. if (littleEndian)
  199584. {
  199585. while (--numSamples >= 0)
  199586. {
  199587. *dest++ = (float) (g * (short) littleEndianShort (src));
  199588. src += srcStrideBytes;
  199589. }
  199590. }
  199591. else
  199592. {
  199593. while (--numSamples >= 0)
  199594. {
  199595. *dest++ = (float) (g * (short) bigEndianShort (src));
  199596. src += srcStrideBytes;
  199597. }
  199598. }
  199599. }
  199600. static void convertFloatToInt16 (const float* src,
  199601. char* dest,
  199602. const int dstStrideBytes,
  199603. int numSamples,
  199604. const bool littleEndian) throw()
  199605. {
  199606. const double maxVal = (double) 0x7fff;
  199607. if (littleEndian)
  199608. {
  199609. while (--numSamples >= 0)
  199610. {
  199611. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199612. dest += dstStrideBytes;
  199613. }
  199614. }
  199615. else
  199616. {
  199617. while (--numSamples >= 0)
  199618. {
  199619. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199620. dest += dstStrideBytes;
  199621. }
  199622. }
  199623. }
  199624. static void convertInt24ToFloat (const char* src,
  199625. float* dest,
  199626. const int srcStrideBytes,
  199627. int numSamples,
  199628. const bool littleEndian) throw()
  199629. {
  199630. const double g = 1.0 / 0x7fffff;
  199631. if (littleEndian)
  199632. {
  199633. while (--numSamples >= 0)
  199634. {
  199635. *dest++ = (float) (g * littleEndian24Bit (src));
  199636. src += srcStrideBytes;
  199637. }
  199638. }
  199639. else
  199640. {
  199641. while (--numSamples >= 0)
  199642. {
  199643. *dest++ = (float) (g * bigEndian24Bit (src));
  199644. src += srcStrideBytes;
  199645. }
  199646. }
  199647. }
  199648. static void convertFloatToInt24 (const float* src,
  199649. char* dest,
  199650. const int dstStrideBytes,
  199651. int numSamples,
  199652. const bool littleEndian) throw()
  199653. {
  199654. const double maxVal = (double) 0x7fffff;
  199655. if (littleEndian)
  199656. {
  199657. while (--numSamples >= 0)
  199658. {
  199659. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  199660. dest += dstStrideBytes;
  199661. }
  199662. }
  199663. else
  199664. {
  199665. while (--numSamples >= 0)
  199666. {
  199667. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  199668. dest += dstStrideBytes;
  199669. }
  199670. }
  199671. }
  199672. static void convertInt32ToFloat (const char* src,
  199673. float* dest,
  199674. const int srcStrideBytes,
  199675. int numSamples,
  199676. const bool littleEndian) throw()
  199677. {
  199678. const double g = 1.0 / 0x7fffffff;
  199679. if (littleEndian)
  199680. {
  199681. while (--numSamples >= 0)
  199682. {
  199683. *dest++ = (float) (g * (int) littleEndianInt (src));
  199684. src += srcStrideBytes;
  199685. }
  199686. }
  199687. else
  199688. {
  199689. while (--numSamples >= 0)
  199690. {
  199691. *dest++ = (float) (g * (int) bigEndianInt (src));
  199692. src += srcStrideBytes;
  199693. }
  199694. }
  199695. }
  199696. static void convertFloatToInt32 (const float* src,
  199697. char* dest,
  199698. const int dstStrideBytes,
  199699. int numSamples,
  199700. const bool littleEndian) throw()
  199701. {
  199702. const double maxVal = (double) 0x7fffffff;
  199703. if (littleEndian)
  199704. {
  199705. while (--numSamples >= 0)
  199706. {
  199707. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199708. dest += dstStrideBytes;
  199709. }
  199710. }
  199711. else
  199712. {
  199713. while (--numSamples >= 0)
  199714. {
  199715. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199716. dest += dstStrideBytes;
  199717. }
  199718. }
  199719. }
  199720. static void typeToFormatParameters (const long type,
  199721. int& bitDepth,
  199722. int& byteStride,
  199723. bool& formatIsFloat,
  199724. bool& littleEndian) throw()
  199725. {
  199726. bitDepth = 0;
  199727. littleEndian = false;
  199728. formatIsFloat = false;
  199729. switch (type)
  199730. {
  199731. case ASIOSTInt16MSB:
  199732. case ASIOSTInt16LSB:
  199733. case ASIOSTInt32MSB16:
  199734. case ASIOSTInt32LSB16:
  199735. bitDepth = 16; break;
  199736. case ASIOSTFloat32MSB:
  199737. case ASIOSTFloat32LSB:
  199738. formatIsFloat = true;
  199739. bitDepth = 32; break;
  199740. case ASIOSTInt32MSB:
  199741. case ASIOSTInt32LSB:
  199742. bitDepth = 32; break;
  199743. case ASIOSTInt24MSB:
  199744. case ASIOSTInt24LSB:
  199745. case ASIOSTInt32MSB24:
  199746. case ASIOSTInt32LSB24:
  199747. case ASIOSTInt32MSB18:
  199748. case ASIOSTInt32MSB20:
  199749. case ASIOSTInt32LSB18:
  199750. case ASIOSTInt32LSB20:
  199751. bitDepth = 24; break;
  199752. case ASIOSTFloat64MSB:
  199753. case ASIOSTFloat64LSB:
  199754. default:
  199755. bitDepth = 64;
  199756. break;
  199757. }
  199758. switch (type)
  199759. {
  199760. case ASIOSTInt16MSB:
  199761. case ASIOSTInt32MSB16:
  199762. case ASIOSTFloat32MSB:
  199763. case ASIOSTFloat64MSB:
  199764. case ASIOSTInt32MSB:
  199765. case ASIOSTInt32MSB18:
  199766. case ASIOSTInt32MSB20:
  199767. case ASIOSTInt32MSB24:
  199768. case ASIOSTInt24MSB:
  199769. littleEndian = false; break;
  199770. case ASIOSTInt16LSB:
  199771. case ASIOSTInt32LSB16:
  199772. case ASIOSTFloat32LSB:
  199773. case ASIOSTFloat64LSB:
  199774. case ASIOSTInt32LSB:
  199775. case ASIOSTInt32LSB18:
  199776. case ASIOSTInt32LSB20:
  199777. case ASIOSTInt32LSB24:
  199778. case ASIOSTInt24LSB:
  199779. littleEndian = true; break;
  199780. default:
  199781. break;
  199782. }
  199783. switch (type)
  199784. {
  199785. case ASIOSTInt16LSB:
  199786. case ASIOSTInt16MSB:
  199787. byteStride = 2; break;
  199788. case ASIOSTInt24LSB:
  199789. case ASIOSTInt24MSB:
  199790. byteStride = 3; break;
  199791. case ASIOSTInt32MSB16:
  199792. case ASIOSTInt32LSB16:
  199793. case ASIOSTInt32MSB:
  199794. case ASIOSTInt32MSB18:
  199795. case ASIOSTInt32MSB20:
  199796. case ASIOSTInt32MSB24:
  199797. case ASIOSTInt32LSB:
  199798. case ASIOSTInt32LSB18:
  199799. case ASIOSTInt32LSB20:
  199800. case ASIOSTInt32LSB24:
  199801. case ASIOSTFloat32LSB:
  199802. case ASIOSTFloat32MSB:
  199803. byteStride = 4; break;
  199804. case ASIOSTFloat64MSB:
  199805. case ASIOSTFloat64LSB:
  199806. byteStride = 8; break;
  199807. default:
  199808. break;
  199809. }
  199810. }
  199811. };
  199812. class ASIOAudioIODeviceType : public AudioIODeviceType
  199813. {
  199814. public:
  199815. ASIOAudioIODeviceType()
  199816. : AudioIODeviceType (T("ASIO")),
  199817. classIds (2),
  199818. hasScanned (false)
  199819. {
  199820. CoInitialize (0);
  199821. }
  199822. ~ASIOAudioIODeviceType()
  199823. {
  199824. }
  199825. void scanForDevices()
  199826. {
  199827. hasScanned = true;
  199828. deviceNames.clear();
  199829. classIds.clear();
  199830. HKEY hk = 0;
  199831. int index = 0;
  199832. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  199833. {
  199834. for (;;)
  199835. {
  199836. char name [256];
  199837. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  199838. {
  199839. addDriverInfo (name, hk);
  199840. }
  199841. else
  199842. {
  199843. break;
  199844. }
  199845. }
  199846. RegCloseKey (hk);
  199847. }
  199848. }
  199849. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  199850. {
  199851. jassert (hasScanned); // need to call scanForDevices() before doing this
  199852. return deviceNames;
  199853. }
  199854. const String getDefaultDeviceName (const bool /*preferInputNames*/,
  199855. const int /*numInputChannelsNeeded*/,
  199856. const int /*numOutputChannelsNeeded*/) const
  199857. {
  199858. jassert (hasScanned); // need to call scanForDevices() before doing this
  199859. return deviceNames [0];
  199860. }
  199861. AudioIODevice* createDevice (const String& deviceName)
  199862. {
  199863. jassert (hasScanned); // need to call scanForDevices() before doing this
  199864. const int index = deviceNames.indexOf (deviceName);
  199865. if (index >= 0)
  199866. {
  199867. jassert (currentASIODev == 0); // unfortunately you can't have more than one ASIO device
  199868. // open at the same time..
  199869. if (currentASIODev == 0)
  199870. return new ASIOAudioIODevice (deviceName, *(classIds [index]));
  199871. }
  199872. return 0;
  199873. }
  199874. juce_UseDebuggingNewOperator
  199875. private:
  199876. StringArray deviceNames;
  199877. OwnedArray <CLSID> classIds;
  199878. bool hasScanned;
  199879. static bool checkClassIsOk (const String& classId)
  199880. {
  199881. HKEY hk = 0;
  199882. bool ok = false;
  199883. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  199884. {
  199885. int index = 0;
  199886. for (;;)
  199887. {
  199888. char buf [512];
  199889. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  199890. {
  199891. if (classId.equalsIgnoreCase (buf))
  199892. {
  199893. HKEY subKey, pathKey;
  199894. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  199895. {
  199896. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  199897. {
  199898. char pathName [600];
  199899. DWORD dtype = REG_SZ;
  199900. DWORD dsize = sizeof (pathName);
  199901. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  199902. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  199903. {
  199904. OFSTRUCT of;
  199905. zerostruct (of);
  199906. of.cBytes = sizeof (of);
  199907. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  199908. }
  199909. RegCloseKey (pathKey);
  199910. }
  199911. RegCloseKey (subKey);
  199912. }
  199913. break;
  199914. }
  199915. }
  199916. else
  199917. {
  199918. break;
  199919. }
  199920. }
  199921. RegCloseKey (hk);
  199922. }
  199923. return ok;
  199924. }
  199925. void addDriverInfo (const String& keyName, HKEY hk)
  199926. {
  199927. HKEY subKey;
  199928. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  199929. {
  199930. char buf [256];
  199931. DWORD dtype = REG_SZ;
  199932. DWORD dsize = sizeof (buf);
  199933. zeromem (buf, dsize);
  199934. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  199935. {
  199936. if (dsize > 0 && checkClassIsOk (buf))
  199937. {
  199938. wchar_t classIdStr [130];
  199939. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  199940. String deviceName;
  199941. CLSID classId;
  199942. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  199943. {
  199944. dtype = REG_SZ;
  199945. dsize = sizeof (buf);
  199946. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  199947. deviceName = buf;
  199948. else
  199949. deviceName = keyName;
  199950. log (T("found ") + deviceName);
  199951. deviceNames.add (deviceName);
  199952. classIds.add (new CLSID (classId));
  199953. }
  199954. }
  199955. RegCloseKey (subKey);
  199956. }
  199957. }
  199958. }
  199959. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  199960. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  199961. };
  199962. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  199963. {
  199964. return new ASIOAudioIODeviceType();
  199965. }
  199966. END_JUCE_NAMESPACE
  199967. #undef log
  199968. #endif
  199969. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  199970. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  199971. #ifdef _MSC_VER
  199972. #pragma warning (disable: 4514)
  199973. #pragma warning (push)
  199974. #endif
  199975. #include <stddef.h>
  199976. #if JUCE_USE_CDBURNER
  199977. // you'll need the Platform SDK for these headers - if you don't have it and don't
  199978. // need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  199979. // flag in juce_Config.h to avoid these includes.
  199980. #include <imapi.h>
  199981. #include <imapierror.h>
  199982. #endif
  199983. BEGIN_JUCE_NAMESPACE
  199984. #ifdef _MSC_VER
  199985. #pragma warning (pop)
  199986. #endif
  199987. //***************************************************************************
  199988. // %%% TARGET STATUS VALUES %%%
  199989. //***************************************************************************
  199990. #define STATUS_GOOD 0x00 // Status Good
  199991. #define STATUS_CHKCOND 0x02 // Check Condition
  199992. #define STATUS_CONDMET 0x04 // Condition Met
  199993. #define STATUS_BUSY 0x08 // Busy
  199994. #define STATUS_INTERM 0x10 // Intermediate
  199995. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  199996. #define STATUS_RESCONF 0x18 // Reservation conflict
  199997. #define STATUS_COMTERM 0x22 // Command Terminated
  199998. #define STATUS_QFULL 0x28 // Queue full
  199999. //***************************************************************************
  200000. // %%% SCSI MISCELLANEOUS EQUATES %%%
  200001. //***************************************************************************
  200002. #define MAXLUN 7 // Maximum Logical Unit Id
  200003. #define MAXTARG 7 // Maximum Target Id
  200004. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  200005. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  200006. //***************************************************************************
  200007. // %%% Commands for all Device Types %%%
  200008. //***************************************************************************
  200009. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  200010. #define SCSI_COMPARE 0x39 // Compare (O)
  200011. #define SCSI_COPY 0x18 // Copy (O)
  200012. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  200013. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  200014. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  200015. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  200016. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  200017. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  200018. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  200019. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  200020. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  200021. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  200022. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  200023. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  200024. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  200025. //***************************************************************************
  200026. // %%% Commands Unique to Direct Access Devices %%%
  200027. //***************************************************************************
  200028. #define SCSI_COMPARE 0x39 // Compare (O)
  200029. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  200030. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  200031. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  200032. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  200033. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  200034. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  200035. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  200036. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  200037. #define SCSI_READ_LONG 0x3E // Read Long (O)
  200038. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  200039. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  200040. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  200041. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  200042. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  200043. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  200044. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  200045. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  200046. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  200047. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  200048. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  200049. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  200050. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  200051. #define SCSI_VERIFY 0x2F // Verify (O)
  200052. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  200053. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  200054. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  200055. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  200056. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  200057. //***************************************************************************
  200058. // %%% Commands Unique to Sequential Access Devices %%%
  200059. //***************************************************************************
  200060. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  200061. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  200062. #define SCSI_LOCATE 0x2B // Locate (O)
  200063. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  200064. #define SCSI_READ_POS 0x34 // Read Position (O)
  200065. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  200066. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  200067. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  200068. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  200069. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  200070. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  200071. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  200072. //***************************************************************************
  200073. // %%% Commands Unique to Printer Devices %%%
  200074. //***************************************************************************
  200075. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  200076. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  200077. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  200078. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  200079. //***************************************************************************
  200080. // %%% Commands Unique to Processor Devices %%%
  200081. //***************************************************************************
  200082. #define SCSI_RECEIVE 0x08 // Receive (O)
  200083. #define SCSI_SEND 0x0A // Send (O)
  200084. //***************************************************************************
  200085. // %%% Commands Unique to Write-Once Devices %%%
  200086. //***************************************************************************
  200087. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  200088. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  200089. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  200090. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  200091. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  200092. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  200093. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  200094. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  200095. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  200096. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  200097. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  200098. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  200099. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  200100. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  200101. //***************************************************************************
  200102. // %%% Commands Unique to CD-ROM Devices %%%
  200103. //***************************************************************************
  200104. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  200105. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  200106. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  200107. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  200108. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  200109. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  200110. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  200111. #define SCSI_READHEADER 0x44 // Read Header (O)
  200112. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  200113. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  200114. //***************************************************************************
  200115. // %%% Commands Unique to Scanner Devices %%%
  200116. //***************************************************************************
  200117. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  200118. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  200119. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  200120. #define SCSI_SCAN 0x1B // Scan (O)
  200121. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  200122. //***************************************************************************
  200123. // %%% Commands Unique to Optical Memory Devices %%%
  200124. //***************************************************************************
  200125. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  200126. //***************************************************************************
  200127. // %%% Commands Unique to Medium Changer Devices %%%
  200128. //***************************************************************************
  200129. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  200130. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  200131. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  200132. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  200133. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  200134. //***************************************************************************
  200135. // %%% Commands Unique to Communication Devices %%%
  200136. //***************************************************************************
  200137. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  200138. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  200139. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  200140. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  200141. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  200142. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  200143. //***************************************************************************
  200144. // %%% Request Sense Data Format %%%
  200145. //***************************************************************************
  200146. typedef struct {
  200147. BYTE ErrorCode; // Error Code (70H or 71H)
  200148. BYTE SegmentNum; // Number of current segment descriptor
  200149. BYTE SenseKey; // Sense Key(See bit definitions too)
  200150. BYTE InfoByte0; // Information MSB
  200151. BYTE InfoByte1; // Information MID
  200152. BYTE InfoByte2; // Information MID
  200153. BYTE InfoByte3; // Information LSB
  200154. BYTE AddSenLen; // Additional Sense Length
  200155. BYTE ComSpecInf0; // Command Specific Information MSB
  200156. BYTE ComSpecInf1; // Command Specific Information MID
  200157. BYTE ComSpecInf2; // Command Specific Information MID
  200158. BYTE ComSpecInf3; // Command Specific Information LSB
  200159. BYTE AddSenseCode; // Additional Sense Code
  200160. BYTE AddSenQual; // Additional Sense Code Qualifier
  200161. BYTE FieldRepUCode; // Field Replaceable Unit Code
  200162. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  200163. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  200164. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  200165. BYTE AddSenseBytes; // Additional Sense Bytes
  200166. } SENSE_DATA_FMT;
  200167. //***************************************************************************
  200168. // %%% REQUEST SENSE ERROR CODE %%%
  200169. //***************************************************************************
  200170. #define SERROR_CURRENT 0x70 // Current Errors
  200171. #define SERROR_DEFERED 0x71 // Deferred Errors
  200172. //***************************************************************************
  200173. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  200174. //***************************************************************************
  200175. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  200176. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  200177. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  200178. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  200179. //***************************************************************************
  200180. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  200181. //***************************************************************************
  200182. #define KEY_NOSENSE 0x00 // No Sense
  200183. #define KEY_RECERROR 0x01 // Recovered Error
  200184. #define KEY_NOTREADY 0x02 // Not Ready
  200185. #define KEY_MEDIUMERR 0x03 // Medium Error
  200186. #define KEY_HARDERROR 0x04 // Hardware Error
  200187. #define KEY_ILLGLREQ 0x05 // Illegal Request
  200188. #define KEY_UNITATT 0x06 // Unit Attention
  200189. #define KEY_DATAPROT 0x07 // Data Protect
  200190. #define KEY_BLANKCHK 0x08 // Blank Check
  200191. #define KEY_VENDSPEC 0x09 // Vendor Specific
  200192. #define KEY_COPYABORT 0x0A // Copy Abort
  200193. #define KEY_EQUAL 0x0C // Equal (Search)
  200194. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  200195. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  200196. #define KEY_RESERVED 0x0F // Reserved
  200197. //***************************************************************************
  200198. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  200199. //***************************************************************************
  200200. #define DTYPE_DASD 0x00 // Disk Device
  200201. #define DTYPE_SEQD 0x01 // Tape Device
  200202. #define DTYPE_PRNT 0x02 // Printer
  200203. #define DTYPE_PROC 0x03 // Processor
  200204. #define DTYPE_WORM 0x04 // Write-once read-multiple
  200205. #define DTYPE_CROM 0x05 // CD-ROM device
  200206. #define DTYPE_SCAN 0x06 // Scanner device
  200207. #define DTYPE_OPTI 0x07 // Optical memory device
  200208. #define DTYPE_JUKE 0x08 // Medium Changer device
  200209. #define DTYPE_COMM 0x09 // Communications device
  200210. #define DTYPE_RESL 0x0A // Reserved (low)
  200211. #define DTYPE_RESH 0x1E // Reserved (high)
  200212. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  200213. //***************************************************************************
  200214. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  200215. //***************************************************************************
  200216. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  200217. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  200218. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  200219. #define ANSI_RESLO 0x3 // Reserved (low)
  200220. #define ANSI_RESHI 0x7 // Reserved (high)
  200221. typedef struct
  200222. {
  200223. USHORT Length;
  200224. UCHAR ScsiStatus;
  200225. UCHAR PathId;
  200226. UCHAR TargetId;
  200227. UCHAR Lun;
  200228. UCHAR CdbLength;
  200229. UCHAR SenseInfoLength;
  200230. UCHAR DataIn;
  200231. ULONG DataTransferLength;
  200232. ULONG TimeOutValue;
  200233. ULONG DataBufferOffset;
  200234. ULONG SenseInfoOffset;
  200235. UCHAR Cdb[16];
  200236. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  200237. typedef struct
  200238. {
  200239. USHORT Length;
  200240. UCHAR ScsiStatus;
  200241. UCHAR PathId;
  200242. UCHAR TargetId;
  200243. UCHAR Lun;
  200244. UCHAR CdbLength;
  200245. UCHAR SenseInfoLength;
  200246. UCHAR DataIn;
  200247. ULONG DataTransferLength;
  200248. ULONG TimeOutValue;
  200249. PVOID DataBuffer;
  200250. ULONG SenseInfoOffset;
  200251. UCHAR Cdb[16];
  200252. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  200253. typedef struct
  200254. {
  200255. SCSI_PASS_THROUGH_DIRECT spt;
  200256. ULONG Filler;
  200257. UCHAR ucSenseBuf[32];
  200258. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  200259. typedef struct
  200260. {
  200261. ULONG Length;
  200262. UCHAR PortNumber;
  200263. UCHAR PathId;
  200264. UCHAR TargetId;
  200265. UCHAR Lun;
  200266. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  200267. #define METHOD_BUFFERED 0
  200268. #define METHOD_IN_DIRECT 1
  200269. #define METHOD_OUT_DIRECT 2
  200270. #define METHOD_NEITHER 3
  200271. #define FILE_ANY_ACCESS 0
  200272. #ifndef FILE_READ_ACCESS
  200273. #define FILE_READ_ACCESS (0x0001)
  200274. #endif
  200275. #ifndef FILE_WRITE_ACCESS
  200276. #define FILE_WRITE_ACCESS (0x0002)
  200277. #endif
  200278. #define IOCTL_SCSI_BASE 0x00000004
  200279. #define SCSI_IOCTL_DATA_OUT 0
  200280. #define SCSI_IOCTL_DATA_IN 1
  200281. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  200282. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  200283. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  200284. )
  200285. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  200286. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  200287. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  200288. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  200289. #define SENSE_LEN 14
  200290. #define SRB_DIR_SCSI 0x00
  200291. #define SRB_POSTING 0x01
  200292. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  200293. #define SRB_DIR_IN 0x08
  200294. #define SRB_DIR_OUT 0x10
  200295. #define SRB_EVENT_NOTIFY 0x40
  200296. #define RESIDUAL_COUNT_SUPPORTED 0x02
  200297. #define MAX_SRB_TIMEOUT 1080001u
  200298. #define DEFAULT_SRB_TIMEOUT 1080001u
  200299. #define SC_HA_INQUIRY 0x00
  200300. #define SC_GET_DEV_TYPE 0x01
  200301. #define SC_EXEC_SCSI_CMD 0x02
  200302. #define SC_ABORT_SRB 0x03
  200303. #define SC_RESET_DEV 0x04
  200304. #define SC_SET_HA_PARMS 0x05
  200305. #define SC_GET_DISK_INFO 0x06
  200306. #define SC_RESCAN_SCSI_BUS 0x07
  200307. #define SC_GETSET_TIMEOUTS 0x08
  200308. #define SS_PENDING 0x00
  200309. #define SS_COMP 0x01
  200310. #define SS_ABORTED 0x02
  200311. #define SS_ABORT_FAIL 0x03
  200312. #define SS_ERR 0x04
  200313. #define SS_INVALID_CMD 0x80
  200314. #define SS_INVALID_HA 0x81
  200315. #define SS_NO_DEVICE 0x82
  200316. #define SS_INVALID_SRB 0xE0
  200317. #define SS_OLD_MANAGER 0xE1
  200318. #define SS_BUFFER_ALIGN 0xE1
  200319. #define SS_ILLEGAL_MODE 0xE2
  200320. #define SS_NO_ASPI 0xE3
  200321. #define SS_FAILED_INIT 0xE4
  200322. #define SS_ASPI_IS_BUSY 0xE5
  200323. #define SS_BUFFER_TO_BIG 0xE6
  200324. #define SS_BUFFER_TOO_BIG 0xE6
  200325. #define SS_MISMATCHED_COMPONENTS 0xE7
  200326. #define SS_NO_ADAPTERS 0xE8
  200327. #define SS_INSUFFICIENT_RESOURCES 0xE9
  200328. #define SS_ASPI_IS_SHUTDOWN 0xEA
  200329. #define SS_BAD_INSTALL 0xEB
  200330. #define HASTAT_OK 0x00
  200331. #define HASTAT_SEL_TO 0x11
  200332. #define HASTAT_DO_DU 0x12
  200333. #define HASTAT_BUS_FREE 0x13
  200334. #define HASTAT_PHASE_ERR 0x14
  200335. #define HASTAT_TIMEOUT 0x09
  200336. #define HASTAT_COMMAND_TIMEOUT 0x0B
  200337. #define HASTAT_MESSAGE_REJECT 0x0D
  200338. #define HASTAT_BUS_RESET 0x0E
  200339. #define HASTAT_PARITY_ERROR 0x0F
  200340. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  200341. #define PACKED
  200342. #pragma pack(1)
  200343. typedef struct
  200344. {
  200345. BYTE SRB_Cmd;
  200346. BYTE SRB_Status;
  200347. BYTE SRB_HaID;
  200348. BYTE SRB_Flags;
  200349. DWORD SRB_Hdr_Rsvd;
  200350. BYTE HA_Count;
  200351. BYTE HA_SCSI_ID;
  200352. BYTE HA_ManagerId[16];
  200353. BYTE HA_Identifier[16];
  200354. BYTE HA_Unique[16];
  200355. WORD HA_Rsvd1;
  200356. BYTE pad[20];
  200357. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  200358. typedef struct
  200359. {
  200360. BYTE SRB_Cmd;
  200361. BYTE SRB_Status;
  200362. BYTE SRB_HaID;
  200363. BYTE SRB_Flags;
  200364. DWORD SRB_Hdr_Rsvd;
  200365. BYTE SRB_Target;
  200366. BYTE SRB_Lun;
  200367. BYTE SRB_DeviceType;
  200368. BYTE SRB_Rsvd1;
  200369. BYTE pad[68];
  200370. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  200371. typedef struct
  200372. {
  200373. BYTE SRB_Cmd;
  200374. BYTE SRB_Status;
  200375. BYTE SRB_HaID;
  200376. BYTE SRB_Flags;
  200377. DWORD SRB_Hdr_Rsvd;
  200378. BYTE SRB_Target;
  200379. BYTE SRB_Lun;
  200380. WORD SRB_Rsvd1;
  200381. DWORD SRB_BufLen;
  200382. BYTE FAR *SRB_BufPointer;
  200383. BYTE SRB_SenseLen;
  200384. BYTE SRB_CDBLen;
  200385. BYTE SRB_HaStat;
  200386. BYTE SRB_TargStat;
  200387. VOID FAR *SRB_PostProc;
  200388. BYTE SRB_Rsvd2[20];
  200389. BYTE CDBByte[16];
  200390. BYTE SenseArea[SENSE_LEN+2];
  200391. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  200392. typedef struct
  200393. {
  200394. BYTE SRB_Cmd;
  200395. BYTE SRB_Status;
  200396. BYTE SRB_HaId;
  200397. BYTE SRB_Flags;
  200398. DWORD SRB_Hdr_Rsvd;
  200399. } PACKED SRB, *PSRB, FAR *LPSRB;
  200400. #pragma pack()
  200401. struct CDDeviceInfo
  200402. {
  200403. char vendor[9];
  200404. char productId[17];
  200405. char rev[5];
  200406. char vendorSpec[21];
  200407. BYTE ha;
  200408. BYTE tgt;
  200409. BYTE lun;
  200410. char scsiDriveLetter; // will be 0 if not using scsi
  200411. };
  200412. class CDReadBuffer
  200413. {
  200414. public:
  200415. int startFrame;
  200416. int numFrames;
  200417. int dataStartOffset;
  200418. int dataLength;
  200419. BYTE* buffer;
  200420. int bufferSize;
  200421. int index;
  200422. bool wantsIndex;
  200423. CDReadBuffer (const int numberOfFrames)
  200424. : startFrame (0),
  200425. numFrames (0),
  200426. dataStartOffset (0),
  200427. dataLength (0),
  200428. index (0),
  200429. wantsIndex (false)
  200430. {
  200431. bufferSize = 2352 * numberOfFrames;
  200432. buffer = (BYTE*) malloc (bufferSize);
  200433. }
  200434. ~CDReadBuffer()
  200435. {
  200436. free (buffer);
  200437. }
  200438. bool isZero() const
  200439. {
  200440. BYTE* p = buffer + dataStartOffset;
  200441. for (int i = dataLength; --i >= 0;)
  200442. if (*p++ != 0)
  200443. return false;
  200444. return true;
  200445. }
  200446. };
  200447. class CDDeviceHandle;
  200448. class CDController
  200449. {
  200450. public:
  200451. CDController();
  200452. virtual ~CDController();
  200453. virtual bool read (CDReadBuffer* t) = 0;
  200454. virtual void shutDown();
  200455. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  200456. int getLastIndex();
  200457. public:
  200458. bool initialised;
  200459. CDDeviceHandle* deviceInfo;
  200460. int framesToCheck, framesOverlap;
  200461. void prepare (SRB_ExecSCSICmd& s);
  200462. void perform (SRB_ExecSCSICmd& s);
  200463. void setPaused (bool paused);
  200464. };
  200465. #pragma pack(1)
  200466. struct TOCTRACK
  200467. {
  200468. BYTE rsvd;
  200469. BYTE ADR;
  200470. BYTE trackNumber;
  200471. BYTE rsvd2;
  200472. BYTE addr[4];
  200473. };
  200474. struct TOC
  200475. {
  200476. WORD tocLen;
  200477. BYTE firstTrack;
  200478. BYTE lastTrack;
  200479. TOCTRACK tracks[100];
  200480. };
  200481. #pragma pack()
  200482. enum
  200483. {
  200484. READTYPE_ANY = 0,
  200485. READTYPE_ATAPI1 = 1,
  200486. READTYPE_ATAPI2 = 2,
  200487. READTYPE_READ6 = 3,
  200488. READTYPE_READ10 = 4,
  200489. READTYPE_READ_D8 = 5,
  200490. READTYPE_READ_D4 = 6,
  200491. READTYPE_READ_D4_1 = 7,
  200492. READTYPE_READ10_2 = 8
  200493. };
  200494. class CDDeviceHandle
  200495. {
  200496. public:
  200497. CDDeviceHandle (const CDDeviceInfo* const device)
  200498. : scsiHandle (0),
  200499. readType (READTYPE_ANY),
  200500. controller (0)
  200501. {
  200502. memcpy (&info, device, sizeof (info));
  200503. }
  200504. ~CDDeviceHandle()
  200505. {
  200506. if (controller != 0)
  200507. {
  200508. controller->shutDown();
  200509. delete controller;
  200510. }
  200511. if (scsiHandle != 0)
  200512. CloseHandle (scsiHandle);
  200513. }
  200514. bool readTOC (TOC* lpToc, bool useMSF);
  200515. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  200516. void openDrawer (bool shouldBeOpen);
  200517. CDDeviceInfo info;
  200518. HANDLE scsiHandle;
  200519. BYTE readType;
  200520. private:
  200521. CDController* controller;
  200522. bool testController (const int readType,
  200523. CDController* const newController,
  200524. CDReadBuffer* const bufferToUse);
  200525. };
  200526. DWORD (*fGetASPI32SupportInfo)(void);
  200527. DWORD (*fSendASPI32Command)(LPSRB);
  200528. static HINSTANCE winAspiLib = 0;
  200529. static bool usingScsi = false;
  200530. static bool initialised = false;
  200531. static bool InitialiseCDRipper()
  200532. {
  200533. if (! initialised)
  200534. {
  200535. initialised = true;
  200536. OSVERSIONINFO info;
  200537. info.dwOSVersionInfoSize = sizeof (info);
  200538. GetVersionEx (&info);
  200539. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  200540. if (! usingScsi)
  200541. {
  200542. fGetASPI32SupportInfo = 0;
  200543. fSendASPI32Command = 0;
  200544. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  200545. if (winAspiLib != 0)
  200546. {
  200547. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  200548. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  200549. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  200550. return false;
  200551. }
  200552. else
  200553. {
  200554. usingScsi = true;
  200555. }
  200556. }
  200557. }
  200558. return true;
  200559. }
  200560. static void DeinitialiseCDRipper()
  200561. {
  200562. if (winAspiLib != 0)
  200563. {
  200564. fGetASPI32SupportInfo = 0;
  200565. fSendASPI32Command = 0;
  200566. FreeLibrary (winAspiLib);
  200567. winAspiLib = 0;
  200568. }
  200569. initialised = false;
  200570. }
  200571. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  200572. {
  200573. TCHAR devicePath[8];
  200574. devicePath[0] = '\\';
  200575. devicePath[1] = '\\';
  200576. devicePath[2] = '.';
  200577. devicePath[3] = '\\';
  200578. devicePath[4] = driveLetter;
  200579. devicePath[5] = ':';
  200580. devicePath[6] = 0;
  200581. OSVERSIONINFO info;
  200582. info.dwOSVersionInfoSize = sizeof (info);
  200583. GetVersionEx (&info);
  200584. DWORD flags = GENERIC_READ;
  200585. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  200586. flags = GENERIC_READ | GENERIC_WRITE;
  200587. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  200588. if (h == INVALID_HANDLE_VALUE)
  200589. {
  200590. flags ^= GENERIC_WRITE;
  200591. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  200592. }
  200593. return h;
  200594. }
  200595. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  200596. const char driveLetter,
  200597. HANDLE& deviceHandle,
  200598. const bool retryOnFailure = true)
  200599. {
  200600. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  200601. zerostruct (s);
  200602. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  200603. s.spt.CdbLength = srb->SRB_CDBLen;
  200604. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  200605. ? SCSI_IOCTL_DATA_IN
  200606. : ((srb->SRB_Flags & SRB_DIR_OUT)
  200607. ? SCSI_IOCTL_DATA_OUT
  200608. : SCSI_IOCTL_DATA_UNSPECIFIED));
  200609. s.spt.DataTransferLength = srb->SRB_BufLen;
  200610. s.spt.TimeOutValue = 5;
  200611. s.spt.DataBuffer = srb->SRB_BufPointer;
  200612. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  200613. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  200614. srb->SRB_Status = SS_ERR;
  200615. srb->SRB_TargStat = 0x0004;
  200616. DWORD bytesReturned = 0;
  200617. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  200618. &s, sizeof (s),
  200619. &s, sizeof (s),
  200620. &bytesReturned, 0) != 0)
  200621. {
  200622. srb->SRB_Status = SS_COMP;
  200623. }
  200624. else if (retryOnFailure)
  200625. {
  200626. const DWORD error = GetLastError();
  200627. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  200628. {
  200629. if (error != ERROR_INVALID_HANDLE)
  200630. CloseHandle (deviceHandle);
  200631. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  200632. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  200633. }
  200634. }
  200635. return srb->SRB_Status;
  200636. }
  200637. // Controller types..
  200638. class ControllerType1 : public CDController
  200639. {
  200640. public:
  200641. ControllerType1() {}
  200642. ~ControllerType1() {}
  200643. bool read (CDReadBuffer* rb)
  200644. {
  200645. if (rb->numFrames * 2352 > rb->bufferSize)
  200646. return false;
  200647. SRB_ExecSCSICmd s;
  200648. prepare (s);
  200649. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200650. s.SRB_BufLen = rb->bufferSize;
  200651. s.SRB_BufPointer = rb->buffer;
  200652. s.SRB_CDBLen = 12;
  200653. s.CDBByte[0] = 0xBE;
  200654. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200655. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200656. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200657. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200658. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  200659. perform (s);
  200660. if (s.SRB_Status != SS_COMP)
  200661. return false;
  200662. rb->dataLength = rb->numFrames * 2352;
  200663. rb->dataStartOffset = 0;
  200664. return true;
  200665. }
  200666. };
  200667. class ControllerType2 : public CDController
  200668. {
  200669. public:
  200670. ControllerType2() {}
  200671. ~ControllerType2() {}
  200672. void shutDown()
  200673. {
  200674. if (initialised)
  200675. {
  200676. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  200677. SRB_ExecSCSICmd s;
  200678. prepare (s);
  200679. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  200680. s.SRB_BufLen = 0x0C;
  200681. s.SRB_BufPointer = bufPointer;
  200682. s.SRB_CDBLen = 6;
  200683. s.CDBByte[0] = 0x15;
  200684. s.CDBByte[4] = 0x0C;
  200685. perform (s);
  200686. }
  200687. }
  200688. bool init()
  200689. {
  200690. SRB_ExecSCSICmd s;
  200691. s.SRB_Status = SS_ERR;
  200692. if (deviceInfo->readType == READTYPE_READ10_2)
  200693. {
  200694. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  200695. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  200696. for (int i = 0; i < 2; ++i)
  200697. {
  200698. prepare (s);
  200699. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200700. s.SRB_BufLen = 0x14;
  200701. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  200702. s.SRB_CDBLen = 6;
  200703. s.CDBByte[0] = 0x15;
  200704. s.CDBByte[1] = 0x10;
  200705. s.CDBByte[4] = 0x14;
  200706. perform (s);
  200707. if (s.SRB_Status != SS_COMP)
  200708. return false;
  200709. }
  200710. }
  200711. else
  200712. {
  200713. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  200714. prepare (s);
  200715. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200716. s.SRB_BufLen = 0x0C;
  200717. s.SRB_BufPointer = bufPointer;
  200718. s.SRB_CDBLen = 6;
  200719. s.CDBByte[0] = 0x15;
  200720. s.CDBByte[4] = 0x0C;
  200721. perform (s);
  200722. }
  200723. return s.SRB_Status == SS_COMP;
  200724. }
  200725. bool read (CDReadBuffer* rb)
  200726. {
  200727. if (rb->numFrames * 2352 > rb->bufferSize)
  200728. return false;
  200729. if (!initialised)
  200730. {
  200731. initialised = init();
  200732. if (!initialised)
  200733. return false;
  200734. }
  200735. SRB_ExecSCSICmd s;
  200736. prepare (s);
  200737. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200738. s.SRB_BufLen = rb->bufferSize;
  200739. s.SRB_BufPointer = rb->buffer;
  200740. s.SRB_CDBLen = 10;
  200741. s.CDBByte[0] = 0x28;
  200742. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  200743. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200744. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200745. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200746. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200747. perform (s);
  200748. if (s.SRB_Status != SS_COMP)
  200749. return false;
  200750. rb->dataLength = rb->numFrames * 2352;
  200751. rb->dataStartOffset = 0;
  200752. return true;
  200753. }
  200754. };
  200755. class ControllerType3 : public CDController
  200756. {
  200757. public:
  200758. ControllerType3() {}
  200759. ~ControllerType3() {}
  200760. bool read (CDReadBuffer* rb)
  200761. {
  200762. if (rb->numFrames * 2352 > rb->bufferSize)
  200763. return false;
  200764. if (!initialised)
  200765. {
  200766. setPaused (false);
  200767. initialised = true;
  200768. }
  200769. SRB_ExecSCSICmd s;
  200770. prepare (s);
  200771. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200772. s.SRB_BufLen = rb->numFrames * 2352;
  200773. s.SRB_BufPointer = rb->buffer;
  200774. s.SRB_CDBLen = 12;
  200775. s.CDBByte[0] = 0xD8;
  200776. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200777. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200778. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200779. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  200780. perform (s);
  200781. if (s.SRB_Status != SS_COMP)
  200782. return false;
  200783. rb->dataLength = rb->numFrames * 2352;
  200784. rb->dataStartOffset = 0;
  200785. return true;
  200786. }
  200787. };
  200788. class ControllerType4 : public CDController
  200789. {
  200790. public:
  200791. ControllerType4() {}
  200792. ~ControllerType4() {}
  200793. bool selectD4Mode()
  200794. {
  200795. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  200796. SRB_ExecSCSICmd s;
  200797. prepare (s);
  200798. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200799. s.SRB_CDBLen = 6;
  200800. s.SRB_BufLen = 12;
  200801. s.SRB_BufPointer = bufPointer;
  200802. s.CDBByte[0] = 0x15;
  200803. s.CDBByte[1] = 0x10;
  200804. s.CDBByte[4] = 0x08;
  200805. perform (s);
  200806. return s.SRB_Status == SS_COMP;
  200807. }
  200808. bool read (CDReadBuffer* rb)
  200809. {
  200810. if (rb->numFrames * 2352 > rb->bufferSize)
  200811. return false;
  200812. if (!initialised)
  200813. {
  200814. setPaused (true);
  200815. if (deviceInfo->readType == READTYPE_READ_D4_1)
  200816. selectD4Mode();
  200817. initialised = true;
  200818. }
  200819. SRB_ExecSCSICmd s;
  200820. prepare (s);
  200821. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200822. s.SRB_BufLen = rb->bufferSize;
  200823. s.SRB_BufPointer = rb->buffer;
  200824. s.SRB_CDBLen = 10;
  200825. s.CDBByte[0] = 0xD4;
  200826. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200827. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200828. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200829. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200830. perform (s);
  200831. if (s.SRB_Status != SS_COMP)
  200832. return false;
  200833. rb->dataLength = rb->numFrames * 2352;
  200834. rb->dataStartOffset = 0;
  200835. return true;
  200836. }
  200837. };
  200838. CDController::CDController() : initialised (false)
  200839. {
  200840. }
  200841. CDController::~CDController()
  200842. {
  200843. }
  200844. void CDController::prepare (SRB_ExecSCSICmd& s)
  200845. {
  200846. zerostruct (s);
  200847. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  200848. s.SRB_HaID = deviceInfo->info.ha;
  200849. s.SRB_Target = deviceInfo->info.tgt;
  200850. s.SRB_Lun = deviceInfo->info.lun;
  200851. s.SRB_SenseLen = SENSE_LEN;
  200852. }
  200853. void CDController::perform (SRB_ExecSCSICmd& s)
  200854. {
  200855. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  200856. s.SRB_PostProc = (void*)event;
  200857. ResetEvent (event);
  200858. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  200859. deviceInfo->info.scsiDriveLetter,
  200860. deviceInfo->scsiHandle)
  200861. : fSendASPI32Command ((LPSRB)&s);
  200862. if (status == SS_PENDING)
  200863. WaitForSingleObject (event, 4000);
  200864. CloseHandle (event);
  200865. }
  200866. void CDController::setPaused (bool paused)
  200867. {
  200868. SRB_ExecSCSICmd s;
  200869. prepare (s);
  200870. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200871. s.SRB_CDBLen = 10;
  200872. s.CDBByte[0] = 0x4B;
  200873. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  200874. perform (s);
  200875. }
  200876. void CDController::shutDown()
  200877. {
  200878. }
  200879. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  200880. {
  200881. if (overlapBuffer != 0)
  200882. {
  200883. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  200884. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  200885. if (doJitter
  200886. && overlapBuffer->startFrame > 0
  200887. && overlapBuffer->numFrames > 0
  200888. && overlapBuffer->dataLength > 0)
  200889. {
  200890. const int numFrames = rb->numFrames;
  200891. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  200892. {
  200893. rb->startFrame -= framesOverlap;
  200894. if (framesToCheck < framesOverlap
  200895. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  200896. rb->numFrames += framesOverlap;
  200897. }
  200898. else
  200899. {
  200900. overlapBuffer->dataLength = 0;
  200901. overlapBuffer->startFrame = 0;
  200902. overlapBuffer->numFrames = 0;
  200903. }
  200904. }
  200905. if (! read (rb))
  200906. return false;
  200907. if (doJitter)
  200908. {
  200909. const int checkLen = framesToCheck * 2352;
  200910. const int maxToCheck = rb->dataLength - checkLen;
  200911. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  200912. return true;
  200913. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  200914. bool found = false;
  200915. for (int i = 0; i < maxToCheck; ++i)
  200916. {
  200917. if (!memcmp (p, rb->buffer + i, checkLen))
  200918. {
  200919. i += checkLen;
  200920. rb->dataStartOffset = i;
  200921. rb->dataLength -= i;
  200922. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  200923. found = true;
  200924. break;
  200925. }
  200926. }
  200927. rb->numFrames = rb->dataLength / 2352;
  200928. rb->dataLength = 2352 * rb->numFrames;
  200929. if (!found)
  200930. return false;
  200931. }
  200932. if (canDoJitter)
  200933. {
  200934. memcpy (overlapBuffer->buffer,
  200935. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  200936. 2352 * framesToCheck);
  200937. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  200938. overlapBuffer->numFrames = framesToCheck;
  200939. overlapBuffer->dataLength = 2352 * framesToCheck;
  200940. overlapBuffer->dataStartOffset = 0;
  200941. }
  200942. else
  200943. {
  200944. overlapBuffer->startFrame = 0;
  200945. overlapBuffer->numFrames = 0;
  200946. overlapBuffer->dataLength = 0;
  200947. }
  200948. return true;
  200949. }
  200950. else
  200951. {
  200952. return read (rb);
  200953. }
  200954. }
  200955. int CDController::getLastIndex()
  200956. {
  200957. char qdata[100];
  200958. SRB_ExecSCSICmd s;
  200959. prepare (s);
  200960. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200961. s.SRB_BufLen = sizeof (qdata);
  200962. s.SRB_BufPointer = (BYTE*)qdata;
  200963. s.SRB_CDBLen = 12;
  200964. s.CDBByte[0] = 0x42;
  200965. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  200966. s.CDBByte[2] = 64;
  200967. s.CDBByte[3] = 1; // get current position
  200968. s.CDBByte[7] = 0;
  200969. s.CDBByte[8] = (BYTE)sizeof (qdata);
  200970. perform (s);
  200971. if (s.SRB_Status == SS_COMP)
  200972. return qdata[7];
  200973. return 0;
  200974. }
  200975. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  200976. {
  200977. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  200978. SRB_ExecSCSICmd s;
  200979. zerostruct (s);
  200980. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  200981. s.SRB_HaID = info.ha;
  200982. s.SRB_Target = info.tgt;
  200983. s.SRB_Lun = info.lun;
  200984. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200985. s.SRB_BufLen = 0x324;
  200986. s.SRB_BufPointer = (BYTE*)lpToc;
  200987. s.SRB_SenseLen = 0x0E;
  200988. s.SRB_CDBLen = 0x0A;
  200989. s.SRB_PostProc = (void*)event;
  200990. s.CDBByte[0] = 0x43;
  200991. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  200992. s.CDBByte[7] = 0x03;
  200993. s.CDBByte[8] = 0x24;
  200994. ResetEvent (event);
  200995. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  200996. : fSendASPI32Command ((LPSRB)&s);
  200997. if (status == SS_PENDING)
  200998. WaitForSingleObject (event, 4000);
  200999. CloseHandle (event);
  201000. return (s.SRB_Status == SS_COMP);
  201001. }
  201002. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  201003. CDReadBuffer* const overlapBuffer)
  201004. {
  201005. if (controller == 0)
  201006. {
  201007. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  201008. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  201009. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  201010. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  201011. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  201012. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  201013. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  201014. }
  201015. buffer->index = 0;
  201016. if ((controller != 0)
  201017. && controller->readAudio (buffer, overlapBuffer))
  201018. {
  201019. if (buffer->wantsIndex)
  201020. buffer->index = controller->getLastIndex();
  201021. return true;
  201022. }
  201023. return false;
  201024. }
  201025. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  201026. {
  201027. if (shouldBeOpen)
  201028. {
  201029. if (controller != 0)
  201030. {
  201031. controller->shutDown();
  201032. delete controller;
  201033. controller = 0;
  201034. }
  201035. if (scsiHandle != 0)
  201036. {
  201037. CloseHandle (scsiHandle);
  201038. scsiHandle = 0;
  201039. }
  201040. }
  201041. SRB_ExecSCSICmd s;
  201042. zerostruct (s);
  201043. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201044. s.SRB_HaID = info.ha;
  201045. s.SRB_Target = info.tgt;
  201046. s.SRB_Lun = info.lun;
  201047. s.SRB_SenseLen = SENSE_LEN;
  201048. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201049. s.SRB_BufLen = 0;
  201050. s.SRB_BufPointer = 0;
  201051. s.SRB_CDBLen = 12;
  201052. s.CDBByte[0] = 0x1b;
  201053. s.CDBByte[1] = (BYTE)(info.lun << 5);
  201054. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  201055. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201056. s.SRB_PostProc = (void*)event;
  201057. ResetEvent (event);
  201058. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201059. : fSendASPI32Command ((LPSRB)&s);
  201060. if (status == SS_PENDING)
  201061. WaitForSingleObject (event, 4000);
  201062. CloseHandle (event);
  201063. }
  201064. bool CDDeviceHandle::testController (const int type,
  201065. CDController* const newController,
  201066. CDReadBuffer* const rb)
  201067. {
  201068. controller = newController;
  201069. readType = (BYTE)type;
  201070. controller->deviceInfo = this;
  201071. controller->framesToCheck = 1;
  201072. controller->framesOverlap = 3;
  201073. bool passed = false;
  201074. memset (rb->buffer, 0xcd, rb->bufferSize);
  201075. if (controller->read (rb))
  201076. {
  201077. passed = true;
  201078. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  201079. int wrong = 0;
  201080. for (int i = rb->dataLength / 4; --i >= 0;)
  201081. {
  201082. if (*p++ == (int) 0xcdcdcdcd)
  201083. {
  201084. if (++wrong == 4)
  201085. {
  201086. passed = false;
  201087. break;
  201088. }
  201089. }
  201090. else
  201091. {
  201092. wrong = 0;
  201093. }
  201094. }
  201095. }
  201096. if (! passed)
  201097. {
  201098. controller->shutDown();
  201099. delete controller;
  201100. controller = 0;
  201101. }
  201102. return passed;
  201103. }
  201104. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  201105. {
  201106. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201107. const int bufSize = 128;
  201108. BYTE buffer[bufSize];
  201109. zeromem (buffer, bufSize);
  201110. SRB_ExecSCSICmd s;
  201111. zerostruct (s);
  201112. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201113. s.SRB_HaID = ha;
  201114. s.SRB_Target = tgt;
  201115. s.SRB_Lun = lun;
  201116. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201117. s.SRB_BufLen = bufSize;
  201118. s.SRB_BufPointer = buffer;
  201119. s.SRB_SenseLen = SENSE_LEN;
  201120. s.SRB_CDBLen = 6;
  201121. s.SRB_PostProc = (void*)event;
  201122. s.CDBByte[0] = SCSI_INQUIRY;
  201123. s.CDBByte[4] = 100;
  201124. ResetEvent (event);
  201125. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  201126. WaitForSingleObject (event, 4000);
  201127. CloseHandle (event);
  201128. if (s.SRB_Status == SS_COMP)
  201129. {
  201130. memcpy (dev->vendor, &buffer[8], 8);
  201131. memcpy (dev->productId, &buffer[16], 16);
  201132. memcpy (dev->rev, &buffer[32], 4);
  201133. memcpy (dev->vendorSpec, &buffer[36], 20);
  201134. }
  201135. }
  201136. static int FindCDDevices (CDDeviceInfo* const list,
  201137. int maxItems)
  201138. {
  201139. int count = 0;
  201140. if (usingScsi)
  201141. {
  201142. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  201143. {
  201144. TCHAR drivePath[8];
  201145. drivePath[0] = driveLetter;
  201146. drivePath[1] = ':';
  201147. drivePath[2] = '\\';
  201148. drivePath[3] = 0;
  201149. if (GetDriveType (drivePath) == DRIVE_CDROM)
  201150. {
  201151. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  201152. if (h != INVALID_HANDLE_VALUE)
  201153. {
  201154. BYTE buffer[100], passThroughStruct[1024];
  201155. zeromem (buffer, sizeof (buffer));
  201156. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201157. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  201158. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  201159. p->spt.CdbLength = 6;
  201160. p->spt.SenseInfoLength = 24;
  201161. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  201162. p->spt.DataTransferLength = 100;
  201163. p->spt.TimeOutValue = 2;
  201164. p->spt.DataBuffer = buffer;
  201165. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201166. p->spt.Cdb[0] = 0x12;
  201167. p->spt.Cdb[4] = 100;
  201168. DWORD bytesReturned = 0;
  201169. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201170. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201171. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201172. &bytesReturned, 0) != 0)
  201173. {
  201174. zeromem (&list[count], sizeof (CDDeviceInfo));
  201175. list[count].scsiDriveLetter = driveLetter;
  201176. memcpy (list[count].vendor, &buffer[8], 8);
  201177. memcpy (list[count].productId, &buffer[16], 16);
  201178. memcpy (list[count].rev, &buffer[32], 4);
  201179. memcpy (list[count].vendorSpec, &buffer[36], 20);
  201180. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201181. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  201182. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  201183. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  201184. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  201185. &bytesReturned, 0) != 0)
  201186. {
  201187. list[count].ha = scsiAddr->PortNumber;
  201188. list[count].tgt = scsiAddr->TargetId;
  201189. list[count].lun = scsiAddr->Lun;
  201190. ++count;
  201191. }
  201192. }
  201193. CloseHandle (h);
  201194. }
  201195. }
  201196. }
  201197. }
  201198. else
  201199. {
  201200. const DWORD d = fGetASPI32SupportInfo();
  201201. BYTE status = HIBYTE (LOWORD (d));
  201202. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  201203. return 0;
  201204. const int numAdapters = LOBYTE (LOWORD (d));
  201205. for (BYTE ha = 0; ha < numAdapters; ++ha)
  201206. {
  201207. SRB_HAInquiry s;
  201208. zerostruct (s);
  201209. s.SRB_Cmd = SC_HA_INQUIRY;
  201210. s.SRB_HaID = ha;
  201211. fSendASPI32Command ((LPSRB)&s);
  201212. if (s.SRB_Status == SS_COMP)
  201213. {
  201214. maxItems = (int)s.HA_Unique[3];
  201215. if (maxItems == 0)
  201216. maxItems = 8;
  201217. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  201218. {
  201219. for (BYTE lun = 0; lun < 8; ++lun)
  201220. {
  201221. SRB_GDEVBlock sb;
  201222. zerostruct (sb);
  201223. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  201224. sb.SRB_HaID = ha;
  201225. sb.SRB_Target = tgt;
  201226. sb.SRB_Lun = lun;
  201227. fSendASPI32Command ((LPSRB) &sb);
  201228. if (sb.SRB_Status == SS_COMP
  201229. && sb.SRB_DeviceType == DTYPE_CROM)
  201230. {
  201231. zeromem (&list[count], sizeof (CDDeviceInfo));
  201232. list[count].ha = ha;
  201233. list[count].tgt = tgt;
  201234. list[count].lun = lun;
  201235. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  201236. ++count;
  201237. }
  201238. }
  201239. }
  201240. }
  201241. }
  201242. }
  201243. return count;
  201244. }
  201245. static int ripperUsers = 0;
  201246. static bool initialisedOk = false;
  201247. class DeinitialiseTimer : private Timer,
  201248. private DeletedAtShutdown
  201249. {
  201250. DeinitialiseTimer (const DeinitialiseTimer&);
  201251. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  201252. public:
  201253. DeinitialiseTimer()
  201254. {
  201255. startTimer (4000);
  201256. }
  201257. ~DeinitialiseTimer()
  201258. {
  201259. if (--ripperUsers == 0)
  201260. DeinitialiseCDRipper();
  201261. }
  201262. void timerCallback()
  201263. {
  201264. delete this;
  201265. }
  201266. juce_UseDebuggingNewOperator
  201267. };
  201268. static void incUserCount()
  201269. {
  201270. if (ripperUsers++ == 0)
  201271. initialisedOk = InitialiseCDRipper();
  201272. }
  201273. static void decUserCount()
  201274. {
  201275. new DeinitialiseTimer();
  201276. }
  201277. struct CDDeviceWrapper
  201278. {
  201279. CDDeviceHandle* cdH;
  201280. CDReadBuffer* overlapBuffer;
  201281. bool jitter;
  201282. };
  201283. static int getAddressOf (const TOCTRACK* const t)
  201284. {
  201285. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  201286. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  201287. }
  201288. static int getMSFAddressOf (const TOCTRACK* const t)
  201289. {
  201290. return 60 * t->addr[1] + t->addr[2];
  201291. }
  201292. static const int samplesPerFrame = 44100 / 75;
  201293. static const int bytesPerFrame = samplesPerFrame * 4;
  201294. const StringArray AudioCDReader::getAvailableCDNames()
  201295. {
  201296. StringArray results;
  201297. incUserCount();
  201298. if (initialisedOk)
  201299. {
  201300. CDDeviceInfo list[8];
  201301. const int num = FindCDDevices (list, 8);
  201302. decUserCount();
  201303. for (int i = 0; i < num; ++i)
  201304. {
  201305. String s;
  201306. if (list[i].scsiDriveLetter > 0)
  201307. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  201308. s << String (list[i].vendor).trim()
  201309. << T(" ") << String (list[i].productId).trim()
  201310. << T(" ") << String (list[i].rev).trim();
  201311. results.add (s);
  201312. }
  201313. }
  201314. return results;
  201315. }
  201316. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  201317. {
  201318. SRB_GDEVBlock s;
  201319. zerostruct (s);
  201320. s.SRB_Cmd = SC_GET_DEV_TYPE;
  201321. s.SRB_HaID = device->ha;
  201322. s.SRB_Target = device->tgt;
  201323. s.SRB_Lun = device->lun;
  201324. if (usingScsi)
  201325. {
  201326. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  201327. if (h != INVALID_HANDLE_VALUE)
  201328. {
  201329. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  201330. cdh->scsiHandle = h;
  201331. return cdh;
  201332. }
  201333. }
  201334. else
  201335. {
  201336. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  201337. && s.SRB_DeviceType == DTYPE_CROM)
  201338. {
  201339. return new CDDeviceHandle (device);
  201340. }
  201341. }
  201342. return 0;
  201343. }
  201344. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  201345. {
  201346. incUserCount();
  201347. if (initialisedOk)
  201348. {
  201349. CDDeviceInfo list[8];
  201350. const int num = FindCDDevices (list, 8);
  201351. if (((unsigned int) deviceIndex) < (unsigned int) num)
  201352. {
  201353. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  201354. if (handle != 0)
  201355. {
  201356. CDDeviceWrapper* const d = new CDDeviceWrapper();
  201357. d->cdH = handle;
  201358. d->overlapBuffer = new CDReadBuffer(3);
  201359. return new AudioCDReader (d);
  201360. }
  201361. }
  201362. }
  201363. decUserCount();
  201364. return 0;
  201365. }
  201366. AudioCDReader::AudioCDReader (void* handle_)
  201367. : AudioFormatReader (0, T("CD Audio")),
  201368. handle (handle_),
  201369. indexingEnabled (false),
  201370. lastIndex (0),
  201371. firstFrameInBuffer (0),
  201372. samplesInBuffer (0)
  201373. {
  201374. jassert (handle_ != 0);
  201375. refreshTrackLengths();
  201376. sampleRate = 44100.0;
  201377. bitsPerSample = 16;
  201378. lengthInSamples = getPositionOfTrackStart (numTracks);
  201379. numChannels = 2;
  201380. usesFloatingPointData = false;
  201381. buffer.setSize (4 * bytesPerFrame, true);
  201382. }
  201383. AudioCDReader::~AudioCDReader()
  201384. {
  201385. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  201386. delete device->cdH;
  201387. delete device->overlapBuffer;
  201388. delete device;
  201389. decUserCount();
  201390. }
  201391. bool AudioCDReader::read (int** destSamples,
  201392. int64 startSampleInFile,
  201393. int numSamples)
  201394. {
  201395. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  201396. bool ok = true;
  201397. int offset = 0;
  201398. if (startSampleInFile < 0)
  201399. {
  201400. int* l = destSamples[0];
  201401. int* r = destSamples[1];
  201402. numSamples += (int) startSampleInFile;
  201403. offset -= (int) startSampleInFile;
  201404. while (++startSampleInFile <= 0)
  201405. {
  201406. *l++ = 0;
  201407. if (r != 0)
  201408. *r++ = 0;
  201409. }
  201410. }
  201411. while (numSamples > 0)
  201412. {
  201413. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  201414. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  201415. if (startSampleInFile >= bufferStartSample
  201416. && startSampleInFile < bufferEndSample)
  201417. {
  201418. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  201419. int* const l = destSamples[0] + offset;
  201420. int* const r = destSamples[1] + offset;
  201421. const short* src = (const short*) buffer.getData();
  201422. src += 2 * (startSampleInFile - bufferStartSample);
  201423. for (int i = 0; i < toDo; ++i)
  201424. {
  201425. l[i] = src [i << 1] << 16;
  201426. if (r != 0)
  201427. r[i] = src [(i << 1) + 1] << 16;
  201428. }
  201429. offset += toDo;
  201430. startSampleInFile += toDo;
  201431. numSamples -= toDo;
  201432. }
  201433. else
  201434. {
  201435. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  201436. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  201437. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  201438. {
  201439. device->overlapBuffer->dataLength = 0;
  201440. device->overlapBuffer->startFrame = 0;
  201441. device->overlapBuffer->numFrames = 0;
  201442. device->jitter = false;
  201443. }
  201444. firstFrameInBuffer = frameNeeded;
  201445. lastIndex = 0;
  201446. CDReadBuffer readBuffer (framesInBuffer + 4);
  201447. readBuffer.wantsIndex = indexingEnabled;
  201448. int i;
  201449. for (i = 5; --i >= 0;)
  201450. {
  201451. readBuffer.startFrame = frameNeeded;
  201452. readBuffer.numFrames = framesInBuffer;
  201453. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  201454. break;
  201455. else
  201456. device->overlapBuffer->dataLength = 0;
  201457. }
  201458. if (i >= 0)
  201459. {
  201460. memcpy ((char*) buffer.getData(),
  201461. readBuffer.buffer + readBuffer.dataStartOffset,
  201462. readBuffer.dataLength);
  201463. samplesInBuffer = readBuffer.dataLength >> 2;
  201464. lastIndex = readBuffer.index;
  201465. }
  201466. else
  201467. {
  201468. int* l = destSamples[0] + offset;
  201469. int* r = destSamples[1] + offset;
  201470. while (--numSamples >= 0)
  201471. {
  201472. *l++ = 0;
  201473. if (r != 0)
  201474. *r++ = 0;
  201475. }
  201476. // sometimes the read fails for just the very last couple of blocks, so
  201477. // we'll ignore and errors in the last half-second of the disk..
  201478. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  201479. break;
  201480. }
  201481. }
  201482. }
  201483. return ok;
  201484. }
  201485. bool AudioCDReader::isCDStillPresent() const
  201486. {
  201487. TOC toc;
  201488. zerostruct (toc);
  201489. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  201490. }
  201491. int AudioCDReader::getNumTracks() const
  201492. {
  201493. return numTracks;
  201494. }
  201495. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  201496. {
  201497. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  201498. : 0;
  201499. }
  201500. void AudioCDReader::refreshTrackLengths()
  201501. {
  201502. zeromem (trackStarts, sizeof (trackStarts));
  201503. zeromem (audioTracks, sizeof (audioTracks));
  201504. TOC toc;
  201505. zerostruct (toc);
  201506. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  201507. {
  201508. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  201509. for (int i = 0; i <= numTracks; ++i)
  201510. {
  201511. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  201512. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  201513. }
  201514. }
  201515. else
  201516. {
  201517. numTracks = 0;
  201518. }
  201519. }
  201520. bool AudioCDReader::isTrackAudio (int trackNum) const
  201521. {
  201522. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  201523. : false;
  201524. }
  201525. void AudioCDReader::enableIndexScanning (bool b)
  201526. {
  201527. indexingEnabled = b;
  201528. }
  201529. int AudioCDReader::getLastIndex() const
  201530. {
  201531. return lastIndex;
  201532. }
  201533. const int framesPerIndexRead = 4;
  201534. int AudioCDReader::getIndexAt (int samplePos)
  201535. {
  201536. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  201537. const int frameNeeded = samplePos / samplesPerFrame;
  201538. device->overlapBuffer->dataLength = 0;
  201539. device->overlapBuffer->startFrame = 0;
  201540. device->overlapBuffer->numFrames = 0;
  201541. device->jitter = false;
  201542. firstFrameInBuffer = 0;
  201543. lastIndex = 0;
  201544. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  201545. readBuffer.wantsIndex = true;
  201546. int i;
  201547. for (i = 5; --i >= 0;)
  201548. {
  201549. readBuffer.startFrame = frameNeeded;
  201550. readBuffer.numFrames = framesPerIndexRead;
  201551. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  201552. break;
  201553. }
  201554. if (i >= 0)
  201555. return readBuffer.index;
  201556. return -1;
  201557. }
  201558. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  201559. {
  201560. Array <int> indexes;
  201561. const int trackStart = getPositionOfTrackStart (trackNumber);
  201562. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  201563. bool needToScan = true;
  201564. if (trackEnd - trackStart > 20 * 44100)
  201565. {
  201566. // check the end of the track for indexes before scanning the whole thing
  201567. needToScan = false;
  201568. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  201569. bool seenAnIndex = false;
  201570. while (pos <= trackEnd - samplesPerFrame)
  201571. {
  201572. const int index = getIndexAt (pos);
  201573. if (index == 0)
  201574. {
  201575. // lead-out, so skip back a bit if we've not found any indexes yet..
  201576. if (seenAnIndex)
  201577. break;
  201578. pos -= 44100 * 5;
  201579. if (pos < trackStart)
  201580. break;
  201581. }
  201582. else
  201583. {
  201584. if (index > 0)
  201585. seenAnIndex = true;
  201586. if (index > 1)
  201587. {
  201588. needToScan = true;
  201589. break;
  201590. }
  201591. pos += samplesPerFrame * framesPerIndexRead;
  201592. }
  201593. }
  201594. }
  201595. if (needToScan)
  201596. {
  201597. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  201598. int pos = trackStart;
  201599. int last = -1;
  201600. while (pos < trackEnd - samplesPerFrame * 10)
  201601. {
  201602. const int frameNeeded = pos / samplesPerFrame;
  201603. device->overlapBuffer->dataLength = 0;
  201604. device->overlapBuffer->startFrame = 0;
  201605. device->overlapBuffer->numFrames = 0;
  201606. device->jitter = false;
  201607. firstFrameInBuffer = 0;
  201608. CDReadBuffer readBuffer (4);
  201609. readBuffer.wantsIndex = true;
  201610. int i;
  201611. for (i = 5; --i >= 0;)
  201612. {
  201613. readBuffer.startFrame = frameNeeded;
  201614. readBuffer.numFrames = framesPerIndexRead;
  201615. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  201616. break;
  201617. }
  201618. if (i < 0)
  201619. break;
  201620. if (readBuffer.index > last && readBuffer.index > 1)
  201621. {
  201622. last = readBuffer.index;
  201623. indexes.add (pos);
  201624. }
  201625. pos += samplesPerFrame * framesPerIndexRead;
  201626. }
  201627. indexes.removeValue (trackStart);
  201628. }
  201629. return indexes;
  201630. }
  201631. int AudioCDReader::getCDDBId()
  201632. {
  201633. refreshTrackLengths();
  201634. if (numTracks > 0)
  201635. {
  201636. TOC toc;
  201637. zerostruct (toc);
  201638. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  201639. {
  201640. int n = 0;
  201641. for (int i = numTracks; --i >= 0;)
  201642. {
  201643. int j = getMSFAddressOf (&toc.tracks[i]);
  201644. while (j > 0)
  201645. {
  201646. n += (j % 10);
  201647. j /= 10;
  201648. }
  201649. }
  201650. if (n != 0)
  201651. {
  201652. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  201653. - getMSFAddressOf (&toc.tracks[0]);
  201654. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  201655. }
  201656. }
  201657. }
  201658. return 0;
  201659. }
  201660. void AudioCDReader::ejectDisk()
  201661. {
  201662. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  201663. }
  201664. #if JUCE_USE_CDBURNER
  201665. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  201666. {
  201667. CoInitialize (0);
  201668. IDiscMaster* dm;
  201669. IDiscRecorder* result = 0;
  201670. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  201671. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  201672. IID_IDiscMaster,
  201673. (void**) &dm)))
  201674. {
  201675. if (SUCCEEDED (dm->Open()))
  201676. {
  201677. IEnumDiscRecorders* drEnum = 0;
  201678. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  201679. {
  201680. IDiscRecorder* dr = 0;
  201681. DWORD dummy;
  201682. int index = 0;
  201683. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  201684. {
  201685. if (indexToOpen == index)
  201686. {
  201687. result = dr;
  201688. break;
  201689. }
  201690. else if (list != 0)
  201691. {
  201692. BSTR path;
  201693. if (SUCCEEDED (dr->GetPath (&path)))
  201694. list->add ((const WCHAR*) path);
  201695. }
  201696. ++index;
  201697. dr->Release();
  201698. }
  201699. drEnum->Release();
  201700. }
  201701. /*if (redbookFormat != 0)
  201702. {
  201703. IEnumDiscMasterFormats* mfEnum;
  201704. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  201705. {
  201706. IID formatIID;
  201707. DWORD dummy;
  201708. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  201709. {
  201710. }
  201711. mfEnum->Release();
  201712. }
  201713. redbookFormat
  201714. }*/
  201715. if (master == 0)
  201716. dm->Close();
  201717. }
  201718. if (master != 0)
  201719. *master = dm;
  201720. else
  201721. dm->Release();
  201722. }
  201723. return result;
  201724. }
  201725. const StringArray AudioCDBurner::findAvailableDevices()
  201726. {
  201727. StringArray devs;
  201728. enumCDBurners (&devs, -1, 0);
  201729. return devs;
  201730. }
  201731. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  201732. {
  201733. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  201734. if (b->internal == 0)
  201735. deleteAndZero (b);
  201736. return b;
  201737. }
  201738. class CDBurnerInfo : public IDiscMasterProgressEvents
  201739. {
  201740. public:
  201741. CDBurnerInfo()
  201742. : refCount (1),
  201743. progress (0),
  201744. shouldCancel (false),
  201745. listener (0)
  201746. {
  201747. }
  201748. ~CDBurnerInfo()
  201749. {
  201750. }
  201751. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  201752. {
  201753. if (result == 0)
  201754. return E_POINTER;
  201755. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  201756. {
  201757. AddRef();
  201758. *result = this;
  201759. return S_OK;
  201760. }
  201761. *result = 0;
  201762. return E_NOINTERFACE;
  201763. }
  201764. ULONG __stdcall AddRef() { return ++refCount; }
  201765. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  201766. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  201767. {
  201768. if (listener != 0 && ! shouldCancel)
  201769. shouldCancel = listener->audioCDBurnProgress (progress);
  201770. *pbCancel = shouldCancel;
  201771. return S_OK;
  201772. }
  201773. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  201774. {
  201775. progress = nCompleted / (float) nTotal;
  201776. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  201777. return E_NOTIMPL;
  201778. }
  201779. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  201780. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  201781. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  201782. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  201783. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  201784. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  201785. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  201786. IDiscMaster* discMaster;
  201787. IDiscRecorder* discRecorder;
  201788. IRedbookDiscMaster* redbook;
  201789. AudioCDBurner::BurnProgressListener* listener;
  201790. float progress;
  201791. bool shouldCancel;
  201792. private:
  201793. int refCount;
  201794. };
  201795. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  201796. : internal (0)
  201797. {
  201798. IDiscMaster* discMaster;
  201799. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  201800. if (dr != 0)
  201801. {
  201802. IRedbookDiscMaster* redbook;
  201803. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  201804. hr = discMaster->SetActiveDiscRecorder (dr);
  201805. CDBurnerInfo* const info = new CDBurnerInfo();
  201806. internal = info;
  201807. info->discMaster = discMaster;
  201808. info->discRecorder = dr;
  201809. info->redbook = redbook;
  201810. }
  201811. }
  201812. AudioCDBurner::~AudioCDBurner()
  201813. {
  201814. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201815. if (info != 0)
  201816. {
  201817. info->discRecorder->Close();
  201818. info->redbook->Release();
  201819. info->discRecorder->Release();
  201820. info->discMaster->Release();
  201821. info->Release();
  201822. }
  201823. }
  201824. bool AudioCDBurner::isDiskPresent() const
  201825. {
  201826. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201827. HRESULT hr = info->discRecorder->OpenExclusive();
  201828. long type, flags;
  201829. hr = info->discRecorder->QueryMediaType (&type, &flags);
  201830. info->discRecorder->Close();
  201831. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  201832. }
  201833. int AudioCDBurner::getNumAvailableAudioBlocks() const
  201834. {
  201835. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201836. long blocksFree = 0;
  201837. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  201838. return blocksFree;
  201839. }
  201840. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  201841. const bool ejectDiscAfterwards,
  201842. const bool performFakeBurnForTesting)
  201843. {
  201844. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201845. info->listener = listener;
  201846. info->progress = 0;
  201847. info->shouldCancel = false;
  201848. UINT_PTR cookie;
  201849. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  201850. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  201851. ejectDiscAfterwards);
  201852. String error;
  201853. if (hr != S_OK)
  201854. {
  201855. const char* e = "Couldn't open or write to the CD device";
  201856. if (hr == IMAPI_E_USERABORT)
  201857. e = "User cancelled the write operation";
  201858. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  201859. e = "No Disk present";
  201860. error = e;
  201861. }
  201862. info->discMaster->ProgressUnadvise (cookie);
  201863. info->listener = 0;
  201864. return error;
  201865. }
  201866. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  201867. {
  201868. if (source == 0)
  201869. return false;
  201870. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201871. long bytesPerBlock;
  201872. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  201873. const int samplesPerBlock = bytesPerBlock / 4;
  201874. bool ok = true;
  201875. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  201876. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  201877. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  201878. int samplesDone = 0;
  201879. source->prepareToPlay (samplesPerBlock, 44100.0);
  201880. while (ok)
  201881. {
  201882. {
  201883. AudioSourceChannelInfo info;
  201884. info.buffer = &sourceBuffer;
  201885. info.numSamples = samplesPerBlock;
  201886. info.startSample = 0;
  201887. sourceBuffer.clear();
  201888. source->getNextAudioBlock (info);
  201889. }
  201890. zeromem (buffer, bytesPerBlock);
  201891. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  201892. buffer, samplesPerBlock, 4);
  201893. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  201894. buffer + 2, samplesPerBlock, 4);
  201895. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  201896. if (hr != S_OK)
  201897. ok = false;
  201898. samplesDone += samplesPerBlock;
  201899. if (samplesDone >= numSamples)
  201900. break;
  201901. }
  201902. juce_free (buffer);
  201903. hr = info->redbook->CloseAudioTrack();
  201904. delete source;
  201905. return ok && hr == S_OK;
  201906. }
  201907. #endif
  201908. END_JUCE_NAMESPACE
  201909. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  201910. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  201911. extern "C"
  201912. {
  201913. // Declare just the minimum number of interfaces for the DSound objects that we need..
  201914. typedef struct typeDSBUFFERDESC
  201915. {
  201916. DWORD dwSize;
  201917. DWORD dwFlags;
  201918. DWORD dwBufferBytes;
  201919. DWORD dwReserved;
  201920. LPWAVEFORMATEX lpwfxFormat;
  201921. GUID guid3DAlgorithm;
  201922. } DSBUFFERDESC;
  201923. struct IDirectSoundBuffer;
  201924. #undef INTERFACE
  201925. #define INTERFACE IDirectSound
  201926. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  201927. {
  201928. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201929. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201930. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201931. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  201932. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201933. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  201934. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  201935. STDMETHOD(Compact) (THIS) PURE;
  201936. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  201937. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  201938. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  201939. };
  201940. #undef INTERFACE
  201941. #define INTERFACE IDirectSoundBuffer
  201942. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  201943. {
  201944. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201945. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201946. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201947. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201948. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  201949. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  201950. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  201951. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  201952. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  201953. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  201954. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  201955. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  201956. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  201957. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  201958. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  201959. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  201960. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  201961. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  201962. STDMETHOD(Stop) (THIS) PURE;
  201963. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  201964. STDMETHOD(Restore) (THIS) PURE;
  201965. };
  201966. typedef struct typeDSCBUFFERDESC
  201967. {
  201968. DWORD dwSize;
  201969. DWORD dwFlags;
  201970. DWORD dwBufferBytes;
  201971. DWORD dwReserved;
  201972. LPWAVEFORMATEX lpwfxFormat;
  201973. } DSCBUFFERDESC;
  201974. struct IDirectSoundCaptureBuffer;
  201975. #undef INTERFACE
  201976. #define INTERFACE IDirectSoundCapture
  201977. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  201978. {
  201979. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201980. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201981. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201982. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  201983. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201984. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  201985. };
  201986. #undef INTERFACE
  201987. #define INTERFACE IDirectSoundCaptureBuffer
  201988. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  201989. {
  201990. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201991. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201992. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201993. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201994. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  201995. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  201996. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  201997. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  201998. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  201999. STDMETHOD(Start) (THIS_ DWORD) PURE;
  202000. STDMETHOD(Stop) (THIS) PURE;
  202001. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202002. };
  202003. };
  202004. BEGIN_JUCE_NAMESPACE
  202005. static const String getDSErrorMessage (HRESULT hr)
  202006. {
  202007. const char* result = 0;
  202008. switch (hr)
  202009. {
  202010. case MAKE_HRESULT(1, 0x878, 10):
  202011. result = "Device already allocated";
  202012. break;
  202013. case MAKE_HRESULT(1, 0x878, 30):
  202014. result = "Control unavailable";
  202015. break;
  202016. case E_INVALIDARG:
  202017. result = "Invalid parameter";
  202018. break;
  202019. case MAKE_HRESULT(1, 0x878, 50):
  202020. result = "Invalid call";
  202021. break;
  202022. case E_FAIL:
  202023. result = "Generic error";
  202024. break;
  202025. case MAKE_HRESULT(1, 0x878, 70):
  202026. result = "Priority level error";
  202027. break;
  202028. case E_OUTOFMEMORY:
  202029. result = "Out of memory";
  202030. break;
  202031. case MAKE_HRESULT(1, 0x878, 100):
  202032. result = "Bad format";
  202033. break;
  202034. case E_NOTIMPL:
  202035. result = "Unsupported function";
  202036. break;
  202037. case MAKE_HRESULT(1, 0x878, 120):
  202038. result = "No driver";
  202039. break;
  202040. case MAKE_HRESULT(1, 0x878, 130):
  202041. result = "Already initialised";
  202042. break;
  202043. case CLASS_E_NOAGGREGATION:
  202044. result = "No aggregation";
  202045. break;
  202046. case MAKE_HRESULT(1, 0x878, 150):
  202047. result = "Buffer lost";
  202048. break;
  202049. case MAKE_HRESULT(1, 0x878, 160):
  202050. result = "Another app has priority";
  202051. break;
  202052. case MAKE_HRESULT(1, 0x878, 170):
  202053. result = "Uninitialised";
  202054. break;
  202055. case E_NOINTERFACE:
  202056. result = "No interface";
  202057. break;
  202058. case S_OK:
  202059. result = "No error";
  202060. break;
  202061. default:
  202062. return "Unknown error: " + String ((int) hr);
  202063. }
  202064. return result;
  202065. }
  202066. #define DS_DEBUGGING 1
  202067. #ifdef DS_DEBUGGING
  202068. #define CATCH JUCE_CATCH_EXCEPTION
  202069. #undef log
  202070. #define log(a) Logger::writeToLog(a);
  202071. #undef logError
  202072. #define logError(a) logDSError(a, __LINE__);
  202073. static void logDSError (HRESULT hr, int lineNum)
  202074. {
  202075. if (hr != S_OK)
  202076. {
  202077. String error ("DS error at line ");
  202078. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  202079. log (error);
  202080. }
  202081. }
  202082. #else
  202083. #define CATCH JUCE_CATCH_ALL
  202084. #define log(a)
  202085. #define logError(a)
  202086. #endif
  202087. #define DSOUND_FUNCTION(functionName, params) \
  202088. typedef HRESULT (WINAPI *type##functionName) params; \
  202089. static type##functionName ds##functionName = 0;
  202090. #define DSOUND_FUNCTION_LOAD(functionName) \
  202091. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  202092. jassert (ds##functionName != 0);
  202093. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  202094. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  202095. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  202096. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  202097. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202098. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202099. static void initialiseDSoundFunctions()
  202100. {
  202101. if (dsDirectSoundCreate == 0)
  202102. {
  202103. HMODULE h = LoadLibraryA ("dsound.dll");
  202104. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  202105. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  202106. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  202107. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  202108. }
  202109. }
  202110. class DSoundInternalOutChannel
  202111. {
  202112. String name;
  202113. LPGUID guid;
  202114. int sampleRate, bufferSizeSamples;
  202115. float* leftBuffer;
  202116. float* rightBuffer;
  202117. IDirectSound* pDirectSound;
  202118. IDirectSoundBuffer* pOutputBuffer;
  202119. DWORD writeOffset;
  202120. int totalBytesPerBuffer;
  202121. int bytesPerBuffer;
  202122. unsigned int lastPlayCursor;
  202123. public:
  202124. int bitDepth;
  202125. bool doneFlag;
  202126. DSoundInternalOutChannel (const String& name_,
  202127. LPGUID guid_,
  202128. int rate,
  202129. int bufferSize,
  202130. float* left,
  202131. float* right)
  202132. : name (name_),
  202133. guid (guid_),
  202134. sampleRate (rate),
  202135. bufferSizeSamples (bufferSize),
  202136. leftBuffer (left),
  202137. rightBuffer (right),
  202138. pDirectSound (0),
  202139. pOutputBuffer (0),
  202140. bitDepth (16)
  202141. {
  202142. }
  202143. ~DSoundInternalOutChannel()
  202144. {
  202145. close();
  202146. }
  202147. void close()
  202148. {
  202149. HRESULT hr;
  202150. if (pOutputBuffer != 0)
  202151. {
  202152. JUCE_TRY
  202153. {
  202154. log (T("closing dsound out: ") + name);
  202155. hr = pOutputBuffer->Stop();
  202156. logError (hr);
  202157. }
  202158. CATCH
  202159. JUCE_TRY
  202160. {
  202161. hr = pOutputBuffer->Release();
  202162. logError (hr);
  202163. }
  202164. CATCH
  202165. pOutputBuffer = 0;
  202166. }
  202167. if (pDirectSound != 0)
  202168. {
  202169. JUCE_TRY
  202170. {
  202171. hr = pDirectSound->Release();
  202172. logError (hr);
  202173. }
  202174. CATCH
  202175. pDirectSound = 0;
  202176. }
  202177. }
  202178. const String open()
  202179. {
  202180. log (T("opening dsound out device: ") + name
  202181. + T(" rate=") + String (sampleRate)
  202182. + T(" bits=") + String (bitDepth)
  202183. + T(" buf=") + String (bufferSizeSamples));
  202184. pDirectSound = 0;
  202185. pOutputBuffer = 0;
  202186. writeOffset = 0;
  202187. String error;
  202188. HRESULT hr = E_NOINTERFACE;
  202189. if (dsDirectSoundCreate != 0)
  202190. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  202191. if (hr == S_OK)
  202192. {
  202193. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202194. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202195. const int numChannels = 2;
  202196. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 3 /* DSSCL_EXCLUSIVE */);
  202197. logError (hr);
  202198. if (hr == S_OK)
  202199. {
  202200. IDirectSoundBuffer* pPrimaryBuffer;
  202201. DSBUFFERDESC primaryDesc;
  202202. zerostruct (primaryDesc);
  202203. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202204. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  202205. primaryDesc.dwBufferBytes = 0;
  202206. primaryDesc.lpwfxFormat = 0;
  202207. log ("opening dsound out step 2");
  202208. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  202209. logError (hr);
  202210. if (hr == S_OK)
  202211. {
  202212. WAVEFORMATEX wfFormat;
  202213. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202214. wfFormat.nChannels = (unsigned short) numChannels;
  202215. wfFormat.nSamplesPerSec = sampleRate;
  202216. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  202217. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  202218. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202219. wfFormat.cbSize = 0;
  202220. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  202221. logError (hr);
  202222. if (hr == S_OK)
  202223. {
  202224. DSBUFFERDESC secondaryDesc;
  202225. zerostruct (secondaryDesc);
  202226. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202227. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  202228. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  202229. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  202230. secondaryDesc.lpwfxFormat = &wfFormat;
  202231. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  202232. logError (hr);
  202233. if (hr == S_OK)
  202234. {
  202235. log ("opening dsound out step 3");
  202236. DWORD dwDataLen;
  202237. unsigned char* pDSBuffData;
  202238. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  202239. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  202240. logError (hr);
  202241. if (hr == S_OK)
  202242. {
  202243. zeromem (pDSBuffData, dwDataLen);
  202244. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  202245. if (hr == S_OK)
  202246. {
  202247. hr = pOutputBuffer->SetCurrentPosition (0);
  202248. if (hr == S_OK)
  202249. {
  202250. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  202251. if (hr == S_OK)
  202252. return String::empty;
  202253. }
  202254. }
  202255. }
  202256. }
  202257. }
  202258. }
  202259. }
  202260. }
  202261. error = getDSErrorMessage (hr);
  202262. close();
  202263. return error;
  202264. }
  202265. void synchronisePosition()
  202266. {
  202267. if (pOutputBuffer != 0)
  202268. {
  202269. DWORD playCursor;
  202270. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  202271. }
  202272. }
  202273. bool service()
  202274. {
  202275. if (pOutputBuffer == 0)
  202276. return true;
  202277. DWORD playCursor, writeCursor;
  202278. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  202279. if (hr != S_OK)
  202280. {
  202281. logError (hr);
  202282. jassertfalse
  202283. return true;
  202284. }
  202285. int playWriteGap = writeCursor - playCursor;
  202286. if (playWriteGap < 0)
  202287. playWriteGap += totalBytesPerBuffer;
  202288. int bytesEmpty = playCursor - writeOffset;
  202289. if (bytesEmpty < 0)
  202290. bytesEmpty += totalBytesPerBuffer;
  202291. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  202292. {
  202293. writeOffset = writeCursor;
  202294. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  202295. }
  202296. if (bytesEmpty >= bytesPerBuffer)
  202297. {
  202298. LPBYTE lpbuf1 = 0;
  202299. LPBYTE lpbuf2 = 0;
  202300. DWORD dwSize1 = 0;
  202301. DWORD dwSize2 = 0;
  202302. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  202303. bytesPerBuffer,
  202304. (void**) &lpbuf1, &dwSize1,
  202305. (void**) &lpbuf2, &dwSize2, 0);
  202306. if (hr == S_OK)
  202307. {
  202308. if (bitDepth == 16)
  202309. {
  202310. const float gainL = 32767.0f;
  202311. const float gainR = 32767.0f;
  202312. int* dest = (int*)lpbuf1;
  202313. const float* left = leftBuffer;
  202314. const float* right = rightBuffer;
  202315. int samples1 = dwSize1 >> 2;
  202316. int samples2 = dwSize2 >> 2;
  202317. if (left == 0)
  202318. {
  202319. while (--samples1 >= 0)
  202320. {
  202321. int r = roundFloatToInt (gainR * *right++);
  202322. if (r < -32768)
  202323. r = -32768;
  202324. else if (r > 32767)
  202325. r = 32767;
  202326. *dest++ = (r << 16);
  202327. }
  202328. dest = (int*)lpbuf2;
  202329. while (--samples2 >= 0)
  202330. {
  202331. int r = roundFloatToInt (gainR * *right++);
  202332. if (r < -32768)
  202333. r = -32768;
  202334. else if (r > 32767)
  202335. r = 32767;
  202336. *dest++ = (r << 16);
  202337. }
  202338. }
  202339. else if (right == 0)
  202340. {
  202341. while (--samples1 >= 0)
  202342. {
  202343. int l = roundFloatToInt (gainL * *left++);
  202344. if (l < -32768)
  202345. l = -32768;
  202346. else if (l > 32767)
  202347. l = 32767;
  202348. l &= 0xffff;
  202349. *dest++ = l;
  202350. }
  202351. dest = (int*)lpbuf2;
  202352. while (--samples2 >= 0)
  202353. {
  202354. int l = roundFloatToInt (gainL * *left++);
  202355. if (l < -32768)
  202356. l = -32768;
  202357. else if (l > 32767)
  202358. l = 32767;
  202359. l &= 0xffff;
  202360. *dest++ = l;
  202361. }
  202362. }
  202363. else
  202364. {
  202365. while (--samples1 >= 0)
  202366. {
  202367. int l = roundFloatToInt (gainL * *left++);
  202368. if (l < -32768)
  202369. l = -32768;
  202370. else if (l > 32767)
  202371. l = 32767;
  202372. l &= 0xffff;
  202373. int r = roundFloatToInt (gainR * *right++);
  202374. if (r < -32768)
  202375. r = -32768;
  202376. else if (r > 32767)
  202377. r = 32767;
  202378. *dest++ = (r << 16) | l;
  202379. }
  202380. dest = (int*)lpbuf2;
  202381. while (--samples2 >= 0)
  202382. {
  202383. int l = roundFloatToInt (gainL * *left++);
  202384. if (l < -32768)
  202385. l = -32768;
  202386. else if (l > 32767)
  202387. l = 32767;
  202388. l &= 0xffff;
  202389. int r = roundFloatToInt (gainR * *right++);
  202390. if (r < -32768)
  202391. r = -32768;
  202392. else if (r > 32767)
  202393. r = 32767;
  202394. *dest++ = (r << 16) | l;
  202395. }
  202396. }
  202397. }
  202398. else
  202399. {
  202400. jassertfalse
  202401. }
  202402. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  202403. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  202404. }
  202405. else
  202406. {
  202407. jassertfalse
  202408. logError (hr);
  202409. }
  202410. bytesEmpty -= bytesPerBuffer;
  202411. return true;
  202412. }
  202413. else
  202414. {
  202415. return false;
  202416. }
  202417. }
  202418. };
  202419. struct DSoundInternalInChannel
  202420. {
  202421. String name;
  202422. LPGUID guid;
  202423. int sampleRate, bufferSizeSamples;
  202424. float* leftBuffer;
  202425. float* rightBuffer;
  202426. IDirectSound* pDirectSound;
  202427. IDirectSoundCapture* pDirectSoundCapture;
  202428. IDirectSoundCaptureBuffer* pInputBuffer;
  202429. public:
  202430. unsigned int readOffset;
  202431. int bytesPerBuffer, totalBytesPerBuffer;
  202432. int bitDepth;
  202433. bool doneFlag;
  202434. DSoundInternalInChannel (const String& name_,
  202435. LPGUID guid_,
  202436. int rate,
  202437. int bufferSize,
  202438. float* left,
  202439. float* right)
  202440. : name (name_),
  202441. guid (guid_),
  202442. sampleRate (rate),
  202443. bufferSizeSamples (bufferSize),
  202444. leftBuffer (left),
  202445. rightBuffer (right),
  202446. pDirectSound (0),
  202447. pDirectSoundCapture (0),
  202448. pInputBuffer (0),
  202449. bitDepth (16)
  202450. {
  202451. }
  202452. ~DSoundInternalInChannel()
  202453. {
  202454. close();
  202455. }
  202456. void close()
  202457. {
  202458. HRESULT hr;
  202459. if (pInputBuffer != 0)
  202460. {
  202461. JUCE_TRY
  202462. {
  202463. log (T("closing dsound in: ") + name);
  202464. hr = pInputBuffer->Stop();
  202465. logError (hr);
  202466. }
  202467. CATCH
  202468. JUCE_TRY
  202469. {
  202470. hr = pInputBuffer->Release();
  202471. logError (hr);
  202472. }
  202473. CATCH
  202474. pInputBuffer = 0;
  202475. }
  202476. if (pDirectSoundCapture != 0)
  202477. {
  202478. JUCE_TRY
  202479. {
  202480. hr = pDirectSoundCapture->Release();
  202481. logError (hr);
  202482. }
  202483. CATCH
  202484. pDirectSoundCapture = 0;
  202485. }
  202486. if (pDirectSound != 0)
  202487. {
  202488. JUCE_TRY
  202489. {
  202490. hr = pDirectSound->Release();
  202491. logError (hr);
  202492. }
  202493. CATCH
  202494. pDirectSound = 0;
  202495. }
  202496. }
  202497. const String open()
  202498. {
  202499. log (T("opening dsound in device: ") + name
  202500. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  202501. pDirectSound = 0;
  202502. pDirectSoundCapture = 0;
  202503. pInputBuffer = 0;
  202504. readOffset = 0;
  202505. totalBytesPerBuffer = 0;
  202506. String error;
  202507. HRESULT hr = E_NOINTERFACE;
  202508. if (dsDirectSoundCaptureCreate != 0)
  202509. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  202510. logError (hr);
  202511. if (hr == S_OK)
  202512. {
  202513. const int numChannels = 2;
  202514. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202515. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202516. WAVEFORMATEX wfFormat;
  202517. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202518. wfFormat.nChannels = (unsigned short)numChannels;
  202519. wfFormat.nSamplesPerSec = sampleRate;
  202520. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  202521. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  202522. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202523. wfFormat.cbSize = 0;
  202524. DSCBUFFERDESC captureDesc;
  202525. zerostruct (captureDesc);
  202526. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  202527. captureDesc.dwFlags = 0;
  202528. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  202529. captureDesc.lpwfxFormat = &wfFormat;
  202530. log (T("opening dsound in step 2"));
  202531. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  202532. logError (hr);
  202533. if (hr == S_OK)
  202534. {
  202535. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  202536. logError (hr);
  202537. if (hr == S_OK)
  202538. return String::empty;
  202539. }
  202540. }
  202541. error = getDSErrorMessage (hr);
  202542. close();
  202543. return error;
  202544. }
  202545. void synchronisePosition()
  202546. {
  202547. if (pInputBuffer != 0)
  202548. {
  202549. DWORD capturePos;
  202550. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  202551. }
  202552. }
  202553. bool service()
  202554. {
  202555. if (pInputBuffer == 0)
  202556. return true;
  202557. DWORD capturePos, readPos;
  202558. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  202559. logError (hr);
  202560. if (hr != S_OK)
  202561. return true;
  202562. int bytesFilled = readPos - readOffset;
  202563. if (bytesFilled < 0)
  202564. bytesFilled += totalBytesPerBuffer;
  202565. if (bytesFilled >= bytesPerBuffer)
  202566. {
  202567. LPBYTE lpbuf1 = 0;
  202568. LPBYTE lpbuf2 = 0;
  202569. DWORD dwsize1 = 0;
  202570. DWORD dwsize2 = 0;
  202571. HRESULT hr = pInputBuffer->Lock (readOffset,
  202572. bytesPerBuffer,
  202573. (void**) &lpbuf1, &dwsize1,
  202574. (void**) &lpbuf2, &dwsize2, 0);
  202575. if (hr == S_OK)
  202576. {
  202577. if (bitDepth == 16)
  202578. {
  202579. const float g = 1.0f / 32768.0f;
  202580. float* destL = leftBuffer;
  202581. float* destR = rightBuffer;
  202582. int samples1 = dwsize1 >> 2;
  202583. int samples2 = dwsize2 >> 2;
  202584. const short* src = (const short*)lpbuf1;
  202585. if (destL == 0)
  202586. {
  202587. while (--samples1 >= 0)
  202588. {
  202589. ++src;
  202590. *destR++ = *src++ * g;
  202591. }
  202592. src = (const short*)lpbuf2;
  202593. while (--samples2 >= 0)
  202594. {
  202595. ++src;
  202596. *destR++ = *src++ * g;
  202597. }
  202598. }
  202599. else if (destR == 0)
  202600. {
  202601. while (--samples1 >= 0)
  202602. {
  202603. *destL++ = *src++ * g;
  202604. ++src;
  202605. }
  202606. src = (const short*)lpbuf2;
  202607. while (--samples2 >= 0)
  202608. {
  202609. *destL++ = *src++ * g;
  202610. ++src;
  202611. }
  202612. }
  202613. else
  202614. {
  202615. while (--samples1 >= 0)
  202616. {
  202617. *destL++ = *src++ * g;
  202618. *destR++ = *src++ * g;
  202619. }
  202620. src = (const short*)lpbuf2;
  202621. while (--samples2 >= 0)
  202622. {
  202623. *destL++ = *src++ * g;
  202624. *destR++ = *src++ * g;
  202625. }
  202626. }
  202627. }
  202628. else
  202629. {
  202630. jassertfalse
  202631. }
  202632. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  202633. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  202634. }
  202635. else
  202636. {
  202637. logError (hr);
  202638. jassertfalse
  202639. }
  202640. bytesFilled -= bytesPerBuffer;
  202641. return true;
  202642. }
  202643. else
  202644. {
  202645. return false;
  202646. }
  202647. }
  202648. };
  202649. static int findBestMatchForName (const String& name, const StringArray& names)
  202650. {
  202651. int i = names.indexOf (name);
  202652. if (i >= 0)
  202653. return i;
  202654. StringArray tokens1;
  202655. tokens1.addTokens (name, T(" :-"), 0);
  202656. int bestResult = -1;
  202657. int bestNumMatches = 1;
  202658. for (i = 0; i < names.size(); ++i)
  202659. {
  202660. StringArray tokens2;
  202661. tokens2.addTokens (names[i], T(" :-"), 0);
  202662. int matches = 0;
  202663. for (int j = tokens1.size(); --j >= 0;)
  202664. if (tokens2.contains (tokens1 [j]))
  202665. ++matches;
  202666. if (matches > bestNumMatches)
  202667. bestResult = i;
  202668. }
  202669. return bestResult;
  202670. }
  202671. class DSoundAudioIODevice : public AudioIODevice,
  202672. public Thread
  202673. {
  202674. public:
  202675. DSoundAudioIODevice (const String& deviceName,
  202676. const int index,
  202677. const int inputIndex_)
  202678. : AudioIODevice (deviceName, "DirectSound"),
  202679. Thread ("Juce DSound"),
  202680. isOpen_ (false),
  202681. isStarted (false),
  202682. deviceIndex (index),
  202683. inputIndex (inputIndex_),
  202684. inChans (4),
  202685. outChans (4),
  202686. numInputBuffers (0),
  202687. numOutputBuffers (0),
  202688. totalSamplesOut (0),
  202689. sampleRate (0.0),
  202690. inputBuffers (0),
  202691. outputBuffers (0),
  202692. callback (0)
  202693. {
  202694. }
  202695. ~DSoundAudioIODevice()
  202696. {
  202697. close();
  202698. }
  202699. const StringArray getOutputChannelNames()
  202700. {
  202701. return outChannels;
  202702. }
  202703. const StringArray getInputChannelNames()
  202704. {
  202705. return inChannels;
  202706. }
  202707. int getNumSampleRates()
  202708. {
  202709. return 4;
  202710. }
  202711. double getSampleRate (int index)
  202712. {
  202713. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  202714. return samps [jlimit (0, 3, index)];
  202715. }
  202716. int getNumBufferSizesAvailable()
  202717. {
  202718. return 50;
  202719. }
  202720. int getBufferSizeSamples (int index)
  202721. {
  202722. int n = 64;
  202723. for (int i = 0; i < index; ++i)
  202724. n += (n < 512) ? 32
  202725. : ((n < 1024) ? 64
  202726. : ((n < 2048) ? 128 : 256));
  202727. return n;
  202728. }
  202729. int getDefaultBufferSize()
  202730. {
  202731. return 2560;
  202732. }
  202733. const String open (const BitArray& inputChannels,
  202734. const BitArray& outputChannels,
  202735. double sampleRate,
  202736. int bufferSizeSamples)
  202737. {
  202738. BitArray ins, outs;
  202739. if (deviceIndex >= 0)
  202740. {
  202741. if (outputChannels[0])
  202742. outs.setBit (2 * deviceIndex);
  202743. if (outputChannels[1])
  202744. outs.setBit (2 * deviceIndex + 1);
  202745. if (inputIndex >= 0)
  202746. {
  202747. if (inputChannels[0])
  202748. ins.setBit (2 * inputIndex);
  202749. if (inputChannels[1])
  202750. ins.setBit (2 * inputIndex + 1);
  202751. }
  202752. }
  202753. else
  202754. {
  202755. ins = inputChannels;
  202756. outs = outputChannels;
  202757. }
  202758. lastError = openDevice (ins, outs, sampleRate, bufferSizeSamples);
  202759. isOpen_ = lastError.isEmpty();
  202760. return lastError;
  202761. }
  202762. void close()
  202763. {
  202764. stop();
  202765. if (isOpen_)
  202766. {
  202767. closeDevice();
  202768. isOpen_ = false;
  202769. }
  202770. }
  202771. bool isOpen()
  202772. {
  202773. return isOpen_ && isThreadRunning();
  202774. }
  202775. int getCurrentBufferSizeSamples()
  202776. {
  202777. return bufferSizeSamples;
  202778. }
  202779. double getCurrentSampleRate()
  202780. {
  202781. return sampleRate;
  202782. }
  202783. int getCurrentBitDepth()
  202784. {
  202785. int i, bits = 256;
  202786. for (i = inChans.size(); --i >= 0;)
  202787. if (inChans[i] != 0)
  202788. bits = jmin (bits, inChans[i]->bitDepth);
  202789. for (i = outChans.size(); --i >= 0;)
  202790. if (outChans[i] != 0)
  202791. bits = jmin (bits, outChans[i]->bitDepth);
  202792. if (bits > 32)
  202793. bits = 16;
  202794. return bits;
  202795. }
  202796. const BitArray getActiveOutputChannels() const
  202797. {
  202798. return enabledOutputs;
  202799. }
  202800. const BitArray getActiveInputChannels() const
  202801. {
  202802. return enabledInputs;
  202803. }
  202804. int getOutputLatencyInSamples()
  202805. {
  202806. return (int) (getCurrentBufferSizeSamples() * 1.5);
  202807. }
  202808. int getInputLatencyInSamples()
  202809. {
  202810. return getOutputLatencyInSamples();
  202811. }
  202812. void start (AudioIODeviceCallback* call)
  202813. {
  202814. if (isOpen_ && call != 0 && ! isStarted)
  202815. {
  202816. if (! isThreadRunning())
  202817. {
  202818. // something gone wrong and the thread's stopped..
  202819. isOpen_ = false;
  202820. return;
  202821. }
  202822. call->audioDeviceAboutToStart (this);
  202823. const ScopedLock sl (startStopLock);
  202824. callback = call;
  202825. isStarted = true;
  202826. }
  202827. }
  202828. void stop()
  202829. {
  202830. if (isStarted)
  202831. {
  202832. AudioIODeviceCallback* const callbackLocal = callback;
  202833. {
  202834. const ScopedLock sl (startStopLock);
  202835. isStarted = false;
  202836. }
  202837. if (callbackLocal != 0)
  202838. callbackLocal->audioDeviceStopped();
  202839. }
  202840. }
  202841. bool isPlaying()
  202842. {
  202843. return isStarted && isOpen_ && isThreadRunning();
  202844. }
  202845. const String getLastError()
  202846. {
  202847. return lastError;
  202848. }
  202849. juce_UseDebuggingNewOperator
  202850. StringArray inChannels, outChannels;
  202851. private:
  202852. bool isOpen_;
  202853. bool isStarted;
  202854. String lastError;
  202855. int deviceIndex, inputIndex;
  202856. OwnedArray <DSoundInternalInChannel> inChans;
  202857. OwnedArray <DSoundInternalOutChannel> outChans;
  202858. WaitableEvent startEvent;
  202859. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  202860. int volatile totalSamplesOut;
  202861. int64 volatile lastBlockTime;
  202862. double sampleRate;
  202863. BitArray enabledInputs, enabledOutputs;
  202864. float** inputBuffers;
  202865. float** outputBuffers;
  202866. AudioIODeviceCallback* callback;
  202867. CriticalSection startStopLock;
  202868. DSoundAudioIODevice (const DSoundAudioIODevice&);
  202869. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  202870. const String openDevice (const BitArray& inputChannels,
  202871. const BitArray& outputChannels,
  202872. double sampleRate_,
  202873. int bufferSizeSamples_);
  202874. void closeDevice()
  202875. {
  202876. isStarted = false;
  202877. stopThread (5000);
  202878. inChans.clear();
  202879. outChans.clear();
  202880. int i;
  202881. for (i = 0; i < numInputBuffers; ++i)
  202882. juce_free (inputBuffers[i]);
  202883. delete[] inputBuffers;
  202884. inputBuffers = 0;
  202885. numInputBuffers = 0;
  202886. for (i = 0; i < numOutputBuffers; ++i)
  202887. juce_free (outputBuffers[i]);
  202888. delete[] outputBuffers;
  202889. outputBuffers = 0;
  202890. numOutputBuffers = 0;
  202891. }
  202892. void resync()
  202893. {
  202894. int i;
  202895. for (i = outChans.size(); --i >= 0;)
  202896. {
  202897. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  202898. if (out != 0)
  202899. out->close();
  202900. }
  202901. for (i = inChans.size(); --i >= 0;)
  202902. {
  202903. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  202904. if (in != 0)
  202905. in->close();
  202906. }
  202907. if (threadShouldExit())
  202908. return;
  202909. // boost our priority while opening the devices to try to get better sync between them
  202910. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  202911. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  202912. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  202913. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  202914. for (i = outChans.size(); --i >= 0;)
  202915. {
  202916. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  202917. if (out != 0)
  202918. out->open();
  202919. }
  202920. for (i = inChans.size(); --i >= 0;)
  202921. {
  202922. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  202923. if (in != 0)
  202924. in->open();
  202925. }
  202926. if (! threadShouldExit())
  202927. {
  202928. sleep (5);
  202929. for (i = 0; i < numOutputBuffers; ++i)
  202930. if (outChans[i] != 0)
  202931. outChans[i]->synchronisePosition();
  202932. for (i = 0; i < numInputBuffers; ++i)
  202933. if (inChans[i] != 0)
  202934. inChans[i]->synchronisePosition();
  202935. }
  202936. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  202937. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  202938. }
  202939. public:
  202940. void run()
  202941. {
  202942. while (! threadShouldExit())
  202943. {
  202944. if (wait (100))
  202945. break;
  202946. }
  202947. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  202948. const int maxTimeMS = jmax (5, 3 * latencyMs);
  202949. while (! threadShouldExit())
  202950. {
  202951. int numToDo = 0;
  202952. uint32 startTime = Time::getMillisecondCounter();
  202953. int i;
  202954. for (i = inChans.size(); --i >= 0;)
  202955. {
  202956. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  202957. if (in != 0)
  202958. {
  202959. in->doneFlag = false;
  202960. ++numToDo;
  202961. }
  202962. }
  202963. for (i = outChans.size(); --i >= 0;)
  202964. {
  202965. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  202966. if (out != 0)
  202967. {
  202968. out->doneFlag = false;
  202969. ++numToDo;
  202970. }
  202971. }
  202972. if (numToDo > 0)
  202973. {
  202974. const int maxCount = 3;
  202975. int count = maxCount;
  202976. for (;;)
  202977. {
  202978. for (i = inChans.size(); --i >= 0;)
  202979. {
  202980. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  202981. if (in != 0 && !in->doneFlag)
  202982. {
  202983. if (in->service())
  202984. {
  202985. in->doneFlag = true;
  202986. --numToDo;
  202987. }
  202988. }
  202989. }
  202990. for (i = outChans.size(); --i >= 0;)
  202991. {
  202992. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  202993. if (out != 0 && !out->doneFlag)
  202994. {
  202995. if (out->service())
  202996. {
  202997. out->doneFlag = true;
  202998. --numToDo;
  202999. }
  203000. }
  203001. }
  203002. if (numToDo <= 0)
  203003. break;
  203004. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  203005. {
  203006. resync();
  203007. break;
  203008. }
  203009. if (--count <= 0)
  203010. {
  203011. Sleep (1);
  203012. count = maxCount;
  203013. }
  203014. if (threadShouldExit())
  203015. return;
  203016. }
  203017. }
  203018. else
  203019. {
  203020. sleep (1);
  203021. }
  203022. const ScopedLock sl (startStopLock);
  203023. if (isStarted)
  203024. {
  203025. JUCE_TRY
  203026. {
  203027. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  203028. numInputBuffers,
  203029. outputBuffers,
  203030. numOutputBuffers,
  203031. bufferSizeSamples);
  203032. }
  203033. JUCE_CATCH_EXCEPTION
  203034. totalSamplesOut += bufferSizeSamples;
  203035. }
  203036. else
  203037. {
  203038. for (i = 0; i < numOutputBuffers; ++i)
  203039. if (outputBuffers[i] != 0)
  203040. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  203041. totalSamplesOut = 0;
  203042. sleep (1);
  203043. }
  203044. }
  203045. }
  203046. };
  203047. class DSoundAudioIODeviceType : public AudioIODeviceType
  203048. {
  203049. public:
  203050. DSoundAudioIODeviceType()
  203051. : AudioIODeviceType (T("DirectSound")),
  203052. hasScanned (false)
  203053. {
  203054. initialiseDSoundFunctions();
  203055. }
  203056. ~DSoundAudioIODeviceType()
  203057. {
  203058. }
  203059. void scanForDevices()
  203060. {
  203061. hasScanned = true;
  203062. outputDeviceNames.clear();
  203063. outputGuids.clear();
  203064. inputDeviceNames.clear();
  203065. inputGuids.clear();
  203066. if (dsDirectSoundEnumerateW != 0)
  203067. {
  203068. dsDirectSoundEnumerateW (outputEnumProcW, this);
  203069. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  203070. }
  203071. }
  203072. const StringArray getDeviceNames (const bool preferInputNames) const
  203073. {
  203074. jassert (hasScanned); // need to call scanForDevices() before doing this
  203075. return preferInputNames ? inputDeviceNames
  203076. : outputDeviceNames;
  203077. }
  203078. const String getDefaultDeviceName (const bool preferInputNames,
  203079. const int /*numInputChannelsNeeded*/,
  203080. const int /*numOutputChannelsNeeded*/) const
  203081. {
  203082. jassert (hasScanned); // need to call scanForDevices() before doing this
  203083. return getDeviceNames (preferInputNames) [0];
  203084. }
  203085. AudioIODevice* createDevice (const String& deviceName)
  203086. {
  203087. jassert (hasScanned); // need to call scanForDevices() before doing this
  203088. if (deviceName.isEmpty() || deviceName.equalsIgnoreCase (T("DirectSound")))
  203089. {
  203090. DSoundAudioIODevice* device = new DSoundAudioIODevice (deviceName, -1, -1);
  203091. int i;
  203092. for (i = 0; i < outputDeviceNames.size(); ++i)
  203093. {
  203094. device->outChannels.add (outputDeviceNames[i] + TRANS(" (left)"));
  203095. device->outChannels.add (outputDeviceNames[i] + TRANS(" (right)"));
  203096. }
  203097. for (i = 0; i < inputDeviceNames.size(); ++i)
  203098. {
  203099. device->inChannels.add (inputDeviceNames[i] + TRANS(" (left)"));
  203100. device->inChannels.add (inputDeviceNames[i] + TRANS(" (right)"));
  203101. }
  203102. return device;
  203103. }
  203104. else if (outputDeviceNames.contains (deviceName)
  203105. || inputDeviceNames.contains (deviceName))
  203106. {
  203107. int outputIndex = outputDeviceNames.indexOf (deviceName);
  203108. int inputIndex = findBestMatchForName (deviceName, inputDeviceNames);
  203109. if (outputIndex < 0)
  203110. {
  203111. // using an input device name instead..
  203112. inputIndex = inputDeviceNames.indexOf (deviceName);
  203113. outputIndex = jmax (0, findBestMatchForName (deviceName, outputDeviceNames));
  203114. }
  203115. DSoundAudioIODevice* device = new DSoundAudioIODevice (deviceName, outputIndex, inputIndex);
  203116. device->outChannels.add (TRANS("Left"));
  203117. device->outChannels.add (TRANS("Right"));
  203118. if (inputIndex >= 0)
  203119. {
  203120. device->inChannels.add (TRANS("Left"));
  203121. device->inChannels.add (TRANS("Right"));
  203122. }
  203123. return device;
  203124. }
  203125. return 0;
  203126. }
  203127. juce_UseDebuggingNewOperator
  203128. StringArray outputDeviceNames;
  203129. OwnedArray <GUID> outputGuids;
  203130. StringArray inputDeviceNames;
  203131. OwnedArray <GUID> inputGuids;
  203132. private:
  203133. bool hasScanned;
  203134. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  203135. {
  203136. desc = desc.trim();
  203137. if (desc.isNotEmpty())
  203138. {
  203139. const String origDesc (desc);
  203140. int n = 2;
  203141. while (outputDeviceNames.contains (desc))
  203142. desc = origDesc + T(" (") + String (n++) + T(")");
  203143. outputDeviceNames.add (desc);
  203144. if (lpGUID != 0)
  203145. outputGuids.add (new GUID (*lpGUID));
  203146. else
  203147. outputGuids.add (0);
  203148. }
  203149. return TRUE;
  203150. }
  203151. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203152. {
  203153. return ((DSoundAudioIODeviceType*) object)
  203154. ->outputEnumProc (lpGUID, String (description));
  203155. }
  203156. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203157. {
  203158. return ((DSoundAudioIODeviceType*) object)
  203159. ->outputEnumProc (lpGUID, String (description));
  203160. }
  203161. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  203162. {
  203163. desc = desc.trim();
  203164. if (desc.isNotEmpty())
  203165. {
  203166. const String origDesc (desc);
  203167. int n = 2;
  203168. while (inputDeviceNames.contains (desc))
  203169. desc = origDesc + T(" (") + String (n++) + T(")");
  203170. inputDeviceNames.add (desc);
  203171. if (lpGUID != 0)
  203172. inputGuids.add (new GUID (*lpGUID));
  203173. else
  203174. inputGuids.add (0);
  203175. }
  203176. return TRUE;
  203177. }
  203178. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203179. {
  203180. return ((DSoundAudioIODeviceType*) object)
  203181. ->inputEnumProc (lpGUID, String (description));
  203182. }
  203183. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203184. {
  203185. return ((DSoundAudioIODeviceType*) object)
  203186. ->inputEnumProc (lpGUID, String (description));
  203187. }
  203188. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  203189. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  203190. };
  203191. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  203192. {
  203193. return new DSoundAudioIODeviceType();
  203194. }
  203195. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  203196. const BitArray& outputChannels,
  203197. double sampleRate_,
  203198. int bufferSizeSamples_)
  203199. {
  203200. closeDevice();
  203201. totalSamplesOut = 0;
  203202. enabledInputs.clear();
  203203. enabledOutputs.clear();
  203204. sampleRate = sampleRate_;
  203205. if (bufferSizeSamples_ <= 0)
  203206. bufferSizeSamples_ = 960; // use as a default size if none is set.
  203207. bufferSizeSamples = bufferSizeSamples_ & ~7;
  203208. DSoundAudioIODeviceType dlh;
  203209. dlh.scanForDevices();
  203210. numInputBuffers = 2 * dlh.inputDeviceNames.size();
  203211. inputBuffers = new float* [numInputBuffers + 2];
  203212. numOutputBuffers = 2 * dlh.outputDeviceNames.size();
  203213. outputBuffers = new float* [numOutputBuffers + 2];
  203214. int i;
  203215. for (i = 0; i < numInputBuffers + 2; ++i)
  203216. {
  203217. if (inputChannels[i] && i < numInputBuffers)
  203218. {
  203219. inputBuffers[i] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203220. enabledInputs.setBit (i);
  203221. }
  203222. else
  203223. {
  203224. inputBuffers[i] = 0;
  203225. }
  203226. }
  203227. for (i = 0; i < numOutputBuffers + 2; ++i)
  203228. {
  203229. if (outputChannels[i] && i < numOutputBuffers)
  203230. {
  203231. outputBuffers[i] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203232. enabledOutputs.setBit (i);
  203233. }
  203234. else
  203235. {
  203236. outputBuffers[i] = 0;
  203237. }
  203238. }
  203239. for (i = 0; i < numInputBuffers; ++i)
  203240. {
  203241. if (inputChannels[i] || inputChannels[i + 1])
  203242. {
  203243. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [i / 2],
  203244. dlh.inputGuids [i / 2],
  203245. (int) sampleRate, bufferSizeSamples,
  203246. inputBuffers[i], inputBuffers[i + 1]));
  203247. }
  203248. else
  203249. {
  203250. inChans.add (0);
  203251. }
  203252. ++i;
  203253. }
  203254. for (i = 0; i < numOutputBuffers; ++i)
  203255. {
  203256. if (outputChannels[i] || outputChannels[i + 1])
  203257. {
  203258. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[i / 2],
  203259. dlh.outputGuids [i / 2],
  203260. (int) sampleRate, bufferSizeSamples,
  203261. outputBuffers[i], outputBuffers[i + 1]));
  203262. }
  203263. else
  203264. {
  203265. outChans.add (0);
  203266. }
  203267. ++i;
  203268. }
  203269. String error;
  203270. // boost our priority while opening the devices to try to get better sync between them
  203271. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203272. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203273. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203274. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203275. for (i = 0; i < numOutputBuffers; ++i)
  203276. {
  203277. if (outChans[i] != 0)
  203278. {
  203279. error = outChans[i]->open();
  203280. if (error.isNotEmpty())
  203281. {
  203282. error = T("Error opening ") + dlh.outputDeviceNames[i]
  203283. + T(": \"") + error + T("\"");
  203284. break;
  203285. }
  203286. }
  203287. }
  203288. if (error.isEmpty())
  203289. {
  203290. for (i = 0; i < numInputBuffers; ++i)
  203291. {
  203292. if (inChans[i] != 0)
  203293. {
  203294. error = inChans[i]->open();
  203295. if (error.isNotEmpty())
  203296. {
  203297. error = T("Error opening ") + dlh.inputDeviceNames[i]
  203298. + T(": \"") + error + T("\"");
  203299. break;
  203300. }
  203301. }
  203302. }
  203303. }
  203304. if (error.isEmpty())
  203305. {
  203306. totalSamplesOut = 0;
  203307. for (i = 0; i < numOutputBuffers; ++i)
  203308. if (outChans[i] != 0)
  203309. outChans[i]->synchronisePosition();
  203310. for (i = 0; i < numInputBuffers; ++i)
  203311. if (inChans[i] != 0)
  203312. inChans[i]->synchronisePosition();
  203313. startThread (9);
  203314. sleep (10);
  203315. notify();
  203316. }
  203317. else
  203318. {
  203319. log (error);
  203320. }
  203321. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203322. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203323. return error;
  203324. }
  203325. #undef log
  203326. END_JUCE_NAMESPACE
  203327. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  203328. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203329. #ifdef _MSC_VER
  203330. #pragma warning (disable: 4514)
  203331. #pragma warning (push)
  203332. #endif
  203333. #include <shlobj.h>
  203334. BEGIN_JUCE_NAMESPACE
  203335. #ifdef _MSC_VER
  203336. #pragma warning (pop)
  203337. #endif
  203338. static const void* defaultDirPath = 0;
  203339. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203340. static Component* currentExtraFileWin = 0;
  203341. static bool areThereAnyAlwaysOnTopWindows()
  203342. {
  203343. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203344. {
  203345. Component* c = Desktop::getInstance().getComponent (i);
  203346. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203347. return true;
  203348. }
  203349. return false;
  203350. }
  203351. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203352. {
  203353. if (msg == BFFM_INITIALIZED)
  203354. {
  203355. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203356. }
  203357. else if (msg == BFFM_VALIDATEFAILEDW)
  203358. {
  203359. returnedString = (LPCWSTR) lParam;
  203360. }
  203361. else if (msg == BFFM_VALIDATEFAILEDA)
  203362. {
  203363. returnedString = (const char*) lParam;
  203364. }
  203365. return 0;
  203366. }
  203367. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  203368. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203369. {
  203370. if (currentExtraFileWin != 0)
  203371. {
  203372. if (uiMsg == WM_INITDIALOG)
  203373. {
  203374. HWND dialogH = GetParent (hdlg);
  203375. jassert (dialogH != 0);
  203376. if (dialogH == 0)
  203377. dialogH = hdlg;
  203378. RECT r, cr;
  203379. GetWindowRect (dialogH, &r);
  203380. GetClientRect (dialogH, &cr);
  203381. SetWindowPos (dialogH, 0,
  203382. r.left, r.top,
  203383. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203384. jmax (150, r.bottom - r.top),
  203385. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203386. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203387. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203388. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203389. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203390. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203391. }
  203392. else if (uiMsg == WM_NOTIFY)
  203393. {
  203394. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203395. if (ofn->hdr.code == CDN_SELCHANGE)
  203396. {
  203397. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203398. if (comp != 0)
  203399. {
  203400. TCHAR path [MAX_PATH * 2];
  203401. path[0] = 0;
  203402. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203403. const String fn ((const WCHAR*) path);
  203404. comp->selectedFileChanged (File (fn));
  203405. }
  203406. }
  203407. }
  203408. }
  203409. return 0;
  203410. }
  203411. class FPComponentHolder : public Component
  203412. {
  203413. public:
  203414. FPComponentHolder()
  203415. {
  203416. setVisible (true);
  203417. setOpaque (true);
  203418. }
  203419. ~FPComponentHolder()
  203420. {
  203421. }
  203422. void paint (Graphics& g)
  203423. {
  203424. g.fillAll (Colours::lightgrey);
  203425. }
  203426. private:
  203427. FPComponentHolder (const FPComponentHolder&);
  203428. const FPComponentHolder& operator= (const FPComponentHolder&);
  203429. };
  203430. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203431. const String& title,
  203432. const File& currentFileOrDirectory,
  203433. const String& filter,
  203434. bool selectsDirectory,
  203435. bool isSaveDialogue,
  203436. bool warnAboutOverwritingExistingFiles,
  203437. bool selectMultipleFiles,
  203438. FilePreviewComponent* extraInfoComponent)
  203439. {
  203440. const int numCharsAvailable = 32768;
  203441. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203442. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203443. int fnameIdx = 0;
  203444. JUCE_TRY
  203445. {
  203446. // use a modal window as the parent for this dialog box
  203447. // to block input from other app windows
  203448. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203449. Component w (String::empty);
  203450. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203451. mainMon.getY() + mainMon.getHeight() / 4,
  203452. 0, 0);
  203453. w.setOpaque (true);
  203454. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203455. w.addToDesktop (0);
  203456. if (extraInfoComponent == 0)
  203457. w.enterModalState();
  203458. String initialDir;
  203459. if (currentFileOrDirectory.isDirectory())
  203460. {
  203461. initialDir = currentFileOrDirectory.getFullPathName();
  203462. }
  203463. else
  203464. {
  203465. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203466. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203467. }
  203468. if (currentExtraFileWin->isValidComponent())
  203469. {
  203470. jassertfalse
  203471. return;
  203472. }
  203473. if (selectsDirectory)
  203474. {
  203475. LPITEMIDLIST list = 0;
  203476. filenameSpace.fillWith (0);
  203477. {
  203478. BROWSEINFO bi;
  203479. zerostruct (bi);
  203480. bi.hwndOwner = (HWND) w.getWindowHandle();
  203481. bi.pszDisplayName = fname;
  203482. bi.lpszTitle = title;
  203483. bi.lpfn = browseCallbackProc;
  203484. #ifdef BIF_USENEWUI
  203485. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203486. #else
  203487. bi.ulFlags = 0x50;
  203488. #endif
  203489. defaultDirPath = (const WCHAR*) initialDir;
  203490. list = SHBrowseForFolder (&bi);
  203491. if (! SHGetPathFromIDListW (list, fname))
  203492. {
  203493. fname[0] = 0;
  203494. returnedString = String::empty;
  203495. }
  203496. }
  203497. LPMALLOC al;
  203498. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203499. al->Free (list);
  203500. defaultDirPath = 0;
  203501. if (returnedString.isNotEmpty())
  203502. {
  203503. const String stringFName (fname);
  203504. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203505. returnedString = String::empty;
  203506. return;
  203507. }
  203508. }
  203509. else
  203510. {
  203511. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203512. if (warnAboutOverwritingExistingFiles)
  203513. flags |= OFN_OVERWRITEPROMPT;
  203514. if (selectMultipleFiles)
  203515. flags |= OFN_ALLOWMULTISELECT;
  203516. if (extraInfoComponent != 0)
  203517. {
  203518. flags |= OFN_ENABLEHOOK;
  203519. currentExtraFileWin = new FPComponentHolder();
  203520. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203521. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203522. extraInfoComponent->getHeight());
  203523. currentExtraFileWin->addToDesktop (0);
  203524. currentExtraFileWin->enterModalState();
  203525. }
  203526. {
  203527. WCHAR filters [1024];
  203528. zeromem (filters, sizeof (filters));
  203529. filter.copyToBuffer (filters, 1024);
  203530. filter.copyToBuffer (filters + filter.length() + 1,
  203531. 1022 - filter.length());
  203532. OPENFILENAMEW of;
  203533. zerostruct (of);
  203534. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203535. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203536. #else
  203537. of.lStructSize = sizeof (of);
  203538. #endif
  203539. of.hwndOwner = (HWND) w.getWindowHandle();
  203540. of.lpstrFilter = filters;
  203541. of.nFilterIndex = 1;
  203542. of.lpstrFile = fname;
  203543. of.nMaxFile = numCharsAvailable;
  203544. of.lpstrInitialDir = initialDir;
  203545. of.lpstrTitle = title;
  203546. of.Flags = flags;
  203547. if (extraInfoComponent != 0)
  203548. of.lpfnHook = &openCallback;
  203549. if (isSaveDialogue)
  203550. {
  203551. if (! GetSaveFileName (&of))
  203552. fname[0] = 0;
  203553. else
  203554. fnameIdx = of.nFileOffset;
  203555. }
  203556. else
  203557. {
  203558. if (! GetOpenFileName (&of))
  203559. fname[0] = 0;
  203560. else
  203561. fnameIdx = of.nFileOffset;
  203562. }
  203563. }
  203564. }
  203565. }
  203566. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203567. catch (...)
  203568. {
  203569. fname[0] = 0;
  203570. }
  203571. #endif
  203572. deleteAndZero (currentExtraFileWin);
  203573. const WCHAR* const files = fname;
  203574. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203575. {
  203576. const WCHAR* filename = files + fnameIdx;
  203577. while (*filename != 0)
  203578. {
  203579. const String filepath (String (files) + T("\\") + String (filename));
  203580. results.add (new File (filepath));
  203581. filename += CharacterFunctions::length (filename) + 1;
  203582. }
  203583. }
  203584. else if (files[0] != 0)
  203585. {
  203586. results.add (new File (files));
  203587. }
  203588. }
  203589. END_JUCE_NAMESPACE
  203590. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203591. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203592. BEGIN_JUCE_NAMESPACE
  203593. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203594. NEWTEXTMETRICEXW*,
  203595. int type,
  203596. LPARAM lParam)
  203597. {
  203598. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  203599. {
  203600. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203601. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203602. }
  203603. return 1;
  203604. }
  203605. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203606. NEWTEXTMETRICEXW*,
  203607. int type,
  203608. LPARAM lParam)
  203609. {
  203610. if (lpelfe != 0
  203611. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  203612. {
  203613. LOGFONTW lf;
  203614. zerostruct (lf);
  203615. lf.lfWeight = FW_DONTCARE;
  203616. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  203617. lf.lfQuality = DEFAULT_QUALITY;
  203618. lf.lfCharSet = DEFAULT_CHARSET;
  203619. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203620. lf.lfPitchAndFamily = FF_DONTCARE;
  203621. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203622. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203623. HDC dc = CreateCompatibleDC (0);
  203624. EnumFontFamiliesEx (dc, &lf,
  203625. (FONTENUMPROCW) &wfontEnum2,
  203626. lParam, 0);
  203627. DeleteDC (dc);
  203628. }
  203629. return 1;
  203630. }
  203631. const StringArray Font::findAllTypefaceNames() throw()
  203632. {
  203633. StringArray results;
  203634. HDC dc = CreateCompatibleDC (0);
  203635. {
  203636. LOGFONTW lf;
  203637. zerostruct (lf);
  203638. lf.lfWeight = FW_DONTCARE;
  203639. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  203640. lf.lfQuality = DEFAULT_QUALITY;
  203641. lf.lfCharSet = DEFAULT_CHARSET;
  203642. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203643. lf.lfPitchAndFamily = FF_DONTCARE;
  203644. lf.lfFaceName[0] = 0;
  203645. EnumFontFamiliesEx (dc, &lf,
  203646. (FONTENUMPROCW) &wfontEnum1,
  203647. (LPARAM) &results, 0);
  203648. }
  203649. DeleteDC (dc);
  203650. results.sort (true);
  203651. return results;
  203652. }
  203653. extern bool juce_IsRunningInWine() throw();
  203654. void Font::getDefaultFontNames (String& defaultSans,
  203655. String& defaultSerif,
  203656. String& defaultFixed) throw()
  203657. {
  203658. if (juce_IsRunningInWine())
  203659. {
  203660. // If we're running in Wine, then use fonts that might be available on Linux..
  203661. defaultSans = "Bitstream Vera Sans";
  203662. defaultSerif = "Bitstream Vera Serif";
  203663. defaultFixed = "Bitstream Vera Sans Mono";
  203664. }
  203665. else
  203666. {
  203667. defaultSans = "Verdana";
  203668. defaultSerif = "Times";
  203669. defaultFixed = "Lucida Console";
  203670. }
  203671. }
  203672. class FontDCHolder : private DeletedAtShutdown
  203673. {
  203674. HDC dc;
  203675. String fontName;
  203676. KERNINGPAIR* kps;
  203677. int numKPs;
  203678. bool bold, italic;
  203679. int size;
  203680. FontDCHolder (const FontDCHolder&);
  203681. const FontDCHolder& operator= (const FontDCHolder&);
  203682. public:
  203683. HFONT fontH;
  203684. FontDCHolder() throw()
  203685. : dc (0),
  203686. kps (0),
  203687. numKPs (0),
  203688. bold (false),
  203689. italic (false),
  203690. size (0)
  203691. {
  203692. }
  203693. ~FontDCHolder() throw()
  203694. {
  203695. if (dc != 0)
  203696. {
  203697. DeleteDC (dc);
  203698. DeleteObject (fontH);
  203699. juce_free (kps);
  203700. }
  203701. clearSingletonInstance();
  203702. }
  203703. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203704. HDC loadFont (const String& fontName_,
  203705. const bool bold_,
  203706. const bool italic_,
  203707. const int size_) throw()
  203708. {
  203709. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203710. {
  203711. fontName = fontName_;
  203712. bold = bold_;
  203713. italic = italic_;
  203714. size = size_;
  203715. if (dc != 0)
  203716. {
  203717. DeleteDC (dc);
  203718. DeleteObject (fontH);
  203719. juce_free (kps);
  203720. kps = 0;
  203721. }
  203722. fontH = 0;
  203723. dc = CreateCompatibleDC (0);
  203724. SetMapperFlags (dc, 0);
  203725. SetMapMode (dc, MM_TEXT);
  203726. LOGFONTW lfw;
  203727. zerostruct (lfw);
  203728. lfw.lfCharSet = DEFAULT_CHARSET;
  203729. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203730. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203731. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203732. lfw.lfQuality = PROOF_QUALITY;
  203733. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203734. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203735. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203736. lfw.lfHeight = size > 0 ? size : -256;
  203737. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203738. if (standardSizedFont != 0)
  203739. {
  203740. if (SelectObject (dc, standardSizedFont) != 0)
  203741. {
  203742. fontH = standardSizedFont;
  203743. if (size == 0)
  203744. {
  203745. OUTLINETEXTMETRIC otm;
  203746. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203747. {
  203748. lfw.lfHeight = -(int) otm.otmEMSquare;
  203749. fontH = CreateFontIndirect (&lfw);
  203750. SelectObject (dc, fontH);
  203751. DeleteObject (standardSizedFont);
  203752. }
  203753. }
  203754. }
  203755. else
  203756. {
  203757. jassertfalse
  203758. }
  203759. }
  203760. else
  203761. {
  203762. jassertfalse
  203763. }
  203764. }
  203765. return dc;
  203766. }
  203767. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203768. {
  203769. if (kps == 0)
  203770. {
  203771. numKPs = GetKerningPairs (dc, 0, 0);
  203772. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203773. GetKerningPairs (dc, numKPs, kps);
  203774. }
  203775. numKPs_ = numKPs;
  203776. return kps;
  203777. }
  203778. };
  203779. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203780. static bool addGlyphToTypeface (HDC dc,
  203781. juce_wchar character,
  203782. Typeface& dest,
  203783. bool addKerning)
  203784. {
  203785. Path destShape;
  203786. GLYPHMETRICS gm;
  203787. float height;
  203788. BOOL ok = false;
  203789. {
  203790. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203791. WORD index = 0;
  203792. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203793. && index == 0xffff)
  203794. {
  203795. return false;
  203796. }
  203797. }
  203798. TEXTMETRIC tm;
  203799. ok = GetTextMetrics (dc, &tm);
  203800. height = (float) tm.tmHeight;
  203801. if (! ok)
  203802. {
  203803. dest.addGlyph (character, destShape, 0);
  203804. return true;
  203805. }
  203806. const float scaleX = 1.0f / height;
  203807. const float scaleY = -1.0f / height;
  203808. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203809. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203810. &gm, 0, 0, &identityMatrix);
  203811. if (bufSize > 0)
  203812. {
  203813. char* const data = (char*) juce_malloc (bufSize);
  203814. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203815. bufSize, data, &identityMatrix);
  203816. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203817. while ((char*) pheader < data + bufSize)
  203818. {
  203819. #define remapX(v) (scaleX * (v).x.value)
  203820. #define remapY(v) (scaleY * (v).y.value)
  203821. float x = remapX (pheader->pfxStart);
  203822. float y = remapY (pheader->pfxStart);
  203823. destShape.startNewSubPath (x, y);
  203824. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203825. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203826. while ((const char*) curve < curveEnd)
  203827. {
  203828. if (curve->wType == TT_PRIM_LINE)
  203829. {
  203830. for (int i = 0; i < curve->cpfx; ++i)
  203831. {
  203832. x = remapX (curve->apfx [i]);
  203833. y = remapY (curve->apfx [i]);
  203834. destShape.lineTo (x, y);
  203835. }
  203836. }
  203837. else if (curve->wType == TT_PRIM_QSPLINE)
  203838. {
  203839. for (int i = 0; i < curve->cpfx - 1; ++i)
  203840. {
  203841. const float x2 = remapX (curve->apfx [i]);
  203842. const float y2 = remapY (curve->apfx [i]);
  203843. float x3, y3;
  203844. if (i < curve->cpfx - 2)
  203845. {
  203846. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203847. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203848. }
  203849. else
  203850. {
  203851. x3 = remapX (curve->apfx [i + 1]);
  203852. y3 = remapY (curve->apfx [i + 1]);
  203853. }
  203854. destShape.quadraticTo (x2, y2, x3, y3);
  203855. x = x3;
  203856. y = y3;
  203857. }
  203858. }
  203859. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203860. }
  203861. pheader = (const TTPOLYGONHEADER*) curve;
  203862. destShape.closeSubPath();
  203863. }
  203864. juce_free (data);
  203865. }
  203866. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203867. if (addKerning)
  203868. {
  203869. int numKPs;
  203870. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203871. for (int i = 0; i < numKPs; ++i)
  203872. {
  203873. if (kps[i].wFirst == character)
  203874. {
  203875. dest.addKerningPair (kps[i].wFirst,
  203876. kps[i].wSecond,
  203877. kps[i].iKernAmount / height);
  203878. }
  203879. }
  203880. }
  203881. return true;
  203882. }
  203883. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203884. {
  203885. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203886. return addGlyphToTypeface (dc, character, *this, true);
  203887. }
  203888. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203889. {
  203890. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203891. int bufSize;
  203892. GLYPHMETRICS gm;
  203893. const UINT format = GGO_GRAY2_BITMAP;
  203894. const int shift = 6;
  203895. if (wGetGlyphOutlineW != 0)
  203896. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203897. else
  203898. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203899. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203900. if (bufSize > 0)
  203901. {
  203902. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203903. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203904. uint8* const data = (uint8*) juce_calloc (bufSize);
  203905. if (wGetGlyphOutlineW != 0)
  203906. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203907. else
  203908. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203909. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203910. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203911. {
  203912. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203913. {
  203914. const int level = data [x + y * stride] << shift;
  203915. if (level > 0)
  203916. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203917. }
  203918. }
  203919. juce_free (data);
  203920. }
  203921. return im;
  203922. }*/
  203923. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203924. bool bold,
  203925. bool italic,
  203926. bool addAllGlyphsToFont) throw()
  203927. {
  203928. clear();
  203929. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203930. float height;
  203931. int firstChar, lastChar;
  203932. {
  203933. TEXTMETRIC tm;
  203934. GetTextMetrics (dc, &tm);
  203935. height = (float) tm.tmHeight;
  203936. firstChar = tm.tmFirstChar;
  203937. lastChar = tm.tmLastChar;
  203938. setAscent (tm.tmAscent / height);
  203939. setDefaultCharacter (tm.tmDefaultChar);
  203940. }
  203941. setName (fontName);
  203942. setBold (bold);
  203943. setItalic (italic);
  203944. if (addAllGlyphsToFont)
  203945. {
  203946. for (int character = firstChar; character <= lastChar; ++character)
  203947. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203948. int numKPs;
  203949. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203950. for (int i = 0; i < numKPs; ++i)
  203951. {
  203952. addKerningPair (kps[i].wFirst,
  203953. kps[i].wSecond,
  203954. kps[i].iKernAmount / height);
  203955. }
  203956. }
  203957. }
  203958. END_JUCE_NAMESPACE
  203959. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203960. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  203961. BEGIN_JUCE_NAMESPACE
  203962. static const unsigned int specialId = WM_APP + 0x4400;
  203963. static const unsigned int broadcastId = WM_APP + 0x4403;
  203964. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  203965. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  203966. HWND juce_messageWindowHandle = 0;
  203967. extern long improbableWindowNumber; // defined in windowing.cpp
  203968. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  203969. const UINT message,
  203970. const WPARAM wParam,
  203971. const LPARAM lParam) throw()
  203972. {
  203973. JUCE_TRY
  203974. {
  203975. if (h == juce_messageWindowHandle)
  203976. {
  203977. if (message == specialCallbackId)
  203978. {
  203979. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  203980. return (LRESULT) (*func) ((void*) lParam);
  203981. }
  203982. else if (message == specialId)
  203983. {
  203984. // these are trapped early in the dispatch call, but must also be checked
  203985. // here in case there are windows modal dialog boxes doing their own
  203986. // dispatch loop and not calling our version
  203987. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  203988. return 0;
  203989. }
  203990. else if (message == broadcastId)
  203991. {
  203992. String* const messageString = (String*) lParam;
  203993. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  203994. delete messageString;
  203995. return 0;
  203996. }
  203997. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  203998. {
  203999. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204000. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204001. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204002. return 0;
  204003. }
  204004. }
  204005. }
  204006. JUCE_CATCH_EXCEPTION
  204007. return DefWindowProc (h, message, wParam, lParam);
  204008. }
  204009. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204010. {
  204011. MSG m;
  204012. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204013. return false;
  204014. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  204015. {
  204016. if (m.message == specialId
  204017. && m.hwnd == juce_messageWindowHandle)
  204018. {
  204019. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204020. }
  204021. else
  204022. {
  204023. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  204024. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  204025. {
  204026. // if it's someone else's window being clicked on, and the focus is
  204027. // currently on a juce window, pass the kb focus over..
  204028. HWND currentFocus = GetFocus();
  204029. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204030. SetFocus (m.hwnd);
  204031. }
  204032. TranslateMessage (&m);
  204033. DispatchMessage (&m);
  204034. }
  204035. }
  204036. return true;
  204037. }
  204038. bool juce_postMessageToSystemQueue (void* message)
  204039. {
  204040. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204041. }
  204042. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204043. void* userData)
  204044. {
  204045. if (MessageManager::getInstance()->isThisTheMessageThread())
  204046. {
  204047. return (*callback) (userData);
  204048. }
  204049. else
  204050. {
  204051. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204052. // deadlock because the message manager is blocked from running, and can't
  204053. // call your function..
  204054. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204055. return (void*) SendMessage (juce_messageWindowHandle,
  204056. specialCallbackId,
  204057. (WPARAM) callback,
  204058. (LPARAM) userData);
  204059. }
  204060. }
  204061. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204062. {
  204063. if (hwnd != juce_messageWindowHandle)
  204064. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  204065. return TRUE;
  204066. }
  204067. void MessageManager::broadcastMessage (const String& value) throw()
  204068. {
  204069. VoidArray windows;
  204070. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204071. const String localCopy (value);
  204072. COPYDATASTRUCT data;
  204073. data.dwData = broadcastId;
  204074. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204075. data.lpData = (void*) (const juce_wchar*) localCopy;
  204076. for (int i = windows.size(); --i >= 0;)
  204077. {
  204078. HWND hwnd = (HWND) windows.getUnchecked(i);
  204079. TCHAR windowName [64]; // no need to read longer strings than this
  204080. GetWindowText (hwnd, windowName, 64);
  204081. windowName [63] = 0;
  204082. if (String (windowName) == String (messageWindowName))
  204083. {
  204084. DWORD_PTR result;
  204085. SendMessageTimeout (hwnd, WM_COPYDATA,
  204086. (WPARAM) juce_messageWindowHandle,
  204087. (LPARAM) &data,
  204088. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204089. 8000,
  204090. &result);
  204091. }
  204092. }
  204093. }
  204094. static const String getMessageWindowClassName()
  204095. {
  204096. // this name has to be different for each app/dll instance because otherwise
  204097. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204098. // window class).
  204099. static int number = 0;
  204100. if (number == 0)
  204101. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204102. return T("JUCEcs_") + String (number);
  204103. }
  204104. void MessageManager::doPlatformSpecificInitialisation()
  204105. {
  204106. OleInitialize (0);
  204107. const String className (getMessageWindowClassName());
  204108. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204109. WNDCLASSEX wc;
  204110. zerostruct (wc);
  204111. wc.cbSize = sizeof (wc);
  204112. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204113. wc.cbWndExtra = 4;
  204114. wc.hInstance = hmod;
  204115. wc.lpszClassName = className;
  204116. RegisterClassEx (&wc);
  204117. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204118. messageWindowName,
  204119. 0, 0, 0, 0, 0, 0, 0,
  204120. hmod, 0);
  204121. }
  204122. void MessageManager::doPlatformSpecificShutdown()
  204123. {
  204124. DestroyWindow (juce_messageWindowHandle);
  204125. UnregisterClass (getMessageWindowClassName(), 0);
  204126. OleUninitialize();
  204127. }
  204128. END_JUCE_NAMESPACE
  204129. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  204130. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  204131. BEGIN_JUCE_NAMESPACE
  204132. #if JUCE_MSVC
  204133. #pragma warning (disable: 4312)
  204134. #endif
  204135. using ::free;
  204136. static const int midiBufferSize = 1024 * 10;
  204137. static const int numInHeaders = 32;
  204138. static const int inBufferSize = 256;
  204139. static Array <void*, CriticalSection> activeMidiThreads;
  204140. class MidiInThread : public Thread
  204141. {
  204142. public:
  204143. MidiInThread (MidiInput* const input_,
  204144. MidiInputCallback* const callback_)
  204145. : Thread ("Juce Midi"),
  204146. hIn (0),
  204147. input (input_),
  204148. callback (callback_),
  204149. isStarted (false),
  204150. startTime (0),
  204151. pendingLength(0)
  204152. {
  204153. for (int i = numInHeaders; --i >= 0;)
  204154. {
  204155. zeromem (&hdr[i], sizeof (MIDIHDR));
  204156. hdr[i].lpData = inData[i];
  204157. hdr[i].dwBufferLength = inBufferSize;
  204158. }
  204159. };
  204160. ~MidiInThread()
  204161. {
  204162. stop();
  204163. if (hIn != 0)
  204164. {
  204165. int count = 5;
  204166. while (--count >= 0)
  204167. {
  204168. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  204169. break;
  204170. Sleep (20);
  204171. }
  204172. }
  204173. }
  204174. void handle (const uint32 message, const uint32 timeStamp) throw()
  204175. {
  204176. const int byte = message & 0xff;
  204177. if (byte < 0x80)
  204178. return;
  204179. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  204180. const double time = timeStampToTime (timeStamp);
  204181. lock.enter();
  204182. if (pendingLength < midiBufferSize - 12)
  204183. {
  204184. char* const p = pending + pendingLength;
  204185. *(double*) p = time;
  204186. *(uint32*) (p + 8) = numBytes;
  204187. *(uint32*) (p + 12) = message;
  204188. pendingLength += 12 + numBytes;
  204189. }
  204190. else
  204191. {
  204192. jassertfalse // midi buffer overflow! You might need to increase the size..
  204193. }
  204194. lock.exit();
  204195. notify();
  204196. }
  204197. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  204198. {
  204199. const int num = hdr->dwBytesRecorded;
  204200. if (num > 0)
  204201. {
  204202. const double time = timeStampToTime (timeStamp);
  204203. lock.enter();
  204204. if (pendingLength < midiBufferSize - (8 + num))
  204205. {
  204206. char* const p = pending + pendingLength;
  204207. *(double*) p = time;
  204208. *(uint32*) (p + 8) = num;
  204209. memcpy (p + 12, hdr->lpData, num);
  204210. pendingLength += 12 + num;
  204211. }
  204212. else
  204213. {
  204214. jassertfalse // midi buffer overflow! You might need to increase the size..
  204215. }
  204216. lock.exit();
  204217. notify();
  204218. }
  204219. }
  204220. void writeBlock (const int i) throw()
  204221. {
  204222. hdr[i].dwBytesRecorded = 0;
  204223. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204224. jassert (res == MMSYSERR_NOERROR);
  204225. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  204226. jassert (res == MMSYSERR_NOERROR);
  204227. }
  204228. void run()
  204229. {
  204230. MemoryBlock pendingCopy (64);
  204231. while (! threadShouldExit())
  204232. {
  204233. for (int i = 0; i < numInHeaders; ++i)
  204234. {
  204235. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204236. {
  204237. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204238. (void) res;
  204239. jassert (res == MMSYSERR_NOERROR);
  204240. writeBlock (i);
  204241. }
  204242. }
  204243. lock.enter();
  204244. int len = pendingLength;
  204245. if (len > 0)
  204246. {
  204247. pendingCopy.ensureSize (len);
  204248. pendingCopy.copyFrom (pending, 0, len);
  204249. pendingLength = 0;
  204250. }
  204251. lock.exit();
  204252. //xxx needs to figure out if blocks are broken up or not
  204253. if (len == 0)
  204254. {
  204255. wait (500);
  204256. }
  204257. else
  204258. {
  204259. const char* p = (const char*) pendingCopy.getData();
  204260. while (len > 0)
  204261. {
  204262. const double time = *(const double*) p;
  204263. const int messageLen = *(const int*) (p + 8);
  204264. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  204265. callback->handleIncomingMidiMessage (input, message);
  204266. p += 12 + messageLen;
  204267. len -= 12 + messageLen;
  204268. }
  204269. }
  204270. }
  204271. }
  204272. void start() throw()
  204273. {
  204274. jassert (hIn != 0);
  204275. if (hIn != 0 && ! isStarted)
  204276. {
  204277. stop();
  204278. activeMidiThreads.addIfNotAlreadyThere (this);
  204279. int i;
  204280. for (i = 0; i < numInHeaders; ++i)
  204281. writeBlock (i);
  204282. startTime = Time::getMillisecondCounter();
  204283. MMRESULT res = midiInStart (hIn);
  204284. jassert (res == MMSYSERR_NOERROR);
  204285. if (res == MMSYSERR_NOERROR)
  204286. {
  204287. isStarted = true;
  204288. pendingLength = 0;
  204289. startThread (6);
  204290. }
  204291. }
  204292. }
  204293. void stop() throw()
  204294. {
  204295. if (isStarted)
  204296. {
  204297. stopThread (5000);
  204298. midiInReset (hIn);
  204299. midiInStop (hIn);
  204300. activeMidiThreads.removeValue (this);
  204301. lock.enter();
  204302. lock.exit();
  204303. for (int i = numInHeaders; --i >= 0;)
  204304. {
  204305. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204306. {
  204307. int c = 10;
  204308. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  204309. Sleep (20);
  204310. jassert (c >= 0);
  204311. }
  204312. }
  204313. isStarted = false;
  204314. pendingLength = 0;
  204315. }
  204316. }
  204317. juce_UseDebuggingNewOperator
  204318. HMIDIIN hIn;
  204319. private:
  204320. MidiInput* input;
  204321. MidiInputCallback* callback;
  204322. bool isStarted;
  204323. uint32 startTime;
  204324. CriticalSection lock;
  204325. MIDIHDR hdr [numInHeaders];
  204326. char inData [numInHeaders] [inBufferSize];
  204327. int pendingLength;
  204328. char pending [midiBufferSize];
  204329. double timeStampToTime (uint32 timeStamp) throw()
  204330. {
  204331. timeStamp += startTime;
  204332. const uint32 now = Time::getMillisecondCounter();
  204333. if (timeStamp > now)
  204334. {
  204335. if (timeStamp > now + 2)
  204336. --startTime;
  204337. timeStamp = now;
  204338. }
  204339. return 0.001 * timeStamp;
  204340. }
  204341. MidiInThread (const MidiInThread&);
  204342. const MidiInThread& operator= (const MidiInThread&);
  204343. };
  204344. static void CALLBACK midiInCallback (HMIDIIN,
  204345. UINT uMsg,
  204346. DWORD_PTR dwInstance,
  204347. DWORD_PTR midiMessage,
  204348. DWORD_PTR timeStamp)
  204349. {
  204350. MidiInThread* const thread = (MidiInThread*) dwInstance;
  204351. if (thread != 0 && activeMidiThreads.contains (thread))
  204352. {
  204353. if (uMsg == MIM_DATA)
  204354. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  204355. else if (uMsg == MIM_LONGDATA)
  204356. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  204357. }
  204358. }
  204359. const StringArray MidiInput::getDevices()
  204360. {
  204361. StringArray s;
  204362. const int num = midiInGetNumDevs();
  204363. for (int i = 0; i < num; ++i)
  204364. {
  204365. MIDIINCAPS mc;
  204366. zerostruct (mc);
  204367. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204368. s.add (String (mc.szPname, sizeof (mc.szPname)));
  204369. }
  204370. return s;
  204371. }
  204372. int MidiInput::getDefaultDeviceIndex()
  204373. {
  204374. return 0;
  204375. }
  204376. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  204377. {
  204378. if (callback == 0)
  204379. return 0;
  204380. UINT deviceId = MIDI_MAPPER;
  204381. int n = 0;
  204382. String name;
  204383. const int num = midiInGetNumDevs();
  204384. for (int i = 0; i < num; ++i)
  204385. {
  204386. MIDIINCAPS mc;
  204387. zerostruct (mc);
  204388. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204389. {
  204390. if (index == n)
  204391. {
  204392. deviceId = i;
  204393. name = String (mc.szPname, sizeof (mc.szPname));
  204394. break;
  204395. }
  204396. ++n;
  204397. }
  204398. }
  204399. MidiInput* const in = new MidiInput (name);
  204400. MidiInThread* const thread = new MidiInThread (in, callback);
  204401. HMIDIIN h;
  204402. HRESULT err = midiInOpen (&h, deviceId,
  204403. (DWORD_PTR) &midiInCallback,
  204404. (DWORD_PTR) thread,
  204405. CALLBACK_FUNCTION);
  204406. if (err == MMSYSERR_NOERROR)
  204407. {
  204408. thread->hIn = h;
  204409. in->internal = (void*) thread;
  204410. return in;
  204411. }
  204412. else
  204413. {
  204414. delete in;
  204415. delete thread;
  204416. return 0;
  204417. }
  204418. }
  204419. MidiInput::MidiInput (const String& name_)
  204420. : name (name_),
  204421. internal (0)
  204422. {
  204423. }
  204424. MidiInput::~MidiInput()
  204425. {
  204426. if (internal != 0)
  204427. {
  204428. MidiInThread* const thread = (MidiInThread*) internal;
  204429. delete thread;
  204430. }
  204431. }
  204432. void MidiInput::start()
  204433. {
  204434. ((MidiInThread*) internal)->start();
  204435. }
  204436. void MidiInput::stop()
  204437. {
  204438. ((MidiInThread*) internal)->stop();
  204439. }
  204440. struct MidiOutHandle
  204441. {
  204442. int refCount;
  204443. UINT deviceId;
  204444. HMIDIOUT handle;
  204445. juce_UseDebuggingNewOperator
  204446. };
  204447. static VoidArray handles (4);
  204448. const StringArray MidiOutput::getDevices()
  204449. {
  204450. StringArray s;
  204451. const int num = midiOutGetNumDevs();
  204452. for (int i = 0; i < num; ++i)
  204453. {
  204454. MIDIOUTCAPS mc;
  204455. zerostruct (mc);
  204456. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204457. s.add (String (mc.szPname, sizeof (mc.szPname)));
  204458. }
  204459. return s;
  204460. }
  204461. int MidiOutput::getDefaultDeviceIndex()
  204462. {
  204463. const int num = midiOutGetNumDevs();
  204464. int n = 0;
  204465. for (int i = 0; i < num; ++i)
  204466. {
  204467. MIDIOUTCAPS mc;
  204468. zerostruct (mc);
  204469. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204470. {
  204471. if ((mc.wTechnology & MOD_MAPPER) != 0)
  204472. return n;
  204473. ++n;
  204474. }
  204475. }
  204476. return 0;
  204477. }
  204478. MidiOutput* MidiOutput::openDevice (int index)
  204479. {
  204480. UINT deviceId = MIDI_MAPPER;
  204481. const int num = midiOutGetNumDevs();
  204482. int i, n = 0;
  204483. for (i = 0; i < num; ++i)
  204484. {
  204485. MIDIOUTCAPS mc;
  204486. zerostruct (mc);
  204487. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204488. {
  204489. // use the microsoft sw synth as a default - best not to allow deviceId
  204490. // to be MIDI_MAPPER, or else device sharing breaks
  204491. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  204492. deviceId = i;
  204493. if (index == n)
  204494. {
  204495. deviceId = i;
  204496. break;
  204497. }
  204498. ++n;
  204499. }
  204500. }
  204501. for (i = handles.size(); --i >= 0;)
  204502. {
  204503. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  204504. if (han != 0 && han->deviceId == deviceId)
  204505. {
  204506. han->refCount++;
  204507. MidiOutput* const out = new MidiOutput();
  204508. out->internal = (void*) han;
  204509. return out;
  204510. }
  204511. }
  204512. for (i = 4; --i >= 0;)
  204513. {
  204514. HMIDIOUT h = 0;
  204515. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  204516. if (res == MMSYSERR_NOERROR)
  204517. {
  204518. MidiOutHandle* const han = new MidiOutHandle();
  204519. han->deviceId = deviceId;
  204520. han->refCount = 1;
  204521. han->handle = h;
  204522. handles.add (han);
  204523. MidiOutput* const out = new MidiOutput();
  204524. out->internal = (void*) han;
  204525. return out;
  204526. }
  204527. else if (res == MMSYSERR_ALLOCATED)
  204528. {
  204529. Sleep (100);
  204530. }
  204531. else
  204532. {
  204533. break;
  204534. }
  204535. }
  204536. return 0;
  204537. }
  204538. MidiOutput::~MidiOutput()
  204539. {
  204540. MidiOutHandle* const h = (MidiOutHandle*) internal;
  204541. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  204542. {
  204543. midiOutClose (h->handle);
  204544. handles.removeValue ((void*) h);
  204545. delete h;
  204546. }
  204547. }
  204548. void MidiOutput::reset()
  204549. {
  204550. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  204551. midiOutReset (h->handle);
  204552. }
  204553. bool MidiOutput::getVolume (float& leftVol,
  204554. float& rightVol)
  204555. {
  204556. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  204557. DWORD n;
  204558. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  204559. {
  204560. const unsigned short* const nn = (const unsigned short*) &n;
  204561. rightVol = nn[0] / (float) 0xffff;
  204562. leftVol = nn[1] / (float) 0xffff;
  204563. return true;
  204564. }
  204565. else
  204566. {
  204567. rightVol = leftVol = 1.0f;
  204568. return false;
  204569. }
  204570. }
  204571. void MidiOutput::setVolume (float leftVol,
  204572. float rightVol)
  204573. {
  204574. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  204575. DWORD n;
  204576. unsigned short* const nn = (unsigned short*) &n;
  204577. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  204578. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  204579. midiOutSetVolume (handle->handle, n);
  204580. }
  204581. void MidiOutput::sendMessageNow (const MidiMessage& message)
  204582. {
  204583. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  204584. if (message.getRawDataSize() > 3
  204585. || message.isSysEx())
  204586. {
  204587. MIDIHDR h;
  204588. zerostruct (h);
  204589. h.lpData = (char*) message.getRawData();
  204590. h.dwBufferLength = message.getRawDataSize();
  204591. h.dwBytesRecorded = message.getRawDataSize();
  204592. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  204593. {
  204594. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  204595. if (res == MMSYSERR_NOERROR)
  204596. {
  204597. while ((h.dwFlags & MHDR_DONE) == 0)
  204598. Sleep (1);
  204599. int count = 500; // 1 sec timeout
  204600. while (--count >= 0)
  204601. {
  204602. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  204603. if (res == MIDIERR_STILLPLAYING)
  204604. Sleep (2);
  204605. else
  204606. break;
  204607. }
  204608. }
  204609. }
  204610. }
  204611. else
  204612. {
  204613. midiOutShortMsg (handle->handle,
  204614. *(unsigned int*) message.getRawData());
  204615. }
  204616. }
  204617. END_JUCE_NAMESPACE
  204618. /********* End of inlined file: juce_win32_Midi.cpp *********/
  204619. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204620. #ifdef _MSC_VER
  204621. #pragma warning (disable: 4514)
  204622. #pragma warning (push)
  204623. #endif
  204624. #include <comutil.h>
  204625. #include <Exdisp.h>
  204626. #include <exdispid.h>
  204627. #ifdef _MSC_VER
  204628. #pragma warning (pop)
  204629. #pragma warning (disable: 4312 4244)
  204630. #endif
  204631. BEGIN_JUCE_NAMESPACE
  204632. class WebBrowserComponentInternal : public ActiveXControlComponent
  204633. {
  204634. public:
  204635. WebBrowserComponentInternal()
  204636. : browser (0),
  204637. connectionPoint (0),
  204638. adviseCookie (0)
  204639. {
  204640. }
  204641. ~WebBrowserComponentInternal()
  204642. {
  204643. if (connectionPoint != 0)
  204644. connectionPoint->Unadvise (adviseCookie);
  204645. if (browser != 0)
  204646. browser->Release();
  204647. }
  204648. void createBrowser()
  204649. {
  204650. createControl (&CLSID_WebBrowser);
  204651. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204652. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204653. if (connectionPointContainer != 0)
  204654. {
  204655. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204656. &connectionPoint);
  204657. if (connectionPoint != 0)
  204658. {
  204659. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204660. jassert (owner != 0);
  204661. EventHandler* handler = new EventHandler (owner);
  204662. connectionPoint->Advise (handler, &adviseCookie);
  204663. }
  204664. }
  204665. }
  204666. void goToURL (const String& url,
  204667. const StringArray* headers,
  204668. const MemoryBlock* postData)
  204669. {
  204670. if (browser != 0)
  204671. {
  204672. LPSAFEARRAY sa = 0;
  204673. _variant_t flags, frame, postDataVar, headersVar;
  204674. if (headers != 0)
  204675. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204676. if (postData != 0 && postData->getSize() > 0)
  204677. {
  204678. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204679. if (sa != 0)
  204680. {
  204681. void* data = 0;
  204682. SafeArrayAccessData (sa, &data);
  204683. jassert (data != 0);
  204684. if (data != 0)
  204685. {
  204686. postData->copyTo (data, 0, postData->getSize());
  204687. SafeArrayUnaccessData (sa);
  204688. VARIANT postDataVar2;
  204689. VariantInit (&postDataVar2);
  204690. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204691. V_ARRAY (&postDataVar2) = sa;
  204692. postDataVar = postDataVar2;
  204693. }
  204694. }
  204695. }
  204696. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204697. &flags, &frame,
  204698. &postDataVar, &headersVar);
  204699. if (sa != 0)
  204700. SafeArrayDestroy (sa);
  204701. }
  204702. }
  204703. IWebBrowser2* browser;
  204704. juce_UseDebuggingNewOperator
  204705. private:
  204706. IConnectionPoint* connectionPoint;
  204707. DWORD adviseCookie;
  204708. class EventHandler : public IDispatch
  204709. {
  204710. public:
  204711. EventHandler (WebBrowserComponent* owner_)
  204712. : owner (owner_),
  204713. refCount (0)
  204714. {
  204715. }
  204716. ~EventHandler()
  204717. {
  204718. }
  204719. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204720. {
  204721. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204722. {
  204723. AddRef();
  204724. *result = this;
  204725. return S_OK;
  204726. }
  204727. *result = 0;
  204728. return E_NOINTERFACE;
  204729. }
  204730. ULONG __stdcall AddRef() { return ++refCount; }
  204731. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204732. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204733. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204734. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204735. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204736. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204737. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204738. UINT __RPC_FAR* /*puArgErr*/)
  204739. {
  204740. switch (dispIdMember)
  204741. {
  204742. case DISPID_BEFORENAVIGATE2:
  204743. {
  204744. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204745. String url;
  204746. if ((vurl->vt & VT_BYREF) != 0)
  204747. url = *vurl->pbstrVal;
  204748. else
  204749. url = vurl->bstrVal;
  204750. *pDispParams->rgvarg->pboolVal
  204751. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204752. : VARIANT_TRUE;
  204753. return S_OK;
  204754. }
  204755. default:
  204756. break;
  204757. }
  204758. return E_NOTIMPL;
  204759. }
  204760. juce_UseDebuggingNewOperator
  204761. private:
  204762. WebBrowserComponent* const owner;
  204763. int refCount;
  204764. EventHandler (const EventHandler&);
  204765. const EventHandler& operator= (const EventHandler&);
  204766. };
  204767. };
  204768. WebBrowserComponent::WebBrowserComponent()
  204769. : browser (0),
  204770. blankPageShown (false)
  204771. {
  204772. setOpaque (true);
  204773. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204774. }
  204775. WebBrowserComponent::~WebBrowserComponent()
  204776. {
  204777. delete browser;
  204778. }
  204779. void WebBrowserComponent::goToURL (const String& url,
  204780. const StringArray* headers,
  204781. const MemoryBlock* postData)
  204782. {
  204783. lastURL = url;
  204784. lastHeaders.clear();
  204785. if (headers != 0)
  204786. lastHeaders = *headers;
  204787. lastPostData.setSize (0);
  204788. if (postData != 0)
  204789. lastPostData = *postData;
  204790. blankPageShown = false;
  204791. browser->goToURL (url, headers, postData);
  204792. }
  204793. void WebBrowserComponent::stop()
  204794. {
  204795. if (browser->browser != 0)
  204796. browser->browser->Stop();
  204797. }
  204798. void WebBrowserComponent::goBack()
  204799. {
  204800. lastURL = String::empty;
  204801. blankPageShown = false;
  204802. if (browser->browser != 0)
  204803. browser->browser->GoBack();
  204804. }
  204805. void WebBrowserComponent::goForward()
  204806. {
  204807. lastURL = String::empty;
  204808. if (browser->browser != 0)
  204809. browser->browser->GoForward();
  204810. }
  204811. void WebBrowserComponent::paint (Graphics& g)
  204812. {
  204813. if (browser->browser == 0)
  204814. g.fillAll (Colours::white);
  204815. }
  204816. void WebBrowserComponent::checkWindowAssociation()
  204817. {
  204818. if (isShowing())
  204819. {
  204820. if (blankPageShown)
  204821. goBack();
  204822. if (browser->browser == 0 && getPeer() != 0)
  204823. {
  204824. browser->createBrowser();
  204825. reloadLastURL();
  204826. }
  204827. }
  204828. else
  204829. {
  204830. if (browser != 0 && ! blankPageShown)
  204831. {
  204832. // when the component becomes invisible, some stuff like flash
  204833. // carries on playing audio, so we need to force it onto a blank
  204834. // page to avoid this..
  204835. blankPageShown = true;
  204836. browser->goToURL ("about:blank", 0, 0);
  204837. }
  204838. }
  204839. }
  204840. void WebBrowserComponent::reloadLastURL()
  204841. {
  204842. if (lastURL.isNotEmpty())
  204843. {
  204844. goToURL (lastURL, &lastHeaders, &lastPostData);
  204845. lastURL = String::empty;
  204846. }
  204847. }
  204848. void WebBrowserComponent::parentHierarchyChanged()
  204849. {
  204850. checkWindowAssociation();
  204851. }
  204852. void WebBrowserComponent::moved()
  204853. {
  204854. }
  204855. void WebBrowserComponent::resized()
  204856. {
  204857. browser->setSize (getWidth(), getHeight());
  204858. }
  204859. void WebBrowserComponent::visibilityChanged()
  204860. {
  204861. checkWindowAssociation();
  204862. }
  204863. bool WebBrowserComponent::pageAboutToLoad (const String&)
  204864. {
  204865. return true;
  204866. }
  204867. END_JUCE_NAMESPACE
  204868. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204869. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  204870. #ifdef _MSC_VER
  204871. #pragma warning (disable: 4514)
  204872. #pragma warning (push)
  204873. #endif
  204874. #include <float.h>
  204875. #include <windowsx.h>
  204876. #include <shlobj.h>
  204877. #if JUCE_OPENGL
  204878. #include <gl/gl.h>
  204879. #endif
  204880. #ifdef _MSC_VER
  204881. #pragma warning (pop)
  204882. #pragma warning (disable: 4312 4244)
  204883. #endif
  204884. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204885. // these are in the windows SDK, but need to be repeated here for GCC..
  204886. #ifndef GET_APPCOMMAND_LPARAM
  204887. #define FAPPCOMMAND_MASK 0xF000
  204888. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204889. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204890. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204891. #define APPCOMMAND_MEDIA_STOP 13
  204892. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204893. #define WM_APPCOMMAND 0x0319
  204894. #endif
  204895. BEGIN_JUCE_NAMESPACE
  204896. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  204897. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  204898. extern bool juce_IsRunningInWine() throw();
  204899. #ifndef ULW_ALPHA
  204900. #define ULW_ALPHA 0x00000002
  204901. #endif
  204902. #ifndef AC_SRC_ALPHA
  204903. #define AC_SRC_ALPHA 0x01
  204904. #endif
  204905. #define DEBUG_REPAINT_TIMES 0
  204906. static HPALETTE palette = 0;
  204907. static bool createPaletteIfNeeded = true;
  204908. static bool shouldDeactivateTitleBar = true;
  204909. static bool screenSaverAllowed = true;
  204910. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204911. #define WM_TRAYNOTIFY WM_USER + 100
  204912. using ::abs;
  204913. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204914. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204915. bool Desktop::canUseSemiTransparentWindows() throw()
  204916. {
  204917. if (updateLayeredWindow == 0)
  204918. {
  204919. if (! juce_IsRunningInWine())
  204920. {
  204921. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204922. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204923. }
  204924. }
  204925. return updateLayeredWindow != 0;
  204926. }
  204927. #undef DefWindowProc
  204928. #define DefWindowProc DefWindowProcW
  204929. const int extendedKeyModifier = 0x10000;
  204930. const int KeyPress::spaceKey = VK_SPACE;
  204931. const int KeyPress::returnKey = VK_RETURN;
  204932. const int KeyPress::escapeKey = VK_ESCAPE;
  204933. const int KeyPress::backspaceKey = VK_BACK;
  204934. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204935. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204936. const int KeyPress::tabKey = VK_TAB;
  204937. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204938. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204939. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204940. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204941. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204942. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204943. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204944. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204945. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204946. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204947. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204948. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204949. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204950. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204951. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204952. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204953. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204954. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204955. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204956. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204957. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204958. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204959. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204960. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204961. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204962. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204963. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204964. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204965. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204966. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204967. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204968. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204969. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204970. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204971. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204972. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204973. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204974. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204975. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204976. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204977. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204978. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204979. const int KeyPress::playKey = 0x30000;
  204980. const int KeyPress::stopKey = 0x30001;
  204981. const int KeyPress::fastForwardKey = 0x30002;
  204982. const int KeyPress::rewindKey = 0x30003;
  204983. class WindowsBitmapImage : public Image
  204984. {
  204985. public:
  204986. HBITMAP hBitmap;
  204987. BITMAPV4HEADER bitmapInfo;
  204988. HDC hdc;
  204989. unsigned char* bitmapData;
  204990. WindowsBitmapImage (const PixelFormat format_,
  204991. const int w, const int h, const bool clearImage)
  204992. : Image (format_, w, h)
  204993. {
  204994. jassert (format_ == RGB || format_ == ARGB);
  204995. pixelStride = (format_ == RGB) ? 3 : 4;
  204996. zerostruct (bitmapInfo);
  204997. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204998. bitmapInfo.bV4Width = w;
  204999. bitmapInfo.bV4Height = h;
  205000. bitmapInfo.bV4Planes = 1;
  205001. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  205002. if (format_ == ARGB)
  205003. {
  205004. bitmapInfo.bV4AlphaMask = 0xff000000;
  205005. bitmapInfo.bV4RedMask = 0xff0000;
  205006. bitmapInfo.bV4GreenMask = 0xff00;
  205007. bitmapInfo.bV4BlueMask = 0xff;
  205008. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  205009. }
  205010. else
  205011. {
  205012. bitmapInfo.bV4V4Compression = BI_RGB;
  205013. }
  205014. lineStride = -((w * pixelStride + 3) & ~3);
  205015. HDC dc = GetDC (0);
  205016. hdc = CreateCompatibleDC (dc);
  205017. ReleaseDC (0, dc);
  205018. SetMapMode (hdc, MM_TEXT);
  205019. hBitmap = CreateDIBSection (hdc,
  205020. (BITMAPINFO*) &(bitmapInfo),
  205021. DIB_RGB_COLORS,
  205022. (void**) &bitmapData,
  205023. 0, 0);
  205024. SelectObject (hdc, hBitmap);
  205025. if (format_ == ARGB && clearImage)
  205026. zeromem (bitmapData, abs (h * lineStride));
  205027. imageData = bitmapData - (lineStride * (h - 1));
  205028. }
  205029. ~WindowsBitmapImage()
  205030. {
  205031. DeleteDC (hdc);
  205032. DeleteObject (hBitmap);
  205033. imageData = 0; // to stop the base class freeing this
  205034. }
  205035. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205036. const int x, const int y,
  205037. const RectangleList& maskedRegion) throw()
  205038. {
  205039. static HDRAWDIB hdd = 0;
  205040. static bool needToCreateDrawDib = true;
  205041. if (needToCreateDrawDib)
  205042. {
  205043. needToCreateDrawDib = false;
  205044. HDC dc = GetDC (0);
  205045. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205046. ReleaseDC (0, dc);
  205047. // only open if we're not palettised
  205048. if (n > 8)
  205049. hdd = DrawDibOpen();
  205050. }
  205051. if (createPaletteIfNeeded)
  205052. {
  205053. HDC dc = GetDC (0);
  205054. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205055. ReleaseDC (0, dc);
  205056. if (n <= 8)
  205057. palette = CreateHalftonePalette (dc);
  205058. createPaletteIfNeeded = false;
  205059. }
  205060. if (palette != 0)
  205061. {
  205062. SelectPalette (dc, palette, FALSE);
  205063. RealizePalette (dc);
  205064. SetStretchBltMode (dc, HALFTONE);
  205065. }
  205066. SetMapMode (dc, MM_TEXT);
  205067. if (transparent)
  205068. {
  205069. POINT p, pos;
  205070. SIZE size;
  205071. RECT windowBounds;
  205072. GetWindowRect (hwnd, &windowBounds);
  205073. p.x = -x;
  205074. p.y = -y;
  205075. pos.x = windowBounds.left;
  205076. pos.y = windowBounds.top;
  205077. size.cx = windowBounds.right - windowBounds.left;
  205078. size.cy = windowBounds.bottom - windowBounds.top;
  205079. BLENDFUNCTION bf;
  205080. bf.AlphaFormat = AC_SRC_ALPHA;
  205081. bf.BlendFlags = 0;
  205082. bf.BlendOp = AC_SRC_OVER;
  205083. bf.SourceConstantAlpha = 0xff;
  205084. if (! maskedRegion.isEmpty())
  205085. {
  205086. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205087. {
  205088. const Rectangle& r = *i.getRectangle();
  205089. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205090. }
  205091. }
  205092. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205093. }
  205094. else
  205095. {
  205096. int savedDC = 0;
  205097. if (! maskedRegion.isEmpty())
  205098. {
  205099. savedDC = SaveDC (dc);
  205100. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205101. {
  205102. const Rectangle& r = *i.getRectangle();
  205103. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205104. }
  205105. }
  205106. const int w = getWidth();
  205107. const int h = getHeight();
  205108. if (hdd == 0)
  205109. {
  205110. StretchDIBits (dc,
  205111. x, y, w, h,
  205112. 0, 0, w, h,
  205113. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205114. DIB_RGB_COLORS, SRCCOPY);
  205115. }
  205116. else
  205117. {
  205118. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205119. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205120. 0, 0, w, h, 0);
  205121. }
  205122. if (! maskedRegion.isEmpty())
  205123. RestoreDC (dc, savedDC);
  205124. }
  205125. }
  205126. juce_UseDebuggingNewOperator
  205127. private:
  205128. WindowsBitmapImage (const WindowsBitmapImage&);
  205129. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205130. };
  205131. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205132. static int currentModifiers = 0;
  205133. static int modifiersAtLastCallback = 0;
  205134. static void updateKeyModifiers() throw()
  205135. {
  205136. currentModifiers &= ~(ModifierKeys::shiftModifier
  205137. | ModifierKeys::ctrlModifier
  205138. | ModifierKeys::altModifier);
  205139. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  205140. currentModifiers |= ModifierKeys::shiftModifier;
  205141. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  205142. currentModifiers |= ModifierKeys::ctrlModifier;
  205143. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  205144. currentModifiers |= ModifierKeys::altModifier;
  205145. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  205146. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205147. }
  205148. void ModifierKeys::updateCurrentModifiers() throw()
  205149. {
  205150. currentModifierFlags = currentModifiers;
  205151. }
  205152. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  205153. {
  205154. SHORT k = (SHORT) keyCode;
  205155. if ((keyCode & extendedKeyModifier) == 0
  205156. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  205157. k += (SHORT) T('A') - (SHORT) T('a');
  205158. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205159. (SHORT) '+', VK_OEM_PLUS,
  205160. (SHORT) '-', VK_OEM_MINUS,
  205161. (SHORT) '.', VK_OEM_PERIOD,
  205162. (SHORT) ';', VK_OEM_1,
  205163. (SHORT) ':', VK_OEM_1,
  205164. (SHORT) '/', VK_OEM_2,
  205165. (SHORT) '?', VK_OEM_2,
  205166. (SHORT) '[', VK_OEM_4,
  205167. (SHORT) ']', VK_OEM_6 };
  205168. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205169. if (k == translatedValues [i])
  205170. k = translatedValues [i + 1];
  205171. return (GetKeyState (k) & 0x8000) != 0;
  205172. }
  205173. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205174. {
  205175. updateKeyModifiers();
  205176. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205177. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  205178. currentModifiers |= ModifierKeys::leftButtonModifier;
  205179. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  205180. currentModifiers |= ModifierKeys::rightButtonModifier;
  205181. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  205182. currentModifiers |= ModifierKeys::middleButtonModifier;
  205183. return ModifierKeys (currentModifiers);
  205184. }
  205185. static int64 getMouseEventTime() throw()
  205186. {
  205187. static int64 eventTimeOffset = 0;
  205188. static DWORD lastMessageTime = 0;
  205189. const DWORD thisMessageTime = GetMessageTime();
  205190. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205191. {
  205192. lastMessageTime = thisMessageTime;
  205193. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205194. }
  205195. return eventTimeOffset + thisMessageTime;
  205196. }
  205197. class Win32ComponentPeer : public ComponentPeer
  205198. {
  205199. public:
  205200. Win32ComponentPeer (Component* const component,
  205201. const int windowStyleFlags)
  205202. : ComponentPeer (component, windowStyleFlags),
  205203. dontRepaint (false),
  205204. fullScreen (false),
  205205. isDragging (false),
  205206. isMouseOver (false),
  205207. currentWindowIcon (0),
  205208. taskBarIcon (0),
  205209. dropTarget (0)
  205210. {
  205211. MessageManager::getInstance()
  205212. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  205213. setTitle (component->getName());
  205214. if ((windowStyleFlags & windowHasDropShadow) != 0
  205215. && Desktop::canUseSemiTransparentWindows())
  205216. {
  205217. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205218. if (shadower != 0)
  205219. shadower->setOwner (component);
  205220. }
  205221. else
  205222. {
  205223. shadower = 0;
  205224. }
  205225. }
  205226. ~Win32ComponentPeer()
  205227. {
  205228. setTaskBarIcon (0);
  205229. deleteAndZero (shadower);
  205230. // do this before the next bit to avoid messages arriving for this window
  205231. // before it's destroyed
  205232. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205233. MessageManager::getInstance()
  205234. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  205235. if (currentWindowIcon != 0)
  205236. DestroyIcon (currentWindowIcon);
  205237. if (dropTarget != 0)
  205238. {
  205239. dropTarget->Release();
  205240. dropTarget = 0;
  205241. }
  205242. }
  205243. void* getNativeHandle() const
  205244. {
  205245. return (void*) hwnd;
  205246. }
  205247. void setVisible (bool shouldBeVisible)
  205248. {
  205249. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205250. if (shouldBeVisible)
  205251. InvalidateRect (hwnd, 0, 0);
  205252. else
  205253. lastPaintTime = 0;
  205254. }
  205255. void setTitle (const String& title)
  205256. {
  205257. SetWindowText (hwnd, title);
  205258. }
  205259. void setPosition (int x, int y)
  205260. {
  205261. offsetWithinParent (x, y);
  205262. SetWindowPos (hwnd, 0,
  205263. x - windowBorder.getLeft(),
  205264. y - windowBorder.getTop(),
  205265. 0, 0,
  205266. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205267. }
  205268. void repaintNowIfTransparent()
  205269. {
  205270. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205271. handlePaintMessage();
  205272. }
  205273. void updateBorderSize()
  205274. {
  205275. WINDOWINFO info;
  205276. info.cbSize = sizeof (info);
  205277. if (GetWindowInfo (hwnd, &info))
  205278. {
  205279. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205280. info.rcClient.left - info.rcWindow.left,
  205281. info.rcWindow.bottom - info.rcClient.bottom,
  205282. info.rcWindow.right - info.rcClient.right);
  205283. }
  205284. }
  205285. void setSize (int w, int h)
  205286. {
  205287. SetWindowPos (hwnd, 0, 0, 0,
  205288. w + windowBorder.getLeftAndRight(),
  205289. h + windowBorder.getTopAndBottom(),
  205290. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205291. updateBorderSize();
  205292. repaintNowIfTransparent();
  205293. }
  205294. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  205295. {
  205296. fullScreen = isNowFullScreen;
  205297. offsetWithinParent (x, y);
  205298. SetWindowPos (hwnd, 0,
  205299. x - windowBorder.getLeft(),
  205300. y - windowBorder.getTop(),
  205301. w + windowBorder.getLeftAndRight(),
  205302. h + windowBorder.getTopAndBottom(),
  205303. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205304. updateBorderSize();
  205305. repaintNowIfTransparent();
  205306. }
  205307. void getBounds (int& x, int& y, int& w, int& h) const
  205308. {
  205309. RECT r;
  205310. GetWindowRect (hwnd, &r);
  205311. x = r.left;
  205312. y = r.top;
  205313. w = r.right - x;
  205314. h = r.bottom - y;
  205315. HWND parentH = GetParent (hwnd);
  205316. if (parentH != 0)
  205317. {
  205318. GetWindowRect (parentH, &r);
  205319. x -= r.left;
  205320. y -= r.top;
  205321. }
  205322. x += windowBorder.getLeft();
  205323. y += windowBorder.getTop();
  205324. w -= windowBorder.getLeftAndRight();
  205325. h -= windowBorder.getTopAndBottom();
  205326. }
  205327. int getScreenX() const
  205328. {
  205329. RECT r;
  205330. GetWindowRect (hwnd, &r);
  205331. return r.left + windowBorder.getLeft();
  205332. }
  205333. int getScreenY() const
  205334. {
  205335. RECT r;
  205336. GetWindowRect (hwnd, &r);
  205337. return r.top + windowBorder.getTop();
  205338. }
  205339. void relativePositionToGlobal (int& x, int& y)
  205340. {
  205341. RECT r;
  205342. GetWindowRect (hwnd, &r);
  205343. x += r.left + windowBorder.getLeft();
  205344. y += r.top + windowBorder.getTop();
  205345. }
  205346. void globalPositionToRelative (int& x, int& y)
  205347. {
  205348. RECT r;
  205349. GetWindowRect (hwnd, &r);
  205350. x -= r.left + windowBorder.getLeft();
  205351. y -= r.top + windowBorder.getTop();
  205352. }
  205353. void setMinimised (bool shouldBeMinimised)
  205354. {
  205355. if (shouldBeMinimised != isMinimised())
  205356. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205357. }
  205358. bool isMinimised() const
  205359. {
  205360. WINDOWPLACEMENT wp;
  205361. wp.length = sizeof (WINDOWPLACEMENT);
  205362. GetWindowPlacement (hwnd, &wp);
  205363. return wp.showCmd == SW_SHOWMINIMIZED;
  205364. }
  205365. void setFullScreen (bool shouldBeFullScreen)
  205366. {
  205367. setMinimised (false);
  205368. if (fullScreen != shouldBeFullScreen)
  205369. {
  205370. fullScreen = shouldBeFullScreen;
  205371. const ComponentDeletionWatcher deletionChecker (component);
  205372. if (! fullScreen)
  205373. {
  205374. const Rectangle boundsCopy (lastNonFullscreenBounds);
  205375. if (hasTitleBar())
  205376. ShowWindow (hwnd, SW_SHOWNORMAL);
  205377. if (! boundsCopy.isEmpty())
  205378. {
  205379. setBounds (boundsCopy.getX(),
  205380. boundsCopy.getY(),
  205381. boundsCopy.getWidth(),
  205382. boundsCopy.getHeight(),
  205383. false);
  205384. }
  205385. }
  205386. else
  205387. {
  205388. if (hasTitleBar())
  205389. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205390. else
  205391. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205392. }
  205393. if (! deletionChecker.hasBeenDeleted())
  205394. handleMovedOrResized();
  205395. }
  205396. }
  205397. bool isFullScreen() const
  205398. {
  205399. if (! hasTitleBar())
  205400. return fullScreen;
  205401. WINDOWPLACEMENT wp;
  205402. wp.length = sizeof (wp);
  205403. GetWindowPlacement (hwnd, &wp);
  205404. return wp.showCmd == SW_SHOWMAXIMIZED;
  205405. }
  205406. bool contains (int x, int y, bool trueIfInAChildWindow) const
  205407. {
  205408. RECT r;
  205409. GetWindowRect (hwnd, &r);
  205410. POINT p;
  205411. p.x = x + r.left + windowBorder.getLeft();
  205412. p.y = y + r.top + windowBorder.getTop();
  205413. HWND w = WindowFromPoint (p);
  205414. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205415. }
  205416. const BorderSize getFrameSize() const
  205417. {
  205418. return windowBorder;
  205419. }
  205420. bool setAlwaysOnTop (bool alwaysOnTop)
  205421. {
  205422. const bool oldDeactivate = shouldDeactivateTitleBar;
  205423. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205424. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205425. 0, 0, 0, 0,
  205426. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205427. shouldDeactivateTitleBar = oldDeactivate;
  205428. if (shadower != 0)
  205429. shadower->componentBroughtToFront (*component);
  205430. return true;
  205431. }
  205432. void toFront (bool makeActive)
  205433. {
  205434. setMinimised (false);
  205435. const bool oldDeactivate = shouldDeactivateTitleBar;
  205436. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205437. MessageManager::getInstance()
  205438. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  205439. : &toFrontCallback2,
  205440. (void*) hwnd);
  205441. shouldDeactivateTitleBar = oldDeactivate;
  205442. if (! makeActive)
  205443. {
  205444. // in this case a broughttofront call won't have occured, so do it now..
  205445. handleBroughtToFront();
  205446. }
  205447. }
  205448. void toBehind (ComponentPeer* other)
  205449. {
  205450. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205451. jassert (otherPeer != 0); // wrong type of window?
  205452. if (otherPeer != 0)
  205453. {
  205454. setMinimised (false);
  205455. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205456. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205457. }
  205458. }
  205459. bool isFocused() const
  205460. {
  205461. return MessageManager::getInstance()
  205462. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  205463. }
  205464. void grabFocus()
  205465. {
  205466. const bool oldDeactivate = shouldDeactivateTitleBar;
  205467. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205468. MessageManager::getInstance()
  205469. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  205470. shouldDeactivateTitleBar = oldDeactivate;
  205471. }
  205472. void repaint (int x, int y, int w, int h)
  205473. {
  205474. const RECT r = { x, y, x + w, y + h };
  205475. InvalidateRect (hwnd, &r, FALSE);
  205476. }
  205477. void performAnyPendingRepaintsNow()
  205478. {
  205479. MSG m;
  205480. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205481. DispatchMessage (&m);
  205482. }
  205483. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205484. {
  205485. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205486. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  205487. return 0;
  205488. }
  205489. void setTaskBarIcon (const Image* const image)
  205490. {
  205491. if (image != 0)
  205492. {
  205493. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  205494. if (taskBarIcon == 0)
  205495. {
  205496. taskBarIcon = new NOTIFYICONDATA();
  205497. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205498. taskBarIcon->hWnd = (HWND) hwnd;
  205499. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205500. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205501. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205502. taskBarIcon->hIcon = hicon;
  205503. taskBarIcon->szTip[0] = 0;
  205504. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205505. }
  205506. else
  205507. {
  205508. HICON oldIcon = taskBarIcon->hIcon;
  205509. taskBarIcon->hIcon = hicon;
  205510. taskBarIcon->uFlags = NIF_ICON;
  205511. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205512. DestroyIcon (oldIcon);
  205513. }
  205514. DestroyIcon (hicon);
  205515. }
  205516. else if (taskBarIcon != 0)
  205517. {
  205518. taskBarIcon->uFlags = 0;
  205519. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205520. DestroyIcon (taskBarIcon->hIcon);
  205521. deleteAndZero (taskBarIcon);
  205522. }
  205523. }
  205524. void setTaskBarIconToolTip (const String& toolTip) const
  205525. {
  205526. if (taskBarIcon != 0)
  205527. {
  205528. taskBarIcon->uFlags = NIF_TIP;
  205529. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205530. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205531. }
  205532. }
  205533. juce_UseDebuggingNewOperator
  205534. bool dontRepaint;
  205535. private:
  205536. HWND hwnd;
  205537. DropShadower* shadower;
  205538. bool fullScreen, isDragging, isMouseOver;
  205539. BorderSize windowBorder;
  205540. HICON currentWindowIcon;
  205541. NOTIFYICONDATA* taskBarIcon;
  205542. IDropTarget* dropTarget;
  205543. class TemporaryImage : public Timer
  205544. {
  205545. public:
  205546. TemporaryImage()
  205547. : image (0)
  205548. {
  205549. }
  205550. ~TemporaryImage()
  205551. {
  205552. delete image;
  205553. }
  205554. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  205555. {
  205556. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205557. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  205558. {
  205559. delete image;
  205560. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  205561. }
  205562. startTimer (3000);
  205563. return image;
  205564. }
  205565. void timerCallback()
  205566. {
  205567. stopTimer();
  205568. deleteAndZero (image);
  205569. }
  205570. private:
  205571. WindowsBitmapImage* image;
  205572. TemporaryImage (const TemporaryImage&);
  205573. const TemporaryImage& operator= (const TemporaryImage&);
  205574. };
  205575. TemporaryImage offscreenImageGenerator;
  205576. class WindowClassHolder : public DeletedAtShutdown
  205577. {
  205578. public:
  205579. WindowClassHolder()
  205580. : windowClassName ("JUCE_")
  205581. {
  205582. // this name has to be different for each app/dll instance because otherwise
  205583. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205584. // window class).
  205585. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205586. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205587. TCHAR moduleFile [1024];
  205588. moduleFile[0] = 0;
  205589. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205590. WORD iconNum = 0;
  205591. WNDCLASSEX wcex;
  205592. wcex.cbSize = sizeof (wcex);
  205593. wcex.style = CS_OWNDC;
  205594. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205595. wcex.lpszClassName = windowClassName;
  205596. wcex.cbClsExtra = 0;
  205597. wcex.cbWndExtra = 32;
  205598. wcex.hInstance = moduleHandle;
  205599. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205600. iconNum = 1;
  205601. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205602. wcex.hCursor = 0;
  205603. wcex.hbrBackground = 0;
  205604. wcex.lpszMenuName = 0;
  205605. RegisterClassEx (&wcex);
  205606. }
  205607. ~WindowClassHolder()
  205608. {
  205609. if (ComponentPeer::getNumPeers() == 0)
  205610. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205611. clearSingletonInstance();
  205612. }
  205613. String windowClassName;
  205614. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205615. };
  205616. static void* createWindowCallback (void* userData)
  205617. {
  205618. ((Win32ComponentPeer*) userData)->createWindow();
  205619. return 0;
  205620. }
  205621. void createWindow()
  205622. {
  205623. DWORD exstyle = WS_EX_ACCEPTFILES;
  205624. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205625. if (hasTitleBar())
  205626. {
  205627. type |= WS_OVERLAPPED;
  205628. exstyle |= WS_EX_APPWINDOW;
  205629. if ((styleFlags & windowHasCloseButton) != 0)
  205630. {
  205631. type |= WS_SYSMENU;
  205632. }
  205633. else
  205634. {
  205635. // annoyingly, windows won't let you have a min/max button without a close button
  205636. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205637. }
  205638. if ((styleFlags & windowIsResizable) != 0)
  205639. type |= WS_THICKFRAME;
  205640. }
  205641. else
  205642. {
  205643. type |= WS_POPUP | WS_SYSMENU;
  205644. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205645. exstyle |= WS_EX_TOOLWINDOW;
  205646. else
  205647. exstyle |= WS_EX_APPWINDOW;
  205648. }
  205649. if ((styleFlags & windowHasMinimiseButton) != 0)
  205650. type |= WS_MINIMIZEBOX;
  205651. if ((styleFlags & windowHasMaximiseButton) != 0)
  205652. type |= WS_MAXIMIZEBOX;
  205653. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205654. exstyle |= WS_EX_TRANSPARENT;
  205655. if ((styleFlags & windowIsSemiTransparent) != 0
  205656. && Desktop::canUseSemiTransparentWindows())
  205657. exstyle |= WS_EX_LAYERED;
  205658. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205659. if (hwnd != 0)
  205660. {
  205661. SetWindowLongPtr (hwnd, 0, 0);
  205662. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205663. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205664. if (dropTarget == 0)
  205665. dropTarget = new JuceDropTarget (this);
  205666. RegisterDragDrop (hwnd, dropTarget);
  205667. updateBorderSize();
  205668. // Calling this function here is (for some reason) necessary to make Windows
  205669. // correctly enable the menu items that we specify in the wm_initmenu message.
  205670. GetSystemMenu (hwnd, false);
  205671. }
  205672. else
  205673. {
  205674. jassertfalse
  205675. }
  205676. }
  205677. static void* destroyWindowCallback (void* handle)
  205678. {
  205679. RevokeDragDrop ((HWND) handle);
  205680. DestroyWindow ((HWND) handle);
  205681. return 0;
  205682. }
  205683. static void* toFrontCallback1 (void* h)
  205684. {
  205685. SetForegroundWindow ((HWND) h);
  205686. return 0;
  205687. }
  205688. static void* toFrontCallback2 (void* h)
  205689. {
  205690. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205691. return 0;
  205692. }
  205693. static void* setFocusCallback (void* h)
  205694. {
  205695. SetFocus ((HWND) h);
  205696. return 0;
  205697. }
  205698. static void* getFocusCallback (void*)
  205699. {
  205700. return (void*) GetFocus();
  205701. }
  205702. void offsetWithinParent (int& x, int& y) const
  205703. {
  205704. if (isTransparent())
  205705. {
  205706. HWND parentHwnd = GetParent (hwnd);
  205707. if (parentHwnd != 0)
  205708. {
  205709. RECT parentRect;
  205710. GetWindowRect (parentHwnd, &parentRect);
  205711. x += parentRect.left;
  205712. y += parentRect.top;
  205713. }
  205714. }
  205715. }
  205716. bool isTransparent() const
  205717. {
  205718. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205719. }
  205720. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205721. void setIcon (const Image& newIcon)
  205722. {
  205723. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205724. if (hicon != 0)
  205725. {
  205726. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205727. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205728. if (currentWindowIcon != 0)
  205729. DestroyIcon (currentWindowIcon);
  205730. currentWindowIcon = hicon;
  205731. }
  205732. }
  205733. void handlePaintMessage()
  205734. {
  205735. #if DEBUG_REPAINT_TIMES
  205736. const double paintStart = Time::getMillisecondCounterHiRes();
  205737. #endif
  205738. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205739. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205740. PAINTSTRUCT paintStruct;
  205741. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205742. // message and become re-entrant, but that's OK
  205743. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205744. // corrupt the image it's using to paint into, so do a check here.
  205745. static bool reentrant = false;
  205746. if (reentrant)
  205747. {
  205748. DeleteObject (rgn);
  205749. EndPaint (hwnd, &paintStruct);
  205750. return;
  205751. }
  205752. reentrant = true;
  205753. // this is the rectangle to update..
  205754. int x = paintStruct.rcPaint.left;
  205755. int y = paintStruct.rcPaint.top;
  205756. int w = paintStruct.rcPaint.right - x;
  205757. int h = paintStruct.rcPaint.bottom - y;
  205758. const bool transparent = isTransparent();
  205759. if (transparent)
  205760. {
  205761. // it's not possible to have a transparent window with a title bar at the moment!
  205762. jassert (! hasTitleBar());
  205763. RECT r;
  205764. GetWindowRect (hwnd, &r);
  205765. x = y = 0;
  205766. w = r.right - r.left;
  205767. h = r.bottom - r.top;
  205768. }
  205769. if (w > 0 && h > 0)
  205770. {
  205771. clearMaskedRegion();
  205772. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  205773. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  205774. RectangleList* const contextClip = context.getRawClipRegion();
  205775. contextClip->clear();
  205776. context.setOrigin (-x, -y);
  205777. bool needToPaintAll = true;
  205778. if (regionType == COMPLEXREGION && ! transparent)
  205779. {
  205780. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205781. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205782. DeleteObject (clipRgn);
  205783. char rgnData [8192];
  205784. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205785. if (res > 0 && res <= sizeof (rgnData))
  205786. {
  205787. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205788. if (hdr->iType == RDH_RECTANGLES
  205789. && hdr->rcBound.right - hdr->rcBound.left >= w
  205790. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205791. {
  205792. needToPaintAll = false;
  205793. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205794. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205795. while (--num >= 0)
  205796. {
  205797. // (need to move this one pixel to the left because of a win32 bug)
  205798. const int cx = jmax (x, rects->left - 1);
  205799. const int cy = rects->top;
  205800. const int cw = rects->right - cx;
  205801. const int ch = rects->bottom - rects->top;
  205802. if (cx + cw - x <= w && cy + ch - y <= h)
  205803. {
  205804. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  205805. }
  205806. else
  205807. {
  205808. needToPaintAll = true;
  205809. break;
  205810. }
  205811. ++rects;
  205812. }
  205813. }
  205814. }
  205815. }
  205816. if (needToPaintAll)
  205817. {
  205818. contextClip->clear();
  205819. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  205820. }
  205821. if (transparent)
  205822. {
  205823. RectangleList::Iterator i (*contextClip);
  205824. while (i.next())
  205825. {
  205826. const Rectangle& r = *i.getRectangle();
  205827. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  205828. }
  205829. }
  205830. // if the component's not opaque, this won't draw properly unless the platform can support this
  205831. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205832. updateCurrentModifiers();
  205833. handlePaint (context);
  205834. if (! dontRepaint)
  205835. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205836. }
  205837. DeleteObject (rgn);
  205838. EndPaint (hwnd, &paintStruct);
  205839. reentrant = false;
  205840. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205841. _fpreset(); // because some graphics cards can unmask FP exceptions
  205842. #endif
  205843. lastPaintTime = Time::getMillisecondCounter();
  205844. #if DEBUG_REPAINT_TIMES
  205845. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  205846. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  205847. #endif
  205848. }
  205849. void doMouseMove (const int x, const int y)
  205850. {
  205851. static uint32 lastMouseTime = 0;
  205852. // this can be set to throttle the mouse-messages to less than a
  205853. // certain number per second, as things can get unresponsive
  205854. // if each drag or move callback has to do a lot of work.
  205855. const int maxMouseMovesPerSecond = 60;
  205856. const int64 mouseEventTime = getMouseEventTime();
  205857. if (! isMouseOver)
  205858. {
  205859. isMouseOver = true;
  205860. TRACKMOUSEEVENT tme;
  205861. tme.cbSize = sizeof (tme);
  205862. tme.dwFlags = TME_LEAVE;
  205863. tme.hwndTrack = hwnd;
  205864. tme.dwHoverTime = 0;
  205865. if (! TrackMouseEvent (&tme))
  205866. {
  205867. jassertfalse;
  205868. }
  205869. updateKeyModifiers();
  205870. handleMouseEnter (x, y, mouseEventTime);
  205871. }
  205872. else if (! isDragging)
  205873. {
  205874. if (((unsigned int) x) < (unsigned int) component->getWidth()
  205875. && ((unsigned int) y) < (unsigned int) component->getHeight())
  205876. {
  205877. RECT r;
  205878. GetWindowRect (hwnd, &r);
  205879. POINT p;
  205880. p.x = x + r.left + windowBorder.getLeft();
  205881. p.y = y + r.top + windowBorder.getTop();
  205882. if (WindowFromPoint (p) == hwnd)
  205883. {
  205884. const uint32 now = Time::getMillisecondCounter();
  205885. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205886. {
  205887. lastMouseTime = now;
  205888. handleMouseMove (x, y, mouseEventTime);
  205889. }
  205890. }
  205891. }
  205892. }
  205893. else
  205894. {
  205895. const uint32 now = Time::getMillisecondCounter();
  205896. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205897. {
  205898. lastMouseTime = now;
  205899. handleMouseDrag (x, y, mouseEventTime);
  205900. }
  205901. }
  205902. }
  205903. void doMouseDown (const int x, const int y, const WPARAM wParam)
  205904. {
  205905. if (GetCapture() != hwnd)
  205906. SetCapture (hwnd);
  205907. doMouseMove (x, y);
  205908. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205909. if ((wParam & MK_LBUTTON) != 0)
  205910. currentModifiers |= ModifierKeys::leftButtonModifier;
  205911. if ((wParam & MK_RBUTTON) != 0)
  205912. currentModifiers |= ModifierKeys::rightButtonModifier;
  205913. if ((wParam & MK_MBUTTON) != 0)
  205914. currentModifiers |= ModifierKeys::middleButtonModifier;
  205915. updateKeyModifiers();
  205916. isDragging = true;
  205917. handleMouseDown (x, y, getMouseEventTime());
  205918. }
  205919. void doMouseUp (const int x, const int y, const WPARAM wParam)
  205920. {
  205921. int numButtons = 0;
  205922. if ((wParam & MK_LBUTTON) != 0)
  205923. ++numButtons;
  205924. if ((wParam & MK_RBUTTON) != 0)
  205925. ++numButtons;
  205926. if ((wParam & MK_MBUTTON) != 0)
  205927. ++numButtons;
  205928. const int oldModifiers = currentModifiers;
  205929. // update the currentmodifiers only after the callback, so the callback
  205930. // knows which button was released.
  205931. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205932. if ((wParam & MK_LBUTTON) != 0)
  205933. currentModifiers |= ModifierKeys::leftButtonModifier;
  205934. if ((wParam & MK_RBUTTON) != 0)
  205935. currentModifiers |= ModifierKeys::rightButtonModifier;
  205936. if ((wParam & MK_MBUTTON) != 0)
  205937. currentModifiers |= ModifierKeys::middleButtonModifier;
  205938. updateKeyModifiers();
  205939. isDragging = false;
  205940. // release the mouse capture if the user's not still got a button down
  205941. if (numButtons == 0 && hwnd == GetCapture())
  205942. ReleaseCapture();
  205943. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  205944. }
  205945. void doCaptureChanged()
  205946. {
  205947. if (isDragging)
  205948. {
  205949. RECT wr;
  205950. GetWindowRect (hwnd, &wr);
  205951. const DWORD mp = GetMessagePos();
  205952. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205953. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  205954. getMouseEventTime());
  205955. }
  205956. }
  205957. void doMouseExit()
  205958. {
  205959. if (isMouseOver)
  205960. {
  205961. isMouseOver = false;
  205962. RECT wr;
  205963. GetWindowRect (hwnd, &wr);
  205964. const DWORD mp = GetMessagePos();
  205965. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205966. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  205967. getMouseEventTime());
  205968. }
  205969. }
  205970. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  205971. {
  205972. updateKeyModifiers();
  205973. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  205974. handleMouseWheel (isVertical ? 0 : amount,
  205975. isVertical ? amount : 0,
  205976. getMouseEventTime());
  205977. }
  205978. void sendModifierKeyChangeIfNeeded()
  205979. {
  205980. if (modifiersAtLastCallback != currentModifiers)
  205981. {
  205982. modifiersAtLastCallback = currentModifiers;
  205983. handleModifierKeysChange();
  205984. }
  205985. }
  205986. bool doKeyUp (const WPARAM key)
  205987. {
  205988. updateKeyModifiers();
  205989. switch (key)
  205990. {
  205991. case VK_SHIFT:
  205992. case VK_CONTROL:
  205993. case VK_MENU:
  205994. case VK_CAPITAL:
  205995. case VK_LWIN:
  205996. case VK_RWIN:
  205997. case VK_APPS:
  205998. case VK_NUMLOCK:
  205999. case VK_SCROLL:
  206000. case VK_LSHIFT:
  206001. case VK_RSHIFT:
  206002. case VK_LCONTROL:
  206003. case VK_LMENU:
  206004. case VK_RCONTROL:
  206005. case VK_RMENU:
  206006. sendModifierKeyChangeIfNeeded();
  206007. }
  206008. return handleKeyUpOrDown();
  206009. }
  206010. bool doKeyDown (const WPARAM key)
  206011. {
  206012. updateKeyModifiers();
  206013. bool used = false;
  206014. switch (key)
  206015. {
  206016. case VK_SHIFT:
  206017. case VK_LSHIFT:
  206018. case VK_RSHIFT:
  206019. case VK_CONTROL:
  206020. case VK_LCONTROL:
  206021. case VK_RCONTROL:
  206022. case VK_MENU:
  206023. case VK_LMENU:
  206024. case VK_RMENU:
  206025. case VK_LWIN:
  206026. case VK_RWIN:
  206027. case VK_CAPITAL:
  206028. case VK_NUMLOCK:
  206029. case VK_SCROLL:
  206030. case VK_APPS:
  206031. sendModifierKeyChangeIfNeeded();
  206032. break;
  206033. case VK_LEFT:
  206034. case VK_RIGHT:
  206035. case VK_UP:
  206036. case VK_DOWN:
  206037. case VK_PRIOR:
  206038. case VK_NEXT:
  206039. case VK_HOME:
  206040. case VK_END:
  206041. case VK_DELETE:
  206042. case VK_INSERT:
  206043. case VK_F1:
  206044. case VK_F2:
  206045. case VK_F3:
  206046. case VK_F4:
  206047. case VK_F5:
  206048. case VK_F6:
  206049. case VK_F7:
  206050. case VK_F8:
  206051. case VK_F9:
  206052. case VK_F10:
  206053. case VK_F11:
  206054. case VK_F12:
  206055. case VK_F13:
  206056. case VK_F14:
  206057. case VK_F15:
  206058. case VK_F16:
  206059. used = handleKeyUpOrDown();
  206060. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  206061. break;
  206062. case VK_ADD:
  206063. case VK_SUBTRACT:
  206064. case VK_MULTIPLY:
  206065. case VK_DIVIDE:
  206066. case VK_SEPARATOR:
  206067. case VK_DECIMAL:
  206068. used = handleKeyUpOrDown();
  206069. break;
  206070. default:
  206071. used = handleKeyUpOrDown();
  206072. {
  206073. MSG msg;
  206074. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  206075. {
  206076. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  206077. // manually generate the key-press event that matches this key-down.
  206078. const UINT keyChar = MapVirtualKey (key, 2);
  206079. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  206080. }
  206081. }
  206082. break;
  206083. }
  206084. return used;
  206085. }
  206086. bool doKeyChar (int key, const LPARAM flags)
  206087. {
  206088. updateKeyModifiers();
  206089. juce_wchar textChar = (juce_wchar) key;
  206090. const int virtualScanCode = (flags >> 16) & 0xff;
  206091. if (key >= '0' && key <= '9')
  206092. {
  206093. switch (virtualScanCode) // check for a numeric keypad scan-code
  206094. {
  206095. case 0x52:
  206096. case 0x4f:
  206097. case 0x50:
  206098. case 0x51:
  206099. case 0x4b:
  206100. case 0x4c:
  206101. case 0x4d:
  206102. case 0x47:
  206103. case 0x48:
  206104. case 0x49:
  206105. key = (key - '0') + KeyPress::numberPad0;
  206106. break;
  206107. default:
  206108. break;
  206109. }
  206110. }
  206111. else
  206112. {
  206113. // convert the scan code to an unmodified character code..
  206114. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  206115. UINT keyChar = MapVirtualKey (virtualKey, 2);
  206116. keyChar = LOWORD (keyChar);
  206117. if (keyChar != 0)
  206118. key = (int) keyChar;
  206119. // avoid sending junk text characters for some control-key combinations
  206120. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  206121. textChar = 0;
  206122. }
  206123. return handleKeyPress (key, textChar);
  206124. }
  206125. bool doAppCommand (const LPARAM lParam)
  206126. {
  206127. int key = 0;
  206128. switch (GET_APPCOMMAND_LPARAM (lParam))
  206129. {
  206130. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206131. key = KeyPress::playKey;
  206132. break;
  206133. case APPCOMMAND_MEDIA_STOP:
  206134. key = KeyPress::stopKey;
  206135. break;
  206136. case APPCOMMAND_MEDIA_NEXTTRACK:
  206137. key = KeyPress::fastForwardKey;
  206138. break;
  206139. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206140. key = KeyPress::rewindKey;
  206141. break;
  206142. }
  206143. if (key != 0)
  206144. {
  206145. updateKeyModifiers();
  206146. if (hwnd == GetActiveWindow())
  206147. {
  206148. handleKeyPress (key, 0);
  206149. return true;
  206150. }
  206151. }
  206152. return false;
  206153. }
  206154. class JuceDropTarget : public IDropTarget
  206155. {
  206156. public:
  206157. JuceDropTarget (Win32ComponentPeer* const owner_)
  206158. : owner (owner_),
  206159. refCount (1)
  206160. {
  206161. }
  206162. virtual ~JuceDropTarget()
  206163. {
  206164. jassert (refCount == 0);
  206165. }
  206166. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206167. {
  206168. if (id == IID_IUnknown || id == IID_IDropTarget)
  206169. {
  206170. AddRef();
  206171. *result = this;
  206172. return S_OK;
  206173. }
  206174. *result = 0;
  206175. return E_NOINTERFACE;
  206176. }
  206177. ULONG __stdcall AddRef() { return ++refCount; }
  206178. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206179. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206180. {
  206181. updateFileList (pDataObject);
  206182. int x = mousePos.x, y = mousePos.y;
  206183. owner->globalPositionToRelative (x, y);
  206184. owner->handleFileDragMove (files, x, y);
  206185. *pdwEffect = DROPEFFECT_COPY;
  206186. return S_OK;
  206187. }
  206188. HRESULT __stdcall DragLeave()
  206189. {
  206190. owner->handleFileDragExit (files);
  206191. return S_OK;
  206192. }
  206193. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206194. {
  206195. int x = mousePos.x, y = mousePos.y;
  206196. owner->globalPositionToRelative (x, y);
  206197. owner->handleFileDragMove (files, x, y);
  206198. *pdwEffect = DROPEFFECT_COPY;
  206199. return S_OK;
  206200. }
  206201. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206202. {
  206203. updateFileList (pDataObject);
  206204. int x = mousePos.x, y = mousePos.y;
  206205. owner->globalPositionToRelative (x, y);
  206206. owner->handleFileDragDrop (files, x, y);
  206207. *pdwEffect = DROPEFFECT_COPY;
  206208. return S_OK;
  206209. }
  206210. private:
  206211. Win32ComponentPeer* const owner;
  206212. int refCount;
  206213. StringArray files;
  206214. void updateFileList (IDataObject* const pDataObject)
  206215. {
  206216. files.clear();
  206217. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206218. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206219. if (pDataObject->GetData (&format, &medium) == S_OK)
  206220. {
  206221. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206222. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206223. unsigned int i = 0;
  206224. if (pDropFiles->fWide)
  206225. {
  206226. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206227. for (;;)
  206228. {
  206229. unsigned int len = 0;
  206230. while (i + len < totalLen && fname [i + len] != 0)
  206231. ++len;
  206232. if (len == 0)
  206233. break;
  206234. files.add (String (fname + i, len));
  206235. i += len + 1;
  206236. }
  206237. }
  206238. else
  206239. {
  206240. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206241. for (;;)
  206242. {
  206243. unsigned int len = 0;
  206244. while (i + len < totalLen && fname [i + len] != 0)
  206245. ++len;
  206246. if (len == 0)
  206247. break;
  206248. files.add (String (fname + i, len));
  206249. i += len + 1;
  206250. }
  206251. }
  206252. GlobalUnlock (medium.hGlobal);
  206253. }
  206254. }
  206255. JuceDropTarget (const JuceDropTarget&);
  206256. const JuceDropTarget& operator= (const JuceDropTarget&);
  206257. };
  206258. void doSettingChange()
  206259. {
  206260. Desktop::getInstance().refreshMonitorSizes();
  206261. if (fullScreen && ! isMinimised())
  206262. {
  206263. const Rectangle r (component->getParentMonitorArea());
  206264. SetWindowPos (hwnd, 0,
  206265. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206266. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206267. }
  206268. }
  206269. public:
  206270. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206271. {
  206272. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206273. if (peer != 0)
  206274. return peer->peerWindowProc (h, message, wParam, lParam);
  206275. return DefWindowProc (h, message, wParam, lParam);
  206276. }
  206277. private:
  206278. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206279. {
  206280. {
  206281. const MessageManagerLock messLock;
  206282. if (isValidPeer (this))
  206283. {
  206284. switch (message)
  206285. {
  206286. case WM_NCHITTEST:
  206287. if (hasTitleBar())
  206288. break;
  206289. return HTCLIENT;
  206290. case WM_PAINT:
  206291. handlePaintMessage();
  206292. return 0;
  206293. case WM_NCPAINT:
  206294. if (wParam != 1)
  206295. handlePaintMessage();
  206296. if (hasTitleBar())
  206297. break;
  206298. return 0;
  206299. case WM_ERASEBKGND:
  206300. case WM_NCCALCSIZE:
  206301. if (hasTitleBar())
  206302. break;
  206303. return 1;
  206304. case WM_MOUSEMOVE:
  206305. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206306. return 0;
  206307. case WM_MOUSELEAVE:
  206308. doMouseExit();
  206309. return 0;
  206310. case WM_LBUTTONDOWN:
  206311. case WM_MBUTTONDOWN:
  206312. case WM_RBUTTONDOWN:
  206313. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206314. return 0;
  206315. case WM_LBUTTONUP:
  206316. case WM_MBUTTONUP:
  206317. case WM_RBUTTONUP:
  206318. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206319. return 0;
  206320. case WM_CAPTURECHANGED:
  206321. doCaptureChanged();
  206322. return 0;
  206323. case WM_NCMOUSEMOVE:
  206324. if (hasTitleBar())
  206325. break;
  206326. return 0;
  206327. case 0x020A: /* WM_MOUSEWHEEL */
  206328. doMouseWheel (wParam, true);
  206329. return 0;
  206330. case 0x020E: /* WM_MOUSEHWHEEL */
  206331. doMouseWheel (wParam, false);
  206332. return 0;
  206333. case WM_WINDOWPOSCHANGING:
  206334. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206335. {
  206336. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206337. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206338. {
  206339. if (constrainer != 0)
  206340. {
  206341. const Rectangle current (component->getX() - windowBorder.getLeft(),
  206342. component->getY() - windowBorder.getTop(),
  206343. component->getWidth() + windowBorder.getLeftAndRight(),
  206344. component->getHeight() + windowBorder.getTopAndBottom());
  206345. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  206346. current,
  206347. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206348. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  206349. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  206350. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  206351. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  206352. }
  206353. }
  206354. }
  206355. return 0;
  206356. case WM_WINDOWPOSCHANGED:
  206357. handleMovedOrResized();
  206358. if (dontRepaint)
  206359. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206360. else
  206361. return 0;
  206362. case WM_KEYDOWN:
  206363. case WM_SYSKEYDOWN:
  206364. if (doKeyDown (wParam))
  206365. return 0;
  206366. break;
  206367. case WM_KEYUP:
  206368. case WM_SYSKEYUP:
  206369. if (doKeyUp (wParam))
  206370. return 0;
  206371. break;
  206372. case WM_CHAR:
  206373. if (doKeyChar ((int) wParam, lParam))
  206374. return 0;
  206375. break;
  206376. case WM_APPCOMMAND:
  206377. if (doAppCommand (lParam))
  206378. return TRUE;
  206379. break;
  206380. case WM_SETFOCUS:
  206381. updateKeyModifiers();
  206382. handleFocusGain();
  206383. break;
  206384. case WM_KILLFOCUS:
  206385. handleFocusLoss();
  206386. break;
  206387. case WM_ACTIVATEAPP:
  206388. // Windows does weird things to process priority when you swap apps,
  206389. // so this forces an update when the app is brought to the front
  206390. if (wParam != FALSE)
  206391. juce_repeatLastProcessPriority();
  206392. juce_CheckCurrentlyFocusedTopLevelWindow();
  206393. modifiersAtLastCallback = -1;
  206394. return 0;
  206395. case WM_ACTIVATE:
  206396. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206397. {
  206398. modifiersAtLastCallback = -1;
  206399. updateKeyModifiers();
  206400. if (isMinimised())
  206401. {
  206402. component->repaint();
  206403. handleMovedOrResized();
  206404. if (! isValidMessageListener())
  206405. return 0;
  206406. }
  206407. if (LOWORD (wParam) == WA_CLICKACTIVE
  206408. && component->isCurrentlyBlockedByAnotherModalComponent())
  206409. {
  206410. int mx, my;
  206411. component->getMouseXYRelative (mx, my);
  206412. Component* const underMouse = component->getComponentAt (mx, my);
  206413. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206414. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206415. return 0;
  206416. }
  206417. handleBroughtToFront();
  206418. return 0;
  206419. }
  206420. break;
  206421. case WM_NCACTIVATE:
  206422. // while a temporary window is being shown, prevent Windows from deactivating the
  206423. // title bars of our main windows.
  206424. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206425. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206426. break;
  206427. case WM_MOUSEACTIVATE:
  206428. if (! component->getMouseClickGrabsKeyboardFocus())
  206429. return MA_NOACTIVATE;
  206430. break;
  206431. case WM_SHOWWINDOW:
  206432. if (wParam != 0)
  206433. handleBroughtToFront();
  206434. break;
  206435. case WM_CLOSE:
  206436. handleUserClosingWindow();
  206437. return 0;
  206438. case WM_QUIT:
  206439. JUCEApplication::quit();
  206440. return 0;
  206441. case WM_TRAYNOTIFY:
  206442. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206443. {
  206444. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206445. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206446. {
  206447. Component* const current = Component::getCurrentlyModalComponent();
  206448. if (current != 0)
  206449. current->inputAttemptWhenModal();
  206450. }
  206451. }
  206452. else
  206453. {
  206454. const int oldModifiers = currentModifiers;
  206455. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  206456. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  206457. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206458. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  206459. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206460. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  206461. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206462. {
  206463. SetFocus (hwnd);
  206464. SetForegroundWindow (hwnd);
  206465. component->mouseDown (e);
  206466. }
  206467. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206468. {
  206469. e.mods = ModifierKeys (oldModifiers);
  206470. component->mouseUp (e);
  206471. }
  206472. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206473. {
  206474. e.mods = ModifierKeys (oldModifiers);
  206475. component->mouseDoubleClick (e);
  206476. }
  206477. else if (lParam == WM_MOUSEMOVE)
  206478. {
  206479. component->mouseMove (e);
  206480. }
  206481. }
  206482. break;
  206483. case WM_SYNCPAINT:
  206484. return 0;
  206485. case WM_PALETTECHANGED:
  206486. InvalidateRect (h, 0, 0);
  206487. break;
  206488. case WM_DISPLAYCHANGE:
  206489. InvalidateRect (h, 0, 0);
  206490. createPaletteIfNeeded = true;
  206491. // intentional fall-through...
  206492. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206493. doSettingChange();
  206494. break;
  206495. case WM_INITMENU:
  206496. if (! hasTitleBar())
  206497. {
  206498. if (isFullScreen())
  206499. {
  206500. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206501. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206502. }
  206503. else if (! isMinimised())
  206504. {
  206505. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206506. }
  206507. }
  206508. break;
  206509. case WM_SYSCOMMAND:
  206510. switch (wParam & 0xfff0)
  206511. {
  206512. case SC_CLOSE:
  206513. if (hasTitleBar())
  206514. {
  206515. PostMessage (h, WM_CLOSE, 0, 0);
  206516. return 0;
  206517. }
  206518. break;
  206519. case SC_KEYMENU:
  206520. if (hasTitleBar() && h == GetCapture())
  206521. ReleaseCapture();
  206522. break;
  206523. case SC_MAXIMIZE:
  206524. setFullScreen (true);
  206525. return 0;
  206526. case SC_MINIMIZE:
  206527. if (! hasTitleBar())
  206528. {
  206529. setMinimised (true);
  206530. return 0;
  206531. }
  206532. break;
  206533. case SC_RESTORE:
  206534. if (hasTitleBar())
  206535. {
  206536. if (isFullScreen())
  206537. {
  206538. setFullScreen (false);
  206539. return 0;
  206540. }
  206541. }
  206542. else
  206543. {
  206544. if (isMinimised())
  206545. setMinimised (false);
  206546. else if (isFullScreen())
  206547. setFullScreen (false);
  206548. return 0;
  206549. }
  206550. break;
  206551. case SC_MONITORPOWER:
  206552. case SC_SCREENSAVE:
  206553. if (! screenSaverAllowed)
  206554. return 0;
  206555. break;
  206556. }
  206557. break;
  206558. case WM_NCLBUTTONDOWN:
  206559. case WM_NCRBUTTONDOWN:
  206560. case WM_NCMBUTTONDOWN:
  206561. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206562. {
  206563. Component* const current = Component::getCurrentlyModalComponent();
  206564. if (current != 0)
  206565. current->inputAttemptWhenModal();
  206566. }
  206567. break;
  206568. //case WM_IME_STARTCOMPOSITION;
  206569. // return 0;
  206570. case WM_GETDLGCODE:
  206571. return DLGC_WANTALLKEYS;
  206572. default:
  206573. break;
  206574. }
  206575. }
  206576. }
  206577. // (the message manager lock exits before calling this, to avoid deadlocks if
  206578. // this calls into non-juce windows)
  206579. return DefWindowProc (h, message, wParam, lParam);
  206580. }
  206581. Win32ComponentPeer (const Win32ComponentPeer&);
  206582. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206583. };
  206584. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206585. {
  206586. return new Win32ComponentPeer (this, styleFlags);
  206587. }
  206588. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206589. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206590. {
  206591. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206592. if (wp != 0)
  206593. wp->setTaskBarIcon (&newImage);
  206594. }
  206595. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206596. {
  206597. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206598. if (wp != 0)
  206599. wp->setTaskBarIconToolTip (tooltip);
  206600. }
  206601. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206602. {
  206603. DWORD val = GetWindowLong (h, styleType);
  206604. if (bitIsSet)
  206605. val |= feature;
  206606. else
  206607. val &= ~feature;
  206608. SetWindowLongPtr (h, styleType, val);
  206609. SetWindowPos (h, 0, 0, 0, 0, 0,
  206610. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206611. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206612. }
  206613. bool Process::isForegroundProcess() throw()
  206614. {
  206615. HWND fg = GetForegroundWindow();
  206616. if (fg == 0)
  206617. return true;
  206618. DWORD processId = 0;
  206619. GetWindowThreadProcessId (fg, &processId);
  206620. return processId == GetCurrentProcessId();
  206621. }
  206622. void Desktop::getMousePosition (int& x, int& y) throw()
  206623. {
  206624. POINT mousePos;
  206625. GetCursorPos (&mousePos);
  206626. x = mousePos.x;
  206627. y = mousePos.y;
  206628. }
  206629. void Desktop::setMousePosition (int x, int y) throw()
  206630. {
  206631. SetCursorPos (x, y);
  206632. }
  206633. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206634. {
  206635. screenSaverAllowed = isEnabled;
  206636. }
  206637. bool Desktop::isScreenSaverEnabled() throw()
  206638. {
  206639. return screenSaverAllowed;
  206640. }
  206641. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206642. {
  206643. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  206644. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206645. return TRUE;
  206646. }
  206647. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  206648. {
  206649. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206650. // make sure the first in the list is the main monitor
  206651. for (int i = 1; i < monitorCoords.size(); ++i)
  206652. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206653. monitorCoords.swap (i, 0);
  206654. if (monitorCoords.size() == 0)
  206655. {
  206656. RECT r;
  206657. GetWindowRect (GetDesktopWindow(), &r);
  206658. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206659. }
  206660. if (clipToWorkArea)
  206661. {
  206662. // clip the main monitor to the active non-taskbar area
  206663. RECT r;
  206664. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206665. Rectangle& screen = monitorCoords.getReference (0);
  206666. screen.setPosition (jmax (screen.getX(), r.left),
  206667. jmax (screen.getY(), r.top));
  206668. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  206669. jmin (screen.getBottom(), r.bottom) - screen.getY());
  206670. }
  206671. }
  206672. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  206673. {
  206674. Image* im = 0;
  206675. if (bitmap != 0)
  206676. {
  206677. BITMAP bm;
  206678. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206679. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206680. {
  206681. HDC tempDC = GetDC (0);
  206682. HDC dc = CreateCompatibleDC (tempDC);
  206683. ReleaseDC (0, tempDC);
  206684. SelectObject (dc, bitmap);
  206685. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206686. for (int y = bm.bmHeight; --y >= 0;)
  206687. {
  206688. for (int x = bm.bmWidth; --x >= 0;)
  206689. {
  206690. COLORREF col = GetPixel (dc, x, y);
  206691. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  206692. (uint8) GetGValue (col),
  206693. (uint8) GetBValue (col)));
  206694. }
  206695. }
  206696. DeleteDC (dc);
  206697. }
  206698. }
  206699. return im;
  206700. }
  206701. static Image* createImageFromHICON (HICON icon) throw()
  206702. {
  206703. ICONINFO info;
  206704. if (GetIconInfo (icon, &info))
  206705. {
  206706. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  206707. if (mask == 0)
  206708. return 0;
  206709. Image* const image = createImageFromHBITMAP (info.hbmColor);
  206710. if (image == 0)
  206711. return mask;
  206712. for (int y = image->getHeight(); --y >= 0;)
  206713. {
  206714. for (int x = image->getWidth(); --x >= 0;)
  206715. {
  206716. const float brightness = mask->getPixelAt (x, y).getBrightness();
  206717. if (brightness > 0.0f)
  206718. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  206719. }
  206720. }
  206721. delete mask;
  206722. return image;
  206723. }
  206724. return 0;
  206725. }
  206726. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206727. {
  206728. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206729. ICONINFO info;
  206730. info.fIcon = isIcon;
  206731. info.xHotspot = hotspotX;
  206732. info.yHotspot = hotspotY;
  206733. info.hbmMask = mask;
  206734. HICON hi = 0;
  206735. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  206736. {
  206737. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206738. Graphics g (bitmap);
  206739. g.drawImageAt (&image, 0, 0);
  206740. info.hbmColor = bitmap.hBitmap;
  206741. hi = CreateIconIndirect (&info);
  206742. }
  206743. else
  206744. {
  206745. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  206746. HDC colDC = CreateCompatibleDC (GetDC (0));
  206747. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  206748. SelectObject (colDC, colour);
  206749. SelectObject (alphaDC, mask);
  206750. for (int y = image.getHeight(); --y >= 0;)
  206751. {
  206752. for (int x = image.getWidth(); --x >= 0;)
  206753. {
  206754. const Colour c (image.getPixelAt (x, y));
  206755. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  206756. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  206757. }
  206758. }
  206759. DeleteDC (colDC);
  206760. DeleteDC (alphaDC);
  206761. info.hbmColor = colour;
  206762. hi = CreateIconIndirect (&info);
  206763. DeleteObject (colour);
  206764. }
  206765. DeleteObject (mask);
  206766. return hi;
  206767. }
  206768. Image* juce_createIconForFile (const File& file)
  206769. {
  206770. Image* image = 0;
  206771. TCHAR filename [1024];
  206772. file.getFullPathName().copyToBuffer (filename, 1023);
  206773. WORD iconNum = 0;
  206774. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206775. filename, &iconNum);
  206776. if (icon != 0)
  206777. {
  206778. image = createImageFromHICON (icon);
  206779. DestroyIcon (icon);
  206780. }
  206781. return image;
  206782. }
  206783. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  206784. {
  206785. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206786. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206787. const Image* im = &image;
  206788. Image* newIm = 0;
  206789. if (image.getWidth() > maxW || image.getHeight() > maxH)
  206790. {
  206791. im = newIm = image.createCopy (maxW, maxH);
  206792. hotspotX = (hotspotX * maxW) / image.getWidth();
  206793. hotspotY = (hotspotY * maxH) / image.getHeight();
  206794. }
  206795. void* cursorH = 0;
  206796. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  206797. if (os == SystemStats::WinXP)
  206798. {
  206799. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  206800. }
  206801. else
  206802. {
  206803. const int stride = (maxW + 7) >> 3;
  206804. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  206805. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  206806. int index = 0;
  206807. for (int y = 0; y < maxH; ++y)
  206808. {
  206809. for (int x = 0; x < maxW; ++x)
  206810. {
  206811. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  206812. const Colour pixelColour (im->getPixelAt (x, y));
  206813. if (pixelColour.getAlpha() < 127)
  206814. andPlane [index + (x >> 3)] |= bit;
  206815. else if (pixelColour.getBrightness() >= 0.5f)
  206816. xorPlane [index + (x >> 3)] |= bit;
  206817. }
  206818. index += stride;
  206819. }
  206820. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  206821. juce_free (andPlane);
  206822. juce_free (xorPlane);
  206823. }
  206824. delete newIm;
  206825. return cursorH;
  206826. }
  206827. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  206828. {
  206829. if (cursorHandle != 0 && ! isStandard)
  206830. DestroyCursor ((HCURSOR) cursorHandle);
  206831. }
  206832. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  206833. {
  206834. LPCTSTR cursorName = IDC_ARROW;
  206835. switch (type)
  206836. {
  206837. case MouseCursor::NormalCursor:
  206838. cursorName = IDC_ARROW;
  206839. break;
  206840. case MouseCursor::NoCursor:
  206841. return 0;
  206842. case MouseCursor::DraggingHandCursor:
  206843. {
  206844. static void* dragHandCursor = 0;
  206845. if (dragHandCursor == 0)
  206846. {
  206847. static const unsigned char dragHandData[] =
  206848. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  206849. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39, 132,117,151,116,132,146,248,60,209,138,
  206850. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  206851. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  206852. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  206853. delete image;
  206854. }
  206855. return dragHandCursor;
  206856. }
  206857. case MouseCursor::WaitCursor:
  206858. cursorName = IDC_WAIT;
  206859. break;
  206860. case MouseCursor::IBeamCursor:
  206861. cursorName = IDC_IBEAM;
  206862. break;
  206863. case MouseCursor::PointingHandCursor:
  206864. cursorName = MAKEINTRESOURCE(32649);
  206865. break;
  206866. case MouseCursor::LeftRightResizeCursor:
  206867. case MouseCursor::LeftEdgeResizeCursor:
  206868. case MouseCursor::RightEdgeResizeCursor:
  206869. cursorName = IDC_SIZEWE;
  206870. break;
  206871. case MouseCursor::UpDownResizeCursor:
  206872. case MouseCursor::TopEdgeResizeCursor:
  206873. case MouseCursor::BottomEdgeResizeCursor:
  206874. cursorName = IDC_SIZENS;
  206875. break;
  206876. case MouseCursor::TopLeftCornerResizeCursor:
  206877. case MouseCursor::BottomRightCornerResizeCursor:
  206878. cursorName = IDC_SIZENWSE;
  206879. break;
  206880. case MouseCursor::TopRightCornerResizeCursor:
  206881. case MouseCursor::BottomLeftCornerResizeCursor:
  206882. cursorName = IDC_SIZENESW;
  206883. break;
  206884. case MouseCursor::UpDownLeftRightResizeCursor:
  206885. cursorName = IDC_SIZEALL;
  206886. break;
  206887. case MouseCursor::CrosshairCursor:
  206888. cursorName = IDC_CROSS;
  206889. break;
  206890. case MouseCursor::CopyingCursor:
  206891. // can't seem to find one of these in the win32 list..
  206892. break;
  206893. }
  206894. HCURSOR cursorH = LoadCursor (0, cursorName);
  206895. if (cursorH == 0)
  206896. cursorH = LoadCursor (0, IDC_ARROW);
  206897. return (void*) cursorH;
  206898. }
  206899. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  206900. {
  206901. SetCursor ((HCURSOR) getHandle());
  206902. }
  206903. void MouseCursor::showInAllWindows() const throw()
  206904. {
  206905. showInWindow (0);
  206906. }
  206907. class JuceDropSource : public IDropSource
  206908. {
  206909. int refCount;
  206910. public:
  206911. JuceDropSource()
  206912. : refCount (1)
  206913. {
  206914. }
  206915. virtual ~JuceDropSource()
  206916. {
  206917. jassert (refCount == 0);
  206918. }
  206919. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206920. {
  206921. if (id == IID_IUnknown || id == IID_IDropSource)
  206922. {
  206923. AddRef();
  206924. *result = this;
  206925. return S_OK;
  206926. }
  206927. *result = 0;
  206928. return E_NOINTERFACE;
  206929. }
  206930. ULONG __stdcall AddRef() { return ++refCount; }
  206931. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206932. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206933. {
  206934. if (escapePressed)
  206935. return DRAGDROP_S_CANCEL;
  206936. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206937. return DRAGDROP_S_DROP;
  206938. return S_OK;
  206939. }
  206940. HRESULT __stdcall GiveFeedback (DWORD)
  206941. {
  206942. return DRAGDROP_S_USEDEFAULTCURSORS;
  206943. }
  206944. };
  206945. class JuceEnumFormatEtc : public IEnumFORMATETC
  206946. {
  206947. public:
  206948. JuceEnumFormatEtc (const FORMATETC* const format_)
  206949. : refCount (1),
  206950. format (format_),
  206951. index (0)
  206952. {
  206953. }
  206954. virtual ~JuceEnumFormatEtc()
  206955. {
  206956. jassert (refCount == 0);
  206957. }
  206958. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206959. {
  206960. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  206961. {
  206962. AddRef();
  206963. *result = this;
  206964. return S_OK;
  206965. }
  206966. *result = 0;
  206967. return E_NOINTERFACE;
  206968. }
  206969. ULONG __stdcall AddRef() { return ++refCount; }
  206970. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206971. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206972. {
  206973. if (result == 0)
  206974. return E_POINTER;
  206975. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206976. newOne->index = index;
  206977. *result = newOne;
  206978. return S_OK;
  206979. }
  206980. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206981. {
  206982. if (pceltFetched != 0)
  206983. *pceltFetched = 0;
  206984. else if (celt != 1)
  206985. return S_FALSE;
  206986. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206987. {
  206988. copyFormatEtc (lpFormatEtc [0], *format);
  206989. ++index;
  206990. if (pceltFetched != 0)
  206991. *pceltFetched = 1;
  206992. return S_OK;
  206993. }
  206994. return S_FALSE;
  206995. }
  206996. HRESULT __stdcall Skip (ULONG celt)
  206997. {
  206998. if (index + (int) celt >= 1)
  206999. return S_FALSE;
  207000. index += celt;
  207001. return S_OK;
  207002. }
  207003. HRESULT __stdcall Reset()
  207004. {
  207005. index = 0;
  207006. return S_OK;
  207007. }
  207008. private:
  207009. int refCount;
  207010. const FORMATETC* const format;
  207011. int index;
  207012. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  207013. {
  207014. dest = source;
  207015. if (source.ptd != 0)
  207016. {
  207017. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  207018. *(dest.ptd) = *(source.ptd);
  207019. }
  207020. }
  207021. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  207022. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  207023. };
  207024. class JuceDataObject : public IDataObject
  207025. {
  207026. JuceDropSource* const dropSource;
  207027. const FORMATETC* const format;
  207028. const STGMEDIUM* const medium;
  207029. int refCount;
  207030. JuceDataObject (const JuceDataObject&);
  207031. const JuceDataObject& operator= (const JuceDataObject&);
  207032. public:
  207033. JuceDataObject (JuceDropSource* const dropSource_,
  207034. const FORMATETC* const format_,
  207035. const STGMEDIUM* const medium_)
  207036. : dropSource (dropSource_),
  207037. format (format_),
  207038. medium (medium_),
  207039. refCount (1)
  207040. {
  207041. }
  207042. virtual ~JuceDataObject()
  207043. {
  207044. jassert (refCount == 0);
  207045. }
  207046. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207047. {
  207048. if (id == IID_IUnknown || id == IID_IDataObject)
  207049. {
  207050. AddRef();
  207051. *result = this;
  207052. return S_OK;
  207053. }
  207054. *result = 0;
  207055. return E_NOINTERFACE;
  207056. }
  207057. ULONG __stdcall AddRef() { return ++refCount; }
  207058. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207059. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  207060. {
  207061. if (pFormatEtc->tymed == format->tymed
  207062. && pFormatEtc->cfFormat == format->cfFormat
  207063. && pFormatEtc->dwAspect == format->dwAspect)
  207064. {
  207065. pMedium->tymed = format->tymed;
  207066. pMedium->pUnkForRelease = 0;
  207067. if (format->tymed == TYMED_HGLOBAL)
  207068. {
  207069. const SIZE_T len = GlobalSize (medium->hGlobal);
  207070. void* const src = GlobalLock (medium->hGlobal);
  207071. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  207072. memcpy (dst, src, len);
  207073. GlobalUnlock (medium->hGlobal);
  207074. pMedium->hGlobal = dst;
  207075. return S_OK;
  207076. }
  207077. }
  207078. return DV_E_FORMATETC;
  207079. }
  207080. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  207081. {
  207082. if (f == 0)
  207083. return E_INVALIDARG;
  207084. if (f->tymed == format->tymed
  207085. && f->cfFormat == format->cfFormat
  207086. && f->dwAspect == format->dwAspect)
  207087. return S_OK;
  207088. return DV_E_FORMATETC;
  207089. }
  207090. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  207091. {
  207092. pFormatEtcOut->ptd = 0;
  207093. return E_NOTIMPL;
  207094. }
  207095. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  207096. {
  207097. if (result == 0)
  207098. return E_POINTER;
  207099. if (direction == DATADIR_GET)
  207100. {
  207101. *result = new JuceEnumFormatEtc (format);
  207102. return S_OK;
  207103. }
  207104. *result = 0;
  207105. return E_NOTIMPL;
  207106. }
  207107. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  207108. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  207109. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  207110. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  207111. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  207112. };
  207113. static HDROP createHDrop (const StringArray& fileNames) throw()
  207114. {
  207115. int totalChars = 0;
  207116. for (int i = fileNames.size(); --i >= 0;)
  207117. totalChars += fileNames[i].length() + 1;
  207118. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  207119. sizeof (DROPFILES)
  207120. + sizeof (WCHAR) * (totalChars + 2));
  207121. if (hDrop != 0)
  207122. {
  207123. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  207124. pDropFiles->pFiles = sizeof (DROPFILES);
  207125. pDropFiles->fWide = true;
  207126. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  207127. for (int i = 0; i < fileNames.size(); ++i)
  207128. {
  207129. fileNames[i].copyToBuffer (fname, 2048);
  207130. fname += fileNames[i].length() + 1;
  207131. }
  207132. *fname = 0;
  207133. GlobalUnlock (hDrop);
  207134. }
  207135. return hDrop;
  207136. }
  207137. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  207138. {
  207139. JuceDropSource* const source = new JuceDropSource();
  207140. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  207141. DWORD effect;
  207142. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  207143. data->Release();
  207144. source->Release();
  207145. return res == DRAGDROP_S_DROP;
  207146. }
  207147. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207148. {
  207149. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207150. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207151. medium.hGlobal = createHDrop (files);
  207152. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207153. : DROPEFFECT_COPY);
  207154. }
  207155. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207156. {
  207157. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207158. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207159. const int numChars = text.length();
  207160. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207161. char* d = (char*) GlobalLock (medium.hGlobal);
  207162. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  207163. format.cfFormat = CF_UNICODETEXT;
  207164. GlobalUnlock (medium.hGlobal);
  207165. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207166. }
  207167. #if JUCE_OPENGL
  207168. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207169. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207170. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207171. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207172. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207173. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207174. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207175. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207176. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207177. #define WGL_ACCELERATION_ARB 0x2003
  207178. #define WGL_SWAP_METHOD_ARB 0x2007
  207179. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207180. #define WGL_PIXEL_TYPE_ARB 0x2013
  207181. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207182. #define WGL_COLOR_BITS_ARB 0x2014
  207183. #define WGL_RED_BITS_ARB 0x2015
  207184. #define WGL_GREEN_BITS_ARB 0x2017
  207185. #define WGL_BLUE_BITS_ARB 0x2019
  207186. #define WGL_ALPHA_BITS_ARB 0x201B
  207187. #define WGL_DEPTH_BITS_ARB 0x2022
  207188. #define WGL_STENCIL_BITS_ARB 0x2023
  207189. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207190. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207191. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207192. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207193. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207194. #define WGL_STEREO_ARB 0x2012
  207195. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207196. #define WGL_SAMPLES_ARB 0x2042
  207197. #define WGL_TYPE_RGBA_ARB 0x202B
  207198. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207199. {
  207200. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207201. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207202. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207203. else
  207204. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  207205. }
  207206. class WindowedGLContext : public OpenGLContext
  207207. {
  207208. public:
  207209. WindowedGLContext (Component* const component_,
  207210. HGLRC contextToShareWith,
  207211. const OpenGLPixelFormat& pixelFormat)
  207212. : renderContext (0),
  207213. nativeWindow (0),
  207214. dc (0),
  207215. component (component_)
  207216. {
  207217. jassert (component != 0);
  207218. createNativeWindow();
  207219. // Use a default pixel format that should be supported everywhere
  207220. PIXELFORMATDESCRIPTOR pfd;
  207221. zerostruct (pfd);
  207222. pfd.nSize = sizeof (pfd);
  207223. pfd.nVersion = 1;
  207224. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  207225. pfd.iPixelType = PFD_TYPE_RGBA;
  207226. pfd.cColorBits = 24;
  207227. pfd.cDepthBits = 16;
  207228. const int format = ChoosePixelFormat (dc, &pfd);
  207229. if (format != 0)
  207230. SetPixelFormat (dc, format, &pfd);
  207231. renderContext = wglCreateContext (dc);
  207232. makeActive();
  207233. setPixelFormat (pixelFormat);
  207234. if (contextToShareWith != 0 && renderContext != 0)
  207235. wglShareLists (contextToShareWith, renderContext);
  207236. }
  207237. ~WindowedGLContext()
  207238. {
  207239. makeInactive();
  207240. wglDeleteContext (renderContext);
  207241. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207242. delete nativeWindow;
  207243. }
  207244. bool makeActive() const throw()
  207245. {
  207246. jassert (renderContext != 0);
  207247. return wglMakeCurrent (dc, renderContext) != 0;
  207248. }
  207249. bool makeInactive() const throw()
  207250. {
  207251. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  207252. }
  207253. bool isActive() const throw()
  207254. {
  207255. return wglGetCurrentContext() == renderContext;
  207256. }
  207257. const OpenGLPixelFormat getPixelFormat() const
  207258. {
  207259. OpenGLPixelFormat pf;
  207260. makeActive();
  207261. StringArray availableExtensions;
  207262. getWglExtensions (dc, availableExtensions);
  207263. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  207264. return pf;
  207265. }
  207266. void* getRawContext() const throw()
  207267. {
  207268. return renderContext;
  207269. }
  207270. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  207271. {
  207272. makeActive();
  207273. PIXELFORMATDESCRIPTOR pfd;
  207274. zerostruct (pfd);
  207275. pfd.nSize = sizeof (pfd);
  207276. pfd.nVersion = 1;
  207277. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  207278. pfd.iPixelType = PFD_TYPE_RGBA;
  207279. pfd.iLayerType = PFD_MAIN_PLANE;
  207280. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  207281. pfd.cRedBits = pixelFormat.redBits;
  207282. pfd.cGreenBits = pixelFormat.greenBits;
  207283. pfd.cBlueBits = pixelFormat.blueBits;
  207284. pfd.cAlphaBits = pixelFormat.alphaBits;
  207285. pfd.cDepthBits = pixelFormat.depthBufferBits;
  207286. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  207287. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  207288. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  207289. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  207290. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  207291. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  207292. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  207293. int format = 0;
  207294. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  207295. StringArray availableExtensions;
  207296. getWglExtensions (dc, availableExtensions);
  207297. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207298. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  207299. {
  207300. int attributes[64];
  207301. int n = 0;
  207302. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  207303. attributes[n++] = GL_TRUE;
  207304. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  207305. attributes[n++] = GL_TRUE;
  207306. attributes[n++] = WGL_ACCELERATION_ARB;
  207307. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  207308. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  207309. attributes[n++] = GL_TRUE;
  207310. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  207311. attributes[n++] = WGL_TYPE_RGBA_ARB;
  207312. attributes[n++] = WGL_COLOR_BITS_ARB;
  207313. attributes[n++] = pfd.cColorBits;
  207314. attributes[n++] = WGL_RED_BITS_ARB;
  207315. attributes[n++] = pixelFormat.redBits;
  207316. attributes[n++] = WGL_GREEN_BITS_ARB;
  207317. attributes[n++] = pixelFormat.greenBits;
  207318. attributes[n++] = WGL_BLUE_BITS_ARB;
  207319. attributes[n++] = pixelFormat.blueBits;
  207320. attributes[n++] = WGL_ALPHA_BITS_ARB;
  207321. attributes[n++] = pixelFormat.alphaBits;
  207322. attributes[n++] = WGL_DEPTH_BITS_ARB;
  207323. attributes[n++] = pixelFormat.depthBufferBits;
  207324. if (pixelFormat.stencilBufferBits > 0)
  207325. {
  207326. attributes[n++] = WGL_STENCIL_BITS_ARB;
  207327. attributes[n++] = pixelFormat.stencilBufferBits;
  207328. }
  207329. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  207330. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  207331. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  207332. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  207333. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  207334. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  207335. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  207336. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  207337. if (availableExtensions.contains ("WGL_ARB_multisample")
  207338. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  207339. {
  207340. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  207341. attributes[n++] = 1;
  207342. attributes[n++] = WGL_SAMPLES_ARB;
  207343. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  207344. }
  207345. attributes[n++] = 0;
  207346. UINT formatsCount;
  207347. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  207348. (void) ok;
  207349. jassert (ok);
  207350. }
  207351. else
  207352. {
  207353. format = ChoosePixelFormat (dc, &pfd);
  207354. }
  207355. if (format != 0)
  207356. {
  207357. makeInactive();
  207358. // win32 can't change the pixel format of a window, so need to delete the
  207359. // old one and create a new one..
  207360. jassert (nativeWindow != 0);
  207361. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207362. delete nativeWindow;
  207363. createNativeWindow();
  207364. if (SetPixelFormat (dc, format, &pfd))
  207365. {
  207366. wglDeleteContext (renderContext);
  207367. renderContext = wglCreateContext (dc);
  207368. jassert (renderContext != 0);
  207369. return renderContext != 0;
  207370. }
  207371. }
  207372. return false;
  207373. }
  207374. void updateWindowPosition (int x, int y, int w, int h, int)
  207375. {
  207376. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  207377. x, y, w, h,
  207378. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207379. }
  207380. void repaint()
  207381. {
  207382. int x, y, w, h;
  207383. nativeWindow->getBounds (x, y, w, h);
  207384. nativeWindow->repaint (0, 0, w, h);
  207385. }
  207386. void swapBuffers()
  207387. {
  207388. SwapBuffers (dc);
  207389. }
  207390. bool setSwapInterval (const int numFramesPerSwap)
  207391. {
  207392. makeActive();
  207393. StringArray availableExtensions;
  207394. getWglExtensions (dc, availableExtensions);
  207395. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  207396. return availableExtensions.contains ("WGL_EXT_swap_control")
  207397. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  207398. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  207399. }
  207400. int getSwapInterval() const
  207401. {
  207402. makeActive();
  207403. StringArray availableExtensions;
  207404. getWglExtensions (dc, availableExtensions);
  207405. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  207406. if (availableExtensions.contains ("WGL_EXT_swap_control")
  207407. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  207408. return wglGetSwapIntervalEXT();
  207409. return 0;
  207410. }
  207411. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  207412. {
  207413. jassert (isActive());
  207414. StringArray availableExtensions;
  207415. getWglExtensions (dc, availableExtensions);
  207416. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  207417. int numTypes = 0;
  207418. if (availableExtensions.contains("WGL_ARB_pixel_format")
  207419. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  207420. {
  207421. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  207422. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  207423. jassertfalse
  207424. }
  207425. else
  207426. {
  207427. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  207428. }
  207429. OpenGLPixelFormat pf;
  207430. for (int i = 0; i < numTypes; ++i)
  207431. {
  207432. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  207433. {
  207434. bool alreadyListed = false;
  207435. for (int j = results.size(); --j >= 0;)
  207436. if (pf == *results.getUnchecked(j))
  207437. alreadyListed = true;
  207438. if (! alreadyListed)
  207439. results.add (new OpenGLPixelFormat (pf));
  207440. }
  207441. }
  207442. }
  207443. juce_UseDebuggingNewOperator
  207444. HGLRC renderContext;
  207445. private:
  207446. Win32ComponentPeer* nativeWindow;
  207447. Component* const component;
  207448. HDC dc;
  207449. void createNativeWindow()
  207450. {
  207451. nativeWindow = new Win32ComponentPeer (component, 0);
  207452. nativeWindow->dontRepaint = true;
  207453. nativeWindow->setVisible (true);
  207454. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  207455. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  207456. if (peer != 0)
  207457. {
  207458. SetParent (hwnd, (HWND) peer->getNativeHandle());
  207459. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  207460. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  207461. }
  207462. dc = GetDC (hwnd);
  207463. }
  207464. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  207465. OpenGLPixelFormat& result,
  207466. const StringArray& availableExtensions) const throw()
  207467. {
  207468. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  207469. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207470. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  207471. {
  207472. int attributes[32];
  207473. int numAttributes = 0;
  207474. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  207475. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  207476. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  207477. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  207478. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  207479. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  207480. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  207481. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  207482. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  207483. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  207484. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  207485. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  207486. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  207487. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  207488. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  207489. if (availableExtensions.contains ("WGL_ARB_multisample"))
  207490. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  207491. int values[32];
  207492. zeromem (values, sizeof (values));
  207493. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  207494. {
  207495. int n = 0;
  207496. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  207497. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  207498. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  207499. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  207500. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  207501. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  207502. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  207503. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  207504. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  207505. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  207506. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  207507. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  207508. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  207509. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  207510. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  207511. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  207512. return isValidFormat;
  207513. }
  207514. else
  207515. {
  207516. jassertfalse
  207517. }
  207518. }
  207519. else
  207520. {
  207521. PIXELFORMATDESCRIPTOR pfd;
  207522. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  207523. {
  207524. result.redBits = pfd.cRedBits;
  207525. result.greenBits = pfd.cGreenBits;
  207526. result.blueBits = pfd.cBlueBits;
  207527. result.alphaBits = pfd.cAlphaBits;
  207528. result.depthBufferBits = pfd.cDepthBits;
  207529. result.stencilBufferBits = pfd.cStencilBits;
  207530. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  207531. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  207532. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  207533. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  207534. result.fullSceneAntiAliasingNumSamples = 0;
  207535. return true;
  207536. }
  207537. else
  207538. {
  207539. jassertfalse
  207540. }
  207541. }
  207542. return false;
  207543. }
  207544. WindowedGLContext (const WindowedGLContext&);
  207545. const WindowedGLContext& operator= (const WindowedGLContext&);
  207546. };
  207547. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  207548. const OpenGLPixelFormat& pixelFormat,
  207549. const OpenGLContext* const contextToShareWith)
  207550. {
  207551. WindowedGLContext* c = new WindowedGLContext (component,
  207552. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  207553. pixelFormat);
  207554. if (c->renderContext == 0)
  207555. deleteAndZero (c);
  207556. return c;
  207557. }
  207558. void juce_glViewport (const int w, const int h)
  207559. {
  207560. glViewport (0, 0, w, h);
  207561. }
  207562. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  207563. OwnedArray <OpenGLPixelFormat>& results)
  207564. {
  207565. Component tempComp;
  207566. {
  207567. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  207568. wc.makeActive();
  207569. wc.findAlternativeOpenGLPixelFormats (results);
  207570. }
  207571. }
  207572. #endif
  207573. class JuceIStorage : public IStorage
  207574. {
  207575. int refCount;
  207576. public:
  207577. JuceIStorage() : refCount (1) {}
  207578. virtual ~JuceIStorage()
  207579. {
  207580. jassert (refCount == 0);
  207581. }
  207582. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207583. {
  207584. if (id == IID_IUnknown || id == IID_IStorage)
  207585. {
  207586. AddRef();
  207587. *result = this;
  207588. return S_OK;
  207589. }
  207590. *result = 0;
  207591. return E_NOINTERFACE;
  207592. }
  207593. ULONG __stdcall AddRef() { return ++refCount; }
  207594. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207595. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207596. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207597. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207598. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207599. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207600. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207601. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207602. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207603. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207604. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207605. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207606. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207607. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207608. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207609. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207610. juce_UseDebuggingNewOperator
  207611. };
  207612. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  207613. {
  207614. int refCount;
  207615. HWND window;
  207616. public:
  207617. JuceOleInPlaceFrame (HWND window_)
  207618. : refCount (1),
  207619. window (window_)
  207620. {
  207621. }
  207622. virtual ~JuceOleInPlaceFrame()
  207623. {
  207624. jassert (refCount == 0);
  207625. }
  207626. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207627. {
  207628. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  207629. {
  207630. AddRef();
  207631. *result = this;
  207632. return S_OK;
  207633. }
  207634. *result = 0;
  207635. return E_NOINTERFACE;
  207636. }
  207637. ULONG __stdcall AddRef() { return ++refCount; }
  207638. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207639. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207640. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207641. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207642. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207643. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207644. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207645. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207646. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207647. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207648. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207649. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207650. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207651. juce_UseDebuggingNewOperator
  207652. };
  207653. class JuceIOleInPlaceSite : public IOleInPlaceSite
  207654. {
  207655. int refCount;
  207656. HWND window;
  207657. JuceOleInPlaceFrame* frame;
  207658. public:
  207659. JuceIOleInPlaceSite (HWND window_)
  207660. : refCount (1),
  207661. window (window_)
  207662. {
  207663. frame = new JuceOleInPlaceFrame (window);
  207664. }
  207665. virtual ~JuceIOleInPlaceSite()
  207666. {
  207667. jassert (refCount == 0);
  207668. frame->Release();
  207669. }
  207670. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207671. {
  207672. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  207673. {
  207674. AddRef();
  207675. *result = this;
  207676. return S_OK;
  207677. }
  207678. *result = 0;
  207679. return E_NOINTERFACE;
  207680. }
  207681. ULONG __stdcall AddRef() { return ++refCount; }
  207682. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207683. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207684. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207685. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207686. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207687. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207688. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207689. {
  207690. frame->AddRef();
  207691. *lplpFrame = frame;
  207692. *lplpDoc = 0;
  207693. lpFrameInfo->fMDIApp = FALSE;
  207694. lpFrameInfo->hwndFrame = window;
  207695. lpFrameInfo->haccel = 0;
  207696. lpFrameInfo->cAccelEntries = 0;
  207697. return S_OK;
  207698. }
  207699. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207700. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207701. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207702. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207703. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207704. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207705. juce_UseDebuggingNewOperator
  207706. };
  207707. class JuceIOleClientSite : public IOleClientSite
  207708. {
  207709. int refCount;
  207710. JuceIOleInPlaceSite* inplaceSite;
  207711. public:
  207712. JuceIOleClientSite (HWND window)
  207713. : refCount (1)
  207714. {
  207715. inplaceSite = new JuceIOleInPlaceSite (window);
  207716. }
  207717. virtual ~JuceIOleClientSite()
  207718. {
  207719. jassert (refCount == 0);
  207720. inplaceSite->Release();
  207721. }
  207722. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207723. {
  207724. if (id == IID_IUnknown || id == IID_IOleClientSite)
  207725. {
  207726. AddRef();
  207727. *result = this;
  207728. return S_OK;
  207729. }
  207730. else if (id == IID_IOleInPlaceSite)
  207731. {
  207732. inplaceSite->AddRef();
  207733. *result = inplaceSite;
  207734. return S_OK;
  207735. }
  207736. *result = 0;
  207737. return E_NOINTERFACE;
  207738. }
  207739. ULONG __stdcall AddRef() { return ++refCount; }
  207740. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207741. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207742. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207743. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207744. HRESULT __stdcall ShowObject() { return S_OK; }
  207745. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207746. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207747. juce_UseDebuggingNewOperator
  207748. };
  207749. class ActiveXControlData : public ComponentMovementWatcher
  207750. {
  207751. ActiveXControlComponent* const owner;
  207752. bool wasShowing;
  207753. public:
  207754. IStorage* storage;
  207755. IOleClientSite* clientSite;
  207756. IOleObject* control;
  207757. ActiveXControlData (HWND hwnd,
  207758. ActiveXControlComponent* const owner_)
  207759. : ComponentMovementWatcher (owner_),
  207760. owner (owner_),
  207761. wasShowing (owner_ != 0 && owner_->isShowing()),
  207762. storage (new JuceIStorage()),
  207763. clientSite (new JuceIOleClientSite (hwnd)),
  207764. control (0)
  207765. {
  207766. }
  207767. ~ActiveXControlData()
  207768. {
  207769. if (control != 0)
  207770. {
  207771. control->Close (OLECLOSE_NOSAVE);
  207772. control->Release();
  207773. }
  207774. clientSite->Release();
  207775. storage->Release();
  207776. }
  207777. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207778. {
  207779. Component* const topComp = owner->getTopLevelComponent();
  207780. if (topComp->getPeer() != 0)
  207781. {
  207782. int x = 0, y = 0;
  207783. owner->relativePositionToOtherComponent (topComp, x, y);
  207784. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  207785. }
  207786. }
  207787. void componentPeerChanged()
  207788. {
  207789. const bool isShowingNow = owner->isShowing();
  207790. if (wasShowing != isShowingNow)
  207791. {
  207792. wasShowing = isShowingNow;
  207793. owner->setControlVisible (isShowingNow);
  207794. }
  207795. }
  207796. void componentVisibilityChanged (Component&)
  207797. {
  207798. componentPeerChanged();
  207799. }
  207800. };
  207801. static VoidArray activeXComps;
  207802. static HWND getHWND (const ActiveXControlComponent* const component)
  207803. {
  207804. HWND hwnd = 0;
  207805. const IID iid = IID_IOleWindow;
  207806. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207807. if (window != 0)
  207808. {
  207809. window->GetWindow (&hwnd);
  207810. window->Release();
  207811. }
  207812. return hwnd;
  207813. }
  207814. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207815. {
  207816. RECT activeXRect, peerRect;
  207817. GetWindowRect (hwnd, &activeXRect);
  207818. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207819. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  207820. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  207821. const int64 mouseEventTime = getMouseEventTime();
  207822. const int oldModifiers = currentModifiers;
  207823. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207824. switch (message)
  207825. {
  207826. case WM_MOUSEMOVE:
  207827. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  207828. peer->handleMouseDrag (mx, my, mouseEventTime);
  207829. else
  207830. peer->handleMouseMove (mx, my, mouseEventTime);
  207831. break;
  207832. case WM_LBUTTONDOWN:
  207833. case WM_MBUTTONDOWN:
  207834. case WM_RBUTTONDOWN:
  207835. peer->handleMouseDown (mx, my, mouseEventTime);
  207836. break;
  207837. case WM_LBUTTONUP:
  207838. case WM_MBUTTONUP:
  207839. case WM_RBUTTONUP:
  207840. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  207841. break;
  207842. default:
  207843. break;
  207844. }
  207845. }
  207846. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207847. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207848. {
  207849. for (int i = activeXComps.size(); --i >= 0;)
  207850. {
  207851. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  207852. HWND controlHWND = getHWND (ax);
  207853. if (controlHWND == hwnd)
  207854. {
  207855. switch (message)
  207856. {
  207857. case WM_MOUSEMOVE:
  207858. case WM_LBUTTONDOWN:
  207859. case WM_MBUTTONDOWN:
  207860. case WM_RBUTTONDOWN:
  207861. case WM_LBUTTONUP:
  207862. case WM_MBUTTONUP:
  207863. case WM_RBUTTONUP:
  207864. case WM_LBUTTONDBLCLK:
  207865. case WM_MBUTTONDBLCLK:
  207866. case WM_RBUTTONDBLCLK:
  207867. if (ax->isShowing())
  207868. {
  207869. ComponentPeer* const peer = ax->getPeer();
  207870. if (peer != 0)
  207871. {
  207872. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207873. if (! ax->areMouseEventsAllowed())
  207874. return 0;
  207875. }
  207876. }
  207877. break;
  207878. default:
  207879. break;
  207880. }
  207881. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  207882. }
  207883. }
  207884. return DefWindowProc (hwnd, message, wParam, lParam);
  207885. }
  207886. ActiveXControlComponent::ActiveXControlComponent()
  207887. : originalWndProc (0),
  207888. control (0),
  207889. mouseEventsAllowed (true)
  207890. {
  207891. activeXComps.add (this);
  207892. }
  207893. ActiveXControlComponent::~ActiveXControlComponent()
  207894. {
  207895. deleteControl();
  207896. activeXComps.removeValue (this);
  207897. }
  207898. void ActiveXControlComponent::paint (Graphics& g)
  207899. {
  207900. if (control == 0)
  207901. g.fillAll (Colours::lightgrey);
  207902. }
  207903. bool ActiveXControlComponent::createControl (const void* controlIID)
  207904. {
  207905. deleteControl();
  207906. ComponentPeer* const peer = getPeer();
  207907. // the component must have already been added to a real window when you call this!
  207908. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207909. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207910. {
  207911. int x = 0, y = 0;
  207912. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  207913. HWND hwnd = (HWND) peer->getNativeHandle();
  207914. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  207915. HRESULT hr;
  207916. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207917. info->clientSite, info->storage,
  207918. (void**) &(info->control))) == S_OK)
  207919. {
  207920. info->control->SetHostNames (L"Juce", 0);
  207921. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  207922. {
  207923. RECT rect;
  207924. rect.left = x;
  207925. rect.top = y;
  207926. rect.right = x + getWidth();
  207927. rect.bottom = y + getHeight();
  207928. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  207929. {
  207930. control = info;
  207931. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  207932. HWND controlHWND = getHWND (this);
  207933. if (controlHWND != 0)
  207934. {
  207935. originalWndProc = (void*) GetWindowLongPtr (controlHWND, GWLP_WNDPROC);
  207936. SetWindowLongPtr (controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  207937. }
  207938. return true;
  207939. }
  207940. }
  207941. }
  207942. delete info;
  207943. }
  207944. return false;
  207945. }
  207946. void ActiveXControlComponent::deleteControl()
  207947. {
  207948. ActiveXControlData* const info = (ActiveXControlData*) control;
  207949. if (info != 0)
  207950. {
  207951. delete info;
  207952. control = 0;
  207953. originalWndProc = 0;
  207954. }
  207955. }
  207956. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207957. {
  207958. ActiveXControlData* const info = (ActiveXControlData*) control;
  207959. void* result = 0;
  207960. if (info != 0 && info->control != 0
  207961. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  207962. return result;
  207963. return 0;
  207964. }
  207965. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  207966. {
  207967. HWND hwnd = getHWND (this);
  207968. if (hwnd != 0)
  207969. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207970. }
  207971. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207972. {
  207973. HWND hwnd = getHWND (this);
  207974. if (hwnd != 0)
  207975. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207976. }
  207977. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207978. {
  207979. mouseEventsAllowed = eventsCanReachControl;
  207980. }
  207981. END_JUCE_NAMESPACE
  207982. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  207983. #endif
  207984. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  207985. // Auto-links to various win32 libs that are needed by library calls..
  207986. #pragma comment(lib, "kernel32.lib")
  207987. #pragma comment(lib, "user32.lib")
  207988. #pragma comment(lib, "shell32.lib")
  207989. #pragma comment(lib, "gdi32.lib")
  207990. #pragma comment(lib, "vfw32.lib")
  207991. #pragma comment(lib, "comdlg32.lib")
  207992. #pragma comment(lib, "winmm.lib")
  207993. #pragma comment(lib, "wininet.lib")
  207994. #pragma comment(lib, "ole32.lib")
  207995. #pragma comment(lib, "advapi32.lib")
  207996. #pragma comment(lib, "ws2_32.lib")
  207997. #pragma comment(lib, "comsupp.lib")
  207998. #if JUCE_OPENGL
  207999. #pragma comment(lib, "OpenGL32.Lib")
  208000. #pragma comment(lib, "GlU32.Lib")
  208001. #endif
  208002. #if JUCE_QUICKTIME
  208003. #pragma comment (lib, "QTMLClient.lib")
  208004. #endif
  208005. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208006. #endif
  208007. //==============================================================================
  208008. #if JUCE_LINUX
  208009. /********* Start of inlined file: juce_linux_Files.cpp *********/
  208010. /********* Start of inlined file: linuxincludes.h *********/
  208011. #ifndef __LINUXINCLUDES_JUCEHEADER__
  208012. #define __LINUXINCLUDES_JUCEHEADER__
  208013. // Linux Header Files:
  208014. #include <unistd.h>
  208015. #include <stdlib.h>
  208016. #include <sched.h>
  208017. #include <pthread.h>
  208018. #include <sys/time.h>
  208019. #include <errno.h>
  208020. /* Remove this macro if you're having problems compiling the cpu affinity
  208021. calls (the API for these has changed about quite a bit in various Linux
  208022. versions, and a lot of distros seem to ship with obsolete versions)
  208023. */
  208024. #ifndef SUPPORT_AFFINITIES
  208025. #define SUPPORT_AFFINITIES 1
  208026. #endif
  208027. #endif // __LINUXINCLUDES_JUCEHEADER__
  208028. /********* End of inlined file: linuxincludes.h *********/
  208029. #include <sys/stat.h>
  208030. #include <sys/dir.h>
  208031. #include <sys/ptrace.h>
  208032. #include <sys/vfs.h> // for statfs
  208033. #include <sys/wait.h>
  208034. #include <unistd.h>
  208035. #include <fnmatch.h>
  208036. #include <utime.h>
  208037. #include <pwd.h>
  208038. #include <fcntl.h>
  208039. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  208040. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  208041. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  208042. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  208043. BEGIN_JUCE_NAMESPACE
  208044. /*
  208045. Note that a lot of methods that you'd expect to find in this file actually
  208046. live in juce_posix_SharedCode.cpp!
  208047. */
  208048. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  208049. /*
  208050. This file contains posix routines that are common to both the Linux and Mac builds.
  208051. It gets included directly in the cpp files for these platforms.
  208052. */
  208053. CriticalSection::CriticalSection() throw()
  208054. {
  208055. pthread_mutexattr_t atts;
  208056. pthread_mutexattr_init (&atts);
  208057. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  208058. pthread_mutex_init (&internal, &atts);
  208059. }
  208060. CriticalSection::~CriticalSection() throw()
  208061. {
  208062. pthread_mutex_destroy (&internal);
  208063. }
  208064. void CriticalSection::enter() const throw()
  208065. {
  208066. pthread_mutex_lock (&internal);
  208067. }
  208068. bool CriticalSection::tryEnter() const throw()
  208069. {
  208070. return pthread_mutex_trylock (&internal) == 0;
  208071. }
  208072. void CriticalSection::exit() const throw()
  208073. {
  208074. pthread_mutex_unlock (&internal);
  208075. }
  208076. struct EventStruct
  208077. {
  208078. pthread_cond_t condition;
  208079. pthread_mutex_t mutex;
  208080. bool triggered;
  208081. };
  208082. WaitableEvent::WaitableEvent() throw()
  208083. {
  208084. EventStruct* const es = new EventStruct();
  208085. es->triggered = false;
  208086. pthread_cond_init (&es->condition, 0);
  208087. pthread_mutex_init (&es->mutex, 0);
  208088. internal = es;
  208089. }
  208090. WaitableEvent::~WaitableEvent() throw()
  208091. {
  208092. EventStruct* const es = (EventStruct*) internal;
  208093. pthread_cond_destroy (&es->condition);
  208094. pthread_mutex_destroy (&es->mutex);
  208095. delete es;
  208096. }
  208097. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  208098. {
  208099. EventStruct* const es = (EventStruct*) internal;
  208100. bool ok = true;
  208101. pthread_mutex_lock (&es->mutex);
  208102. if (! es->triggered)
  208103. {
  208104. if (timeOutMillisecs < 0)
  208105. {
  208106. pthread_cond_wait (&es->condition, &es->mutex);
  208107. }
  208108. else
  208109. {
  208110. struct timespec time;
  208111. #if JUCE_MAC
  208112. time.tv_sec = timeOutMillisecs / 1000;
  208113. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  208114. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  208115. #else
  208116. struct timeval t;
  208117. int timeout = 0;
  208118. gettimeofday (&t, 0);
  208119. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  208120. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  208121. while (time.tv_nsec >= 1000000000)
  208122. {
  208123. time.tv_nsec -= 1000000000;
  208124. time.tv_sec++;
  208125. }
  208126. while (! timeout)
  208127. {
  208128. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  208129. if (! timeout)
  208130. // Success
  208131. break;
  208132. if (timeout == EINTR)
  208133. // Go round again
  208134. timeout = 0;
  208135. }
  208136. #endif
  208137. }
  208138. ok = es->triggered;
  208139. }
  208140. es->triggered = false;
  208141. pthread_mutex_unlock (&es->mutex);
  208142. return ok;
  208143. }
  208144. void WaitableEvent::signal() const throw()
  208145. {
  208146. EventStruct* const es = (EventStruct*) internal;
  208147. pthread_mutex_lock (&es->mutex);
  208148. es->triggered = true;
  208149. pthread_cond_broadcast (&es->condition);
  208150. pthread_mutex_unlock (&es->mutex);
  208151. }
  208152. void WaitableEvent::reset() const throw()
  208153. {
  208154. EventStruct* const es = (EventStruct*) internal;
  208155. pthread_mutex_lock (&es->mutex);
  208156. es->triggered = false;
  208157. pthread_mutex_unlock (&es->mutex);
  208158. }
  208159. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  208160. {
  208161. struct timespec time;
  208162. time.tv_sec = millisecs / 1000;
  208163. time.tv_nsec = (millisecs % 1000) * 1000000;
  208164. nanosleep (&time, 0);
  208165. }
  208166. const tchar File::separator = T('/');
  208167. const tchar* File::separatorString = T("/");
  208168. bool juce_copyFile (const String& s, const String& d) throw();
  208169. static bool juce_stat (const String& fileName, struct stat& info) throw()
  208170. {
  208171. return fileName.isNotEmpty()
  208172. && (stat (fileName.toUTF8(), &info) == 0);
  208173. }
  208174. bool juce_isDirectory (const String& fileName) throw()
  208175. {
  208176. struct stat info;
  208177. return fileName.isEmpty()
  208178. || (juce_stat (fileName, info)
  208179. && ((info.st_mode & S_IFDIR) != 0));
  208180. }
  208181. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  208182. {
  208183. if (fileName.isEmpty())
  208184. return false;
  208185. const char* const fileNameUTF8 = fileName.toUTF8();
  208186. bool exists = access (fileNameUTF8, F_OK) == 0;
  208187. if (exists && dontCountDirectories)
  208188. {
  208189. struct stat info;
  208190. const int res = stat (fileNameUTF8, &info);
  208191. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  208192. exists = false;
  208193. }
  208194. return exists;
  208195. }
  208196. int64 juce_getFileSize (const String& fileName) throw()
  208197. {
  208198. struct stat info;
  208199. return juce_stat (fileName, info) ? info.st_size : 0;
  208200. }
  208201. bool juce_canWriteToFile (const String& fileName) throw()
  208202. {
  208203. return access (fileName.toUTF8(), W_OK) == 0;
  208204. }
  208205. bool juce_deleteFile (const String& fileName) throw()
  208206. {
  208207. const char* const fileNameUTF8 = fileName.toUTF8();
  208208. if (juce_isDirectory (fileName))
  208209. return rmdir (fileNameUTF8) == 0;
  208210. else
  208211. return remove (fileNameUTF8) == 0;
  208212. }
  208213. bool juce_moveFile (const String& source, const String& dest) throw()
  208214. {
  208215. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  208216. return true;
  208217. if (juce_canWriteToFile (source)
  208218. && juce_copyFile (source, dest))
  208219. {
  208220. if (juce_deleteFile (source))
  208221. return true;
  208222. juce_deleteFile (dest);
  208223. }
  208224. return false;
  208225. }
  208226. void juce_createDirectory (const String& fileName) throw()
  208227. {
  208228. mkdir (fileName.toUTF8(), 0777);
  208229. }
  208230. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  208231. {
  208232. const char* const fileNameUTF8 = fileName.toUTF8();
  208233. int flags = O_RDONLY;
  208234. if (forWriting)
  208235. {
  208236. if (juce_fileExists (fileName, false))
  208237. {
  208238. const int f = open (fileNameUTF8, O_RDWR, 00644);
  208239. if (f != -1)
  208240. lseek (f, 0, SEEK_END);
  208241. return (void*) f;
  208242. }
  208243. else
  208244. {
  208245. flags = O_RDWR + O_CREAT;
  208246. }
  208247. }
  208248. return (void*) open (fileNameUTF8, flags, 00644);
  208249. }
  208250. void juce_fileClose (void* handle) throw()
  208251. {
  208252. if (handle != 0)
  208253. close ((int) (pointer_sized_int) handle);
  208254. }
  208255. int juce_fileRead (void* handle, void* buffer, int size) throw()
  208256. {
  208257. if (handle != 0)
  208258. return read ((int) (pointer_sized_int) handle, buffer, size);
  208259. return 0;
  208260. }
  208261. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  208262. {
  208263. if (handle != 0)
  208264. return write ((int) (pointer_sized_int) handle, buffer, size);
  208265. return 0;
  208266. }
  208267. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  208268. {
  208269. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  208270. return pos;
  208271. return -1;
  208272. }
  208273. int64 juce_fileGetPosition (void* handle) throw()
  208274. {
  208275. if (handle != 0)
  208276. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  208277. else
  208278. return -1;
  208279. }
  208280. void juce_fileFlush (void* handle) throw()
  208281. {
  208282. if (handle != 0)
  208283. fsync ((int) (pointer_sized_int) handle);
  208284. }
  208285. // if this file doesn't exist, find a parent of it that does..
  208286. static bool doStatFS (const File* file, struct statfs& result) throw()
  208287. {
  208288. File f (*file);
  208289. for (int i = 5; --i >= 0;)
  208290. {
  208291. if (f.exists())
  208292. break;
  208293. f = f.getParentDirectory();
  208294. }
  208295. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  208296. }
  208297. int64 File::getBytesFreeOnVolume() const throw()
  208298. {
  208299. int64 free_space = 0;
  208300. struct statfs buf;
  208301. if (doStatFS (this, buf))
  208302. // Note: this returns space available to non-super user
  208303. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  208304. return free_space;
  208305. }
  208306. const String juce_getVolumeLabel (const String& filenameOnVolume,
  208307. int& volumeSerialNumber) throw()
  208308. {
  208309. // There is no equivalent on Linux
  208310. volumeSerialNumber = 0;
  208311. return String::empty;
  208312. }
  208313. #if JUCE_64BIT
  208314. #define filedesc ((long long) internal)
  208315. #else
  208316. #define filedesc ((int) internal)
  208317. #endif
  208318. InterProcessLock::InterProcessLock (const String& name_) throw()
  208319. : internal (0),
  208320. name (name_),
  208321. reentrancyLevel (0)
  208322. {
  208323. #if JUCE_MAC
  208324. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  208325. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  208326. #else
  208327. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  208328. #endif
  208329. temp.create();
  208330. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  208331. }
  208332. InterProcessLock::~InterProcessLock() throw()
  208333. {
  208334. while (reentrancyLevel > 0)
  208335. this->exit();
  208336. close (filedesc);
  208337. }
  208338. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  208339. {
  208340. if (internal == 0)
  208341. return false;
  208342. if (reentrancyLevel != 0)
  208343. return true;
  208344. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  208345. struct flock fl;
  208346. zerostruct (fl);
  208347. fl.l_whence = SEEK_SET;
  208348. fl.l_type = F_WRLCK;
  208349. for (;;)
  208350. {
  208351. const int result = fcntl (filedesc, F_SETLK, &fl);
  208352. if (result >= 0)
  208353. {
  208354. ++reentrancyLevel;
  208355. return true;
  208356. }
  208357. if (errno != EINTR)
  208358. {
  208359. if (timeOutMillisecs == 0
  208360. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  208361. break;
  208362. Thread::sleep (10);
  208363. }
  208364. }
  208365. return false;
  208366. }
  208367. void InterProcessLock::exit() throw()
  208368. {
  208369. if (reentrancyLevel > 0 && internal != 0)
  208370. {
  208371. --reentrancyLevel;
  208372. struct flock fl;
  208373. zerostruct (fl);
  208374. fl.l_whence = SEEK_SET;
  208375. fl.l_type = F_UNLCK;
  208376. for (;;)
  208377. {
  208378. const int result = fcntl (filedesc, F_SETLKW, &fl);
  208379. if (result >= 0 || errno != EINTR)
  208380. break;
  208381. }
  208382. }
  208383. }
  208384. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  208385. static File executableFile;
  208386. void juce_getFileTimes (const String& fileName,
  208387. int64& modificationTime,
  208388. int64& accessTime,
  208389. int64& creationTime) throw()
  208390. {
  208391. modificationTime = 0;
  208392. accessTime = 0;
  208393. creationTime = 0;
  208394. struct stat info;
  208395. const int res = stat (fileName.toUTF8(), &info);
  208396. if (res == 0)
  208397. {
  208398. modificationTime = (int64) info.st_mtime * 1000;
  208399. accessTime = (int64) info.st_atime * 1000;
  208400. creationTime = (int64) info.st_ctime * 1000;
  208401. }
  208402. }
  208403. bool juce_setFileTimes (const String& fileName,
  208404. int64 modificationTime,
  208405. int64 accessTime,
  208406. int64 creationTime) throw()
  208407. {
  208408. struct utimbuf times;
  208409. times.actime = (time_t) (accessTime / 1000);
  208410. times.modtime = (time_t) (modificationTime / 1000);
  208411. return utime (fileName.toUTF8(), &times) == 0;
  208412. }
  208413. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  208414. {
  208415. struct stat info;
  208416. const int res = stat (fileName.toUTF8(), &info);
  208417. if (res != 0)
  208418. return false;
  208419. info.st_mode &= 0777; // Just permissions
  208420. if( isReadOnly )
  208421. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  208422. else
  208423. // Give everybody write permission?
  208424. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  208425. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  208426. }
  208427. bool juce_copyFile (const String& s, const String& d) throw()
  208428. {
  208429. const File source (s), dest (d);
  208430. FileInputStream* in = source.createInputStream();
  208431. bool ok = false;
  208432. if (in != 0)
  208433. {
  208434. if (dest.deleteFile())
  208435. {
  208436. FileOutputStream* const out = dest.createOutputStream();
  208437. if (out != 0)
  208438. {
  208439. const int bytesCopied = out->writeFromInputStream (*in, -1);
  208440. delete out;
  208441. ok = (bytesCopied == source.getSize());
  208442. if (! ok)
  208443. dest.deleteFile();
  208444. }
  208445. }
  208446. delete in;
  208447. }
  208448. return ok;
  208449. }
  208450. const StringArray juce_getFileSystemRoots() throw()
  208451. {
  208452. StringArray s;
  208453. s.add (T("/"));
  208454. return s;
  208455. }
  208456. bool File::isOnCDRomDrive() const throw()
  208457. {
  208458. struct statfs buf;
  208459. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  208460. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  208461. // Assume not if this fails for some reason
  208462. return false;
  208463. }
  208464. bool File::isOnHardDisk() const throw()
  208465. {
  208466. struct statfs buf;
  208467. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  208468. {
  208469. switch (buf.f_type)
  208470. {
  208471. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  208472. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  208473. case U_NFS_SUPER_MAGIC: // Network NFS
  208474. case U_SMB_SUPER_MAGIC: // Network Samba
  208475. return false;
  208476. default:
  208477. // Assume anything else is a hard-disk (but note it could
  208478. // be a RAM disk. There isn't a good way of determining
  208479. // this for sure)
  208480. return true;
  208481. }
  208482. }
  208483. // Assume so if this fails for some reason
  208484. return true;
  208485. }
  208486. bool File::isHidden() const throw()
  208487. {
  208488. return getFileName().startsWithChar (T('.'));
  208489. }
  208490. const File File::getSpecialLocation (const SpecialLocationType type)
  208491. {
  208492. switch (type)
  208493. {
  208494. case userHomeDirectory:
  208495. {
  208496. const char* homeDir = getenv ("HOME");
  208497. if (homeDir == 0)
  208498. {
  208499. struct passwd* const pw = getpwuid (getuid());
  208500. if (pw != 0)
  208501. homeDir = pw->pw_dir;
  208502. }
  208503. return File (String::fromUTF8 ((const uint8*) homeDir));
  208504. }
  208505. case userDocumentsDirectory:
  208506. case userMusicDirectory:
  208507. case userMoviesDirectory:
  208508. case userApplicationDataDirectory:
  208509. return File ("~");
  208510. case userDesktopDirectory:
  208511. return File ("~/Desktop");
  208512. case commonApplicationDataDirectory:
  208513. return File ("/var");
  208514. case globalApplicationsDirectory:
  208515. return File ("/usr");
  208516. case tempDirectory:
  208517. {
  208518. File tmp ("/var/tmp");
  208519. if (! tmp.isDirectory())
  208520. {
  208521. tmp = T("/tmp");
  208522. if (! tmp.isDirectory())
  208523. tmp = File::getCurrentWorkingDirectory();
  208524. }
  208525. return tmp;
  208526. }
  208527. case currentExecutableFile:
  208528. case currentApplicationFile:
  208529. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  208530. // was never called to set the filename - this should be done by the juce
  208531. // main() function, so maybe you've hacked it to use your own custom main()?
  208532. jassert (executableFile.exists());
  208533. return executableFile;
  208534. default:
  208535. jassertfalse // unknown type?
  208536. break;
  208537. }
  208538. return File::nonexistent;
  208539. }
  208540. void juce_setCurrentExecutableFileName (const String& filename) throw()
  208541. {
  208542. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  208543. }
  208544. const File File::getCurrentWorkingDirectory() throw()
  208545. {
  208546. char buf [2048];
  208547. getcwd (buf, sizeof(buf));
  208548. return File (String::fromUTF8 ((const uint8*) buf));
  208549. }
  208550. bool File::setAsCurrentWorkingDirectory() const throw()
  208551. {
  208552. return chdir (getFullPathName().toUTF8()) == 0;
  208553. }
  208554. struct FindFileStruct
  208555. {
  208556. String parentDir, wildCard;
  208557. DIR* dir;
  208558. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  208559. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  208560. {
  208561. const char* const wildcardUTF8 = wildCard.toUTF8();
  208562. for (;;)
  208563. {
  208564. struct dirent* const de = readdir (dir);
  208565. if (de == 0)
  208566. break;
  208567. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  208568. {
  208569. result = String::fromUTF8 ((const uint8*) de->d_name);
  208570. const String path (parentDir + result);
  208571. if (isDir != 0 || fileSize != 0)
  208572. {
  208573. struct stat info;
  208574. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  208575. if (isDir != 0)
  208576. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  208577. if (isHidden != 0)
  208578. *isHidden = (de->d_name[0] == '.');
  208579. if (fileSize != 0)
  208580. *fileSize = statOk ? info.st_size : 0;
  208581. }
  208582. if (modTime != 0 || creationTime != 0)
  208583. {
  208584. int64 m, a, c;
  208585. juce_getFileTimes (path, m, a, c);
  208586. if (modTime != 0)
  208587. *modTime = m;
  208588. if (creationTime != 0)
  208589. *creationTime = c;
  208590. }
  208591. if (isReadOnly != 0)
  208592. *isReadOnly = ! juce_canWriteToFile (path);
  208593. return true;
  208594. }
  208595. }
  208596. return false;
  208597. }
  208598. };
  208599. // returns 0 on failure
  208600. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  208601. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  208602. Time* creationTime, bool* isReadOnly) throw()
  208603. {
  208604. DIR* d = opendir (directory.toUTF8());
  208605. if (d != 0)
  208606. {
  208607. FindFileStruct* ff = new FindFileStruct();
  208608. ff->parentDir = directory;
  208609. if (!ff->parentDir.endsWithChar (File::separator))
  208610. ff->parentDir += File::separator;
  208611. ff->wildCard = wildCard;
  208612. if (wildCard == T("*.*"))
  208613. ff->wildCard = T("*");
  208614. ff->dir = d;
  208615. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  208616. {
  208617. return ff;
  208618. }
  208619. else
  208620. {
  208621. firstResultFile = String::empty;
  208622. isDir = false;
  208623. isHidden = false;
  208624. closedir (d);
  208625. delete ff;
  208626. }
  208627. }
  208628. return 0;
  208629. }
  208630. bool juce_findFileNext (void* handle, String& resultFile,
  208631. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  208632. {
  208633. FindFileStruct* const ff = (FindFileStruct*) handle;
  208634. if (ff != 0)
  208635. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  208636. return false;
  208637. }
  208638. void juce_findFileClose (void* handle) throw()
  208639. {
  208640. FindFileStruct* const ff = (FindFileStruct*) handle;
  208641. if (ff != 0)
  208642. {
  208643. closedir (ff->dir);
  208644. delete ff;
  208645. }
  208646. }
  208647. bool juce_launchFile (const String& fileName,
  208648. const String& parameters) throw()
  208649. {
  208650. String cmdString (fileName);
  208651. cmdString << " " << parameters;
  208652. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  208653. {
  208654. // create a command that tries to launch a bunch of likely browsers
  208655. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  208656. StringArray cmdLines;
  208657. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  208658. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  208659. cmdString = cmdLines.joinIntoString (T(" || "));
  208660. }
  208661. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  208662. const int cpid = fork();
  208663. if (cpid == 0)
  208664. {
  208665. setsid();
  208666. // Child process
  208667. execve (argv[0], argv, environ);
  208668. exit (0);
  208669. }
  208670. return cpid >= 0;
  208671. }
  208672. END_JUCE_NAMESPACE
  208673. /********* End of inlined file: juce_linux_Files.cpp *********/
  208674. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  208675. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  208676. #include <sys/stat.h>
  208677. #include <sys/dir.h>
  208678. #include <fcntl.h>
  208679. // As well as being for the mac, this file is included by the linux build.
  208680. #if JUCE_MAC
  208681. #include <Carbon/Carbon.h>
  208682. #else
  208683. #include <sys/wait.h>
  208684. #include <errno.h>
  208685. #include <unistd.h>
  208686. #endif
  208687. BEGIN_JUCE_NAMESPACE
  208688. struct NamedPipeInternal
  208689. {
  208690. String pipeInName, pipeOutName;
  208691. int pipeIn, pipeOut;
  208692. bool volatile createdPipe, blocked, stopReadOperation;
  208693. static void signalHandler (int) {}
  208694. };
  208695. void NamedPipe::cancelPendingReads()
  208696. {
  208697. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  208698. {
  208699. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208700. intern->stopReadOperation = true;
  208701. char buffer [1] = { 0 };
  208702. ::write (intern->pipeIn, buffer, 1);
  208703. int timeout = 2000;
  208704. while (intern->blocked && --timeout >= 0)
  208705. sleep (2);
  208706. intern->stopReadOperation = false;
  208707. }
  208708. }
  208709. void NamedPipe::close()
  208710. {
  208711. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208712. if (intern != 0)
  208713. {
  208714. internal = 0;
  208715. if (intern->pipeIn != -1)
  208716. ::close (intern->pipeIn);
  208717. if (intern->pipeOut != -1)
  208718. ::close (intern->pipeOut);
  208719. if (intern->createdPipe)
  208720. {
  208721. unlink (intern->pipeInName);
  208722. unlink (intern->pipeOutName);
  208723. }
  208724. delete intern;
  208725. }
  208726. }
  208727. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  208728. {
  208729. close();
  208730. NamedPipeInternal* const intern = new NamedPipeInternal();
  208731. internal = intern;
  208732. intern->createdPipe = createPipe;
  208733. intern->blocked = false;
  208734. intern->stopReadOperation = false;
  208735. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  208736. siginterrupt (SIGPIPE, 1);
  208737. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  208738. intern->pipeInName = pipePath + T("_in");
  208739. intern->pipeOutName = pipePath + T("_out");
  208740. intern->pipeIn = -1;
  208741. intern->pipeOut = -1;
  208742. if (createPipe)
  208743. {
  208744. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  208745. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  208746. {
  208747. delete intern;
  208748. internal = 0;
  208749. return false;
  208750. }
  208751. }
  208752. return true;
  208753. }
  208754. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  208755. {
  208756. int bytesRead = -1;
  208757. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208758. if (intern != 0)
  208759. {
  208760. intern->blocked = true;
  208761. if (intern->pipeIn == -1)
  208762. {
  208763. if (intern->createdPipe)
  208764. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  208765. else
  208766. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  208767. if (intern->pipeIn == -1)
  208768. {
  208769. intern->blocked = false;
  208770. return -1;
  208771. }
  208772. }
  208773. bytesRead = 0;
  208774. char* p = (char*) destBuffer;
  208775. while (bytesRead < maxBytesToRead)
  208776. {
  208777. const int bytesThisTime = maxBytesToRead - bytesRead;
  208778. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  208779. if (numRead <= 0 || intern->stopReadOperation)
  208780. {
  208781. bytesRead = -1;
  208782. break;
  208783. }
  208784. bytesRead += numRead;
  208785. p += bytesRead;
  208786. }
  208787. intern->blocked = false;
  208788. }
  208789. return bytesRead;
  208790. }
  208791. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  208792. {
  208793. int bytesWritten = -1;
  208794. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208795. if (intern != 0)
  208796. {
  208797. if (intern->pipeOut == -1)
  208798. {
  208799. if (intern->createdPipe)
  208800. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  208801. else
  208802. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  208803. if (intern->pipeOut == -1)
  208804. {
  208805. return -1;
  208806. }
  208807. }
  208808. const char* p = (const char*) sourceBuffer;
  208809. bytesWritten = 0;
  208810. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  208811. while (bytesWritten < numBytesToWrite
  208812. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  208813. {
  208814. const int bytesThisTime = numBytesToWrite - bytesWritten;
  208815. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  208816. if (numWritten <= 0)
  208817. {
  208818. bytesWritten = -1;
  208819. break;
  208820. }
  208821. bytesWritten += numWritten;
  208822. p += bytesWritten;
  208823. }
  208824. }
  208825. return bytesWritten;
  208826. }
  208827. END_JUCE_NAMESPACE
  208828. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  208829. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  208830. /********* Start of inlined file: juce_linux_Network.cpp *********/
  208831. #include <netdb.h>
  208832. #include <arpa/inet.h>
  208833. #include <netinet/in.h>
  208834. #include <sys/types.h>
  208835. #include <sys/ioctl.h>
  208836. #include <sys/socket.h>
  208837. #include <sys/wait.h>
  208838. #include <linux/if.h>
  208839. BEGIN_JUCE_NAMESPACE
  208840. // we'll borrow the mac's socket-based http streaming code..
  208841. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  208842. // (This file gets included by the mac + linux networking code)
  208843. /** A HTTP input stream that uses sockets.
  208844. */
  208845. class JUCE_HTTPSocketStream
  208846. {
  208847. public:
  208848. JUCE_HTTPSocketStream()
  208849. : readPosition (0),
  208850. socketHandle (-1),
  208851. levelsOfRedirection (0),
  208852. timeoutSeconds (15)
  208853. {
  208854. }
  208855. ~JUCE_HTTPSocketStream()
  208856. {
  208857. closeSocket();
  208858. }
  208859. bool open (const String& url,
  208860. const String& headers,
  208861. const MemoryBlock& postData,
  208862. const bool isPost,
  208863. URL::OpenStreamProgressCallback* callback,
  208864. void* callbackContext)
  208865. {
  208866. closeSocket();
  208867. String hostName, hostPath;
  208868. int hostPort;
  208869. if (! decomposeURL (url, hostName, hostPath, hostPort))
  208870. return false;
  208871. struct hostent* const host
  208872. = gethostbyname ((const char*) hostName.toUTF8());
  208873. if (host == 0)
  208874. return false;
  208875. struct sockaddr_in address;
  208876. zerostruct (address);
  208877. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  208878. address.sin_family = host->h_addrtype;
  208879. address.sin_port = htons (hostPort);
  208880. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  208881. if (socketHandle == -1)
  208882. return false;
  208883. int receiveBufferSize = 16384;
  208884. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  208885. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  208886. #if JUCE_MAC
  208887. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  208888. #endif
  208889. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  208890. {
  208891. closeSocket();
  208892. return false;
  208893. }
  208894. String proxyURL (getenv ("http_proxy"));
  208895. if (! proxyURL.startsWithIgnoreCase (T("http://")))
  208896. proxyURL = String::empty;
  208897. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPath,
  208898. proxyURL, url,
  208899. hostPort,
  208900. headers, postData,
  208901. isPost));
  208902. int totalHeaderSent = 0;
  208903. while (totalHeaderSent < requestHeader.getSize())
  208904. {
  208905. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  208906. if (send (socketHandle,
  208907. ((const char*) requestHeader.getData()) + totalHeaderSent,
  208908. numToSend, 0)
  208909. != numToSend)
  208910. {
  208911. closeSocket();
  208912. return false;
  208913. }
  208914. totalHeaderSent += numToSend;
  208915. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  208916. {
  208917. closeSocket();
  208918. return false;
  208919. }
  208920. }
  208921. const String responseHeader (readResponse());
  208922. if (responseHeader.isNotEmpty())
  208923. {
  208924. //DBG (responseHeader);
  208925. StringArray lines;
  208926. lines.addLines (responseHeader);
  208927. // NB - using charToString() here instead of just T(" "), because that was
  208928. // causing a mysterious gcc internal compiler error...
  208929. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  208930. .substring (0, 3)
  208931. .getIntValue();
  208932. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  208933. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  208934. String location (findHeaderItem (lines, T("Location:")));
  208935. if (statusCode >= 300 && statusCode < 400
  208936. && location.isNotEmpty())
  208937. {
  208938. if (! location.startsWithIgnoreCase (T("http://")))
  208939. location = T("http://") + location;
  208940. if (levelsOfRedirection++ < 3)
  208941. return open (location, headers, postData, isPost, callback, callbackContext);
  208942. }
  208943. else
  208944. {
  208945. levelsOfRedirection = 0;
  208946. return true;
  208947. }
  208948. }
  208949. closeSocket();
  208950. return false;
  208951. }
  208952. int read (void* buffer, int bytesToRead)
  208953. {
  208954. fd_set readbits;
  208955. FD_ZERO (&readbits);
  208956. FD_SET (socketHandle, &readbits);
  208957. struct timeval tv;
  208958. tv.tv_sec = timeoutSeconds;
  208959. tv.tv_usec = 0;
  208960. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  208961. return 0; // (timeout)
  208962. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  208963. readPosition += bytesRead;
  208964. return bytesRead;
  208965. }
  208966. int readPosition;
  208967. juce_UseDebuggingNewOperator
  208968. private:
  208969. int socketHandle, levelsOfRedirection;
  208970. const int timeoutSeconds;
  208971. void closeSocket()
  208972. {
  208973. if (socketHandle >= 0)
  208974. close (socketHandle);
  208975. socketHandle = -1;
  208976. }
  208977. const MemoryBlock createRequestHeader (const String& hostName,
  208978. const String& hostPath,
  208979. const String& proxyURL,
  208980. const String& originalURL,
  208981. const int hostPort,
  208982. const String& headers,
  208983. const MemoryBlock& postData,
  208984. const bool isPost)
  208985. {
  208986. String header (isPost ? "POST " : "GET ");
  208987. if (proxyURL.isEmpty())
  208988. {
  208989. header << hostPath << " HTTP/1.0\r\nHost: "
  208990. << hostName << ':' << hostPort;
  208991. }
  208992. else
  208993. {
  208994. String proxyName, proxyPath;
  208995. int proxyPort;
  208996. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  208997. return MemoryBlock();
  208998. header << originalURL << " HTTP/1.0\r\nHost: "
  208999. << proxyName << ':' << proxyPort;
  209000. /* xxx needs finishing
  209001. const char* proxyAuth = getenv ("http_proxy_auth");
  209002. if (proxyAuth != 0)
  209003. header << T("\r\nProxy-Authorization: ") << Base64Encode (proxyAuth);
  209004. */
  209005. }
  209006. header << "\r\nUser-Agent: JUCE/"
  209007. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  209008. << "\r\nConnection: Close\r\nContent-Length: "
  209009. << postData.getSize() << "\r\n"
  209010. << headers << "\r\n";
  209011. MemoryBlock mb;
  209012. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  209013. mb.append (postData.getData(), postData.getSize());
  209014. return mb;
  209015. }
  209016. const String readResponse()
  209017. {
  209018. int bytesRead = 0, numConsecutiveLFs = 0;
  209019. MemoryBlock buffer (1024, true);
  209020. while (numConsecutiveLFs < 2 && bytesRead < 32768)
  209021. {
  209022. fd_set readbits;
  209023. FD_ZERO (&readbits);
  209024. FD_SET (socketHandle, &readbits);
  209025. struct timeval tv;
  209026. tv.tv_sec = timeoutSeconds;
  209027. tv.tv_usec = 0;
  209028. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209029. return String::empty; // (timeout)
  209030. buffer.ensureSize (bytesRead + 8, true);
  209031. char* const dest = (char*) buffer.getData() + bytesRead;
  209032. if (recv (socketHandle, dest, 1, 0) == -1)
  209033. return String::empty;
  209034. const char lastByte = *dest;
  209035. ++bytesRead;
  209036. if (lastByte == '\n')
  209037. ++numConsecutiveLFs;
  209038. else if (lastByte != '\r')
  209039. numConsecutiveLFs = 0;
  209040. }
  209041. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  209042. if (header.startsWithIgnoreCase (T("HTTP/")))
  209043. return header.trimEnd();
  209044. return String::empty;
  209045. }
  209046. static bool decomposeURL (const String& url,
  209047. String& host, String& path, int& port)
  209048. {
  209049. if (! url.startsWithIgnoreCase (T("http://")))
  209050. return false;
  209051. const int nextSlash = url.indexOfChar (7, '/');
  209052. int nextColon = url.indexOfChar (7, ':');
  209053. if (nextColon > nextSlash && nextSlash > 0)
  209054. nextColon = -1;
  209055. if (nextColon >= 0)
  209056. {
  209057. host = url.substring (7, nextColon);
  209058. if (nextSlash >= 0)
  209059. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  209060. else
  209061. port = url.substring (nextColon + 1).getIntValue();
  209062. }
  209063. else
  209064. {
  209065. port = 80;
  209066. if (nextSlash >= 0)
  209067. host = url.substring (7, nextSlash);
  209068. else
  209069. host = url.substring (7);
  209070. }
  209071. if (nextSlash >= 0)
  209072. path = url.substring (nextSlash);
  209073. else
  209074. path = T("/");
  209075. return true;
  209076. }
  209077. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  209078. {
  209079. for (int i = 0; i < lines.size(); ++i)
  209080. if (lines[i].startsWithIgnoreCase (itemName))
  209081. return lines[i].substring (itemName.length()).trim();
  209082. return String::empty;
  209083. }
  209084. };
  209085. bool juce_isOnLine()
  209086. {
  209087. return true;
  209088. }
  209089. void* juce_openInternetFile (const String& url,
  209090. const String& headers,
  209091. const MemoryBlock& postData,
  209092. const bool isPost,
  209093. URL::OpenStreamProgressCallback* callback,
  209094. void* callbackContext)
  209095. {
  209096. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  209097. if (s->open (url, headers, postData, isPost,
  209098. callback, callbackContext))
  209099. return s;
  209100. delete s;
  209101. return 0;
  209102. }
  209103. void juce_closeInternetFile (void* handle)
  209104. {
  209105. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209106. if (s != 0)
  209107. delete s;
  209108. }
  209109. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  209110. {
  209111. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209112. if (s != 0)
  209113. return s->read (buffer, bytesToRead);
  209114. return 0;
  209115. }
  209116. int juce_seekInInternetFile (void* handle, int newPosition)
  209117. {
  209118. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209119. if (s != 0)
  209120. return s->readPosition;
  209121. return 0;
  209122. }
  209123. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  209124. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  209125. {
  209126. int numResults = 0;
  209127. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  209128. if (s != -1)
  209129. {
  209130. char buf [1024];
  209131. struct ifconf ifc;
  209132. ifc.ifc_len = sizeof (buf);
  209133. ifc.ifc_buf = buf;
  209134. ioctl (s, SIOCGIFCONF, &ifc);
  209135. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  209136. {
  209137. struct ifreq ifr;
  209138. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  209139. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  209140. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  209141. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  209142. && numResults < maxNum)
  209143. {
  209144. int64 a = 0;
  209145. for (int j = 6; --j >= 0;)
  209146. a = (a << 8) | ifr.ifr_hwaddr.sa_data[j];
  209147. *addresses++ = a;
  209148. ++numResults;
  209149. }
  209150. }
  209151. close (s);
  209152. }
  209153. return numResults;
  209154. }
  209155. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  209156. const String& emailSubject,
  209157. const String& bodyText,
  209158. const StringArray& filesToAttach)
  209159. {
  209160. jassertfalse // xxx todo
  209161. return false;
  209162. }
  209163. END_JUCE_NAMESPACE
  209164. /********* End of inlined file: juce_linux_Network.cpp *********/
  209165. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  209166. #include <sys/sysinfo.h>
  209167. #include <dlfcn.h>
  209168. #ifndef CPU_ISSET
  209169. #undef SUPPORT_AFFINITIES
  209170. #endif
  209171. BEGIN_JUCE_NAMESPACE
  209172. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  209173. {
  209174. unsigned int cpu = 0;
  209175. unsigned int ext = 0;
  209176. unsigned int family = 0;
  209177. unsigned int dummy = 0;
  209178. #if JUCE_64BIT
  209179. __asm__ ("cpuid"
  209180. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209181. #else
  209182. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  209183. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209184. #endif
  209185. if (familyModel != 0)
  209186. *familyModel = family;
  209187. if (extFeatures != 0)
  209188. *extFeatures = ext;
  209189. return cpu;
  209190. }*/
  209191. void Logger::outputDebugString (const String& text) throw()
  209192. {
  209193. fprintf (stdout, text.toUTF8());
  209194. fprintf (stdout, "\n");
  209195. }
  209196. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  209197. {
  209198. String text;
  209199. va_list args;
  209200. va_start (args, format);
  209201. text.vprintf(format, args);
  209202. outputDebugString(text);
  209203. }
  209204. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  209205. {
  209206. return Linux;
  209207. }
  209208. const String SystemStats::getOperatingSystemName() throw()
  209209. {
  209210. return T("Linux");
  209211. }
  209212. bool SystemStats::isOperatingSystem64Bit() throw()
  209213. {
  209214. #if JUCE_64BIT
  209215. return true;
  209216. #else
  209217. //xxx not sure how to find this out?..
  209218. return false;
  209219. #endif
  209220. }
  209221. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  209222. {
  209223. String info;
  209224. char buf [256];
  209225. FILE* f = fopen ("/proc/cpuinfo", "r");
  209226. while (f != 0 && fgets (buf, sizeof(buf), f))
  209227. {
  209228. if (strncmp (buf, key, strlen (key)) == 0)
  209229. {
  209230. char* p = buf;
  209231. while (*p && *p != '\n')
  209232. ++p;
  209233. if (*p != 0)
  209234. *p = 0;
  209235. p = buf;
  209236. while (*p != 0 && *p != ':')
  209237. ++p;
  209238. if (*p != 0 && *(p + 1) != 0)
  209239. info = p + 2;
  209240. if (! lastOne)
  209241. break;
  209242. }
  209243. }
  209244. fclose (f);
  209245. return info;
  209246. }
  209247. bool SystemStats::hasMMX() throw()
  209248. {
  209249. return getCpuInfo ("flags").contains (T("mmx"));
  209250. }
  209251. bool SystemStats::hasSSE() throw()
  209252. {
  209253. return getCpuInfo ("flags").contains (T("sse"));
  209254. }
  209255. bool SystemStats::hasSSE2() throw()
  209256. {
  209257. return getCpuInfo ("flags").contains (T("sse2"));
  209258. }
  209259. bool SystemStats::has3DNow() throw()
  209260. {
  209261. return getCpuInfo ("flags").contains (T("3dnow"));
  209262. }
  209263. const String SystemStats::getCpuVendor() throw()
  209264. {
  209265. return getCpuInfo ("vendor_id");
  209266. }
  209267. int SystemStats::getCpuSpeedInMegaherz() throw()
  209268. {
  209269. const String speed (getCpuInfo ("cpu MHz"));
  209270. return (int) (speed.getFloatValue() + 0.5f);
  209271. }
  209272. int SystemStats::getMemorySizeInMegabytes() throw()
  209273. {
  209274. struct sysinfo sysi;
  209275. if (sysinfo (&sysi) == 0)
  209276. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  209277. return 0;
  209278. }
  209279. uint32 juce_millisecondsSinceStartup() throw()
  209280. {
  209281. static unsigned int calibrate = 0;
  209282. static bool calibrated = false;
  209283. timeval t;
  209284. unsigned int ret = 0;
  209285. if (! gettimeofday (&t, 0))
  209286. {
  209287. if (! calibrated)
  209288. {
  209289. struct sysinfo sysi;
  209290. if (sysinfo (&sysi) == 0)
  209291. // Safe to assume system was not brought up earlier than 1970!
  209292. calibrate = t.tv_sec - sysi.uptime;
  209293. calibrated = true;
  209294. }
  209295. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  209296. }
  209297. return ret;
  209298. }
  209299. double Time::getMillisecondCounterHiRes() throw()
  209300. {
  209301. return getHighResolutionTicks() * 0.001;
  209302. }
  209303. int64 Time::getHighResolutionTicks() throw()
  209304. {
  209305. timeval t;
  209306. if (gettimeofday (&t, 0))
  209307. return 0;
  209308. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  209309. }
  209310. int64 Time::getHighResolutionTicksPerSecond() throw()
  209311. {
  209312. // Microseconds
  209313. return 1000000;
  209314. }
  209315. bool Time::setSystemTimeToThisTime() const throw()
  209316. {
  209317. timeval t;
  209318. t.tv_sec = millisSinceEpoch % 1000000;
  209319. t.tv_usec = millisSinceEpoch - t.tv_sec;
  209320. return settimeofday (&t, NULL) ? false : true;
  209321. }
  209322. int SystemStats::getPageSize() throw()
  209323. {
  209324. static int systemPageSize = 0;
  209325. if (systemPageSize == 0)
  209326. systemPageSize = sysconf (_SC_PAGESIZE);
  209327. return systemPageSize;
  209328. }
  209329. int SystemStats::getNumCpus() throw()
  209330. {
  209331. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  209332. return lastCpu + 1;
  209333. }
  209334. void SystemStats::initialiseStats() throw()
  209335. {
  209336. // Process starts off as root when running suid
  209337. Process::lowerPrivilege();
  209338. String s (SystemStats::getJUCEVersion());
  209339. }
  209340. void PlatformUtilities::fpuReset()
  209341. {
  209342. }
  209343. END_JUCE_NAMESPACE
  209344. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  209345. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  209346. #include <dlfcn.h>
  209347. #include <sys/file.h>
  209348. #include <sys/types.h>
  209349. #include <sys/ptrace.h>
  209350. BEGIN_JUCE_NAMESPACE
  209351. /*
  209352. Note that a lot of methods that you'd expect to find in this file actually
  209353. live in juce_posix_SharedCode.cpp!
  209354. */
  209355. #ifndef CPU_ISSET
  209356. #undef SUPPORT_AFFINITIES
  209357. #endif
  209358. void JUCE_API juce_threadEntryPoint (void*);
  209359. void* threadEntryProc (void* value) throw()
  209360. {
  209361. // New threads start off as root when running suid
  209362. Process::lowerPrivilege();
  209363. juce_threadEntryPoint (value);
  209364. return 0;
  209365. }
  209366. void* juce_createThread (void* userData) throw()
  209367. {
  209368. pthread_t handle = 0;
  209369. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  209370. {
  209371. pthread_detach (handle);
  209372. return (void*)handle;
  209373. }
  209374. return 0;
  209375. }
  209376. void juce_killThread (void* handle) throw()
  209377. {
  209378. if (handle != 0)
  209379. pthread_cancel ((pthread_t)handle);
  209380. }
  209381. void juce_setCurrentThreadName (const String& /*name*/) throw()
  209382. {
  209383. }
  209384. int Thread::getCurrentThreadId() throw()
  209385. {
  209386. return (int) pthread_self();
  209387. }
  209388. /*
  209389. * This is all a bit non-ideal... the trouble is that on Linux you
  209390. * need to call setpriority to affect the dynamic priority for
  209391. * non-realtime processes, but this requires the pid, which is not
  209392. * accessible from the pthread_t. We could get it by calling getpid
  209393. * once each thread has started, but then we would need a list of
  209394. * running threads etc etc.
  209395. * Also there is no such thing as IDLE priority on Linux.
  209396. * For the moment, map idle, low and normal process priorities to
  209397. * SCHED_OTHER, with the thread priority ignored for these classes.
  209398. * Map high priority processes to the lower half of the SCHED_RR
  209399. * range, and realtime to the upper half
  209400. */
  209401. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  209402. // priority of the current thread
  209403. void juce_setThreadPriority (void* handle, int priority) throw()
  209404. {
  209405. struct sched_param param;
  209406. int policy, maxp, minp, pri;
  209407. if (handle == 0)
  209408. handle = (void*) pthread_self();
  209409. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  209410. && policy != SCHED_OTHER)
  209411. {
  209412. minp = sched_get_priority_min(policy);
  209413. maxp = sched_get_priority_max(policy);
  209414. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  209415. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  209416. // Realtime process priority
  209417. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  209418. else
  209419. // High process priority
  209420. param.__sched_priority = minp + pri;
  209421. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  209422. pthread_setschedparam ((pthread_t) handle, policy, &param);
  209423. }
  209424. }
  209425. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  209426. {
  209427. #if SUPPORT_AFFINITIES
  209428. cpu_set_t affinity;
  209429. CPU_ZERO (&affinity);
  209430. for (int i = 0; i < 32; ++i)
  209431. if ((affinityMask & (1 << i)) != 0)
  209432. CPU_SET (i, &affinity);
  209433. /*
  209434. N.B. If this line causes a compile error, then you've probably not got the latest
  209435. version of glibc installed.
  209436. If you don't want to update your copy of glibc and don't care about cpu affinities,
  209437. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  209438. from the linuxincludes.h file.
  209439. */
  209440. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  209441. sched_yield();
  209442. #else
  209443. /* affinities aren't supported because either the appropriate header files weren't found,
  209444. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  209445. */
  209446. jassertfalse
  209447. #endif
  209448. }
  209449. void Thread::yield() throw()
  209450. {
  209451. sched_yield();
  209452. }
  209453. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  209454. void Process::setPriority (ProcessPriority prior)
  209455. {
  209456. struct sched_param param;
  209457. int policy, maxp, minp;
  209458. const int p = (int) prior;
  209459. if (p <= 1)
  209460. policy = SCHED_OTHER;
  209461. else
  209462. policy = SCHED_RR;
  209463. minp = sched_get_priority_min (policy);
  209464. maxp = sched_get_priority_max (policy);
  209465. if (p < 2)
  209466. param.__sched_priority = 0;
  209467. else if (p == 2 )
  209468. // Set to middle of lower realtime priority range
  209469. param.__sched_priority = minp + (maxp - minp) / 4;
  209470. else
  209471. // Set to middle of higher realtime priority range
  209472. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  209473. pthread_setschedparam (pthread_self(), policy, &param);
  209474. }
  209475. void Process::terminate()
  209476. {
  209477. exit (0);
  209478. }
  209479. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  209480. {
  209481. static char testResult = 0;
  209482. if (testResult == 0)
  209483. {
  209484. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  209485. if (testResult >= 0)
  209486. {
  209487. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  209488. testResult = 1;
  209489. }
  209490. }
  209491. return testResult < 0;
  209492. }
  209493. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  209494. {
  209495. return juce_isRunningUnderDebugger();
  209496. }
  209497. void Process::raisePrivilege()
  209498. {
  209499. // If running suid root, change effective user
  209500. // to root
  209501. if (geteuid() != 0 && getuid() == 0)
  209502. {
  209503. setreuid (geteuid(), getuid());
  209504. setregid (getegid(), getgid());
  209505. }
  209506. }
  209507. void Process::lowerPrivilege()
  209508. {
  209509. // If runing suid root, change effective user
  209510. // back to real user
  209511. if (geteuid() == 0 && getuid() != 0)
  209512. {
  209513. setreuid (geteuid(), getuid());
  209514. setregid (getegid(), getgid());
  209515. }
  209516. }
  209517. #if JUCE_BUILD_GUI_CLASSES
  209518. void* Process::loadDynamicLibrary (const String& name)
  209519. {
  209520. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  209521. }
  209522. void Process::freeDynamicLibrary (void* handle)
  209523. {
  209524. dlclose(handle);
  209525. }
  209526. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  209527. {
  209528. return dlsym (libraryHandle, (const char*) procedureName);
  209529. }
  209530. #endif
  209531. END_JUCE_NAMESPACE
  209532. /********* End of inlined file: juce_linux_Threads.cpp *********/
  209533. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  209534. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  209535. #if JUCE_BUILD_GUI_CLASSES
  209536. #if JUCE_ALSA
  209537. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  209538. not got your paths set up correctly to find its header files.
  209539. The package you need to install to get ASLA support is "libasound2-dev".
  209540. If you don't have the ALSA library and don't want to build Juce with audio support,
  209541. just disable the JUCE_ALSA flag in juce_Config.h
  209542. */
  209543. #include <alsa/asoundlib.h>
  209544. BEGIN_JUCE_NAMESPACE
  209545. static const int maxNumChans = 64;
  209546. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  209547. {
  209548. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  209549. snd_pcm_hw_params_t* hwParams;
  209550. snd_pcm_hw_params_alloca (&hwParams);
  209551. for (int i = 0; ratesToTry[i] != 0; ++i)
  209552. {
  209553. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  209554. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  209555. {
  209556. rates.add (ratesToTry[i]);
  209557. }
  209558. }
  209559. }
  209560. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  209561. {
  209562. snd_pcm_hw_params_t *params;
  209563. snd_pcm_hw_params_alloca (&params);
  209564. if (snd_pcm_hw_params_any (handle, params) >= 0)
  209565. {
  209566. snd_pcm_hw_params_get_channels_min (params, minChans);
  209567. snd_pcm_hw_params_get_channels_max (params, maxChans);
  209568. }
  209569. }
  209570. static void getDeviceProperties (const String& id,
  209571. unsigned int& minChansOut,
  209572. unsigned int& maxChansOut,
  209573. unsigned int& minChansIn,
  209574. unsigned int& maxChansIn,
  209575. Array <int>& rates)
  209576. {
  209577. snd_ctl_t* handle;
  209578. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  209579. {
  209580. snd_pcm_info_t* info;
  209581. snd_pcm_info_alloca (&info);
  209582. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  209583. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  209584. snd_pcm_info_set_subdevice (info, 0);
  209585. if (snd_ctl_pcm_info (handle, info) >= 0)
  209586. {
  209587. snd_pcm_t* pcmHandle;
  209588. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  209589. {
  209590. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  209591. getDeviceSampleRates (pcmHandle, rates);
  209592. snd_pcm_close (pcmHandle);
  209593. }
  209594. }
  209595. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  209596. if (snd_ctl_pcm_info (handle, info) >= 0)
  209597. {
  209598. snd_pcm_t* pcmHandle;
  209599. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  209600. {
  209601. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  209602. if (rates.size() == 0)
  209603. getDeviceSampleRates (pcmHandle, rates);
  209604. snd_pcm_close (pcmHandle);
  209605. }
  209606. }
  209607. snd_ctl_close (handle);
  209608. }
  209609. }
  209610. class ALSADevice
  209611. {
  209612. public:
  209613. ALSADevice (const String& deviceName,
  209614. const bool forInput)
  209615. : handle (0),
  209616. bitDepth (16),
  209617. numChannelsRunning (0),
  209618. isInput (forInput),
  209619. sampleFormat (AudioDataConverters::int16LE)
  209620. {
  209621. failed (snd_pcm_open (&handle, deviceName,
  209622. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  209623. SND_PCM_ASYNC));
  209624. }
  209625. ~ALSADevice()
  209626. {
  209627. if (handle != 0)
  209628. snd_pcm_close (handle);
  209629. }
  209630. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  209631. {
  209632. if (handle == 0)
  209633. return false;
  209634. snd_pcm_hw_params_t* hwParams;
  209635. snd_pcm_hw_params_alloca (&hwParams);
  209636. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  209637. return false;
  209638. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  209639. isInterleaved = false;
  209640. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  209641. isInterleaved = true;
  209642. else
  209643. {
  209644. jassertfalse
  209645. return false;
  209646. }
  209647. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  209648. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  209649. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  209650. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  209651. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  209652. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  209653. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  209654. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  209655. bitDepth = 0;
  209656. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  209657. {
  209658. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  209659. {
  209660. bitDepth = formatsToTry [i + 1];
  209661. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  209662. break;
  209663. }
  209664. }
  209665. if (bitDepth == 0)
  209666. {
  209667. error = "device doesn't support a compatible PCM format";
  209668. DBG (T("ALSA error: ") + error + T("\n"));
  209669. return false;
  209670. }
  209671. int dir = 0;
  209672. unsigned int periods = 4;
  209673. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  209674. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  209675. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  209676. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  209677. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  209678. || failed (snd_pcm_hw_params (handle, hwParams)))
  209679. {
  209680. return false;
  209681. }
  209682. snd_pcm_sw_params_t* swParams;
  209683. snd_pcm_sw_params_alloca (&swParams);
  209684. if (failed (snd_pcm_sw_params_current (handle, swParams))
  209685. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  209686. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  209687. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  209688. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  209689. || failed (snd_pcm_sw_params (handle, swParams)))
  209690. {
  209691. return false;
  209692. }
  209693. /*
  209694. #ifdef JUCE_DEBUG
  209695. // enable this to dump the config of the devices that get opened
  209696. snd_output_t* out;
  209697. snd_output_stdio_attach (&out, stderr, 0);
  209698. snd_pcm_hw_params_dump (hwParams, out);
  209699. snd_pcm_sw_params_dump (swParams, out);
  209700. #endif
  209701. */
  209702. numChannelsRunning = numChannels;
  209703. return true;
  209704. }
  209705. bool write (float** const data, const int numSamples)
  209706. {
  209707. if (isInterleaved)
  209708. {
  209709. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  209710. float* interleaved = (float*) scratch;
  209711. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  209712. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  209713. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  209714. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  209715. return false;
  209716. }
  209717. else
  209718. {
  209719. for (int i = 0; i < numChannelsRunning; ++i)
  209720. if (data[i] != 0)
  209721. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  209722. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  209723. if (failed (num))
  209724. {
  209725. if (num == -EPIPE)
  209726. {
  209727. if (failed (snd_pcm_prepare (handle)))
  209728. return false;
  209729. }
  209730. else if (num != -ESTRPIPE)
  209731. return false;
  209732. }
  209733. }
  209734. return true;
  209735. }
  209736. bool read (float** const data, const int numSamples)
  209737. {
  209738. if (isInterleaved)
  209739. {
  209740. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  209741. float* interleaved = (float*) scratch;
  209742. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  209743. if (failed (num))
  209744. {
  209745. if (num == -EPIPE)
  209746. {
  209747. if (failed (snd_pcm_prepare (handle)))
  209748. return false;
  209749. }
  209750. else if (num != -ESTRPIPE)
  209751. return false;
  209752. }
  209753. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  209754. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  209755. }
  209756. else
  209757. {
  209758. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  209759. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  209760. return false;
  209761. for (int i = 0; i < numChannelsRunning; ++i)
  209762. if (data[i] != 0)
  209763. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  209764. }
  209765. return true;
  209766. }
  209767. juce_UseDebuggingNewOperator
  209768. snd_pcm_t* handle;
  209769. String error;
  209770. int bitDepth, numChannelsRunning;
  209771. private:
  209772. const bool isInput;
  209773. bool isInterleaved;
  209774. MemoryBlock scratch;
  209775. AudioDataConverters::DataFormat sampleFormat;
  209776. bool failed (const int errorNum)
  209777. {
  209778. if (errorNum >= 0)
  209779. return false;
  209780. error = snd_strerror (errorNum);
  209781. DBG (T("ALSA error: ") + error + T("\n"));
  209782. return true;
  209783. }
  209784. };
  209785. class ALSAThread : public Thread
  209786. {
  209787. public:
  209788. ALSAThread (const String& deviceName_)
  209789. : Thread ("Juce ALSA"),
  209790. sampleRate (0),
  209791. bufferSize (0),
  209792. callback (0),
  209793. deviceName (deviceName_),
  209794. outputDevice (0),
  209795. inputDevice (0),
  209796. numCallbacks (0),
  209797. totalNumInputChannels (0),
  209798. totalNumOutputChannels (0)
  209799. {
  209800. zeromem (outputChannelData, sizeof (outputChannelData));
  209801. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  209802. zeromem (inputChannelData, sizeof (inputChannelData));
  209803. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  209804. initialiseRatesAndChannels();
  209805. }
  209806. ~ALSAThread()
  209807. {
  209808. close();
  209809. }
  209810. void open (const BitArray& inputChannels,
  209811. const BitArray& outputChannels,
  209812. const double sampleRate_,
  209813. const int bufferSize_)
  209814. {
  209815. close();
  209816. error = String::empty;
  209817. sampleRate = sampleRate_;
  209818. bufferSize = bufferSize_;
  209819. currentInputChans.clear();
  209820. currentOutputChans.clear();
  209821. numChannelsRunning = jmax (inputChannels.getHighestBit(),
  209822. outputChannels.getHighestBit()) + 1;
  209823. numChannelsRunning = jmin (maxNumChans, jlimit ((int) minChansIn,
  209824. (int) maxChansIn,
  209825. numChannelsRunning));
  209826. if (inputChannels.getHighestBit() >= 0)
  209827. {
  209828. for (int i = 0; i < numChannelsRunning; ++i)
  209829. {
  209830. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  209831. if (inputChannels[i])
  209832. {
  209833. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  209834. currentInputChans.setBit (i);
  209835. }
  209836. }
  209837. }
  209838. if (outputChannels.getHighestBit() >= 0)
  209839. {
  209840. for (int i = 0; i < numChannelsRunning; ++i)
  209841. {
  209842. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  209843. if (outputChannels[i])
  209844. {
  209845. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  209846. currentOutputChans.setBit (i);
  209847. }
  209848. }
  209849. }
  209850. if (totalNumOutputChannels > 0)
  209851. {
  209852. outputDevice = new ALSADevice (deviceName, false);
  209853. if (outputDevice->error.isNotEmpty())
  209854. {
  209855. error = outputDevice->error;
  209856. deleteAndZero (outputDevice);
  209857. return;
  209858. }
  209859. if (! outputDevice->setParameters ((unsigned int) sampleRate, numChannelsRunning, bufferSize))
  209860. {
  209861. error = outputDevice->error;
  209862. deleteAndZero (outputDevice);
  209863. return;
  209864. }
  209865. }
  209866. if (totalNumInputChannels > 0)
  209867. {
  209868. inputDevice = new ALSADevice (deviceName, true);
  209869. if (inputDevice->error.isNotEmpty())
  209870. {
  209871. error = inputDevice->error;
  209872. deleteAndZero (inputDevice);
  209873. return;
  209874. }
  209875. if (! inputDevice->setParameters ((unsigned int) sampleRate, numChannelsRunning, bufferSize))
  209876. {
  209877. error = inputDevice->error;
  209878. deleteAndZero (inputDevice);
  209879. return;
  209880. }
  209881. }
  209882. if (outputDevice == 0 && inputDevice == 0)
  209883. {
  209884. error = "no channels";
  209885. return;
  209886. }
  209887. if (outputDevice != 0 && inputDevice != 0)
  209888. {
  209889. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  209890. }
  209891. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  209892. return;
  209893. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  209894. return;
  209895. startThread (9);
  209896. int count = 1000;
  209897. while (numCallbacks == 0)
  209898. {
  209899. sleep (5);
  209900. if (--count < 0 || ! isThreadRunning())
  209901. {
  209902. error = "device didn't start";
  209903. break;
  209904. }
  209905. }
  209906. }
  209907. void close()
  209908. {
  209909. stopThread (6000);
  209910. deleteAndZero (inputDevice);
  209911. deleteAndZero (outputDevice);
  209912. for (int i = 0; i < maxNumChans; ++i)
  209913. {
  209914. juce_free (inputChannelData [i]);
  209915. juce_free (outputChannelData [i]);
  209916. }
  209917. zeromem (outputChannelData, sizeof (outputChannelData));
  209918. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  209919. zeromem (inputChannelData, sizeof (inputChannelData));
  209920. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  209921. totalNumOutputChannels = 0;
  209922. totalNumInputChannels = 0;
  209923. numChannelsRunning = 0;
  209924. numCallbacks = 0;
  209925. }
  209926. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  209927. {
  209928. const ScopedLock sl (callbackLock);
  209929. callback = newCallback;
  209930. }
  209931. void run()
  209932. {
  209933. while (! threadShouldExit())
  209934. {
  209935. if (inputDevice != 0)
  209936. {
  209937. jassert (numChannelsRunning >= inputDevice->numChannelsRunning);
  209938. if (! inputDevice->read (inputChannelData, bufferSize))
  209939. {
  209940. DBG ("ALSA: read failure");
  209941. break;
  209942. }
  209943. }
  209944. if (threadShouldExit())
  209945. break;
  209946. {
  209947. const ScopedLock sl (callbackLock);
  209948. ++numCallbacks;
  209949. if (callback != 0)
  209950. {
  209951. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  209952. totalNumInputChannels,
  209953. outputChannelDataForCallback,
  209954. totalNumOutputChannels,
  209955. bufferSize);
  209956. }
  209957. else
  209958. {
  209959. for (int i = 0; i < totalNumOutputChannels; ++i)
  209960. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  209961. }
  209962. }
  209963. if (outputDevice != 0)
  209964. {
  209965. failed (snd_pcm_wait (outputDevice->handle, 2000));
  209966. if (threadShouldExit())
  209967. break;
  209968. failed (snd_pcm_avail_update (outputDevice->handle));
  209969. jassert (numChannelsRunning >= outputDevice->numChannelsRunning);
  209970. if (! outputDevice->write (outputChannelData, bufferSize))
  209971. {
  209972. DBG ("ALSA: write failure");
  209973. break;
  209974. }
  209975. }
  209976. }
  209977. }
  209978. int getBitDepth() const throw()
  209979. {
  209980. if (outputDevice != 0)
  209981. return outputDevice->bitDepth;
  209982. if (inputDevice != 0)
  209983. return inputDevice->bitDepth;
  209984. return 16;
  209985. }
  209986. juce_UseDebuggingNewOperator
  209987. String error;
  209988. double sampleRate;
  209989. int bufferSize;
  209990. BitArray currentInputChans, currentOutputChans;
  209991. Array <int> sampleRates;
  209992. StringArray channelNamesOut, channelNamesIn;
  209993. AudioIODeviceCallback* callback;
  209994. private:
  209995. const String deviceName;
  209996. ALSADevice* outputDevice;
  209997. ALSADevice* inputDevice;
  209998. int numCallbacks;
  209999. CriticalSection callbackLock;
  210000. float* outputChannelData [maxNumChans];
  210001. float* outputChannelDataForCallback [maxNumChans];
  210002. int totalNumInputChannels;
  210003. float* inputChannelData [maxNumChans];
  210004. float* inputChannelDataForCallback [maxNumChans];
  210005. int totalNumOutputChannels;
  210006. int numChannelsRunning;
  210007. unsigned int minChansOut, maxChansOut;
  210008. unsigned int minChansIn, maxChansIn;
  210009. bool failed (const int errorNum) throw()
  210010. {
  210011. if (errorNum >= 0)
  210012. return false;
  210013. error = snd_strerror (errorNum);
  210014. DBG (T("ALSA error: ") + error + T("\n"));
  210015. return true;
  210016. }
  210017. void initialiseRatesAndChannels() throw()
  210018. {
  210019. sampleRates.clear();
  210020. channelNamesOut.clear();
  210021. channelNamesIn.clear();
  210022. minChansOut = 0;
  210023. maxChansOut = 0;
  210024. minChansIn = 0;
  210025. maxChansIn = 0;
  210026. getDeviceProperties (deviceName, minChansOut, maxChansOut, minChansIn, maxChansIn, sampleRates);
  210027. unsigned int i;
  210028. for (i = 0; i < maxChansOut; ++i)
  210029. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  210030. for (i = 0; i < maxChansIn; ++i)
  210031. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  210032. }
  210033. };
  210034. class ALSAAudioIODevice : public AudioIODevice
  210035. {
  210036. public:
  210037. ALSAAudioIODevice (const String& deviceName,
  210038. const String& deviceId)
  210039. : AudioIODevice (deviceName, T("ALSA")),
  210040. isOpen_ (false),
  210041. isStarted (false),
  210042. internal (0)
  210043. {
  210044. internal = new ALSAThread (deviceId);
  210045. }
  210046. ~ALSAAudioIODevice()
  210047. {
  210048. delete internal;
  210049. }
  210050. const StringArray getOutputChannelNames()
  210051. {
  210052. return internal->channelNamesOut;
  210053. }
  210054. const StringArray getInputChannelNames()
  210055. {
  210056. return internal->channelNamesIn;
  210057. }
  210058. int getNumSampleRates()
  210059. {
  210060. return internal->sampleRates.size();
  210061. }
  210062. double getSampleRate (int index)
  210063. {
  210064. return internal->sampleRates [index];
  210065. }
  210066. int getNumBufferSizesAvailable()
  210067. {
  210068. return 50;
  210069. }
  210070. int getBufferSizeSamples (int index)
  210071. {
  210072. int n = 16;
  210073. for (int i = 0; i < index; ++i)
  210074. n += n < 64 ? 16
  210075. : (n < 512 ? 32
  210076. : (n < 1024 ? 64
  210077. : (n < 2048 ? 128 : 256)));
  210078. return n;
  210079. }
  210080. int getDefaultBufferSize()
  210081. {
  210082. return 512;
  210083. }
  210084. const String open (const BitArray& inputChannels,
  210085. const BitArray& outputChannels,
  210086. double sampleRate,
  210087. int bufferSizeSamples)
  210088. {
  210089. close();
  210090. if (bufferSizeSamples <= 0)
  210091. bufferSizeSamples = getDefaultBufferSize();
  210092. if (sampleRate <= 0)
  210093. {
  210094. for (int i = 0; i < getNumSampleRates(); ++i)
  210095. {
  210096. if (getSampleRate (i) >= 44100)
  210097. {
  210098. sampleRate = getSampleRate (i);
  210099. break;
  210100. }
  210101. }
  210102. }
  210103. internal->open (inputChannels, outputChannels,
  210104. sampleRate, bufferSizeSamples);
  210105. isOpen_ = internal->error.isEmpty();
  210106. return internal->error;
  210107. }
  210108. void close()
  210109. {
  210110. stop();
  210111. internal->close();
  210112. isOpen_ = false;
  210113. }
  210114. bool isOpen()
  210115. {
  210116. return isOpen_;
  210117. }
  210118. int getCurrentBufferSizeSamples()
  210119. {
  210120. return internal->bufferSize;
  210121. }
  210122. double getCurrentSampleRate()
  210123. {
  210124. return internal->sampleRate;
  210125. }
  210126. int getCurrentBitDepth()
  210127. {
  210128. return internal->getBitDepth();
  210129. }
  210130. const BitArray getActiveOutputChannels() const
  210131. {
  210132. return internal->currentOutputChans;
  210133. }
  210134. const BitArray getActiveInputChannels() const
  210135. {
  210136. return internal->currentInputChans;
  210137. }
  210138. int getOutputLatencyInSamples()
  210139. {
  210140. return 0;
  210141. }
  210142. int getInputLatencyInSamples()
  210143. {
  210144. return 0;
  210145. }
  210146. void start (AudioIODeviceCallback* callback)
  210147. {
  210148. if (! isOpen_)
  210149. callback = 0;
  210150. internal->setCallback (callback);
  210151. if (callback != 0)
  210152. callback->audioDeviceAboutToStart (this);
  210153. isStarted = (callback != 0);
  210154. }
  210155. void stop()
  210156. {
  210157. AudioIODeviceCallback* const oldCallback = internal->callback;
  210158. start (0);
  210159. if (oldCallback != 0)
  210160. oldCallback->audioDeviceStopped();
  210161. }
  210162. bool isPlaying()
  210163. {
  210164. return isStarted && internal->error.isEmpty();
  210165. }
  210166. const String getLastError()
  210167. {
  210168. return internal->error;
  210169. }
  210170. private:
  210171. bool isOpen_, isStarted;
  210172. ALSAThread* internal;
  210173. };
  210174. class ALSAAudioIODeviceType : public AudioIODeviceType
  210175. {
  210176. public:
  210177. ALSAAudioIODeviceType()
  210178. : AudioIODeviceType (T("ALSA")),
  210179. hasScanned (false)
  210180. {
  210181. }
  210182. ~ALSAAudioIODeviceType()
  210183. {
  210184. }
  210185. void scanForDevices()
  210186. {
  210187. hasScanned = true;
  210188. names.clear();
  210189. ids.clear();
  210190. snd_ctl_t* handle;
  210191. snd_ctl_card_info_t* info;
  210192. snd_ctl_card_info_alloca (&info);
  210193. int cardNum = -1;
  210194. while (ids.size() <= 24)
  210195. {
  210196. snd_card_next (&cardNum);
  210197. if (cardNum < 0)
  210198. break;
  210199. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  210200. {
  210201. if (snd_ctl_card_info (handle, info) >= 0)
  210202. {
  210203. String cardId (snd_ctl_card_info_get_id (info));
  210204. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  210205. cardId = String (cardNum);
  210206. int device = -1;
  210207. for (;;)
  210208. {
  210209. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  210210. break;
  210211. String id, name;
  210212. id << "hw:" << cardId << ',' << device;
  210213. if (testDevice (id))
  210214. {
  210215. name << snd_ctl_card_info_get_name (info);
  210216. if (name.isEmpty())
  210217. name = id;
  210218. if (device > 0)
  210219. name << " (" << (device + 1) << ')';
  210220. ids.add (id);
  210221. names.add (name);
  210222. }
  210223. }
  210224. }
  210225. snd_ctl_close (handle);
  210226. }
  210227. }
  210228. }
  210229. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  210230. {
  210231. jassert (hasScanned); // need to call scanForDevices() before doing this
  210232. StringArray namesCopy (names);
  210233. namesCopy.removeDuplicates (true);
  210234. return namesCopy;
  210235. }
  210236. const String getDefaultDeviceName (const bool /*preferInputNames*/,
  210237. const int /*numInputChannelsNeeded*/,
  210238. const int /*numOutputChannelsNeeded*/) const
  210239. {
  210240. jassert (hasScanned); // need to call scanForDevices() before doing this
  210241. return names[0];
  210242. }
  210243. AudioIODevice* createDevice (const String& deviceName)
  210244. {
  210245. jassert (hasScanned); // need to call scanForDevices() before doing this
  210246. const int index = names.indexOf (deviceName);
  210247. if (index >= 0)
  210248. return new ALSAAudioIODevice (deviceName, ids [index]);
  210249. return 0;
  210250. }
  210251. juce_UseDebuggingNewOperator
  210252. private:
  210253. StringArray names, ids;
  210254. bool hasScanned;
  210255. static bool testDevice (const String& id)
  210256. {
  210257. unsigned int minChansOut = 0, maxChansOut = 0;
  210258. unsigned int minChansIn = 0, maxChansIn = 0;
  210259. Array <int> rates;
  210260. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  210261. DBG (T("ALSA device: ") + id
  210262. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  210263. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  210264. + T(" rates=") + String (rates.size()));
  210265. return (maxChansOut > 0 || maxChansIn > 0) && rates.size() > 0;
  210266. }
  210267. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  210268. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  210269. };
  210270. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  210271. {
  210272. return new ALSAAudioIODeviceType();
  210273. }
  210274. END_JUCE_NAMESPACE
  210275. #else // if ALSA is turned off..
  210276. BEGIN_JUCE_NAMESPACE
  210277. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  210278. END_JUCE_NAMESPACE
  210279. #endif
  210280. #endif
  210281. /********* End of inlined file: juce_linux_Audio.cpp *********/
  210282. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  210283. BEGIN_JUCE_NAMESPACE
  210284. AudioCDReader::AudioCDReader()
  210285. : AudioFormatReader (0, T("CD Audio"))
  210286. {
  210287. }
  210288. const StringArray AudioCDReader::getAvailableCDNames()
  210289. {
  210290. StringArray names;
  210291. return names;
  210292. }
  210293. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  210294. {
  210295. return 0;
  210296. }
  210297. AudioCDReader::~AudioCDReader()
  210298. {
  210299. }
  210300. void AudioCDReader::refreshTrackLengths()
  210301. {
  210302. }
  210303. bool AudioCDReader::read (int** destSamples,
  210304. int64 startSampleInFile,
  210305. int numSamples)
  210306. {
  210307. return false;
  210308. }
  210309. bool AudioCDReader::isCDStillPresent() const
  210310. {
  210311. return false;
  210312. }
  210313. int AudioCDReader::getNumTracks() const
  210314. {
  210315. return 0;
  210316. }
  210317. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210318. {
  210319. return 0;
  210320. }
  210321. bool AudioCDReader::isTrackAudio (int trackNum) const
  210322. {
  210323. return false;
  210324. }
  210325. void AudioCDReader::enableIndexScanning (bool b)
  210326. {
  210327. }
  210328. int AudioCDReader::getLastIndex() const
  210329. {
  210330. return 0;
  210331. }
  210332. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210333. {
  210334. return Array<int>();
  210335. }
  210336. int AudioCDReader::getCDDBId()
  210337. {
  210338. return 0;
  210339. }
  210340. END_JUCE_NAMESPACE
  210341. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  210342. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  210343. #if JUCE_BUILD_GUI_CLASSES
  210344. BEGIN_JUCE_NAMESPACE
  210345. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  210346. const String& title,
  210347. const File& file,
  210348. const String& filters,
  210349. bool isDirectory,
  210350. bool isSave,
  210351. bool warnAboutOverwritingExistingFiles,
  210352. bool selectMultipleFiles,
  210353. FilePreviewComponent* previewComponent)
  210354. {
  210355. //xxx ain't got one!
  210356. jassertfalse
  210357. }
  210358. END_JUCE_NAMESPACE
  210359. #endif
  210360. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  210361. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  210362. #if JUCE_BUILD_GUI_CLASSES
  210363. /* Got a build error here? You'll need to install the freetype library...
  210364. The name of the package to install is "libfreetype6-dev".
  210365. */
  210366. #include <ft2build.h>
  210367. #include FT_FREETYPE_H
  210368. BEGIN_JUCE_NAMESPACE
  210369. class FreeTypeFontFace
  210370. {
  210371. public:
  210372. enum FontStyle
  210373. {
  210374. Plain = 0,
  210375. Bold = 1,
  210376. Italic = 2
  210377. };
  210378. struct FontNameIndex
  210379. {
  210380. String fileName;
  210381. int faceIndex;
  210382. };
  210383. FreeTypeFontFace (const String& familyName)
  210384. : hasSerif (false),
  210385. monospaced (false)
  210386. {
  210387. family = familyName;
  210388. }
  210389. void setFileName (const String& name,
  210390. const int faceIndex,
  210391. FontStyle style)
  210392. {
  210393. if (names[(int) style].fileName.isEmpty())
  210394. {
  210395. names[(int) style].fileName = name;
  210396. names[(int) style].faceIndex = faceIndex;
  210397. }
  210398. }
  210399. const String& getFamilyName() const throw()
  210400. {
  210401. return family;
  210402. }
  210403. const String& getFileName (int style, int* faceIndex) const throw()
  210404. {
  210405. *faceIndex = names [style].faceIndex;
  210406. return names[style].fileName;
  210407. }
  210408. void setMonospaced (bool mono) { monospaced = mono; }
  210409. bool getMonospaced () const throw() { return monospaced; }
  210410. void setSerif (const bool serif) { hasSerif = serif; }
  210411. bool getSerif () const throw() { return hasSerif; }
  210412. private:
  210413. String family;
  210414. FontNameIndex names[4];
  210415. bool hasSerif, monospaced;
  210416. };
  210417. class FreeTypeInterface : public DeletedAtShutdown
  210418. {
  210419. public:
  210420. FreeTypeInterface() throw()
  210421. : lastFace (0),
  210422. lastBold (false),
  210423. lastItalic (false)
  210424. {
  210425. if (FT_Init_FreeType (&ftLib) != 0)
  210426. {
  210427. ftLib = 0;
  210428. DBG (T("Failed to initialize FreeType"));
  210429. }
  210430. StringArray fontDirs;
  210431. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  210432. fontDirs.removeEmptyStrings (true);
  210433. if (fontDirs.size() == 0)
  210434. {
  210435. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  210436. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  210437. if (fontsInfo != 0)
  210438. {
  210439. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  210440. {
  210441. fontDirs.add (e->getAllSubText().trim());
  210442. }
  210443. delete fontsInfo;
  210444. }
  210445. }
  210446. if (fontDirs.size() == 0)
  210447. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  210448. for (int i = 0; i < fontDirs.size(); ++i)
  210449. enumerateFaces (fontDirs[i]);
  210450. }
  210451. ~FreeTypeInterface() throw()
  210452. {
  210453. if (lastFace != 0)
  210454. FT_Done_Face (lastFace);
  210455. if (ftLib != 0)
  210456. FT_Done_FreeType (ftLib);
  210457. clearSingletonInstance();
  210458. }
  210459. FreeTypeFontFace* findOrCreate (const String& familyName,
  210460. const bool create = false) throw()
  210461. {
  210462. for (int i = 0; i < faces.size(); i++)
  210463. if (faces[i]->getFamilyName() == familyName)
  210464. return faces[i];
  210465. if (! create)
  210466. return NULL;
  210467. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  210468. faces.add (newFace);
  210469. return newFace;
  210470. }
  210471. // Enumerate all font faces available in a given directory
  210472. void enumerateFaces (const String& path) throw()
  210473. {
  210474. File dirPath (path);
  210475. if (path.isEmpty() || ! dirPath.isDirectory())
  210476. return;
  210477. DirectoryIterator di (dirPath, true);
  210478. while (di.next())
  210479. {
  210480. File possible (di.getFile());
  210481. if (possible.hasFileExtension (T("ttf"))
  210482. || possible.hasFileExtension (T("pfb"))
  210483. || possible.hasFileExtension (T("pcf")))
  210484. {
  210485. FT_Face face;
  210486. int faceIndex = 0;
  210487. int numFaces = 0;
  210488. do
  210489. {
  210490. if (FT_New_Face (ftLib,
  210491. possible.getFullPathName(),
  210492. faceIndex,
  210493. &face) == 0)
  210494. {
  210495. if (faceIndex == 0)
  210496. numFaces = face->num_faces;
  210497. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  210498. {
  210499. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  210500. int style = (int) FreeTypeFontFace::Plain;
  210501. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  210502. style |= (int) FreeTypeFontFace::Bold;
  210503. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  210504. style |= (int) FreeTypeFontFace::Italic;
  210505. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  210506. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  210507. newFace->setMonospaced (true);
  210508. else
  210509. newFace->setMonospaced (false);
  210510. // Surely there must be a better way to do this?
  210511. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  210512. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  210513. || String (face->family_name).containsIgnoreCase (T("Arial")))
  210514. {
  210515. newFace->setSerif (false);
  210516. }
  210517. else
  210518. {
  210519. newFace->setSerif (true);
  210520. }
  210521. }
  210522. FT_Done_Face (face);
  210523. }
  210524. ++faceIndex;
  210525. }
  210526. while (faceIndex < numFaces);
  210527. }
  210528. }
  210529. }
  210530. // Create a FreeType face object for a given font
  210531. FT_Face createFT_Face (const String& fontName,
  210532. const bool bold,
  210533. const bool italic) throw()
  210534. {
  210535. FT_Face face = NULL;
  210536. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  210537. {
  210538. face = lastFace;
  210539. }
  210540. else
  210541. {
  210542. if (lastFace)
  210543. {
  210544. FT_Done_Face (lastFace);
  210545. lastFace = NULL;
  210546. }
  210547. lastFontName = fontName;
  210548. lastBold = bold;
  210549. lastItalic = italic;
  210550. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  210551. if (ftFace != 0)
  210552. {
  210553. int style = (int) FreeTypeFontFace::Plain;
  210554. if (bold)
  210555. style |= (int) FreeTypeFontFace::Bold;
  210556. if (italic)
  210557. style |= (int) FreeTypeFontFace::Italic;
  210558. int faceIndex;
  210559. String fileName (ftFace->getFileName (style, &faceIndex));
  210560. if (fileName.isEmpty())
  210561. {
  210562. style ^= (int) FreeTypeFontFace::Bold;
  210563. fileName = ftFace->getFileName (style, &faceIndex);
  210564. if (fileName.isEmpty())
  210565. {
  210566. style ^= (int) FreeTypeFontFace::Bold;
  210567. style ^= (int) FreeTypeFontFace::Italic;
  210568. fileName = ftFace->getFileName (style, &faceIndex);
  210569. if (! fileName.length())
  210570. {
  210571. style ^= (int) FreeTypeFontFace::Bold;
  210572. fileName = ftFace->getFileName (style, &faceIndex);
  210573. }
  210574. }
  210575. }
  210576. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  210577. {
  210578. face = lastFace;
  210579. // If there isn't a unicode charmap then select the first one.
  210580. if (FT_Select_Charmap (face, ft_encoding_unicode))
  210581. FT_Set_Charmap (face, face->charmaps[0]);
  210582. }
  210583. }
  210584. }
  210585. return face;
  210586. }
  210587. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  210588. {
  210589. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  210590. const float height = (float) (face->ascender - face->descender);
  210591. const float scaleX = 1.0f / height;
  210592. const float scaleY = -1.0f / height;
  210593. Path destShape;
  210594. #define CONVERTX(val) (scaleX * (val).x)
  210595. #define CONVERTY(val) (scaleY * (val).y)
  210596. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  210597. | FT_LOAD_NO_BITMAP
  210598. | FT_LOAD_IGNORE_TRANSFORM) != 0
  210599. || face->glyph->format != ft_glyph_format_outline)
  210600. {
  210601. return false;
  210602. }
  210603. const FT_Outline* const outline = &face->glyph->outline;
  210604. const short* const contours = outline->contours;
  210605. const char* const tags = outline->tags;
  210606. FT_Vector* const points = outline->points;
  210607. for (int c = 0; c < outline->n_contours; c++)
  210608. {
  210609. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  210610. const int endPoint = contours[c];
  210611. for (int p = startPoint; p <= endPoint; p++)
  210612. {
  210613. const float x = CONVERTX (points[p]);
  210614. const float y = CONVERTY (points[p]);
  210615. if (p == startPoint)
  210616. {
  210617. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  210618. {
  210619. float x2 = CONVERTX (points [endPoint]);
  210620. float y2 = CONVERTY (points [endPoint]);
  210621. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  210622. {
  210623. x2 = (x + x2) * 0.5f;
  210624. y2 = (y + y2) * 0.5f;
  210625. }
  210626. destShape.startNewSubPath (x2, y2);
  210627. }
  210628. else
  210629. {
  210630. destShape.startNewSubPath (x, y);
  210631. }
  210632. }
  210633. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  210634. {
  210635. if (p != startPoint)
  210636. destShape.lineTo (x, y);
  210637. }
  210638. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  210639. {
  210640. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  210641. float x2 = CONVERTX (points [nextIndex]);
  210642. float y2 = CONVERTY (points [nextIndex]);
  210643. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  210644. {
  210645. x2 = (x + x2) * 0.5f;
  210646. y2 = (y + y2) * 0.5f;
  210647. }
  210648. else
  210649. {
  210650. ++p;
  210651. }
  210652. destShape.quadraticTo (x, y, x2, y2);
  210653. }
  210654. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  210655. {
  210656. if (p >= endPoint)
  210657. return false;
  210658. const int next1 = p + 1;
  210659. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  210660. const float x2 = CONVERTX (points [next1]);
  210661. const float y2 = CONVERTY (points [next1]);
  210662. const float x3 = CONVERTX (points [next2]);
  210663. const float y3 = CONVERTY (points [next2]);
  210664. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  210665. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  210666. return false;
  210667. destShape.cubicTo (x, y, x2, y2, x3, y3);
  210668. p += 2;
  210669. }
  210670. }
  210671. destShape.closeSubPath();
  210672. }
  210673. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  210674. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  210675. addKerning (face, dest, character, glyphIndex);
  210676. return true;
  210677. }
  210678. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  210679. {
  210680. const float height = (float) (face->ascender - face->descender);
  210681. uint32 rightGlyphIndex;
  210682. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  210683. while (rightGlyphIndex != 0)
  210684. {
  210685. FT_Vector kerning;
  210686. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  210687. {
  210688. if (kerning.x != 0)
  210689. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  210690. }
  210691. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  210692. }
  210693. }
  210694. // Add a glyph to a font
  210695. bool addGlyphToFont (const uint32 character,
  210696. const tchar* fontName, bool bold, bool italic,
  210697. Typeface& dest) throw()
  210698. {
  210699. FT_Face face = createFT_Face (fontName, bold, italic);
  210700. if (face != 0)
  210701. return addGlyph (face, dest, character);
  210702. return false;
  210703. }
  210704. // Create a Typeface object for given name/style
  210705. bool createTypeface (const String& fontName,
  210706. const bool bold, const bool italic,
  210707. Typeface& dest,
  210708. const bool addAllGlyphs) throw()
  210709. {
  210710. dest.clear();
  210711. dest.setName (fontName);
  210712. dest.setBold (bold);
  210713. dest.setItalic (italic);
  210714. FT_Face face = createFT_Face (fontName, bold, italic);
  210715. if (face == 0)
  210716. {
  210717. #ifdef JUCE_DEBUG
  210718. String msg (T("Failed to create typeface: "));
  210719. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  210720. DBG (msg);
  210721. #endif
  210722. return face;
  210723. }
  210724. const float height = (float) (face->ascender - face->descender);
  210725. dest.setAscent (face->ascender / height);
  210726. dest.setDefaultCharacter (L' ');
  210727. if (addAllGlyphs)
  210728. {
  210729. uint32 glyphIndex;
  210730. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  210731. while (glyphIndex != 0)
  210732. {
  210733. addGlyph (face, dest, charCode);
  210734. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  210735. }
  210736. }
  210737. return true;
  210738. }
  210739. void getFamilyNames (StringArray& familyNames) const throw()
  210740. {
  210741. for (int i = 0; i < faces.size(); i++)
  210742. familyNames.add (faces[i]->getFamilyName());
  210743. }
  210744. void getMonospacedNames (StringArray& monoSpaced) const throw()
  210745. {
  210746. for (int i = 0; i < faces.size(); i++)
  210747. if (faces[i]->getMonospaced())
  210748. monoSpaced.add (faces[i]->getFamilyName());
  210749. }
  210750. void getSerifNames (StringArray& serif) const throw()
  210751. {
  210752. for (int i = 0; i < faces.size(); i++)
  210753. if (faces[i]->getSerif())
  210754. serif.add (faces[i]->getFamilyName());
  210755. }
  210756. void getSansSerifNames (StringArray& sansSerif) const throw()
  210757. {
  210758. for (int i = 0; i < faces.size(); i++)
  210759. if (! faces[i]->getSerif())
  210760. sansSerif.add (faces[i]->getFamilyName());
  210761. }
  210762. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  210763. private:
  210764. FT_Library ftLib;
  210765. FT_Face lastFace;
  210766. String lastFontName;
  210767. bool lastBold, lastItalic;
  210768. OwnedArray<FreeTypeFontFace> faces;
  210769. };
  210770. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  210771. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  210772. bool bold, bool italic,
  210773. bool addAllGlyphsToFont) throw()
  210774. {
  210775. FreeTypeInterface::getInstance()
  210776. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  210777. }
  210778. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  210779. {
  210780. return FreeTypeInterface::getInstance()
  210781. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  210782. }
  210783. const StringArray Font::findAllTypefaceNames() throw()
  210784. {
  210785. StringArray s;
  210786. FreeTypeInterface::getInstance()->getFamilyNames (s);
  210787. s.sort (true);
  210788. return s;
  210789. }
  210790. static const String pickBestFont (const StringArray& names,
  210791. const char* const choicesString)
  210792. {
  210793. StringArray choices;
  210794. choices.addTokens (String (choicesString), T(","), 0);
  210795. choices.trim();
  210796. choices.removeEmptyStrings();
  210797. int i, j;
  210798. for (j = 0; j < choices.size(); ++j)
  210799. if (names.contains (choices[j], true))
  210800. return choices[j];
  210801. for (j = 0; j < choices.size(); ++j)
  210802. for (i = 0; i < names.size(); i++)
  210803. if (names[i].startsWithIgnoreCase (choices[j]))
  210804. return names[i];
  210805. for (j = 0; j < choices.size(); ++j)
  210806. for (i = 0; i < names.size(); i++)
  210807. if (names[i].containsIgnoreCase (choices[j]))
  210808. return names[i];
  210809. return names[0];
  210810. }
  210811. static const String linux_getDefaultSansSerifFontName()
  210812. {
  210813. StringArray allFonts;
  210814. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  210815. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  210816. }
  210817. static const String linux_getDefaultSerifFontName()
  210818. {
  210819. StringArray allFonts;
  210820. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  210821. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  210822. }
  210823. static const String linux_getDefaultMonospacedFontName()
  210824. {
  210825. StringArray allFonts;
  210826. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  210827. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  210828. }
  210829. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  210830. {
  210831. defaultSans = linux_getDefaultSansSerifFontName();
  210832. defaultSerif = linux_getDefaultSerifFontName();
  210833. defaultFixed = linux_getDefaultMonospacedFontName();
  210834. }
  210835. END_JUCE_NAMESPACE
  210836. #endif
  210837. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  210838. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  210839. #if JUCE_BUILD_GUI_CLASSES
  210840. #include <stdio.h>
  210841. #include <signal.h>
  210842. #include <X11/Xlib.h>
  210843. #include <X11/Xatom.h>
  210844. #include <X11/Xresource.h>
  210845. #include <X11/Xutil.h>
  210846. BEGIN_JUCE_NAMESPACE
  210847. #ifdef JUCE_DEBUG
  210848. #define JUCE_DEBUG_XERRORS 1
  210849. #endif
  210850. Display* display = 0; // This is also referenced from WindowDriver.cpp
  210851. static Window juce_messageWindowHandle = None;
  210852. #define SpecialAtom "JUCESpecialAtom"
  210853. #define BroadcastAtom "JUCEBroadcastAtom"
  210854. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  210855. static Atom specialId;
  210856. static Atom broadcastId;
  210857. static Atom specialCallbackId;
  210858. // This is referenced from WindowDriver.cpp
  210859. XContext improbableNumber;
  210860. // Defined in WindowDriver.cpp
  210861. extern void juce_windowMessageReceive (XEvent* event);
  210862. struct MessageThreadFuncCall
  210863. {
  210864. MessageCallbackFunction* func;
  210865. void* parameter;
  210866. void* result;
  210867. CriticalSection lock;
  210868. WaitableEvent event;
  210869. };
  210870. static bool errorCondition = false;
  210871. // (defined in another file to avoid problems including certain headers in this one)
  210872. extern bool juce_isRunningAsApplication();
  210873. // Usually happens when client-server connection is broken
  210874. static int ioErrorHandler (Display* display)
  210875. {
  210876. DBG (T("ERROR: connection to X server broken.. terminating."));
  210877. errorCondition = true;
  210878. if (! juce_isRunningAsApplication())
  210879. Process::terminate();
  210880. return 0;
  210881. }
  210882. // A protocol error has occurred
  210883. static int errorHandler (Display* display, XErrorEvent* event)
  210884. {
  210885. #ifdef JUCE_DEBUG_XERRORS
  210886. char errorStr[64] = { 0 };
  210887. char requestStr[64] = { 0 };
  210888. XGetErrorText (display, event->error_code, errorStr, 64);
  210889. XGetErrorDatabaseText (display,
  210890. "XRequest",
  210891. (const char*) String (event->request_code),
  210892. "Unknown",
  210893. requestStr,
  210894. 64);
  210895. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  210896. #endif
  210897. return 0;
  210898. }
  210899. static bool breakIn = false;
  210900. // Breakin from keyboard
  210901. static void sig_handler (int sig)
  210902. {
  210903. if (sig == SIGINT)
  210904. {
  210905. breakIn = true;
  210906. return;
  210907. }
  210908. static bool reentrant = false;
  210909. if (reentrant == false)
  210910. {
  210911. reentrant = true;
  210912. // Illegal instruction
  210913. fflush (stdout);
  210914. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  210915. errorCondition = true;
  210916. if (juce_isRunningAsApplication())
  210917. Process::terminate();
  210918. }
  210919. else
  210920. {
  210921. if (juce_isRunningAsApplication())
  210922. exit(0);
  210923. }
  210924. }
  210925. void MessageManager::doPlatformSpecificInitialisation()
  210926. {
  210927. // Initialise xlib for multiple thread support
  210928. if (! XInitThreads())
  210929. {
  210930. // This is fatal! Print error and closedown
  210931. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  210932. if (juce_isRunningAsApplication())
  210933. Process::terminate();
  210934. }
  210935. // This is called if the client/server connection is broken
  210936. XSetIOErrorHandler (ioErrorHandler);
  210937. // This is called if a protocol error occurs
  210938. XSetErrorHandler (errorHandler);
  210939. // Install signal handler for break-in
  210940. struct sigaction saction;
  210941. sigset_t maskSet;
  210942. sigemptyset (&maskSet);
  210943. saction.sa_handler = sig_handler;
  210944. saction.sa_mask = maskSet;
  210945. saction.sa_flags = 0;
  210946. sigaction (SIGINT, &saction, NULL);
  210947. #ifndef _DEBUG
  210948. // Setup signal handlers for various fatal errors
  210949. sigaction (SIGILL, &saction, NULL);
  210950. sigaction (SIGBUS, &saction, NULL);
  210951. sigaction (SIGFPE, &saction, NULL);
  210952. sigaction (SIGSEGV, &saction, NULL);
  210953. sigaction (SIGSYS, &saction, NULL);
  210954. #endif
  210955. String displayName (getenv ("DISPLAY"));
  210956. if (displayName.isEmpty())
  210957. displayName = T(":0.0");
  210958. display = XOpenDisplay (displayName);
  210959. if (display == 0)
  210960. {
  210961. // This is fatal! Print error and closedown
  210962. Logger::outputDebugString ("Failed to open the X display.");
  210963. if (juce_isRunningAsApplication())
  210964. Process::terminate();
  210965. }
  210966. // Get defaults for various properties
  210967. int screen = DefaultScreen (display);
  210968. Window root = RootWindow (display, screen);
  210969. Visual* visual = DefaultVisual (display, screen);
  210970. // Create atoms for our ClientMessages (these cannot be deleted)
  210971. specialId = XInternAtom (display, SpecialAtom, false);
  210972. broadcastId = XInternAtom (display, BroadcastAtom, false);
  210973. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  210974. // Create a context to store user data associated with Windows we
  210975. // create in WindowDriver
  210976. improbableNumber = XUniqueContext();
  210977. // We're only interested in client messages for this window
  210978. // which are always sent
  210979. XSetWindowAttributes swa;
  210980. swa.event_mask = NoEventMask;
  210981. // Create our message window (this will never be mapped)
  210982. juce_messageWindowHandle = XCreateWindow (display, root,
  210983. 0, 0, 1, 1, 0, 0, InputOnly,
  210984. visual, CWEventMask, &swa);
  210985. }
  210986. void MessageManager::doPlatformSpecificShutdown()
  210987. {
  210988. if (errorCondition == false)
  210989. {
  210990. XDestroyWindow (display, juce_messageWindowHandle);
  210991. XCloseDisplay (display);
  210992. }
  210993. }
  210994. bool juce_postMessageToSystemQueue (void* message)
  210995. {
  210996. if (errorCondition)
  210997. return false;
  210998. XClientMessageEvent clientMsg;
  210999. clientMsg.display = display;
  211000. clientMsg.window = juce_messageWindowHandle;
  211001. clientMsg.type = ClientMessage;
  211002. clientMsg.format = 32;
  211003. clientMsg.message_type = specialId;
  211004. #if JUCE_64BIT
  211005. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  211006. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  211007. #else
  211008. clientMsg.data.l[0] = (long) message;
  211009. #endif
  211010. XSendEvent (display, juce_messageWindowHandle, false,
  211011. NoEventMask, (XEvent*) &clientMsg);
  211012. XFlush (display); // This is necessary to ensure the event is delivered
  211013. return true;
  211014. }
  211015. void MessageManager::broadcastMessage (const String& value) throw()
  211016. {
  211017. }
  211018. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  211019. void* parameter)
  211020. {
  211021. void* retVal = 0;
  211022. if (! errorCondition)
  211023. {
  211024. if (! isThisTheMessageThread())
  211025. {
  211026. static MessageThreadFuncCall messageFuncCallContext;
  211027. const ScopedLock sl (messageFuncCallContext.lock);
  211028. XClientMessageEvent clientMsg;
  211029. clientMsg.display = display;
  211030. clientMsg.window = juce_messageWindowHandle;
  211031. clientMsg.type = ClientMessage;
  211032. clientMsg.format = 32;
  211033. clientMsg.message_type = specialCallbackId;
  211034. #if JUCE_64BIT
  211035. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  211036. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  211037. #else
  211038. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  211039. #endif
  211040. messageFuncCallContext.func = func;
  211041. messageFuncCallContext.parameter = parameter;
  211042. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  211043. return 0;
  211044. XFlush (display); // This is necessary to ensure the event is delivered
  211045. // Wait for it to complete before continuing
  211046. messageFuncCallContext.event.wait();
  211047. retVal = messageFuncCallContext.result;
  211048. }
  211049. else
  211050. {
  211051. // Just call the function directly
  211052. retVal = func (parameter);
  211053. }
  211054. }
  211055. return retVal;
  211056. }
  211057. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  211058. {
  211059. if (errorCondition)
  211060. return false;
  211061. if (breakIn)
  211062. {
  211063. errorCondition = true;
  211064. if (juce_isRunningAsApplication())
  211065. Process::terminate();
  211066. }
  211067. if (returnIfNoPendingMessages && ! XPending (display))
  211068. return false;
  211069. XEvent evt;
  211070. XNextEvent (display, &evt);
  211071. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  211072. {
  211073. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  211074. if (clientMsg->format != 32)
  211075. {
  211076. jassertfalse
  211077. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  211078. }
  211079. else
  211080. {
  211081. JUCE_TRY
  211082. {
  211083. #if JUCE_64BIT
  211084. void* const messagePtr
  211085. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  211086. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  211087. #else
  211088. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  211089. #endif
  211090. if (clientMsg->message_type == specialId)
  211091. {
  211092. MessageManager::getInstance()->deliverMessage (messagePtr);
  211093. }
  211094. else if (clientMsg->message_type == specialCallbackId)
  211095. {
  211096. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  211097. MessageCallbackFunction* func = call->func;
  211098. call->result = (*func) (call->parameter);
  211099. call->event.signal();
  211100. }
  211101. else if (clientMsg->message_type == broadcastId)
  211102. {
  211103. #if 0
  211104. TCHAR buffer[8192];
  211105. zeromem (buffer, sizeof (buffer));
  211106. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  211107. mq->deliverBroadcastMessage (String (buffer));
  211108. #endif
  211109. }
  211110. else
  211111. {
  211112. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  211113. }
  211114. }
  211115. JUCE_CATCH_ALL
  211116. }
  211117. }
  211118. else if (evt.xany.window != juce_messageWindowHandle)
  211119. {
  211120. juce_windowMessageReceive (&evt);
  211121. }
  211122. return true;
  211123. }
  211124. END_JUCE_NAMESPACE
  211125. #endif
  211126. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  211127. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  211128. #if JUCE_BUILD_GUI_CLASSES
  211129. #if JUCE_ALSA
  211130. #include <alsa/asoundlib.h>
  211131. BEGIN_JUCE_NAMESPACE
  211132. static snd_seq_t* iterateDevices (const bool forInput,
  211133. StringArray& deviceNamesFound,
  211134. const int deviceIndexToOpen)
  211135. {
  211136. snd_seq_t* returnedHandle = 0;
  211137. snd_seq_t* seqHandle;
  211138. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211139. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211140. {
  211141. snd_seq_system_info_t* systemInfo;
  211142. snd_seq_client_info_t* clientInfo;
  211143. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  211144. {
  211145. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  211146. && snd_seq_client_info_malloc (&clientInfo) == 0)
  211147. {
  211148. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  211149. while (--numClients >= 0 && returnedHandle == 0)
  211150. {
  211151. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  211152. {
  211153. snd_seq_port_info_t* portInfo;
  211154. if (snd_seq_port_info_malloc (&portInfo) == 0)
  211155. {
  211156. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  211157. const int client = snd_seq_client_info_get_client (clientInfo);
  211158. snd_seq_port_info_set_client (portInfo, client);
  211159. snd_seq_port_info_set_port (portInfo, -1);
  211160. while (--numPorts >= 0)
  211161. {
  211162. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  211163. && (snd_seq_port_info_get_capability (portInfo)
  211164. & (forInput ? SND_SEQ_PORT_CAP_READ
  211165. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  211166. {
  211167. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  211168. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  211169. {
  211170. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  211171. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  211172. if (sourcePort != -1)
  211173. {
  211174. snd_seq_set_client_name (seqHandle,
  211175. forInput ? "Juce Midi Input"
  211176. : "Juce Midi Output");
  211177. const int portId
  211178. = snd_seq_create_simple_port (seqHandle,
  211179. forInput ? "Juce Midi In Port"
  211180. : "Juce Midi Out Port",
  211181. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211182. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211183. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211184. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  211185. returnedHandle = seqHandle;
  211186. break;
  211187. }
  211188. }
  211189. }
  211190. }
  211191. snd_seq_port_info_free (portInfo);
  211192. }
  211193. }
  211194. }
  211195. snd_seq_client_info_free (clientInfo);
  211196. }
  211197. snd_seq_system_info_free (systemInfo);
  211198. }
  211199. if (returnedHandle == 0)
  211200. snd_seq_close (seqHandle);
  211201. }
  211202. deviceNamesFound.appendNumbersToDuplicates (true, true);
  211203. return returnedHandle;
  211204. }
  211205. static snd_seq_t* createDevice (const bool forInput,
  211206. const String& deviceNameToOpen)
  211207. {
  211208. snd_seq_t* seqHandle = 0;
  211209. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211210. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211211. {
  211212. snd_seq_set_client_name (seqHandle,
  211213. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  211214. : (deviceNameToOpen + T(" Output"))));
  211215. const int portId
  211216. = snd_seq_create_simple_port (seqHandle,
  211217. forInput ? "in"
  211218. : "out",
  211219. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211220. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211221. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  211222. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211223. if (portId < 0)
  211224. {
  211225. snd_seq_close (seqHandle);
  211226. seqHandle = 0;
  211227. }
  211228. }
  211229. return seqHandle;
  211230. }
  211231. class MidiOutputDevice
  211232. {
  211233. public:
  211234. MidiOutputDevice (MidiOutput* const midiOutput_,
  211235. snd_seq_t* const seqHandle_)
  211236. :
  211237. midiOutput (midiOutput_),
  211238. seqHandle (seqHandle_),
  211239. maxEventSize (16 * 1024)
  211240. {
  211241. jassert (seqHandle != 0 && midiOutput != 0);
  211242. snd_midi_event_new (maxEventSize, &midiParser);
  211243. }
  211244. ~MidiOutputDevice()
  211245. {
  211246. snd_midi_event_free (midiParser);
  211247. snd_seq_close (seqHandle);
  211248. }
  211249. void sendMessageNow (const MidiMessage& message)
  211250. {
  211251. if (message.getRawDataSize() > maxEventSize)
  211252. {
  211253. maxEventSize = message.getRawDataSize();
  211254. snd_midi_event_free (midiParser);
  211255. snd_midi_event_new (maxEventSize, &midiParser);
  211256. }
  211257. snd_seq_event_t event;
  211258. snd_seq_ev_clear (&event);
  211259. snd_midi_event_encode (midiParser,
  211260. message.getRawData(),
  211261. message.getRawDataSize(),
  211262. &event);
  211263. snd_midi_event_reset_encode (midiParser);
  211264. snd_seq_ev_set_source (&event, 0);
  211265. snd_seq_ev_set_subs (&event);
  211266. snd_seq_ev_set_direct (&event);
  211267. snd_seq_event_output_direct (seqHandle, &event);
  211268. }
  211269. juce_UseDebuggingNewOperator
  211270. private:
  211271. MidiOutput* const midiOutput;
  211272. snd_seq_t* const seqHandle;
  211273. snd_midi_event_t* midiParser;
  211274. int maxEventSize;
  211275. };
  211276. const StringArray MidiOutput::getDevices()
  211277. {
  211278. StringArray devices;
  211279. iterateDevices (false, devices, -1);
  211280. return devices;
  211281. }
  211282. int MidiOutput::getDefaultDeviceIndex()
  211283. {
  211284. return 0;
  211285. }
  211286. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  211287. {
  211288. MidiOutput* newDevice = 0;
  211289. StringArray devices;
  211290. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  211291. if (handle != 0)
  211292. {
  211293. newDevice = new MidiOutput();
  211294. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  211295. }
  211296. return newDevice;
  211297. }
  211298. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  211299. {
  211300. MidiOutput* newDevice = 0;
  211301. snd_seq_t* const handle = createDevice (false, deviceName);
  211302. if (handle != 0)
  211303. {
  211304. newDevice = new MidiOutput();
  211305. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  211306. }
  211307. return newDevice;
  211308. }
  211309. MidiOutput::~MidiOutput()
  211310. {
  211311. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  211312. delete device;
  211313. }
  211314. void MidiOutput::reset()
  211315. {
  211316. }
  211317. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211318. {
  211319. return false;
  211320. }
  211321. void MidiOutput::setVolume (float leftVol, float rightVol)
  211322. {
  211323. }
  211324. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211325. {
  211326. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  211327. }
  211328. class MidiInputThread : public Thread
  211329. {
  211330. public:
  211331. MidiInputThread (MidiInput* const midiInput_,
  211332. snd_seq_t* const seqHandle_,
  211333. MidiInputCallback* const callback_)
  211334. : Thread (T("Juce MIDI Input")),
  211335. midiInput (midiInput_),
  211336. seqHandle (seqHandle_),
  211337. callback (callback_)
  211338. {
  211339. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  211340. }
  211341. ~MidiInputThread()
  211342. {
  211343. snd_seq_close (seqHandle);
  211344. }
  211345. void run()
  211346. {
  211347. const int maxEventSize = 16 * 1024;
  211348. snd_midi_event_t* midiParser;
  211349. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  211350. {
  211351. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  211352. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  211353. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  211354. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  211355. while (! threadShouldExit())
  211356. {
  211357. if (poll (pfd, numPfds, 500) > 0)
  211358. {
  211359. snd_seq_event_t* inputEvent = 0;
  211360. snd_seq_nonblock (seqHandle, 1);
  211361. do
  211362. {
  211363. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  211364. {
  211365. // xxx what about SYSEXes that are too big for the buffer?
  211366. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  211367. snd_midi_event_reset_decode (midiParser);
  211368. if (numBytes > 0)
  211369. {
  211370. const MidiMessage message ((const uint8*) buffer,
  211371. numBytes,
  211372. Time::getMillisecondCounter() * 0.001);
  211373. callback->handleIncomingMidiMessage (midiInput, message);
  211374. }
  211375. snd_seq_free_event (inputEvent);
  211376. }
  211377. }
  211378. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  211379. snd_seq_free_event (inputEvent);
  211380. }
  211381. }
  211382. snd_midi_event_free (midiParser);
  211383. juce_free (buffer);
  211384. }
  211385. };
  211386. juce_UseDebuggingNewOperator
  211387. private:
  211388. MidiInput* const midiInput;
  211389. snd_seq_t* const seqHandle;
  211390. MidiInputCallback* const callback;
  211391. };
  211392. MidiInput::MidiInput (const String& name_)
  211393. : name (name_),
  211394. internal (0)
  211395. {
  211396. }
  211397. MidiInput::~MidiInput()
  211398. {
  211399. stop();
  211400. MidiInputThread* const thread = (MidiInputThread*) internal;
  211401. delete thread;
  211402. }
  211403. void MidiInput::start()
  211404. {
  211405. ((MidiInputThread*) internal)->startThread();
  211406. }
  211407. void MidiInput::stop()
  211408. {
  211409. ((MidiInputThread*) internal)->stopThread (3000);
  211410. }
  211411. int MidiInput::getDefaultDeviceIndex()
  211412. {
  211413. return 0;
  211414. }
  211415. const StringArray MidiInput::getDevices()
  211416. {
  211417. StringArray devices;
  211418. iterateDevices (true, devices, -1);
  211419. return devices;
  211420. }
  211421. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  211422. {
  211423. MidiInput* newDevice = 0;
  211424. StringArray devices;
  211425. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  211426. if (handle != 0)
  211427. {
  211428. newDevice = new MidiInput (devices [deviceIndex]);
  211429. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  211430. }
  211431. return newDevice;
  211432. }
  211433. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  211434. {
  211435. MidiInput* newDevice = 0;
  211436. snd_seq_t* const handle = createDevice (true, deviceName);
  211437. if (handle != 0)
  211438. {
  211439. newDevice = new MidiInput (deviceName);
  211440. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  211441. }
  211442. return newDevice;
  211443. }
  211444. END_JUCE_NAMESPACE
  211445. #else
  211446. // (These are just stub functions if ALSA is unavailable...)
  211447. BEGIN_JUCE_NAMESPACE
  211448. const StringArray MidiOutput::getDevices() { return StringArray(); }
  211449. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  211450. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  211451. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  211452. MidiOutput::~MidiOutput() {}
  211453. void MidiOutput::reset() {}
  211454. bool MidiOutput::getVolume (float&, float&) { return false; }
  211455. void MidiOutput::setVolume (float, float) {}
  211456. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  211457. MidiInput::MidiInput (const String& name_)
  211458. : name (name_),
  211459. internal (0)
  211460. {}
  211461. MidiInput::~MidiInput() {}
  211462. void MidiInput::start() {}
  211463. void MidiInput::stop() {}
  211464. int MidiInput::getDefaultDeviceIndex() { return 0; }
  211465. const StringArray MidiInput::getDevices() { return StringArray(); }
  211466. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  211467. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  211468. END_JUCE_NAMESPACE
  211469. #endif
  211470. #endif
  211471. /********* End of inlined file: juce_linux_Midi.cpp *********/
  211472. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  211473. BEGIN_JUCE_NAMESPACE
  211474. /*
  211475. Sorry.. This class isn't implemented on Linux!
  211476. */
  211477. WebBrowserComponent::WebBrowserComponent()
  211478. : browser (0),
  211479. blankPageShown (false)
  211480. {
  211481. setOpaque (true);
  211482. }
  211483. WebBrowserComponent::~WebBrowserComponent()
  211484. {
  211485. }
  211486. void WebBrowserComponent::goToURL (const String& url,
  211487. const StringArray* headers,
  211488. const MemoryBlock* postData)
  211489. {
  211490. lastURL = url;
  211491. lastHeaders.clear();
  211492. if (headers != 0)
  211493. lastHeaders = *headers;
  211494. lastPostData.setSize (0);
  211495. if (postData != 0)
  211496. lastPostData = *postData;
  211497. blankPageShown = false;
  211498. }
  211499. void WebBrowserComponent::stop()
  211500. {
  211501. }
  211502. void WebBrowserComponent::goBack()
  211503. {
  211504. lastURL = String::empty;
  211505. blankPageShown = false;
  211506. }
  211507. void WebBrowserComponent::goForward()
  211508. {
  211509. lastURL = String::empty;
  211510. }
  211511. void WebBrowserComponent::paint (Graphics& g)
  211512. {
  211513. g.fillAll (Colours::white);
  211514. }
  211515. void WebBrowserComponent::checkWindowAssociation()
  211516. {
  211517. }
  211518. void WebBrowserComponent::reloadLastURL()
  211519. {
  211520. if (lastURL.isNotEmpty())
  211521. {
  211522. goToURL (lastURL, &lastHeaders, &lastPostData);
  211523. lastURL = String::empty;
  211524. }
  211525. }
  211526. void WebBrowserComponent::parentHierarchyChanged()
  211527. {
  211528. checkWindowAssociation();
  211529. }
  211530. void WebBrowserComponent::moved()
  211531. {
  211532. }
  211533. void WebBrowserComponent::resized()
  211534. {
  211535. }
  211536. void WebBrowserComponent::visibilityChanged()
  211537. {
  211538. checkWindowAssociation();
  211539. }
  211540. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  211541. {
  211542. return true;
  211543. }
  211544. END_JUCE_NAMESPACE
  211545. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  211546. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  211547. #if JUCE_BUILD_GUI_CLASSES
  211548. #include <X11/Xlib.h>
  211549. #include <X11/Xutil.h>
  211550. #include <X11/Xatom.h>
  211551. #include <X11/Xmd.h>
  211552. #include <X11/keysym.h>
  211553. #include <X11/cursorfont.h>
  211554. #include <dlfcn.h>
  211555. #if JUCE_USE_XINERAMA
  211556. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  211557. */
  211558. #include <X11/extensions/Xinerama.h>
  211559. #endif
  211560. #if JUCE_USE_XSHM
  211561. #include <X11/extensions/XShm.h>
  211562. #include <sys/shm.h>
  211563. #include <sys/ipc.h>
  211564. #endif
  211565. #if JUCE_OPENGL
  211566. /* Got an include error here?
  211567. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  211568. and "freeglut3-dev".
  211569. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  211570. want to disable it.
  211571. */
  211572. #include <GL/glx.h>
  211573. #endif
  211574. #undef KeyPress
  211575. BEGIN_JUCE_NAMESPACE
  211576. #define TAKE_FOCUS 0
  211577. #define DELETE_WINDOW 1
  211578. #define SYSTEM_TRAY_REQUEST_DOCK 0
  211579. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  211580. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  211581. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  211582. static Atom wm_ChangeState = None;
  211583. static Atom wm_State = None;
  211584. static Atom wm_Protocols = None;
  211585. static Atom wm_ProtocolList [2] = { None, None };
  211586. static Atom wm_ActiveWin = None;
  211587. #define ourDndVersion 3
  211588. static Atom XA_XdndAware = None;
  211589. static Atom XA_XdndEnter = None;
  211590. static Atom XA_XdndLeave = None;
  211591. static Atom XA_XdndPosition = None;
  211592. static Atom XA_XdndStatus = None;
  211593. static Atom XA_XdndDrop = None;
  211594. static Atom XA_XdndFinished = None;
  211595. static Atom XA_XdndSelection = None;
  211596. static Atom XA_XdndProxy = None;
  211597. static Atom XA_XdndTypeList = None;
  211598. static Atom XA_XdndActionList = None;
  211599. static Atom XA_XdndActionDescription = None;
  211600. static Atom XA_XdndActionCopy = None;
  211601. static Atom XA_XdndActionMove = None;
  211602. static Atom XA_XdndActionLink = None;
  211603. static Atom XA_XdndActionAsk = None;
  211604. static Atom XA_XdndActionPrivate = None;
  211605. static Atom XA_JXSelectionWindowProperty = None;
  211606. static Atom XA_MimeTextPlain = None;
  211607. static Atom XA_MimeTextUriList = None;
  211608. static Atom XA_MimeRootDrop = None;
  211609. static XErrorHandler oldHandler = 0;
  211610. static int trappedErrorCode = 0;
  211611. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  211612. {
  211613. trappedErrorCode = err->error_code;
  211614. return 0;
  211615. }
  211616. static void trapErrors()
  211617. {
  211618. trappedErrorCode = 0;
  211619. oldHandler = XSetErrorHandler (errorTrapHandler);
  211620. }
  211621. static bool untrapErrors()
  211622. {
  211623. XSetErrorHandler (oldHandler);
  211624. return (trappedErrorCode == 0);
  211625. }
  211626. static bool isActiveApplication = false;
  211627. bool Process::isForegroundProcess() throw()
  211628. {
  211629. return isActiveApplication;
  211630. }
  211631. // (used in the messaging code, declared here for build reasons)
  211632. bool juce_isRunningAsApplication()
  211633. {
  211634. return JUCEApplication::getInstance() != 0;
  211635. }
  211636. // These are defined in juce_linux_Messaging.cpp
  211637. extern Display* display;
  211638. extern XContext improbableNumber;
  211639. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  211640. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  211641. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  211642. static int pointerMap[5];
  211643. static int lastMousePosX = 0, lastMousePosY = 0;
  211644. enum MouseButtons
  211645. {
  211646. NoButton = 0,
  211647. LeftButton = 1,
  211648. MiddleButton = 2,
  211649. RightButton = 3,
  211650. WheelUp = 4,
  211651. WheelDown = 5
  211652. };
  211653. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  211654. {
  211655. Window root, child;
  211656. int winx, winy;
  211657. unsigned int mask;
  211658. mouseMods = 0;
  211659. if (XQueryPointer (display,
  211660. RootWindow (display, DefaultScreen (display)),
  211661. &root, &child,
  211662. &x, &y, &winx, &winy, &mask) == False)
  211663. {
  211664. // Pointer not on the default screen
  211665. x = y = -1;
  211666. }
  211667. else
  211668. {
  211669. if ((mask & Button1Mask) != 0)
  211670. mouseMods |= ModifierKeys::leftButtonModifier;
  211671. if ((mask & Button2Mask) != 0)
  211672. mouseMods |= ModifierKeys::middleButtonModifier;
  211673. if ((mask & Button3Mask) != 0)
  211674. mouseMods |= ModifierKeys::rightButtonModifier;
  211675. }
  211676. }
  211677. static int AltMask = 0;
  211678. static int NumLockMask = 0;
  211679. static bool numLock = 0;
  211680. static bool capsLock = 0;
  211681. static char keyStates [32];
  211682. static void updateKeyStates (const int keycode, const bool press) throw()
  211683. {
  211684. const int keybyte = keycode >> 3;
  211685. const int keybit = (1 << (keycode & 7));
  211686. if (press)
  211687. keyStates [keybyte] |= keybit;
  211688. else
  211689. keyStates [keybyte] &= ~keybit;
  211690. }
  211691. static bool keyDown (const int keycode) throw()
  211692. {
  211693. const int keybyte = keycode >> 3;
  211694. const int keybit = (1 << (keycode & 7));
  211695. return (keyStates [keybyte] & keybit) != 0;
  211696. }
  211697. static const int extendedKeyModifier = 0x10000000;
  211698. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  211699. {
  211700. int keysym;
  211701. if (keyCode & extendedKeyModifier)
  211702. {
  211703. keysym = 0xff00 | (keyCode & 0xff);
  211704. }
  211705. else
  211706. {
  211707. keysym = keyCode;
  211708. if (keysym == (XK_Tab & 0xff)
  211709. || keysym == (XK_Return & 0xff)
  211710. || keysym == (XK_Escape & 0xff)
  211711. || keysym == (XK_BackSpace & 0xff))
  211712. {
  211713. keysym |= 0xff00;
  211714. }
  211715. }
  211716. return keyDown (XKeysymToKeycode (display, keysym));
  211717. }
  211718. // Alt and Num lock are not defined by standard X
  211719. // modifier constants: check what they're mapped to
  211720. static void getModifierMapping() throw()
  211721. {
  211722. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  211723. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  211724. AltMask = 0;
  211725. NumLockMask = 0;
  211726. XModifierKeymap* mapping = XGetModifierMapping (display);
  211727. if (mapping)
  211728. {
  211729. for (int i = 0; i < 8; i++)
  211730. {
  211731. if (mapping->modifiermap [i << 1] == altLeftCode)
  211732. AltMask = 1 << i;
  211733. else if (mapping->modifiermap [i << 1] == numLockCode)
  211734. NumLockMask = 1 << i;
  211735. }
  211736. XFreeModifiermap (mapping);
  211737. }
  211738. }
  211739. static int currentModifiers = 0;
  211740. void ModifierKeys::updateCurrentModifiers() throw()
  211741. {
  211742. currentModifierFlags = currentModifiers;
  211743. }
  211744. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  211745. {
  211746. int x, y, mouseMods;
  211747. getMousePos (x, y, mouseMods);
  211748. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  211749. currentModifiers |= mouseMods;
  211750. return ModifierKeys (currentModifiers);
  211751. }
  211752. static void updateKeyModifiers (const int status) throw()
  211753. {
  211754. currentModifiers &= ~(ModifierKeys::shiftModifier
  211755. | ModifierKeys::ctrlModifier
  211756. | ModifierKeys::altModifier);
  211757. if (status & ShiftMask)
  211758. currentModifiers |= ModifierKeys::shiftModifier;
  211759. if (status & ControlMask)
  211760. currentModifiers |= ModifierKeys::ctrlModifier;
  211761. if (status & AltMask)
  211762. currentModifiers |= ModifierKeys::altModifier;
  211763. numLock = ((status & NumLockMask) != 0);
  211764. capsLock = ((status & LockMask) != 0);
  211765. }
  211766. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  211767. {
  211768. int modifier = 0;
  211769. bool isModifier = true;
  211770. switch (sym)
  211771. {
  211772. case XK_Shift_L:
  211773. case XK_Shift_R:
  211774. modifier = ModifierKeys::shiftModifier;
  211775. break;
  211776. case XK_Control_L:
  211777. case XK_Control_R:
  211778. modifier = ModifierKeys::ctrlModifier;
  211779. break;
  211780. case XK_Alt_L:
  211781. case XK_Alt_R:
  211782. modifier = ModifierKeys::altModifier;
  211783. break;
  211784. case XK_Num_Lock:
  211785. if (press)
  211786. numLock = ! numLock;
  211787. break;
  211788. case XK_Caps_Lock:
  211789. if (press)
  211790. capsLock = ! capsLock;
  211791. break;
  211792. case XK_Scroll_Lock:
  211793. break;
  211794. default:
  211795. isModifier = false;
  211796. break;
  211797. }
  211798. if (modifier != 0)
  211799. {
  211800. if (press)
  211801. currentModifiers |= modifier;
  211802. else
  211803. currentModifiers &= ~modifier;
  211804. }
  211805. return isModifier;
  211806. }
  211807. #if JUCE_USE_XSHM
  211808. static bool isShmAvailable() throw()
  211809. {
  211810. static bool isChecked = false;
  211811. static bool isAvailable = false;
  211812. if (! isChecked)
  211813. {
  211814. isChecked = true;
  211815. int major, minor;
  211816. Bool pixmaps;
  211817. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  211818. {
  211819. trapErrors();
  211820. XShmSegmentInfo segmentInfo;
  211821. zerostruct (segmentInfo);
  211822. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  211823. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  211824. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  211825. xImage->bytes_per_line * xImage->height,
  211826. IPC_CREAT | 0777)) >= 0)
  211827. {
  211828. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  211829. if (segmentInfo.shmaddr != (void*) -1)
  211830. {
  211831. segmentInfo.readOnly = False;
  211832. xImage->data = segmentInfo.shmaddr;
  211833. XSync (display, False);
  211834. if (XShmAttach (display, &segmentInfo) != 0)
  211835. {
  211836. XSync (display, False);
  211837. XShmDetach (display, &segmentInfo);
  211838. isAvailable = true;
  211839. }
  211840. }
  211841. XFlush (display);
  211842. XDestroyImage (xImage);
  211843. shmdt (segmentInfo.shmaddr);
  211844. }
  211845. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211846. isAvailable &= untrapErrors();
  211847. }
  211848. }
  211849. return isAvailable;
  211850. }
  211851. #endif
  211852. class XBitmapImage : public Image
  211853. {
  211854. public:
  211855. XBitmapImage (const PixelFormat format_, const int w, const int h,
  211856. const bool clearImage, const bool is16Bit_)
  211857. : Image (format_, w, h),
  211858. is16Bit (is16Bit_)
  211859. {
  211860. jassert (format_ == RGB || format_ == ARGB);
  211861. pixelStride = (format_ == RGB) ? 3 : 4;
  211862. lineStride = ((w * pixelStride + 3) & ~3);
  211863. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  211864. #if JUCE_USE_XSHM
  211865. usingXShm = false;
  211866. if ((! is16Bit) && isShmAvailable())
  211867. {
  211868. zerostruct (segmentInfo);
  211869. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  211870. if (xImage != 0)
  211871. {
  211872. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  211873. xImage->bytes_per_line * xImage->height,
  211874. IPC_CREAT | 0777)) >= 0)
  211875. {
  211876. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  211877. if (segmentInfo.shmaddr != (void*) -1)
  211878. {
  211879. segmentInfo.readOnly = False;
  211880. xImage->data = segmentInfo.shmaddr;
  211881. imageData = (uint8*) segmentInfo.shmaddr;
  211882. XSync (display, False);
  211883. if (XShmAttach (display, &segmentInfo) != 0)
  211884. {
  211885. XSync (display, False);
  211886. usingXShm = true;
  211887. }
  211888. else
  211889. {
  211890. jassertfalse
  211891. }
  211892. }
  211893. else
  211894. {
  211895. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211896. }
  211897. }
  211898. }
  211899. }
  211900. if (! usingXShm)
  211901. #endif
  211902. {
  211903. imageData = (uint8*) juce_malloc (lineStride * h);
  211904. if (format_ == ARGB && clearImage)
  211905. zeromem (imageData, h * lineStride);
  211906. xImage = (XImage*) juce_calloc (sizeof (XImage));
  211907. xImage->width = w;
  211908. xImage->height = h;
  211909. xImage->xoffset = 0;
  211910. xImage->format = ZPixmap;
  211911. xImage->data = (char*) imageData;
  211912. xImage->byte_order = ImageByteOrder (display);
  211913. xImage->bitmap_unit = BitmapUnit (display);
  211914. xImage->bitmap_bit_order = BitmapBitOrder (display);
  211915. xImage->bitmap_pad = 32;
  211916. xImage->depth = pixelStride * 8;
  211917. xImage->bytes_per_line = lineStride;
  211918. xImage->bits_per_pixel = pixelStride * 8;
  211919. xImage->red_mask = 0x00FF0000;
  211920. xImage->green_mask = 0x0000FF00;
  211921. xImage->blue_mask = 0x000000FF;
  211922. if (is16Bit)
  211923. {
  211924. const int pixelStride = 2;
  211925. const int lineStride = ((w * pixelStride + 3) & ~3);
  211926. xImage->data = (char*) juce_malloc (lineStride * h);
  211927. xImage->bitmap_pad = 16;
  211928. xImage->depth = pixelStride * 8;
  211929. xImage->bytes_per_line = lineStride;
  211930. xImage->bits_per_pixel = pixelStride * 8;
  211931. xImage->red_mask = visual->red_mask;
  211932. xImage->green_mask = visual->green_mask;
  211933. xImage->blue_mask = visual->blue_mask;
  211934. }
  211935. if (! XInitImage (xImage))
  211936. {
  211937. jassertfalse
  211938. }
  211939. }
  211940. }
  211941. ~XBitmapImage()
  211942. {
  211943. #if JUCE_USE_XSHM
  211944. if (usingXShm)
  211945. {
  211946. XShmDetach (display, &segmentInfo);
  211947. XFlush (display);
  211948. XDestroyImage (xImage);
  211949. shmdt (segmentInfo.shmaddr);
  211950. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211951. }
  211952. else
  211953. #endif
  211954. {
  211955. juce_free (xImage->data);
  211956. xImage->data = 0;
  211957. XDestroyImage (xImage);
  211958. }
  211959. if (! is16Bit)
  211960. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  211961. }
  211962. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  211963. {
  211964. static GC gc = 0;
  211965. if (gc == 0)
  211966. gc = DefaultGC (display, DefaultScreen (display));
  211967. if (is16Bit)
  211968. {
  211969. const uint32 rMask = xImage->red_mask;
  211970. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  211971. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  211972. const uint32 gMask = xImage->green_mask;
  211973. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  211974. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  211975. const uint32 bMask = xImage->blue_mask;
  211976. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  211977. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  211978. int ls, ps;
  211979. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  211980. jassert (! isARGB())
  211981. for (int y = sy; y < sy + dh; ++y)
  211982. {
  211983. const uint8* p = pixels + y * ls + sx * ps;
  211984. for (int x = sx; x < sx + dw; ++x)
  211985. {
  211986. const PixelRGB* const pixel = (const PixelRGB*) p;
  211987. p += ps;
  211988. XPutPixel (xImage, x, y,
  211989. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  211990. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  211991. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  211992. }
  211993. }
  211994. releasePixelDataReadOnly (pixels);
  211995. }
  211996. // blit results to screen.
  211997. #if JUCE_USE_XSHM
  211998. if (usingXShm)
  211999. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  212000. else
  212001. #endif
  212002. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  212003. }
  212004. juce_UseDebuggingNewOperator
  212005. private:
  212006. XImage* xImage;
  212007. const bool is16Bit;
  212008. #if JUCE_USE_XSHM
  212009. XShmSegmentInfo segmentInfo;
  212010. bool usingXShm;
  212011. #endif
  212012. static int getShiftNeeded (const uint32 mask) throw()
  212013. {
  212014. for (int i = 32; --i >= 0;)
  212015. if (((mask >> i) & 1) != 0)
  212016. return i - 7;
  212017. jassertfalse
  212018. return 0;
  212019. }
  212020. };
  212021. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  212022. class LinuxComponentPeer : public ComponentPeer
  212023. {
  212024. public:
  212025. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  212026. : ComponentPeer (component, windowStyleFlags),
  212027. windowH (0),
  212028. parentWindow (0),
  212029. wx (0),
  212030. wy (0),
  212031. ww (0),
  212032. wh (0),
  212033. taskbarImage (0),
  212034. fullScreen (false),
  212035. entered (false),
  212036. mapped (false)
  212037. {
  212038. // it's dangerous to create a window on a thread other than the message thread..
  212039. checkMessageManagerIsLocked
  212040. repainter = new LinuxRepaintManager (this);
  212041. createWindow();
  212042. setTitle (component->getName());
  212043. }
  212044. ~LinuxComponentPeer()
  212045. {
  212046. // it's dangerous to delete a window on a thread other than the message thread..
  212047. checkMessageManagerIsLocked
  212048. deleteTaskBarIcon();
  212049. destroyWindow();
  212050. windowH = 0;
  212051. delete repainter;
  212052. }
  212053. void* getNativeHandle() const
  212054. {
  212055. return (void*) windowH;
  212056. }
  212057. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  212058. {
  212059. XPointer peer = 0;
  212060. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  212061. {
  212062. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  212063. peer = 0;
  212064. }
  212065. return (LinuxComponentPeer*) peer;
  212066. }
  212067. void setVisible (bool shouldBeVisible)
  212068. {
  212069. if (shouldBeVisible)
  212070. XMapWindow (display, windowH);
  212071. else
  212072. XUnmapWindow (display, windowH);
  212073. }
  212074. void setTitle (const String& title)
  212075. {
  212076. setWindowTitle (windowH, title);
  212077. }
  212078. void setPosition (int x, int y)
  212079. {
  212080. setBounds (x, y, ww, wh, false);
  212081. }
  212082. void setSize (int w, int h)
  212083. {
  212084. setBounds (wx, wy, w, h, false);
  212085. }
  212086. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  212087. {
  212088. fullScreen = isNowFullScreen;
  212089. if (windowH != 0)
  212090. {
  212091. const ComponentDeletionWatcher deletionChecker (component);
  212092. wx = x;
  212093. wy = y;
  212094. ww = jmax (1, w);
  212095. wh = jmax (1, h);
  212096. if (! mapped)
  212097. {
  212098. // Make sure the Window manager does what we want
  212099. XSizeHints* hints = XAllocSizeHints();
  212100. hints->flags = USSize | USPosition;
  212101. hints->width = ww + windowBorder.getLeftAndRight();
  212102. hints->height = wh + windowBorder.getTopAndBottom();
  212103. hints->x = wx - windowBorder.getLeft();
  212104. hints->y = wy - windowBorder.getTop();
  212105. XSetWMNormalHints (display, windowH, hints);
  212106. XFree (hints);
  212107. }
  212108. XMoveResizeWindow (display, windowH,
  212109. wx - windowBorder.getLeft(),
  212110. wy - windowBorder.getTop(),
  212111. ww + windowBorder.getLeftAndRight(),
  212112. wh + windowBorder.getTopAndBottom());
  212113. if (! deletionChecker.hasBeenDeleted())
  212114. {
  212115. updateBorderSize();
  212116. handleMovedOrResized();
  212117. }
  212118. }
  212119. }
  212120. void getBounds (int& x, int& y, int& w, int& h) const
  212121. {
  212122. x = wx;
  212123. y = wy;
  212124. w = ww;
  212125. h = wh;
  212126. }
  212127. int getScreenX() const
  212128. {
  212129. return wx;
  212130. }
  212131. int getScreenY() const
  212132. {
  212133. return wy;
  212134. }
  212135. void relativePositionToGlobal (int& x, int& y)
  212136. {
  212137. x += wx;
  212138. y += wy;
  212139. }
  212140. void globalPositionToRelative (int& x, int& y)
  212141. {
  212142. x -= wx;
  212143. y -= wy;
  212144. }
  212145. void setMinimised (bool shouldBeMinimised)
  212146. {
  212147. if (shouldBeMinimised)
  212148. {
  212149. Window root = RootWindow (display, DefaultScreen (display));
  212150. XClientMessageEvent clientMsg;
  212151. clientMsg.display = display;
  212152. clientMsg.window = windowH;
  212153. clientMsg.type = ClientMessage;
  212154. clientMsg.format = 32;
  212155. clientMsg.message_type = wm_ChangeState;
  212156. clientMsg.data.l[0] = IconicState;
  212157. XSendEvent (display, root, false,
  212158. SubstructureRedirectMask | SubstructureNotifyMask,
  212159. (XEvent*) &clientMsg);
  212160. }
  212161. else
  212162. {
  212163. setVisible (true);
  212164. }
  212165. }
  212166. bool isMinimised() const
  212167. {
  212168. bool minimised = false;
  212169. unsigned char* stateProp;
  212170. unsigned long nitems, bytesLeft;
  212171. Atom actualType;
  212172. int actualFormat;
  212173. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  212174. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  212175. &stateProp) == Success
  212176. && actualType == wm_State
  212177. && actualFormat == 32
  212178. && nitems > 0)
  212179. {
  212180. if (((unsigned long*) stateProp)[0] == IconicState)
  212181. minimised = true;
  212182. XFree (stateProp);
  212183. }
  212184. return minimised;
  212185. }
  212186. void setFullScreen (const bool shouldBeFullScreen)
  212187. {
  212188. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  212189. setMinimised (false);
  212190. if (fullScreen != shouldBeFullScreen)
  212191. {
  212192. if (shouldBeFullScreen)
  212193. r = Desktop::getInstance().getMainMonitorArea();
  212194. if (! r.isEmpty())
  212195. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  212196. getComponent()->repaint();
  212197. }
  212198. }
  212199. bool isFullScreen() const
  212200. {
  212201. return fullScreen;
  212202. }
  212203. bool isChildWindowOf (Window possibleParent) const
  212204. {
  212205. Window* windowList = 0;
  212206. uint32 windowListSize = 0;
  212207. Window parent, root;
  212208. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  212209. {
  212210. if (windowList != 0)
  212211. XFree (windowList);
  212212. return parent == possibleParent;
  212213. }
  212214. return false;
  212215. }
  212216. bool isFrontWindow() const
  212217. {
  212218. Window* windowList = 0;
  212219. uint32 windowListSize = 0;
  212220. bool result = false;
  212221. Window parent, root = RootWindow (display, DefaultScreen (display));
  212222. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  212223. {
  212224. for (int i = windowListSize; --i >= 0;)
  212225. {
  212226. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  212227. if (peer != 0)
  212228. {
  212229. result = (peer == this);
  212230. break;
  212231. }
  212232. }
  212233. }
  212234. if (windowList != 0)
  212235. XFree (windowList);
  212236. return result;
  212237. }
  212238. bool contains (int x, int y, bool trueIfInAChildWindow) const
  212239. {
  212240. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  212241. if (((unsigned int) x) >= (unsigned int) ww
  212242. || ((unsigned int) y) >= (unsigned int) wh)
  212243. return false;
  212244. bool inFront = false;
  212245. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  212246. {
  212247. Component* const c = Desktop::getInstance().getComponent (i);
  212248. if (inFront)
  212249. {
  212250. if (c->contains (x + wx - c->getScreenX(),
  212251. y + wy - c->getScreenY()))
  212252. {
  212253. return false;
  212254. }
  212255. }
  212256. else if (c == getComponent())
  212257. {
  212258. inFront = true;
  212259. }
  212260. }
  212261. if (trueIfInAChildWindow)
  212262. return true;
  212263. ::Window root, child;
  212264. unsigned int bw, depth;
  212265. int wx, wy, w, h;
  212266. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  212267. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  212268. &bw, &depth))
  212269. {
  212270. return false;
  212271. }
  212272. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  212273. return false;
  212274. return child == None;
  212275. }
  212276. const BorderSize getFrameSize() const
  212277. {
  212278. return BorderSize();
  212279. }
  212280. bool setAlwaysOnTop (bool alwaysOnTop)
  212281. {
  212282. if (windowH != 0)
  212283. {
  212284. const bool wasVisible = component->isVisible();
  212285. if (wasVisible)
  212286. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  212287. XSetWindowAttributes swa;
  212288. swa.override_redirect = alwaysOnTop ? True : False;
  212289. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  212290. if (wasVisible)
  212291. setVisible (true);
  212292. }
  212293. return true;
  212294. }
  212295. void toFront (bool makeActive)
  212296. {
  212297. if (makeActive)
  212298. {
  212299. setVisible (true);
  212300. grabFocus();
  212301. }
  212302. XEvent ev;
  212303. ev.xclient.type = ClientMessage;
  212304. ev.xclient.serial = 0;
  212305. ev.xclient.send_event = True;
  212306. ev.xclient.message_type = wm_ActiveWin;
  212307. ev.xclient.window = windowH;
  212308. ev.xclient.format = 32;
  212309. ev.xclient.data.l[0] = 2;
  212310. ev.xclient.data.l[1] = CurrentTime;
  212311. ev.xclient.data.l[2] = 0;
  212312. ev.xclient.data.l[3] = 0;
  212313. ev.xclient.data.l[4] = 0;
  212314. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  212315. False,
  212316. SubstructureRedirectMask | SubstructureNotifyMask,
  212317. &ev);
  212318. XSync (display, False);
  212319. handleBroughtToFront();
  212320. }
  212321. void toBehind (ComponentPeer* other)
  212322. {
  212323. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  212324. jassert (otherPeer != 0); // wrong type of window?
  212325. if (otherPeer != 0)
  212326. {
  212327. setMinimised (false);
  212328. Window newStack[] = { otherPeer->windowH, windowH };
  212329. XRestackWindows (display, newStack, 2);
  212330. }
  212331. }
  212332. bool isFocused() const
  212333. {
  212334. int revert;
  212335. Window focusedWindow = 0;
  212336. XGetInputFocus (display, &focusedWindow, &revert);
  212337. return focusedWindow == windowH;
  212338. }
  212339. void grabFocus()
  212340. {
  212341. XWindowAttributes atts;
  212342. if (windowH != 0
  212343. && XGetWindowAttributes (display, windowH, &atts)
  212344. && atts.map_state == IsViewable
  212345. && ! isFocused())
  212346. {
  212347. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  212348. isActiveApplication = true;
  212349. }
  212350. }
  212351. void repaint (int x, int y, int w, int h)
  212352. {
  212353. if (Rectangle::intersectRectangles (x, y, w, h,
  212354. 0, 0,
  212355. getComponent()->getWidth(),
  212356. getComponent()->getHeight()))
  212357. {
  212358. repainter->repaint (x, y, w, h);
  212359. }
  212360. }
  212361. void performAnyPendingRepaintsNow()
  212362. {
  212363. repainter->performAnyPendingRepaintsNow();
  212364. }
  212365. void setIcon (const Image& newIcon)
  212366. {
  212367. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  212368. uint32* const data = (uint32*) juce_malloc (dataSize);
  212369. int index = 0;
  212370. data[index++] = newIcon.getWidth();
  212371. data[index++] = newIcon.getHeight();
  212372. for (int y = 0; y < newIcon.getHeight(); ++y)
  212373. for (int x = 0; x < newIcon.getWidth(); ++x)
  212374. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  212375. XChangeProperty (display, windowH,
  212376. XInternAtom (display, "_NET_WM_ICON", False),
  212377. XA_CARDINAL, 32, PropModeReplace,
  212378. (unsigned char*) data, dataSize);
  212379. XSync (display, False);
  212380. juce_free (data);
  212381. }
  212382. void handleWindowMessage (XEvent* event)
  212383. {
  212384. switch (event->xany.type)
  212385. {
  212386. case 2: // 'KeyPress'
  212387. {
  212388. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  212389. updateKeyStates (keyEvent->keycode, true);
  212390. char utf8 [64];
  212391. zeromem (utf8, sizeof (utf8));
  212392. KeySym sym;
  212393. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  212394. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  212395. int keyCode = (int) unicodeChar;
  212396. if (keyCode < 0x20)
  212397. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  212398. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  212399. const int oldMods = currentModifiers;
  212400. bool keyPressed = false;
  212401. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  212402. if ((sym & 0xff00) == 0xff00)
  212403. {
  212404. // Translate keypad
  212405. if (sym == XK_KP_Divide)
  212406. keyCode = XK_slash;
  212407. else if (sym == XK_KP_Multiply)
  212408. keyCode = XK_asterisk;
  212409. else if (sym == XK_KP_Subtract)
  212410. keyCode = XK_hyphen;
  212411. else if (sym == XK_KP_Add)
  212412. keyCode = XK_plus;
  212413. else if (sym == XK_KP_Enter)
  212414. keyCode = XK_Return;
  212415. else if (sym == XK_KP_Decimal)
  212416. keyCode = numLock ? XK_period : XK_Delete;
  212417. else if (sym == XK_KP_0)
  212418. keyCode = numLock ? XK_0 : XK_Insert;
  212419. else if (sym == XK_KP_1)
  212420. keyCode = numLock ? XK_1 : XK_End;
  212421. else if (sym == XK_KP_2)
  212422. keyCode = numLock ? XK_2 : XK_Down;
  212423. else if (sym == XK_KP_3)
  212424. keyCode = numLock ? XK_3 : XK_Page_Down;
  212425. else if (sym == XK_KP_4)
  212426. keyCode = numLock ? XK_4 : XK_Left;
  212427. else if (sym == XK_KP_5)
  212428. keyCode = XK_5;
  212429. else if (sym == XK_KP_6)
  212430. keyCode = numLock ? XK_6 : XK_Right;
  212431. else if (sym == XK_KP_7)
  212432. keyCode = numLock ? XK_7 : XK_Home;
  212433. else if (sym == XK_KP_8)
  212434. keyCode = numLock ? XK_8 : XK_Up;
  212435. else if (sym == XK_KP_9)
  212436. keyCode = numLock ? XK_9 : XK_Page_Up;
  212437. switch (sym)
  212438. {
  212439. case XK_Left:
  212440. case XK_Right:
  212441. case XK_Up:
  212442. case XK_Down:
  212443. case XK_Page_Up:
  212444. case XK_Page_Down:
  212445. case XK_End:
  212446. case XK_Home:
  212447. case XK_Delete:
  212448. case XK_Insert:
  212449. keyPressed = true;
  212450. keyCode = (sym & 0xff) | extendedKeyModifier;
  212451. break;
  212452. case XK_Tab:
  212453. case XK_Return:
  212454. case XK_Escape:
  212455. case XK_BackSpace:
  212456. keyPressed = true;
  212457. keyCode &= 0xff;
  212458. break;
  212459. default:
  212460. {
  212461. if (sym >= XK_F1 && sym <= XK_F16)
  212462. {
  212463. keyPressed = true;
  212464. keyCode = (sym & 0xff) | extendedKeyModifier;
  212465. }
  212466. break;
  212467. }
  212468. }
  212469. }
  212470. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  212471. keyPressed = true;
  212472. if (oldMods != currentModifiers)
  212473. handleModifierKeysChange();
  212474. if (keyDownChange)
  212475. handleKeyUpOrDown();
  212476. if (keyPressed)
  212477. handleKeyPress (keyCode, unicodeChar);
  212478. break;
  212479. }
  212480. case KeyRelease:
  212481. {
  212482. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  212483. updateKeyStates (keyEvent->keycode, false);
  212484. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  212485. const int oldMods = currentModifiers;
  212486. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  212487. if (oldMods != currentModifiers)
  212488. handleModifierKeysChange();
  212489. if (keyDownChange)
  212490. handleKeyUpOrDown();
  212491. break;
  212492. }
  212493. case ButtonPress:
  212494. {
  212495. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  212496. bool buttonMsg = false;
  212497. bool wheelUpMsg = false;
  212498. bool wheelDownMsg = false;
  212499. const int map = pointerMap [buttonPressEvent->button - Button1];
  212500. if (map == LeftButton)
  212501. {
  212502. currentModifiers |= ModifierKeys::leftButtonModifier;
  212503. buttonMsg = true;
  212504. }
  212505. else if (map == RightButton)
  212506. {
  212507. currentModifiers |= ModifierKeys::rightButtonModifier;
  212508. buttonMsg = true;
  212509. }
  212510. else if (map == MiddleButton)
  212511. {
  212512. currentModifiers |= ModifierKeys::middleButtonModifier;
  212513. buttonMsg = true;
  212514. }
  212515. else if (map == WheelUp)
  212516. {
  212517. wheelUpMsg = true;
  212518. }
  212519. else if (map == WheelDown)
  212520. {
  212521. wheelDownMsg = true;
  212522. }
  212523. updateKeyModifiers (buttonPressEvent->state);
  212524. if (buttonMsg)
  212525. {
  212526. toFront (true);
  212527. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  212528. getEventTime (buttonPressEvent->time));
  212529. }
  212530. else if (wheelUpMsg || wheelDownMsg)
  212531. {
  212532. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  212533. getEventTime (buttonPressEvent->time));
  212534. }
  212535. lastMousePosX = lastMousePosY = 0x100000;
  212536. break;
  212537. }
  212538. case ButtonRelease:
  212539. {
  212540. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  212541. const int oldModifiers = currentModifiers;
  212542. const int map = pointerMap [buttonRelEvent->button - Button1];
  212543. if (map == LeftButton)
  212544. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  212545. else if (map == RightButton)
  212546. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  212547. else if (map == MiddleButton)
  212548. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  212549. updateKeyModifiers (buttonRelEvent->state);
  212550. handleMouseUp (oldModifiers,
  212551. buttonRelEvent->x, buttonRelEvent->y,
  212552. getEventTime (buttonRelEvent->time));
  212553. lastMousePosX = lastMousePosY = 0x100000;
  212554. break;
  212555. }
  212556. case MotionNotify:
  212557. {
  212558. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  212559. updateKeyModifiers (movedEvent->state);
  212560. int x, y, mouseMods;
  212561. getMousePos (x, y, mouseMods);
  212562. if (lastMousePosX != x || lastMousePosY != y)
  212563. {
  212564. lastMousePosX = x;
  212565. lastMousePosY = y;
  212566. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  212567. {
  212568. Window wRoot = 0, wParent = 0;
  212569. Window* wChild = 0;
  212570. unsigned int numChildren;
  212571. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  212572. if (wParent != 0
  212573. && wParent != windowH
  212574. && wParent != wRoot)
  212575. {
  212576. parentWindow = wParent;
  212577. updateBounds();
  212578. x -= getScreenX();
  212579. y -= getScreenY();
  212580. }
  212581. else
  212582. {
  212583. parentWindow = 0;
  212584. x -= getScreenX();
  212585. y -= getScreenY();
  212586. }
  212587. }
  212588. else
  212589. {
  212590. x -= getScreenX();
  212591. y -= getScreenY();
  212592. }
  212593. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  212594. handleMouseMove (x, y, getEventTime (movedEvent->time));
  212595. else
  212596. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  212597. }
  212598. break;
  212599. }
  212600. case EnterNotify:
  212601. {
  212602. lastMousePosX = lastMousePosY = 0x100000;
  212603. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  212604. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  212605. && ! entered)
  212606. {
  212607. updateKeyModifiers (enterEvent->state);
  212608. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  212609. entered = true;
  212610. }
  212611. break;
  212612. }
  212613. case LeaveNotify:
  212614. {
  212615. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  212616. // Suppress the normal leave if we've got a pointer grab, or if
  212617. // it's a bogus one caused by clicking a mouse button when running
  212618. // in a Window manager
  212619. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  212620. && leaveEvent->mode == NotifyNormal)
  212621. || leaveEvent->mode == NotifyUngrab)
  212622. {
  212623. updateKeyModifiers (leaveEvent->state);
  212624. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  212625. entered = false;
  212626. }
  212627. break;
  212628. }
  212629. case FocusIn:
  212630. {
  212631. isActiveApplication = true;
  212632. if (isFocused())
  212633. handleFocusGain();
  212634. break;
  212635. }
  212636. case FocusOut:
  212637. {
  212638. isActiveApplication = false;
  212639. if (! isFocused())
  212640. handleFocusLoss();
  212641. break;
  212642. }
  212643. case Expose:
  212644. {
  212645. // Batch together all pending expose events
  212646. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  212647. XEvent nextEvent;
  212648. if (exposeEvent->window != windowH)
  212649. {
  212650. Window child;
  212651. XTranslateCoordinates (display, exposeEvent->window, windowH,
  212652. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  212653. &child);
  212654. }
  212655. repaint (exposeEvent->x, exposeEvent->y,
  212656. exposeEvent->width, exposeEvent->height);
  212657. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  212658. {
  212659. XPeekEvent (display, (XEvent*) &nextEvent);
  212660. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  212661. break;
  212662. XNextEvent (display, (XEvent*) &nextEvent);
  212663. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  212664. repaint (nextExposeEvent->x, nextExposeEvent->y,
  212665. nextExposeEvent->width, nextExposeEvent->height);
  212666. }
  212667. break;
  212668. }
  212669. case CirculateNotify:
  212670. case CreateNotify:
  212671. case DestroyNotify:
  212672. // Think we can ignore these
  212673. break;
  212674. case ConfigureNotify:
  212675. {
  212676. updateBounds();
  212677. updateBorderSize();
  212678. handleMovedOrResized();
  212679. // if the native title bar is dragged, need to tell any active menus, etc.
  212680. if ((styleFlags & windowHasTitleBar) != 0
  212681. && component->isCurrentlyBlockedByAnotherModalComponent())
  212682. {
  212683. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  212684. if (currentModalComp != 0)
  212685. currentModalComp->inputAttemptWhenModal();
  212686. }
  212687. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  212688. if (confEvent->window == windowH
  212689. && confEvent->above != 0
  212690. && isFrontWindow())
  212691. {
  212692. handleBroughtToFront();
  212693. }
  212694. break;
  212695. }
  212696. case ReparentNotify:
  212697. case GravityNotify:
  212698. {
  212699. parentWindow = 0;
  212700. Window wRoot = 0;
  212701. Window* wChild = 0;
  212702. unsigned int numChildren;
  212703. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  212704. if (parentWindow == windowH || parentWindow == wRoot)
  212705. parentWindow = 0;
  212706. updateBounds();
  212707. updateBorderSize();
  212708. handleMovedOrResized();
  212709. break;
  212710. }
  212711. case MapNotify:
  212712. mapped = true;
  212713. handleBroughtToFront();
  212714. break;
  212715. case UnmapNotify:
  212716. mapped = false;
  212717. break;
  212718. case MappingNotify:
  212719. {
  212720. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  212721. if (mappingEvent->request != MappingPointer)
  212722. {
  212723. // Deal with modifier/keyboard mapping
  212724. XRefreshKeyboardMapping (mappingEvent);
  212725. getModifierMapping();
  212726. }
  212727. break;
  212728. }
  212729. case ClientMessage:
  212730. {
  212731. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  212732. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  212733. {
  212734. const Atom atom = (Atom) clientMsg->data.l[0];
  212735. if (atom == wm_ProtocolList [TAKE_FOCUS])
  212736. {
  212737. XWindowAttributes atts;
  212738. if (clientMsg->window != 0
  212739. && XGetWindowAttributes (display, clientMsg->window, &atts))
  212740. {
  212741. if (atts.map_state == IsViewable)
  212742. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  212743. }
  212744. }
  212745. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  212746. {
  212747. handleUserClosingWindow();
  212748. }
  212749. }
  212750. else if (clientMsg->message_type == XA_XdndEnter)
  212751. {
  212752. handleDragAndDropEnter (clientMsg);
  212753. }
  212754. else if (clientMsg->message_type == XA_XdndLeave)
  212755. {
  212756. resetDragAndDrop();
  212757. }
  212758. else if (clientMsg->message_type == XA_XdndPosition)
  212759. {
  212760. handleDragAndDropPosition (clientMsg);
  212761. }
  212762. else if (clientMsg->message_type == XA_XdndDrop)
  212763. {
  212764. handleDragAndDropDrop (clientMsg);
  212765. }
  212766. else if (clientMsg->message_type == XA_XdndStatus)
  212767. {
  212768. handleDragAndDropStatus (clientMsg);
  212769. }
  212770. else if (clientMsg->message_type == XA_XdndFinished)
  212771. {
  212772. resetDragAndDrop();
  212773. }
  212774. break;
  212775. }
  212776. case SelectionNotify:
  212777. handleDragAndDropSelection (event);
  212778. break;
  212779. case SelectionClear:
  212780. case SelectionRequest:
  212781. break;
  212782. default:
  212783. break;
  212784. }
  212785. }
  212786. void showMouseCursor (Cursor cursor) throw()
  212787. {
  212788. XDefineCursor (display, windowH, cursor);
  212789. }
  212790. void setTaskBarIcon (const Image& image)
  212791. {
  212792. deleteTaskBarIcon();
  212793. taskbarImage = image.createCopy();
  212794. Screen* const screen = XDefaultScreenOfDisplay (display);
  212795. const int screenNumber = XScreenNumberOfScreen (screen);
  212796. char screenAtom[32];
  212797. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  212798. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  212799. XGrabServer (display);
  212800. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  212801. if (managerWin != None)
  212802. XSelectInput (display, managerWin, StructureNotifyMask);
  212803. XUngrabServer (display);
  212804. XFlush (display);
  212805. if (managerWin != None)
  212806. {
  212807. XEvent ev;
  212808. zerostruct (ev);
  212809. ev.xclient.type = ClientMessage;
  212810. ev.xclient.window = managerWin;
  212811. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  212812. ev.xclient.format = 32;
  212813. ev.xclient.data.l[0] = CurrentTime;
  212814. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  212815. ev.xclient.data.l[2] = windowH;
  212816. ev.xclient.data.l[3] = 0;
  212817. ev.xclient.data.l[4] = 0;
  212818. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  212819. XSync (display, False);
  212820. }
  212821. // For older KDE's ...
  212822. long atomData = 1;
  212823. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  212824. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  212825. // For more recent KDE's...
  212826. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  212827. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  212828. }
  212829. void deleteTaskBarIcon()
  212830. {
  212831. deleteAndZero (taskbarImage);
  212832. }
  212833. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  212834. juce_UseDebuggingNewOperator
  212835. bool dontRepaint;
  212836. private:
  212837. class LinuxRepaintManager : public Timer
  212838. {
  212839. public:
  212840. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  212841. : peer (peer_),
  212842. image (0),
  212843. lastTimeImageUsed (0)
  212844. {
  212845. #if JUCE_USE_XSHM
  212846. useARGBImagesForRendering = isShmAvailable();
  212847. if (useARGBImagesForRendering)
  212848. {
  212849. XShmSegmentInfo segmentinfo;
  212850. XImage* const testImage
  212851. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  212852. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  212853. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  212854. XDestroyImage (testImage);
  212855. }
  212856. #endif
  212857. }
  212858. ~LinuxRepaintManager()
  212859. {
  212860. delete image;
  212861. }
  212862. void timerCallback()
  212863. {
  212864. if (! regionsNeedingRepaint.isEmpty())
  212865. {
  212866. stopTimer();
  212867. performAnyPendingRepaintsNow();
  212868. }
  212869. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  212870. {
  212871. stopTimer();
  212872. deleteAndZero (image);
  212873. }
  212874. }
  212875. void repaint (int x, int y, int w, int h)
  212876. {
  212877. if (! isTimerRunning())
  212878. startTimer (repaintTimerPeriod);
  212879. regionsNeedingRepaint.add (x, y, w, h);
  212880. }
  212881. void performAnyPendingRepaintsNow()
  212882. {
  212883. peer->clearMaskedRegion();
  212884. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  212885. if (! totalArea.isEmpty())
  212886. {
  212887. if (image == 0 || image->getWidth() < totalArea.getWidth()
  212888. || image->getHeight() < totalArea.getHeight())
  212889. {
  212890. delete image;
  212891. #if JUCE_USE_XSHM
  212892. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  212893. : Image::RGB,
  212894. #else
  212895. image = new XBitmapImage (Image::RGB,
  212896. #endif
  212897. (totalArea.getWidth() + 31) & ~31,
  212898. (totalArea.getHeight() + 31) & ~31,
  212899. false,
  212900. peer->depthIs16Bit);
  212901. }
  212902. startTimer (repaintTimerPeriod);
  212903. LowLevelGraphicsSoftwareRenderer context (*image);
  212904. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  212905. if (context.reduceClipRegion (regionsNeedingRepaint))
  212906. peer->handlePaint (context);
  212907. if (! peer->maskedRegion.isEmpty())
  212908. regionsNeedingRepaint.subtract (peer->maskedRegion);
  212909. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  212910. {
  212911. const Rectangle& r = *i.getRectangle();
  212912. image->blitToWindow (peer->windowH,
  212913. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  212914. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  212915. }
  212916. }
  212917. regionsNeedingRepaint.clear();
  212918. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  212919. startTimer (repaintTimerPeriod);
  212920. }
  212921. private:
  212922. LinuxComponentPeer* const peer;
  212923. XBitmapImage* image;
  212924. uint32 lastTimeImageUsed;
  212925. RectangleList regionsNeedingRepaint;
  212926. #if JUCE_USE_XSHM
  212927. bool useARGBImagesForRendering;
  212928. #endif
  212929. LinuxRepaintManager (const LinuxRepaintManager&);
  212930. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  212931. };
  212932. LinuxRepaintManager* repainter;
  212933. friend class LinuxRepaintManager;
  212934. Window windowH, parentWindow;
  212935. int wx, wy, ww, wh;
  212936. Image* taskbarImage;
  212937. bool fullScreen, entered, mapped, depthIs16Bit;
  212938. BorderSize windowBorder;
  212939. void removeWindowDecorations (Window wndH)
  212940. {
  212941. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  212942. if (hints != None)
  212943. {
  212944. typedef struct
  212945. {
  212946. unsigned long flags;
  212947. unsigned long functions;
  212948. unsigned long decorations;
  212949. long input_mode;
  212950. unsigned long status;
  212951. } MotifWmHints;
  212952. MotifWmHints motifHints;
  212953. zerostruct (motifHints);
  212954. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  212955. motifHints.decorations = 0;
  212956. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212957. (unsigned char*) &motifHints, 4);
  212958. }
  212959. hints = XInternAtom (display, "_WIN_HINTS", True);
  212960. if (hints != None)
  212961. {
  212962. long gnomeHints = 0;
  212963. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212964. (unsigned char*) &gnomeHints, 1);
  212965. }
  212966. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  212967. if (hints != None)
  212968. {
  212969. long kwmHints = 2; /*KDE_tinyDecoration*/
  212970. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212971. (unsigned char*) &kwmHints, 1);
  212972. }
  212973. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  212974. if (hints != None)
  212975. {
  212976. long netHints [2];
  212977. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  212978. if ((styleFlags & windowIsTemporary) != 0)
  212979. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  212980. else
  212981. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  212982. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  212983. (unsigned char*) &netHints, 2);
  212984. }
  212985. }
  212986. void addWindowButtons (Window wndH)
  212987. {
  212988. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  212989. if (hints != None)
  212990. {
  212991. typedef struct
  212992. {
  212993. unsigned long flags;
  212994. unsigned long functions;
  212995. unsigned long decorations;
  212996. long input_mode;
  212997. unsigned long status;
  212998. } MotifWmHints;
  212999. MotifWmHints motifHints;
  213000. zerostruct (motifHints);
  213001. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  213002. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  213003. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  213004. if ((styleFlags & windowHasCloseButton) != 0)
  213005. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  213006. if ((styleFlags & windowHasMinimiseButton) != 0)
  213007. {
  213008. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  213009. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  213010. }
  213011. if ((styleFlags & windowHasMaximiseButton) != 0)
  213012. {
  213013. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  213014. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  213015. }
  213016. if ((styleFlags & windowIsResizable) != 0)
  213017. {
  213018. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  213019. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  213020. }
  213021. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  213022. }
  213023. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  213024. if (hints != None)
  213025. {
  213026. long netHints [6];
  213027. int num = 0;
  213028. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  213029. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  213030. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  213031. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  213032. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213033. (unsigned char*) &netHints, num);
  213034. }
  213035. }
  213036. void createWindow()
  213037. {
  213038. static bool atomsInitialised = false;
  213039. if (! atomsInitialised)
  213040. {
  213041. atomsInitialised = true;
  213042. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  213043. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  213044. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  213045. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  213046. wm_State = XInternAtom (display, "WM_STATE", 1);
  213047. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  213048. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  213049. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  213050. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  213051. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  213052. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  213053. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  213054. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  213055. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  213056. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  213057. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  213058. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  213059. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  213060. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  213061. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  213062. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  213063. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  213064. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  213065. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  213066. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  213067. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  213068. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  213069. }
  213070. resetDragAndDrop();
  213071. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  213072. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  213073. allowedMimeTypeAtoms [1] = XA_OtherMime;
  213074. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  213075. allowedActions [0] = XA_XdndActionMove;
  213076. allowedActions [1] = XA_XdndActionCopy;
  213077. allowedActions [2] = XA_XdndActionLink;
  213078. allowedActions [3] = XA_XdndActionAsk;
  213079. allowedActions [4] = XA_XdndActionPrivate;
  213080. // Get defaults for various properties
  213081. const int screen = DefaultScreen (display);
  213082. Window root = RootWindow (display, screen);
  213083. // Attempt to create a 24-bit window on the default screen. If this is not
  213084. // possible then exit
  213085. XVisualInfo desiredVisual;
  213086. desiredVisual.screen = screen;
  213087. desiredVisual.depth = 24;
  213088. depthIs16Bit = false;
  213089. int numVisuals;
  213090. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213091. &desiredVisual, &numVisuals);
  213092. if (numVisuals < 1 || visuals == 0)
  213093. {
  213094. XFree (visuals);
  213095. desiredVisual.depth = 16;
  213096. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213097. &desiredVisual, &numVisuals);
  213098. if (numVisuals < 1 || visuals == 0)
  213099. {
  213100. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  213101. Process::terminate();
  213102. }
  213103. depthIs16Bit = true;
  213104. }
  213105. XFree (visuals);
  213106. // Set up the window attributes
  213107. XSetWindowAttributes swa;
  213108. swa.border_pixel = 0;
  213109. swa.background_pixmap = None;
  213110. swa.colormap = DefaultColormap (display, screen);
  213111. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  213112. swa.event_mask = eventMask;
  213113. Window wndH = XCreateWindow (display, root,
  213114. 0, 0, 1, 1,
  213115. 0, 0, InputOutput, (Visual*) CopyFromParent,
  213116. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  213117. &swa);
  213118. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  213119. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  213120. GrabModeAsync, GrabModeAsync, None, None);
  213121. // Set the window context to identify the window handle object
  213122. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  213123. {
  213124. // Failed
  213125. jassertfalse
  213126. Logger::outputDebugString ("Failed to create context information for window.\n");
  213127. XDestroyWindow (display, wndH);
  213128. wndH = 0;
  213129. }
  213130. // Set window manager hints
  213131. XWMHints* wmHints = XAllocWMHints();
  213132. wmHints->flags = InputHint | StateHint;
  213133. wmHints->input = True; // Locally active input model
  213134. wmHints->initial_state = NormalState;
  213135. XSetWMHints (display, wndH, wmHints);
  213136. XFree (wmHints);
  213137. if ((styleFlags & windowIsSemiTransparent) != 0)
  213138. {
  213139. //xxx
  213140. }
  213141. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  213142. {
  213143. //xxx
  213144. }
  213145. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  213146. if ((styleFlags & windowHasTitleBar) == 0)
  213147. removeWindowDecorations (wndH);
  213148. else
  213149. addWindowButtons (wndH);
  213150. // Set window manager protocols
  213151. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  213152. (unsigned char*) wm_ProtocolList, 2);
  213153. // Set drag and drop flags
  213154. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  213155. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  213156. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  213157. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  213158. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  213159. (const unsigned char*) "", 0);
  213160. unsigned long dndVersion = ourDndVersion;
  213161. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  213162. (const unsigned char*) &dndVersion, 1);
  213163. // Set window name
  213164. setWindowTitle (wndH, getComponent()->getName());
  213165. // Initialise the pointer and keyboard mapping
  213166. // This is not the same as the logical pointer mapping the X server uses:
  213167. // we don't mess with this.
  213168. static bool mappingInitialised = false;
  213169. if (! mappingInitialised)
  213170. {
  213171. mappingInitialised = true;
  213172. const int numButtons = XGetPointerMapping (display, 0, 0);
  213173. if (numButtons == 2)
  213174. {
  213175. pointerMap[0] = LeftButton;
  213176. pointerMap[1] = RightButton;
  213177. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  213178. }
  213179. else if (numButtons >= 3)
  213180. {
  213181. pointerMap[0] = LeftButton;
  213182. pointerMap[1] = MiddleButton;
  213183. pointerMap[2] = RightButton;
  213184. if (numButtons >= 5)
  213185. {
  213186. pointerMap[3] = WheelUp;
  213187. pointerMap[4] = WheelDown;
  213188. }
  213189. }
  213190. getModifierMapping();
  213191. }
  213192. windowH = wndH;
  213193. }
  213194. void destroyWindow()
  213195. {
  213196. XPointer handlePointer;
  213197. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  213198. XDeleteContext (display, (XID) windowH, improbableNumber);
  213199. XDestroyWindow (display, windowH);
  213200. // Wait for it to complete and then remove any events for this
  213201. // window from the event queue.
  213202. XSync (display, false);
  213203. XEvent event;
  213204. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  213205. {}
  213206. }
  213207. static int64 getEventTime (::Time t) throw()
  213208. {
  213209. static int64 eventTimeOffset = 0x12345678;
  213210. const int64 thisMessageTime = t;
  213211. if (eventTimeOffset == 0x12345678)
  213212. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  213213. return eventTimeOffset + thisMessageTime;
  213214. }
  213215. static void setWindowTitle (Window xwin, const char* const title) throw()
  213216. {
  213217. XTextProperty nameProperty;
  213218. char* strings[] = { (char*) title };
  213219. if (XStringListToTextProperty (strings, 1, &nameProperty))
  213220. {
  213221. XSetWMName (display, xwin, &nameProperty);
  213222. XSetWMIconName (display, xwin, &nameProperty);
  213223. XFree (nameProperty.value);
  213224. }
  213225. }
  213226. void updateBorderSize()
  213227. {
  213228. if ((styleFlags & windowHasTitleBar) == 0)
  213229. {
  213230. windowBorder = BorderSize (0);
  213231. }
  213232. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  213233. {
  213234. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  213235. if (hints != None)
  213236. {
  213237. unsigned char* data = 0;
  213238. unsigned long nitems, bytesLeft;
  213239. Atom actualType;
  213240. int actualFormat;
  213241. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  213242. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213243. &data) == Success)
  213244. {
  213245. const unsigned long* const sizes = (const unsigned long*) data;
  213246. if (actualFormat == 32)
  213247. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  213248. (int) sizes[3], (int) sizes[1]);
  213249. XFree (data);
  213250. }
  213251. }
  213252. }
  213253. }
  213254. void updateBounds()
  213255. {
  213256. jassert (windowH != 0);
  213257. if (windowH != 0)
  213258. {
  213259. Window root, child;
  213260. unsigned int bw, depth;
  213261. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213262. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  213263. &bw, &depth))
  213264. {
  213265. wx = wy = ww = wh = 0;
  213266. }
  213267. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  213268. {
  213269. wx = wy = 0;
  213270. }
  213271. }
  213272. }
  213273. void resetDragAndDrop()
  213274. {
  213275. dragAndDropFiles.clear();
  213276. lastDropX = lastDropY = -1;
  213277. dragAndDropCurrentMimeType = 0;
  213278. dragAndDropSourceWindow = 0;
  213279. srcMimeTypeAtomList.clear();
  213280. }
  213281. void sendDragAndDropMessage (XClientMessageEvent& msg)
  213282. {
  213283. msg.type = ClientMessage;
  213284. msg.display = display;
  213285. msg.window = dragAndDropSourceWindow;
  213286. msg.format = 32;
  213287. msg.data.l[0] = windowH;
  213288. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  213289. }
  213290. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  213291. {
  213292. XClientMessageEvent msg;
  213293. zerostruct (msg);
  213294. msg.message_type = XA_XdndStatus;
  213295. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  213296. msg.data.l[4] = dropAction;
  213297. sendDragAndDropMessage (msg);
  213298. }
  213299. void sendDragAndDropLeave()
  213300. {
  213301. XClientMessageEvent msg;
  213302. zerostruct (msg);
  213303. msg.message_type = XA_XdndLeave;
  213304. sendDragAndDropMessage (msg);
  213305. }
  213306. void sendDragAndDropFinish()
  213307. {
  213308. XClientMessageEvent msg;
  213309. zerostruct (msg);
  213310. msg.message_type = XA_XdndFinished;
  213311. sendDragAndDropMessage (msg);
  213312. }
  213313. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  213314. {
  213315. if ((clientMsg->data.l[1] & 1) == 0)
  213316. {
  213317. sendDragAndDropLeave();
  213318. if (dragAndDropFiles.size() > 0)
  213319. handleFileDragExit (dragAndDropFiles);
  213320. dragAndDropFiles.clear();
  213321. }
  213322. }
  213323. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  213324. {
  213325. if (dragAndDropSourceWindow == 0)
  213326. return;
  213327. dragAndDropSourceWindow = clientMsg->data.l[0];
  213328. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  213329. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  213330. if (lastDropX != dropX || lastDropY != dropY)
  213331. {
  213332. lastDropX = dropX;
  213333. lastDropY = dropY;
  213334. dragAndDropTimestamp = clientMsg->data.l[3];
  213335. Atom targetAction = XA_XdndActionCopy;
  213336. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  213337. {
  213338. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  213339. {
  213340. targetAction = allowedActions[i];
  213341. break;
  213342. }
  213343. }
  213344. sendDragAndDropStatus (true, targetAction);
  213345. if (dragAndDropFiles.size() == 0)
  213346. updateDraggedFileList (clientMsg);
  213347. if (dragAndDropFiles.size() > 0)
  213348. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  213349. }
  213350. }
  213351. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  213352. {
  213353. if (dragAndDropFiles.size() == 0)
  213354. updateDraggedFileList (clientMsg);
  213355. const StringArray files (dragAndDropFiles);
  213356. const int lastX = lastDropX, lastY = lastDropY;
  213357. sendDragAndDropFinish();
  213358. resetDragAndDrop();
  213359. if (files.size() > 0)
  213360. handleFileDragDrop (files, lastX, lastY);
  213361. }
  213362. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  213363. {
  213364. dragAndDropFiles.clear();
  213365. srcMimeTypeAtomList.clear();
  213366. dragAndDropCurrentMimeType = 0;
  213367. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  213368. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  213369. {
  213370. dragAndDropSourceWindow = 0;
  213371. return;
  213372. }
  213373. dragAndDropSourceWindow = clientMsg->data.l[0];
  213374. if ((clientMsg->data.l[1] & 1) != 0)
  213375. {
  213376. Atom actual;
  213377. int format;
  213378. unsigned long count = 0, remaining = 0;
  213379. unsigned char* data = 0;
  213380. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  213381. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  213382. &count, &remaining, &data);
  213383. if (data != 0)
  213384. {
  213385. if (actual == XA_ATOM && format == 32 && count != 0)
  213386. {
  213387. const unsigned long* const types = (const unsigned long*) data;
  213388. for (unsigned int i = 0; i < count; ++i)
  213389. if (types[i] != None)
  213390. srcMimeTypeAtomList.add (types[i]);
  213391. }
  213392. XFree (data);
  213393. }
  213394. }
  213395. if (srcMimeTypeAtomList.size() == 0)
  213396. {
  213397. for (int i = 2; i < 5; ++i)
  213398. if (clientMsg->data.l[i] != None)
  213399. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  213400. if (srcMimeTypeAtomList.size() == 0)
  213401. {
  213402. dragAndDropSourceWindow = 0;
  213403. return;
  213404. }
  213405. }
  213406. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  213407. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  213408. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  213409. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  213410. handleDragAndDropPosition (clientMsg);
  213411. }
  213412. void handleDragAndDropSelection (const XEvent* const evt)
  213413. {
  213414. dragAndDropFiles.clear();
  213415. if (evt->xselection.property != 0)
  213416. {
  213417. StringArray lines;
  213418. {
  213419. MemoryBlock dropData;
  213420. for (;;)
  213421. {
  213422. Atom actual;
  213423. uint8* data = 0;
  213424. unsigned long count = 0, remaining = 0;
  213425. int format = 0;
  213426. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  213427. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  213428. &format, &count, &remaining, &data) == Success)
  213429. {
  213430. dropData.append (data, count * format / 8);
  213431. XFree (data);
  213432. if (remaining == 0)
  213433. break;
  213434. }
  213435. else
  213436. {
  213437. XFree (data);
  213438. break;
  213439. }
  213440. }
  213441. lines.addLines (dropData.toString());
  213442. }
  213443. for (int i = 0; i < lines.size(); ++i)
  213444. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  213445. dragAndDropFiles.trim();
  213446. dragAndDropFiles.removeEmptyStrings();
  213447. }
  213448. }
  213449. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  213450. {
  213451. dragAndDropFiles.clear();
  213452. if (dragAndDropSourceWindow != None
  213453. && dragAndDropCurrentMimeType != 0)
  213454. {
  213455. dragAndDropTimestamp = clientMsg->data.l[2];
  213456. XConvertSelection (display,
  213457. XA_XdndSelection,
  213458. dragAndDropCurrentMimeType,
  213459. XA_JXSelectionWindowProperty,
  213460. windowH,
  213461. dragAndDropTimestamp);
  213462. }
  213463. }
  213464. StringArray dragAndDropFiles;
  213465. int dragAndDropTimestamp, lastDropX, lastDropY;
  213466. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  213467. Window dragAndDropSourceWindow;
  213468. unsigned long allowedActions [5];
  213469. unsigned long allowedMimeTypeAtoms [3];
  213470. Array <Atom> srcMimeTypeAtomList;
  213471. };
  213472. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  213473. {
  213474. return new LinuxComponentPeer (this, styleFlags);
  213475. }
  213476. // (this callback is hooked up in the messaging code)
  213477. void juce_windowMessageReceive (XEvent* event)
  213478. {
  213479. if (event->xany.window != None)
  213480. {
  213481. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  213482. const MessageManagerLock messLock;
  213483. if (ComponentPeer::isValidPeer (peer))
  213484. peer->handleWindowMessage (event);
  213485. }
  213486. else
  213487. {
  213488. switch (event->xany.type)
  213489. {
  213490. case KeymapNotify:
  213491. {
  213492. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  213493. memcpy (keyStates, keymapEvent->key_vector, 32);
  213494. break;
  213495. }
  213496. default:
  213497. break;
  213498. }
  213499. }
  213500. }
  213501. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  213502. {
  213503. #if JUCE_USE_XINERAMA
  213504. int major_opcode, first_event, first_error;
  213505. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  213506. && XineramaIsActive (display))
  213507. {
  213508. int numMonitors = 0;
  213509. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  213510. if (screens != 0)
  213511. {
  213512. for (int i = numMonitors; --i >= 0;)
  213513. {
  213514. int index = screens[i].screen_number;
  213515. if (index >= 0)
  213516. {
  213517. while (monitorCoords.size() < index)
  213518. monitorCoords.add (Rectangle (0, 0, 0, 0));
  213519. monitorCoords.set (index, Rectangle (screens[i].x_org,
  213520. screens[i].y_org,
  213521. screens[i].width,
  213522. screens[i].height));
  213523. }
  213524. }
  213525. XFree (screens);
  213526. }
  213527. }
  213528. if (monitorCoords.size() == 0)
  213529. #endif
  213530. {
  213531. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  213532. if (hints != None)
  213533. {
  213534. const int numMonitors = ScreenCount (display);
  213535. for (int i = 0; i < numMonitors; ++i)
  213536. {
  213537. Window root = RootWindow (display, i);
  213538. unsigned long nitems, bytesLeft;
  213539. Atom actualType;
  213540. int actualFormat;
  213541. unsigned char* data = 0;
  213542. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  213543. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213544. &data) == Success)
  213545. {
  213546. const long* const position = (const long*) data;
  213547. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  213548. monitorCoords.add (Rectangle (position[0], position[1],
  213549. position[2], position[3]));
  213550. XFree (data);
  213551. }
  213552. }
  213553. }
  213554. if (monitorCoords.size() == 0)
  213555. {
  213556. monitorCoords.add (Rectangle (0, 0,
  213557. DisplayWidth (display, DefaultScreen (display)),
  213558. DisplayHeight (display, DefaultScreen (display))));
  213559. }
  213560. }
  213561. }
  213562. bool Desktop::canUseSemiTransparentWindows() throw()
  213563. {
  213564. return false;
  213565. }
  213566. void Desktop::getMousePosition (int& x, int& y) throw()
  213567. {
  213568. int mouseMods;
  213569. getMousePos (x, y, mouseMods);
  213570. }
  213571. void Desktop::setMousePosition (int x, int y) throw()
  213572. {
  213573. Window root = RootWindow (display, DefaultScreen (display));
  213574. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  213575. }
  213576. static bool screenSaverAllowed = true;
  213577. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  213578. {
  213579. if (screenSaverAllowed != isEnabled)
  213580. {
  213581. screenSaverAllowed = isEnabled;
  213582. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  213583. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  213584. if (xScreenSaverSuspend == 0)
  213585. {
  213586. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  213587. if (h != 0)
  213588. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  213589. }
  213590. if (xScreenSaverSuspend != 0)
  213591. xScreenSaverSuspend (display, ! isEnabled);
  213592. }
  213593. }
  213594. bool Desktop::isScreenSaverEnabled() throw()
  213595. {
  213596. return screenSaverAllowed;
  213597. }
  213598. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  213599. {
  213600. Window root = RootWindow (display, DefaultScreen (display));
  213601. const unsigned int imageW = image.getWidth();
  213602. const unsigned int imageH = image.getHeight();
  213603. unsigned int cursorW, cursorH;
  213604. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  213605. return 0;
  213606. Image im (Image::ARGB, cursorW, cursorH, true);
  213607. Graphics g (im);
  213608. if (imageW > cursorW || imageH > cursorH)
  213609. {
  213610. hotspotX = (hotspotX * cursorW) / imageW;
  213611. hotspotY = (hotspotY * cursorH) / imageH;
  213612. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  213613. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  213614. false);
  213615. }
  213616. else
  213617. {
  213618. g.drawImageAt (&image, 0, 0);
  213619. }
  213620. const int stride = (cursorW + 7) >> 3;
  213621. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  213622. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  213623. bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  213624. for (int y = cursorH; --y >= 0;)
  213625. {
  213626. for (int x = cursorW; --x >= 0;)
  213627. {
  213628. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  213629. const int offset = y * stride + (x >> 3);
  213630. const Colour c (im.getPixelAt (x, y));
  213631. if (c.getAlpha() >= 128)
  213632. maskPlane[offset] |= mask;
  213633. if (c.getBrightness() >= 0.5f)
  213634. sourcePlane[offset] |= mask;
  213635. }
  213636. }
  213637. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  213638. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  213639. juce_free (maskPlane);
  213640. juce_free (sourcePlane);
  213641. XColor white, black;
  213642. black.red = black.green = black.blue = 0;
  213643. white.red = white.green = white.blue = 0xffff;
  213644. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  213645. XFreePixmap (display, sourcePixmap);
  213646. XFreePixmap (display, maskPixmap);
  213647. return result;
  213648. }
  213649. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  213650. {
  213651. if (cursorHandle != None)
  213652. XFreeCursor (display, (Cursor) cursorHandle);
  213653. }
  213654. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  213655. {
  213656. unsigned int shape;
  213657. switch (type)
  213658. {
  213659. case MouseCursor::NoCursor:
  213660. {
  213661. const Image im (Image::ARGB, 16, 16, true);
  213662. return juce_createMouseCursorFromImage (im, 0, 0);
  213663. }
  213664. case MouseCursor::NormalCursor:
  213665. return (void*) None; // Use parent cursor
  213666. case MouseCursor::DraggingHandCursor:
  213667. {
  213668. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  213669. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  213670. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  213671. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  213672. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  213673. const int dragHandDataSize = 99;
  213674. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  213675. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  213676. delete im;
  213677. return dragHandCursor;
  213678. }
  213679. case MouseCursor::CopyingCursor:
  213680. {
  213681. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  213682. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  213683. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  213684. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  213685. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  213686. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  213687. const int copyCursorSize = 119;
  213688. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  213689. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  213690. delete im;
  213691. return copyCursor;
  213692. }
  213693. case MouseCursor::WaitCursor:
  213694. shape = XC_watch;
  213695. break;
  213696. case MouseCursor::IBeamCursor:
  213697. shape = XC_xterm;
  213698. break;
  213699. case MouseCursor::PointingHandCursor:
  213700. shape = XC_hand2;
  213701. break;
  213702. case MouseCursor::LeftRightResizeCursor:
  213703. shape = XC_sb_h_double_arrow;
  213704. break;
  213705. case MouseCursor::UpDownResizeCursor:
  213706. shape = XC_sb_v_double_arrow;
  213707. break;
  213708. case MouseCursor::UpDownLeftRightResizeCursor:
  213709. shape = XC_fleur;
  213710. break;
  213711. case MouseCursor::TopEdgeResizeCursor:
  213712. shape = XC_top_side;
  213713. break;
  213714. case MouseCursor::BottomEdgeResizeCursor:
  213715. shape = XC_bottom_side;
  213716. break;
  213717. case MouseCursor::LeftEdgeResizeCursor:
  213718. shape = XC_left_side;
  213719. break;
  213720. case MouseCursor::RightEdgeResizeCursor:
  213721. shape = XC_right_side;
  213722. break;
  213723. case MouseCursor::TopLeftCornerResizeCursor:
  213724. shape = XC_top_left_corner;
  213725. break;
  213726. case MouseCursor::TopRightCornerResizeCursor:
  213727. shape = XC_top_right_corner;
  213728. break;
  213729. case MouseCursor::BottomLeftCornerResizeCursor:
  213730. shape = XC_bottom_left_corner;
  213731. break;
  213732. case MouseCursor::BottomRightCornerResizeCursor:
  213733. shape = XC_bottom_right_corner;
  213734. break;
  213735. case MouseCursor::CrosshairCursor:
  213736. shape = XC_crosshair;
  213737. break;
  213738. default:
  213739. return (void*) None; // Use parent cursor
  213740. }
  213741. return (void*) XCreateFontCursor (display, shape);
  213742. }
  213743. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  213744. {
  213745. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  213746. if (lp != 0)
  213747. lp->showMouseCursor ((Cursor) getHandle());
  213748. }
  213749. void MouseCursor::showInAllWindows() const throw()
  213750. {
  213751. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  213752. showInWindow (ComponentPeer::getPeer (i));
  213753. }
  213754. Image* juce_createIconForFile (const File& file)
  213755. {
  213756. return 0;
  213757. }
  213758. #if JUCE_OPENGL
  213759. class WindowedGLContext : public OpenGLContext
  213760. {
  213761. public:
  213762. WindowedGLContext (Component* const component,
  213763. const OpenGLPixelFormat& pixelFormat_,
  213764. GLXContext sharedContext)
  213765. : renderContext (0),
  213766. embeddedWindow (0),
  213767. pixelFormat (pixelFormat_)
  213768. {
  213769. jassert (component != 0);
  213770. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  213771. if (peer == 0)
  213772. return;
  213773. XSync (display, False);
  213774. GLint attribs [64];
  213775. int n = 0;
  213776. attribs[n++] = GLX_RGBA;
  213777. attribs[n++] = GLX_DOUBLEBUFFER;
  213778. attribs[n++] = GLX_RED_SIZE;
  213779. attribs[n++] = pixelFormat.redBits;
  213780. attribs[n++] = GLX_GREEN_SIZE;
  213781. attribs[n++] = pixelFormat.greenBits;
  213782. attribs[n++] = GLX_BLUE_SIZE;
  213783. attribs[n++] = pixelFormat.blueBits;
  213784. attribs[n++] = GLX_ALPHA_SIZE;
  213785. attribs[n++] = pixelFormat.alphaBits;
  213786. attribs[n++] = GLX_DEPTH_SIZE;
  213787. attribs[n++] = pixelFormat.depthBufferBits;
  213788. attribs[n++] = GLX_STENCIL_SIZE;
  213789. attribs[n++] = pixelFormat.stencilBufferBits;
  213790. attribs[n++] = GLX_ACCUM_RED_SIZE;
  213791. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  213792. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  213793. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  213794. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  213795. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  213796. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  213797. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  213798. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  213799. attribs[n++] = None;
  213800. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  213801. if (bestVisual == 0)
  213802. return;
  213803. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  213804. Window windowH = (Window) peer->getNativeHandle();
  213805. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  213806. XSetWindowAttributes swa;
  213807. swa.colormap = colourMap;
  213808. swa.border_pixel = 0;
  213809. swa.event_mask = ExposureMask | StructureNotifyMask;
  213810. embeddedWindow = XCreateWindow (display, windowH,
  213811. 0, 0, 1, 1, 0,
  213812. bestVisual->depth,
  213813. InputOutput,
  213814. bestVisual->visual,
  213815. CWBorderPixel | CWColormap | CWEventMask,
  213816. &swa);
  213817. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  213818. XMapWindow (display, embeddedWindow);
  213819. XFreeColormap (display, colourMap);
  213820. XFree (bestVisual);
  213821. XSync (display, False);
  213822. }
  213823. ~WindowedGLContext()
  213824. {
  213825. makeInactive();
  213826. glXDestroyContext (display, renderContext);
  213827. XUnmapWindow (display, embeddedWindow);
  213828. XDestroyWindow (display, embeddedWindow);
  213829. }
  213830. bool makeActive() const throw()
  213831. {
  213832. jassert (renderContext != 0);
  213833. return glXMakeCurrent (display, embeddedWindow, renderContext)
  213834. && XSync (display, False);
  213835. }
  213836. bool makeInactive() const throw()
  213837. {
  213838. return (! isActive()) || glXMakeCurrent (display, None, 0);
  213839. }
  213840. bool isActive() const throw()
  213841. {
  213842. return glXGetCurrentContext() == renderContext;
  213843. }
  213844. const OpenGLPixelFormat getPixelFormat() const
  213845. {
  213846. return pixelFormat;
  213847. }
  213848. void* getRawContext() const throw()
  213849. {
  213850. return renderContext;
  213851. }
  213852. void updateWindowPosition (int x, int y, int w, int h, int)
  213853. {
  213854. XMoveResizeWindow (display, embeddedWindow,
  213855. x, y, jmax (1, w), jmax (1, h));
  213856. }
  213857. void swapBuffers()
  213858. {
  213859. glXSwapBuffers (display, embeddedWindow);
  213860. }
  213861. bool setSwapInterval (const int numFramesPerSwap)
  213862. {
  213863. // xxx needs doing..
  213864. return false;
  213865. }
  213866. int getSwapInterval() const
  213867. {
  213868. // xxx needs doing..
  213869. return 0;
  213870. }
  213871. void repaint()
  213872. {
  213873. }
  213874. juce_UseDebuggingNewOperator
  213875. GLXContext renderContext;
  213876. private:
  213877. Window embeddedWindow;
  213878. OpenGLPixelFormat pixelFormat;
  213879. WindowedGLContext (const WindowedGLContext&);
  213880. const WindowedGLContext& operator= (const WindowedGLContext&);
  213881. };
  213882. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  213883. const OpenGLPixelFormat& pixelFormat,
  213884. const OpenGLContext* const contextToShareWith)
  213885. {
  213886. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  213887. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  213888. if (c->renderContext == 0)
  213889. deleteAndZero (c);
  213890. return c;
  213891. }
  213892. void juce_glViewport (const int w, const int h)
  213893. {
  213894. glViewport (0, 0, w, h);
  213895. }
  213896. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  213897. OwnedArray <OpenGLPixelFormat>& results)
  213898. {
  213899. results.add (new OpenGLPixelFormat()); // xxx
  213900. }
  213901. #endif
  213902. static void initClipboard (Window root, Atom* cutBuffers) throw()
  213903. {
  213904. static bool init = false;
  213905. if (! init)
  213906. {
  213907. init = true;
  213908. // Make sure all cut buffers exist before use
  213909. for (int i = 0; i < 8; i++)
  213910. {
  213911. XChangeProperty (display, root, cutBuffers[i],
  213912. XA_STRING, 8, PropModeAppend, NULL, 0);
  213913. }
  213914. }
  213915. }
  213916. // Clipboard implemented currently using cut buffers
  213917. // rather than the more powerful selection method
  213918. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  213919. {
  213920. Window root = RootWindow (display, DefaultScreen (display));
  213921. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  213922. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  213923. initClipboard (root, cutBuffers);
  213924. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  213925. XChangeProperty (display, root, cutBuffers[0],
  213926. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  213927. clipText.length());
  213928. }
  213929. const String SystemClipboard::getTextFromClipboard() throw()
  213930. {
  213931. const int bufSize = 64; // in words
  213932. String returnData;
  213933. int byteOffset = 0;
  213934. Window root = RootWindow (display, DefaultScreen (display));
  213935. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  213936. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  213937. initClipboard (root, cutBuffers);
  213938. for (;;)
  213939. {
  213940. unsigned long bytesLeft = 0, nitems = 0;
  213941. unsigned char* clipData = 0;
  213942. int actualFormat = 0;
  213943. Atom actualType;
  213944. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  213945. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  213946. &clipData) == Success)
  213947. {
  213948. if (actualType == XA_STRING && actualFormat == 8)
  213949. {
  213950. byteOffset += nitems;
  213951. returnData += String ((const char*) clipData, nitems);
  213952. }
  213953. else
  213954. {
  213955. bytesLeft = 0;
  213956. }
  213957. if (clipData != 0)
  213958. XFree (clipData);
  213959. }
  213960. if (bytesLeft == 0)
  213961. break;
  213962. }
  213963. return returnData;
  213964. }
  213965. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  213966. {
  213967. jassertfalse // not implemented!
  213968. return false;
  213969. }
  213970. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  213971. {
  213972. jassertfalse // not implemented!
  213973. return false;
  213974. }
  213975. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  213976. {
  213977. if (! isOnDesktop ())
  213978. addToDesktop (0);
  213979. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  213980. if (wp != 0)
  213981. {
  213982. wp->setTaskBarIcon (newImage);
  213983. setVisible (true);
  213984. toFront (false);
  213985. repaint();
  213986. }
  213987. }
  213988. void SystemTrayIconComponent::paint (Graphics& g)
  213989. {
  213990. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  213991. if (wp != 0)
  213992. {
  213993. const Image* const image = wp->getTaskbarIcon();
  213994. if (image != 0)
  213995. g.drawImageAt (image, 0, 0, false);
  213996. }
  213997. }
  213998. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  213999. {
  214000. // xxx not yet implemented!
  214001. }
  214002. void PlatformUtilities::beep()
  214003. {
  214004. fprintf (stdout, "\a");
  214005. fflush (stdout);
  214006. }
  214007. bool AlertWindow::showNativeDialogBox (const String& title,
  214008. const String& bodyText,
  214009. bool isOkCancel)
  214010. {
  214011. // xxx this is supposed to pop up an alert!
  214012. Logger::outputDebugString (title + ": " + bodyText);
  214013. // use a non-native one for the time being..
  214014. if (isOkCancel)
  214015. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  214016. else
  214017. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  214018. return true;
  214019. }
  214020. const int KeyPress::spaceKey = XK_space & 0xff;
  214021. const int KeyPress::returnKey = XK_Return & 0xff;
  214022. const int KeyPress::escapeKey = XK_Escape & 0xff;
  214023. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  214024. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  214025. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  214026. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  214027. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  214028. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  214029. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  214030. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  214031. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  214032. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  214033. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  214034. const int KeyPress::tabKey = XK_Tab & 0xff;
  214035. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  214036. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  214037. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  214038. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  214039. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  214040. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  214041. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  214042. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  214043. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  214044. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  214045. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  214046. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  214047. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  214048. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  214049. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  214050. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  214051. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  214052. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  214053. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  214054. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  214055. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  214056. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  214057. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  214058. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  214059. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  214060. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  214061. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  214062. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  214063. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  214064. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  214065. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  214066. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  214067. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  214068. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  214069. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  214070. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  214071. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  214072. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  214073. END_JUCE_NAMESPACE
  214074. #endif
  214075. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  214076. #endif
  214077. #endif
  214078. //==============================================================================
  214079. #if JUCE_MAC
  214080. /********* Start of inlined file: juce_mac_Files.cpp *********/
  214081. #include <sys/stat.h>
  214082. #include <sys/dir.h>
  214083. #include <sys/param.h>
  214084. #include <sys/mount.h>
  214085. #include <unistd.h>
  214086. #include <fnmatch.h>
  214087. #include <utime.h>
  214088. #include <pwd.h>
  214089. #include <fcntl.h>
  214090. #include <Carbon/Carbon.h>
  214091. BEGIN_JUCE_NAMESPACE
  214092. /*
  214093. Note that a lot of methods that you'd expect to find in this file actually
  214094. live in juce_posix_SharedCode.cpp!
  214095. */
  214096. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  214097. /*
  214098. This file contains posix routines that are common to both the Linux and Mac builds.
  214099. It gets included directly in the cpp files for these platforms.
  214100. */
  214101. CriticalSection::CriticalSection() throw()
  214102. {
  214103. pthread_mutexattr_t atts;
  214104. pthread_mutexattr_init (&atts);
  214105. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  214106. pthread_mutex_init (&internal, &atts);
  214107. }
  214108. CriticalSection::~CriticalSection() throw()
  214109. {
  214110. pthread_mutex_destroy (&internal);
  214111. }
  214112. void CriticalSection::enter() const throw()
  214113. {
  214114. pthread_mutex_lock (&internal);
  214115. }
  214116. bool CriticalSection::tryEnter() const throw()
  214117. {
  214118. return pthread_mutex_trylock (&internal) == 0;
  214119. }
  214120. void CriticalSection::exit() const throw()
  214121. {
  214122. pthread_mutex_unlock (&internal);
  214123. }
  214124. struct EventStruct
  214125. {
  214126. pthread_cond_t condition;
  214127. pthread_mutex_t mutex;
  214128. bool triggered;
  214129. };
  214130. WaitableEvent::WaitableEvent() throw()
  214131. {
  214132. EventStruct* const es = new EventStruct();
  214133. es->triggered = false;
  214134. pthread_cond_init (&es->condition, 0);
  214135. pthread_mutex_init (&es->mutex, 0);
  214136. internal = es;
  214137. }
  214138. WaitableEvent::~WaitableEvent() throw()
  214139. {
  214140. EventStruct* const es = (EventStruct*) internal;
  214141. pthread_cond_destroy (&es->condition);
  214142. pthread_mutex_destroy (&es->mutex);
  214143. delete es;
  214144. }
  214145. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  214146. {
  214147. EventStruct* const es = (EventStruct*) internal;
  214148. bool ok = true;
  214149. pthread_mutex_lock (&es->mutex);
  214150. if (! es->triggered)
  214151. {
  214152. if (timeOutMillisecs < 0)
  214153. {
  214154. pthread_cond_wait (&es->condition, &es->mutex);
  214155. }
  214156. else
  214157. {
  214158. struct timespec time;
  214159. #if JUCE_MAC
  214160. time.tv_sec = timeOutMillisecs / 1000;
  214161. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  214162. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  214163. #else
  214164. struct timeval t;
  214165. int timeout = 0;
  214166. gettimeofday (&t, 0);
  214167. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  214168. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  214169. while (time.tv_nsec >= 1000000000)
  214170. {
  214171. time.tv_nsec -= 1000000000;
  214172. time.tv_sec++;
  214173. }
  214174. while (! timeout)
  214175. {
  214176. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  214177. if (! timeout)
  214178. // Success
  214179. break;
  214180. if (timeout == EINTR)
  214181. // Go round again
  214182. timeout = 0;
  214183. }
  214184. #endif
  214185. }
  214186. ok = es->triggered;
  214187. }
  214188. es->triggered = false;
  214189. pthread_mutex_unlock (&es->mutex);
  214190. return ok;
  214191. }
  214192. void WaitableEvent::signal() const throw()
  214193. {
  214194. EventStruct* const es = (EventStruct*) internal;
  214195. pthread_mutex_lock (&es->mutex);
  214196. es->triggered = true;
  214197. pthread_cond_broadcast (&es->condition);
  214198. pthread_mutex_unlock (&es->mutex);
  214199. }
  214200. void WaitableEvent::reset() const throw()
  214201. {
  214202. EventStruct* const es = (EventStruct*) internal;
  214203. pthread_mutex_lock (&es->mutex);
  214204. es->triggered = false;
  214205. pthread_mutex_unlock (&es->mutex);
  214206. }
  214207. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  214208. {
  214209. struct timespec time;
  214210. time.tv_sec = millisecs / 1000;
  214211. time.tv_nsec = (millisecs % 1000) * 1000000;
  214212. nanosleep (&time, 0);
  214213. }
  214214. const tchar File::separator = T('/');
  214215. const tchar* File::separatorString = T("/");
  214216. bool juce_copyFile (const String& s, const String& d) throw();
  214217. static bool juce_stat (const String& fileName, struct stat& info) throw()
  214218. {
  214219. return fileName.isNotEmpty()
  214220. && (stat (fileName.toUTF8(), &info) == 0);
  214221. }
  214222. bool juce_isDirectory (const String& fileName) throw()
  214223. {
  214224. struct stat info;
  214225. return fileName.isEmpty()
  214226. || (juce_stat (fileName, info)
  214227. && ((info.st_mode & S_IFDIR) != 0));
  214228. }
  214229. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  214230. {
  214231. if (fileName.isEmpty())
  214232. return false;
  214233. const char* const fileNameUTF8 = fileName.toUTF8();
  214234. bool exists = access (fileNameUTF8, F_OK) == 0;
  214235. if (exists && dontCountDirectories)
  214236. {
  214237. struct stat info;
  214238. const int res = stat (fileNameUTF8, &info);
  214239. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  214240. exists = false;
  214241. }
  214242. return exists;
  214243. }
  214244. int64 juce_getFileSize (const String& fileName) throw()
  214245. {
  214246. struct stat info;
  214247. return juce_stat (fileName, info) ? info.st_size : 0;
  214248. }
  214249. bool juce_canWriteToFile (const String& fileName) throw()
  214250. {
  214251. return access (fileName.toUTF8(), W_OK) == 0;
  214252. }
  214253. bool juce_deleteFile (const String& fileName) throw()
  214254. {
  214255. const char* const fileNameUTF8 = fileName.toUTF8();
  214256. if (juce_isDirectory (fileName))
  214257. return rmdir (fileNameUTF8) == 0;
  214258. else
  214259. return remove (fileNameUTF8) == 0;
  214260. }
  214261. bool juce_moveFile (const String& source, const String& dest) throw()
  214262. {
  214263. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  214264. return true;
  214265. if (juce_canWriteToFile (source)
  214266. && juce_copyFile (source, dest))
  214267. {
  214268. if (juce_deleteFile (source))
  214269. return true;
  214270. juce_deleteFile (dest);
  214271. }
  214272. return false;
  214273. }
  214274. void juce_createDirectory (const String& fileName) throw()
  214275. {
  214276. mkdir (fileName.toUTF8(), 0777);
  214277. }
  214278. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  214279. {
  214280. const char* const fileNameUTF8 = fileName.toUTF8();
  214281. int flags = O_RDONLY;
  214282. if (forWriting)
  214283. {
  214284. if (juce_fileExists (fileName, false))
  214285. {
  214286. const int f = open (fileNameUTF8, O_RDWR, 00644);
  214287. if (f != -1)
  214288. lseek (f, 0, SEEK_END);
  214289. return (void*) f;
  214290. }
  214291. else
  214292. {
  214293. flags = O_RDWR + O_CREAT;
  214294. }
  214295. }
  214296. return (void*) open (fileNameUTF8, flags, 00644);
  214297. }
  214298. void juce_fileClose (void* handle) throw()
  214299. {
  214300. if (handle != 0)
  214301. close ((int) (pointer_sized_int) handle);
  214302. }
  214303. int juce_fileRead (void* handle, void* buffer, int size) throw()
  214304. {
  214305. if (handle != 0)
  214306. return read ((int) (pointer_sized_int) handle, buffer, size);
  214307. return 0;
  214308. }
  214309. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  214310. {
  214311. if (handle != 0)
  214312. return write ((int) (pointer_sized_int) handle, buffer, size);
  214313. return 0;
  214314. }
  214315. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  214316. {
  214317. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  214318. return pos;
  214319. return -1;
  214320. }
  214321. int64 juce_fileGetPosition (void* handle) throw()
  214322. {
  214323. if (handle != 0)
  214324. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  214325. else
  214326. return -1;
  214327. }
  214328. void juce_fileFlush (void* handle) throw()
  214329. {
  214330. if (handle != 0)
  214331. fsync ((int) (pointer_sized_int) handle);
  214332. }
  214333. // if this file doesn't exist, find a parent of it that does..
  214334. static bool doStatFS (const File* file, struct statfs& result) throw()
  214335. {
  214336. File f (*file);
  214337. for (int i = 5; --i >= 0;)
  214338. {
  214339. if (f.exists())
  214340. break;
  214341. f = f.getParentDirectory();
  214342. }
  214343. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  214344. }
  214345. int64 File::getBytesFreeOnVolume() const throw()
  214346. {
  214347. int64 free_space = 0;
  214348. struct statfs buf;
  214349. if (doStatFS (this, buf))
  214350. // Note: this returns space available to non-super user
  214351. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  214352. return free_space;
  214353. }
  214354. const String juce_getVolumeLabel (const String& filenameOnVolume,
  214355. int& volumeSerialNumber) throw()
  214356. {
  214357. // There is no equivalent on Linux
  214358. volumeSerialNumber = 0;
  214359. return String::empty;
  214360. }
  214361. #if JUCE_64BIT
  214362. #define filedesc ((long long) internal)
  214363. #else
  214364. #define filedesc ((int) internal)
  214365. #endif
  214366. InterProcessLock::InterProcessLock (const String& name_) throw()
  214367. : internal (0),
  214368. name (name_),
  214369. reentrancyLevel (0)
  214370. {
  214371. #if JUCE_MAC
  214372. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  214373. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  214374. #else
  214375. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  214376. #endif
  214377. temp.create();
  214378. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  214379. }
  214380. InterProcessLock::~InterProcessLock() throw()
  214381. {
  214382. while (reentrancyLevel > 0)
  214383. this->exit();
  214384. close (filedesc);
  214385. }
  214386. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  214387. {
  214388. if (internal == 0)
  214389. return false;
  214390. if (reentrancyLevel != 0)
  214391. return true;
  214392. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  214393. struct flock fl;
  214394. zerostruct (fl);
  214395. fl.l_whence = SEEK_SET;
  214396. fl.l_type = F_WRLCK;
  214397. for (;;)
  214398. {
  214399. const int result = fcntl (filedesc, F_SETLK, &fl);
  214400. if (result >= 0)
  214401. {
  214402. ++reentrancyLevel;
  214403. return true;
  214404. }
  214405. if (errno != EINTR)
  214406. {
  214407. if (timeOutMillisecs == 0
  214408. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  214409. break;
  214410. Thread::sleep (10);
  214411. }
  214412. }
  214413. return false;
  214414. }
  214415. void InterProcessLock::exit() throw()
  214416. {
  214417. if (reentrancyLevel > 0 && internal != 0)
  214418. {
  214419. --reentrancyLevel;
  214420. struct flock fl;
  214421. zerostruct (fl);
  214422. fl.l_whence = SEEK_SET;
  214423. fl.l_type = F_UNLCK;
  214424. for (;;)
  214425. {
  214426. const int result = fcntl (filedesc, F_SETLKW, &fl);
  214427. if (result >= 0 || errno != EINTR)
  214428. break;
  214429. }
  214430. }
  214431. }
  214432. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  214433. static File executableFile;
  214434. void PlatformUtilities::copyToStr255 (Str255& d, const String& s)
  214435. {
  214436. unsigned char* t = (unsigned char*) d;
  214437. t[0] = jmin (254, s.length());
  214438. s.copyToBuffer ((char*) t + 1, 254);
  214439. }
  214440. void PlatformUtilities::copyToStr63 (Str63& d, const String& s)
  214441. {
  214442. unsigned char* t = (unsigned char*) d;
  214443. t[0] = jmin (62, s.length());
  214444. s.copyToBuffer ((char*) t + 1, 62);
  214445. }
  214446. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  214447. {
  214448. String result;
  214449. if (cfString != 0)
  214450. {
  214451. #if JUCE_STRINGS_ARE_UNICODE
  214452. CFRange range = { 0, CFStringGetLength (cfString) };
  214453. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  214454. CFStringGetCharacters (cfString, range, u);
  214455. u[range.length] = 0;
  214456. result = convertUTF16ToString (u);
  214457. juce_free (u);
  214458. #else
  214459. const int len = CFStringGetLength (cfString);
  214460. char* buffer = (char*) juce_malloc (len + 1);
  214461. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  214462. result = buffer;
  214463. juce_free (buffer);
  214464. #endif
  214465. }
  214466. return result;
  214467. }
  214468. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  214469. {
  214470. #if JUCE_STRINGS_ARE_UNICODE
  214471. const int len = s.length();
  214472. const juce_wchar* t = (const juce_wchar*) s;
  214473. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  214474. for (int i = 0; i <= len; ++i)
  214475. temp[i] = t[i];
  214476. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  214477. juce_free (temp);
  214478. return result;
  214479. #else
  214480. return CFStringCreateWithCString (kCFAllocatorDefault,
  214481. (const char*) s,
  214482. CFStringGetSystemEncoding());
  214483. #endif
  214484. }
  214485. const String PlatformUtilities::convertUTF16ToString (const UniChar* utf16)
  214486. {
  214487. String s;
  214488. while (*utf16 != 0)
  214489. s += (juce_wchar) *utf16++;
  214490. return s;
  214491. }
  214492. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  214493. {
  214494. UnicodeMapping map;
  214495. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  214496. kUnicodeNoSubset,
  214497. kTextEncodingDefaultFormat);
  214498. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  214499. kUnicodeCanonicalCompVariant,
  214500. kTextEncodingDefaultFormat);
  214501. map.mappingVersion = kUnicodeUseLatestMapping;
  214502. UnicodeToTextInfo conversionInfo = 0;
  214503. String result;
  214504. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  214505. {
  214506. const int len = s.length();
  214507. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  214508. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  214509. for (int i = 0; i <= len; ++i)
  214510. tempIn[i] = s[i];
  214511. ByteCount bytesRead = 0;
  214512. ByteCount outputBufferSize = 0;
  214513. if (ConvertFromUnicodeToText (conversionInfo,
  214514. len * sizeof (UniChar), tempIn,
  214515. kUnicodeDefaultDirectionMask,
  214516. 0, 0, 0, 0,
  214517. len * sizeof (UniChar), &bytesRead,
  214518. &outputBufferSize, tempOut) == noErr)
  214519. {
  214520. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  214521. tchar* t = const_cast <tchar*> ((const tchar*) result);
  214522. int i;
  214523. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  214524. t[i] = (tchar) tempOut[i];
  214525. t[i] = 0;
  214526. }
  214527. juce_free (tempIn);
  214528. juce_free (tempOut);
  214529. DisposeUnicodeToTextInfo (&conversionInfo);
  214530. }
  214531. return result;
  214532. }
  214533. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  214534. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  214535. {
  214536. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  214537. return 0;
  214538. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  214539. + ((d.fraction * 1000) >> 16)
  214540. - 2082844800000ll;
  214541. }
  214542. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  214543. {
  214544. if (t != 0)
  214545. t += 2082844800000ll;
  214546. d.highSeconds = (t / 1000) >> 32;
  214547. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  214548. d.fraction = ((t % 1000) << 16) / 1000;
  214549. }
  214550. void juce_getFileTimes (const String& fileName,
  214551. int64& modificationTime,
  214552. int64& accessTime,
  214553. int64& creationTime) throw()
  214554. {
  214555. modificationTime = 0;
  214556. accessTime = 0;
  214557. creationTime = 0;
  214558. FSRef fileRef;
  214559. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  214560. {
  214561. FSRefParam info;
  214562. zerostruct (info);
  214563. info.ref = &fileRef;
  214564. info.whichInfo = kFSCatInfoAllDates;
  214565. FSCatalogInfo catInfo;
  214566. info.catInfo = &catInfo;
  214567. if (PBGetCatalogInfoSync (&info) == noErr)
  214568. {
  214569. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  214570. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  214571. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  214572. }
  214573. }
  214574. }
  214575. bool juce_setFileTimes (const String& fileName,
  214576. int64 modificationTime,
  214577. int64 accessTime,
  214578. int64 creationTime) throw()
  214579. {
  214580. FSRef fileRef;
  214581. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  214582. {
  214583. FSRefParam info;
  214584. zerostruct (info);
  214585. info.ref = &fileRef;
  214586. info.whichInfo = kFSCatInfoAllDates;
  214587. FSCatalogInfo catInfo;
  214588. info.catInfo = &catInfo;
  214589. if (PBGetCatalogInfoSync (&info) == noErr)
  214590. {
  214591. if (creationTime != 0)
  214592. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  214593. if (modificationTime != 0)
  214594. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  214595. if (accessTime != 0)
  214596. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  214597. return PBSetCatalogInfoSync (&info) == noErr;
  214598. }
  214599. }
  214600. return false;
  214601. }
  214602. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  214603. {
  214604. const char* const fileNameUTF8 = fileName.toUTF8();
  214605. struct stat info;
  214606. const int res = stat (fileNameUTF8, &info);
  214607. bool ok = false;
  214608. if (res == 0)
  214609. {
  214610. info.st_mode &= 0777; // Just permissions
  214611. if (isReadOnly)
  214612. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  214613. else
  214614. // Give everybody write permission?
  214615. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  214616. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  214617. }
  214618. return ok;
  214619. }
  214620. bool juce_copyFile (const String& src, const String& dst) throw()
  214621. {
  214622. const File destFile (dst);
  214623. if (! destFile.create())
  214624. return false;
  214625. FSRef srcRef, dstRef;
  214626. if (! (PlatformUtilities::makeFSRefFromPath (&srcRef, src)
  214627. && PlatformUtilities::makeFSRefFromPath (&dstRef, dst)))
  214628. {
  214629. return false;
  214630. }
  214631. int okForks = 0;
  214632. CatPositionRec iter;
  214633. iter.initialize = 0;
  214634. HFSUniStr255 forkName;
  214635. // can't just copy the data because this is a bloody Mac, so we need to copy each
  214636. // fork separately...
  214637. while (FSIterateForks (&srcRef, &iter, &forkName, 0, 0) == noErr)
  214638. {
  214639. SInt16 srcForkNum = 0, dstForkNum = 0;
  214640. OSErr err = FSOpenFork (&srcRef, forkName.length, forkName.unicode, fsRdPerm, &srcForkNum);
  214641. if (err == noErr)
  214642. {
  214643. err = FSOpenFork (&dstRef, forkName.length, forkName.unicode, fsRdWrPerm, &dstForkNum);
  214644. if (err == noErr)
  214645. {
  214646. MemoryBlock buf (32768);
  214647. SInt64 pos = 0;
  214648. for (;;)
  214649. {
  214650. ByteCount bytesRead = 0;
  214651. err = FSReadFork (srcForkNum, fsFromStart, pos, buf.getSize(), (char*) buf, &bytesRead);
  214652. if (bytesRead > 0)
  214653. {
  214654. err = FSWriteFork (dstForkNum, fsFromStart, pos, bytesRead, (const char*) buf, &bytesRead);
  214655. pos += bytesRead;
  214656. }
  214657. if (err != noErr)
  214658. {
  214659. if (err == eofErr)
  214660. ++okForks;
  214661. break;
  214662. }
  214663. }
  214664. FSFlushFork (dstForkNum);
  214665. FSCloseFork (dstForkNum);
  214666. }
  214667. FSCloseFork (srcForkNum);
  214668. }
  214669. }
  214670. if (okForks > 0) // some files seem to be ok even if not all their forks get copied..
  214671. {
  214672. // copy permissions..
  214673. struct stat info;
  214674. if (juce_stat (src, info))
  214675. chmod (dst.toUTF8(), info.st_mode & 0777);
  214676. return true;
  214677. }
  214678. return false;
  214679. }
  214680. const StringArray juce_getFileSystemRoots() throw()
  214681. {
  214682. StringArray s;
  214683. s.add (T("/"));
  214684. return s;
  214685. }
  214686. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  214687. {
  214688. struct statfs buf;
  214689. if (doStatFS (f, buf))
  214690. {
  214691. const String type (buf.f_fstypename);
  214692. while (*types != 0)
  214693. if (type.equalsIgnoreCase (*types++))
  214694. return true;
  214695. }
  214696. return false;
  214697. }
  214698. bool File::isOnCDRomDrive() const throw()
  214699. {
  214700. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  214701. return isFileOnDriveType (this, (const char**) cdTypes);
  214702. }
  214703. bool File::isOnHardDisk() const throw()
  214704. {
  214705. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  214706. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  214707. }
  214708. static bool juce_isHiddenFile (const String& path) throw()
  214709. {
  214710. FSRef ref;
  214711. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  214712. return false;
  214713. FSCatalogInfo info;
  214714. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  214715. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  214716. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  214717. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  214718. }
  214719. bool File::isHidden() const throw()
  214720. {
  214721. return juce_isHiddenFile (getFullPathName());
  214722. }
  214723. const File File::getSpecialLocation (const SpecialLocationType type)
  214724. {
  214725. const char* resultPath = 0;
  214726. switch (type)
  214727. {
  214728. case userHomeDirectory:
  214729. resultPath = getenv ("HOME");
  214730. if (resultPath == 0)
  214731. {
  214732. struct passwd* const pw = getpwuid (getuid());
  214733. if (pw != 0)
  214734. resultPath = pw->pw_dir;
  214735. }
  214736. break;
  214737. case userDocumentsDirectory:
  214738. resultPath = "~/Documents";
  214739. break;
  214740. case userDesktopDirectory:
  214741. resultPath = "~/Desktop";
  214742. break;
  214743. case userApplicationDataDirectory:
  214744. resultPath = "~/Library";
  214745. break;
  214746. case commonApplicationDataDirectory:
  214747. resultPath = "/Library";
  214748. break;
  214749. case globalApplicationsDirectory:
  214750. resultPath = "/Applications";
  214751. break;
  214752. case userMusicDirectory:
  214753. resultPath = "~/Music";
  214754. break;
  214755. case userMoviesDirectory:
  214756. resultPath = "~/Movies";
  214757. break;
  214758. case tempDirectory:
  214759. {
  214760. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  214761. tmp.createDirectory();
  214762. return tmp.getFullPathName();
  214763. }
  214764. case currentExecutableFile:
  214765. return executableFile;
  214766. case currentApplicationFile:
  214767. {
  214768. const File parent (executableFile.getParentDirectory());
  214769. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  214770. ? parent.getParentDirectory().getParentDirectory()
  214771. : executableFile;
  214772. }
  214773. default:
  214774. jassertfalse // unknown type?
  214775. break;
  214776. }
  214777. if (resultPath != 0)
  214778. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  214779. return File::nonexistent;
  214780. }
  214781. void juce_setCurrentExecutableFileName (const String& filename) throw()
  214782. {
  214783. executableFile = File::getCurrentWorkingDirectory()
  214784. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  214785. }
  214786. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  214787. {
  214788. CFStringRef bundleIdStringRef = PlatformUtilities::juceStringToCFString (bundleId);
  214789. CFBundleRef bundleRef = CFBundleGetBundleWithIdentifier (bundleIdStringRef);
  214790. CFRelease (bundleIdStringRef);
  214791. if (bundleRef != 0)
  214792. {
  214793. CFURLRef exeURLRef = CFBundleCopyExecutableURL (bundleRef);
  214794. if (exeURLRef != 0)
  214795. {
  214796. CFStringRef pathStringRef = CFURLCopyFileSystemPath (exeURLRef, kCFURLPOSIXPathStyle);
  214797. CFRelease (exeURLRef);
  214798. if (pathStringRef != 0)
  214799. {
  214800. juce_setCurrentExecutableFileName (PlatformUtilities::cfStringToJuceString (pathStringRef));
  214801. CFRelease (pathStringRef);
  214802. }
  214803. }
  214804. }
  214805. }
  214806. const File File::getCurrentWorkingDirectory() throw()
  214807. {
  214808. char buf [2048];
  214809. getcwd (buf, sizeof(buf));
  214810. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  214811. }
  214812. bool File::setAsCurrentWorkingDirectory() const throw()
  214813. {
  214814. return chdir (getFullPathName().toUTF8()) == 0;
  214815. }
  214816. struct FindFileStruct
  214817. {
  214818. String parentDir, wildCard;
  214819. DIR* dir;
  214820. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  214821. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  214822. {
  214823. const char* const wildCardUTF8 = wildCard.toUTF8();
  214824. for (;;)
  214825. {
  214826. struct dirent* const de = readdir (dir);
  214827. if (de == 0)
  214828. break;
  214829. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  214830. {
  214831. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  214832. const String path (parentDir + result);
  214833. if (isDir != 0 || fileSize != 0)
  214834. {
  214835. struct stat info;
  214836. const bool statOk = juce_stat (path, info);
  214837. if (isDir != 0)
  214838. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  214839. if (isHidden != 0)
  214840. *isHidden = (de->d_name[0] == '.')
  214841. || juce_isHiddenFile (path);
  214842. if (fileSize != 0)
  214843. *fileSize = statOk ? info.st_size : 0;
  214844. }
  214845. if (modTime != 0 || creationTime != 0)
  214846. {
  214847. int64 m, a, c;
  214848. juce_getFileTimes (path, m, a, c);
  214849. if (modTime != 0)
  214850. *modTime = m;
  214851. if (creationTime != 0)
  214852. *creationTime = c;
  214853. }
  214854. if (isReadOnly != 0)
  214855. *isReadOnly = ! juce_canWriteToFile (path);
  214856. return true;
  214857. }
  214858. }
  214859. return false;
  214860. }
  214861. };
  214862. // returns 0 on failure
  214863. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  214864. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  214865. Time* creationTime, bool* isReadOnly) throw()
  214866. {
  214867. DIR* const d = opendir (directory.toUTF8());
  214868. if (d != 0)
  214869. {
  214870. FindFileStruct* const ff = new FindFileStruct();
  214871. ff->parentDir = directory;
  214872. if (!ff->parentDir.endsWithChar (File::separator))
  214873. ff->parentDir += File::separator;
  214874. ff->wildCard = wildCard;
  214875. ff->dir = d;
  214876. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  214877. {
  214878. return ff;
  214879. }
  214880. else
  214881. {
  214882. firstResultFile = String::empty;
  214883. isDir = false;
  214884. closedir (d);
  214885. delete ff;
  214886. }
  214887. }
  214888. return 0;
  214889. }
  214890. bool juce_findFileNext (void* handle, String& resultFile,
  214891. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  214892. {
  214893. FindFileStruct* const ff = (FindFileStruct*) handle;
  214894. if (ff != 0)
  214895. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  214896. return false;
  214897. }
  214898. void juce_findFileClose (void* handle) throw()
  214899. {
  214900. FindFileStruct* const ff = (FindFileStruct*)handle;
  214901. if (ff != 0)
  214902. {
  214903. closedir (ff->dir);
  214904. delete ff;
  214905. }
  214906. }
  214907. bool juce_launchExecutable (const String& pathAndArguments) throw()
  214908. {
  214909. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  214910. const int cpid = fork();
  214911. if (cpid == 0)
  214912. {
  214913. // Child process
  214914. if (execve (argv[0], argv, 0) < 0)
  214915. exit (0);
  214916. }
  214917. else
  214918. {
  214919. if (cpid < 0)
  214920. return false;
  214921. }
  214922. return true;
  214923. }
  214924. bool juce_launchFile (const String& fileName,
  214925. const String& parameters) throw()
  214926. {
  214927. bool ok = false;
  214928. if (fileName.startsWithIgnoreCase (T("http:"))
  214929. || fileName.startsWithIgnoreCase (T("https:"))
  214930. || fileName.startsWithIgnoreCase (T("ftp:"))
  214931. || fileName.startsWithIgnoreCase (T("file:")))
  214932. {
  214933. CFStringRef urlString = PlatformUtilities::juceStringToCFString (fileName);
  214934. if (urlString != 0)
  214935. {
  214936. CFURLRef url = CFURLCreateWithString (kCFAllocatorDefault,
  214937. urlString, 0);
  214938. CFRelease (urlString);
  214939. if (url != 0)
  214940. {
  214941. ok = (LSOpenCFURLRef (url, 0) == noErr);
  214942. CFRelease (url);
  214943. }
  214944. }
  214945. }
  214946. else
  214947. {
  214948. FSRef ref;
  214949. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  214950. {
  214951. if (juce_isDirectory (fileName) && parameters.isNotEmpty())
  214952. {
  214953. // if we're launching a bundled app with a document..
  214954. StringArray docs;
  214955. docs.addTokens (parameters, true);
  214956. FSRef* docRefs = new FSRef [docs.size()];
  214957. for (int i = 0; i < docs.size(); ++i)
  214958. PlatformUtilities::makeFSRefFromPath (docRefs + i, docs[i]);
  214959. LSLaunchFSRefSpec ors;
  214960. ors.appRef = &ref;
  214961. ors.numDocs = docs.size();
  214962. ors.itemRefs = docRefs;
  214963. ors.passThruParams = 0;
  214964. ors.launchFlags = kLSLaunchDefaults;
  214965. ors.asyncRefCon = 0;
  214966. FSRef actual;
  214967. ok = (LSOpenFromRefSpec (&ors, &actual) == noErr);
  214968. delete docRefs;
  214969. }
  214970. else
  214971. {
  214972. if (parameters.isNotEmpty())
  214973. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  214974. else
  214975. ok = (LSOpenFSRef (&ref, 0) == noErr);
  214976. }
  214977. }
  214978. }
  214979. return ok;
  214980. }
  214981. bool PlatformUtilities::makeFSSpecFromPath (FSSpec* fs, const String& path)
  214982. {
  214983. FSRef ref;
  214984. return makeFSRefFromPath (&ref, path)
  214985. && FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, fs, 0) == noErr;
  214986. }
  214987. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  214988. {
  214989. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  214990. }
  214991. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  214992. {
  214993. uint8 path [2048];
  214994. zeromem (path, sizeof (path));
  214995. String result;
  214996. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  214997. result = String::fromUTF8 (path);
  214998. return PlatformUtilities::convertToPrecomposedUnicode (result);
  214999. }
  215000. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  215001. {
  215002. FSRef fs;
  215003. if (makeFSRefFromPath (&fs, filename))
  215004. {
  215005. LSItemInfoRecord info;
  215006. if (LSCopyItemInfoForRef (&fs, kLSRequestTypeCreator, &info) == noErr)
  215007. return info.filetype;
  215008. }
  215009. return 0;
  215010. }
  215011. bool PlatformUtilities::isBundle (const String& filename)
  215012. {
  215013. FSRef fs;
  215014. if (makeFSRefFromPath (&fs, filename))
  215015. {
  215016. LSItemInfoRecord info;
  215017. if (LSCopyItemInfoForRef (&fs, kLSItemInfoIsPackage, &info) == noErr)
  215018. return (info.flags & kLSItemInfoIsPackage) != 0;
  215019. }
  215020. return false;
  215021. }
  215022. END_JUCE_NAMESPACE
  215023. /********* End of inlined file: juce_mac_Files.cpp *********/
  215024. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  215025. #include <sys/stat.h>
  215026. #include <sys/dir.h>
  215027. #include <fcntl.h>
  215028. // As well as being for the mac, this file is included by the linux build.
  215029. #if JUCE_MAC
  215030. #include <Carbon/Carbon.h>
  215031. #else
  215032. #include <sys/wait.h>
  215033. #include <errno.h>
  215034. #include <unistd.h>
  215035. #endif
  215036. BEGIN_JUCE_NAMESPACE
  215037. struct NamedPipeInternal
  215038. {
  215039. String pipeInName, pipeOutName;
  215040. int pipeIn, pipeOut;
  215041. bool volatile createdPipe, blocked, stopReadOperation;
  215042. static void signalHandler (int) {}
  215043. };
  215044. void NamedPipe::cancelPendingReads()
  215045. {
  215046. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215047. {
  215048. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215049. intern->stopReadOperation = true;
  215050. char buffer [1] = { 0 };
  215051. ::write (intern->pipeIn, buffer, 1);
  215052. int timeout = 2000;
  215053. while (intern->blocked && --timeout >= 0)
  215054. sleep (2);
  215055. intern->stopReadOperation = false;
  215056. }
  215057. }
  215058. void NamedPipe::close()
  215059. {
  215060. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215061. if (intern != 0)
  215062. {
  215063. internal = 0;
  215064. if (intern->pipeIn != -1)
  215065. ::close (intern->pipeIn);
  215066. if (intern->pipeOut != -1)
  215067. ::close (intern->pipeOut);
  215068. if (intern->createdPipe)
  215069. {
  215070. unlink (intern->pipeInName);
  215071. unlink (intern->pipeOutName);
  215072. }
  215073. delete intern;
  215074. }
  215075. }
  215076. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215077. {
  215078. close();
  215079. NamedPipeInternal* const intern = new NamedPipeInternal();
  215080. internal = intern;
  215081. intern->createdPipe = createPipe;
  215082. intern->blocked = false;
  215083. intern->stopReadOperation = false;
  215084. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  215085. siginterrupt (SIGPIPE, 1);
  215086. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  215087. intern->pipeInName = pipePath + T("_in");
  215088. intern->pipeOutName = pipePath + T("_out");
  215089. intern->pipeIn = -1;
  215090. intern->pipeOut = -1;
  215091. if (createPipe)
  215092. {
  215093. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  215094. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  215095. {
  215096. delete intern;
  215097. internal = 0;
  215098. return false;
  215099. }
  215100. }
  215101. return true;
  215102. }
  215103. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  215104. {
  215105. int bytesRead = -1;
  215106. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215107. if (intern != 0)
  215108. {
  215109. intern->blocked = true;
  215110. if (intern->pipeIn == -1)
  215111. {
  215112. if (intern->createdPipe)
  215113. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  215114. else
  215115. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  215116. if (intern->pipeIn == -1)
  215117. {
  215118. intern->blocked = false;
  215119. return -1;
  215120. }
  215121. }
  215122. bytesRead = 0;
  215123. char* p = (char*) destBuffer;
  215124. while (bytesRead < maxBytesToRead)
  215125. {
  215126. const int bytesThisTime = maxBytesToRead - bytesRead;
  215127. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  215128. if (numRead <= 0 || intern->stopReadOperation)
  215129. {
  215130. bytesRead = -1;
  215131. break;
  215132. }
  215133. bytesRead += numRead;
  215134. p += bytesRead;
  215135. }
  215136. intern->blocked = false;
  215137. }
  215138. return bytesRead;
  215139. }
  215140. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  215141. {
  215142. int bytesWritten = -1;
  215143. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215144. if (intern != 0)
  215145. {
  215146. if (intern->pipeOut == -1)
  215147. {
  215148. if (intern->createdPipe)
  215149. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  215150. else
  215151. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  215152. if (intern->pipeOut == -1)
  215153. {
  215154. return -1;
  215155. }
  215156. }
  215157. const char* p = (const char*) sourceBuffer;
  215158. bytesWritten = 0;
  215159. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  215160. while (bytesWritten < numBytesToWrite
  215161. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  215162. {
  215163. const int bytesThisTime = numBytesToWrite - bytesWritten;
  215164. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  215165. if (numWritten <= 0)
  215166. {
  215167. bytesWritten = -1;
  215168. break;
  215169. }
  215170. bytesWritten += numWritten;
  215171. p += bytesWritten;
  215172. }
  215173. }
  215174. return bytesWritten;
  215175. }
  215176. END_JUCE_NAMESPACE
  215177. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  215178. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  215179. #include <AppKit/AppKit.h>
  215180. #include <Carbon/Carbon.h>
  215181. #include <CoreAudio/HostTime.h>
  215182. #include <ctime>
  215183. #include <sys/resource.h>
  215184. BEGIN_JUCE_NAMESPACE
  215185. static int64 highResTimerFrequency;
  215186. #if JUCE_INTEL
  215187. static void juce_getCpuVendor (char* const v) throw()
  215188. {
  215189. int vendor[4];
  215190. zerostruct (vendor);
  215191. int dummy = 0;
  215192. asm ("mov %%ebx, %%esi \n\t"
  215193. "cpuid \n\t"
  215194. "xchg %%esi, %%ebx"
  215195. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  215196. memcpy (v, vendor, 16);
  215197. }
  215198. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  215199. {
  215200. unsigned int cpu = 0;
  215201. unsigned int ext = 0;
  215202. unsigned int family = 0;
  215203. unsigned int dummy = 0;
  215204. asm ("mov %%ebx, %%esi \n\t"
  215205. "cpuid \n\t"
  215206. "xchg %%esi, %%ebx"
  215207. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  215208. familyModel = family;
  215209. extFeatures = ext;
  215210. return cpu;
  215211. }
  215212. struct CPUFlags
  215213. {
  215214. bool hasMMX : 1;
  215215. bool hasSSE : 1;
  215216. bool hasSSE2 : 1;
  215217. bool has3DNow : 1;
  215218. };
  215219. static CPUFlags cpuFlags;
  215220. #endif
  215221. void Logger::outputDebugString (const String& text) throw()
  215222. {
  215223. String withLineFeed (text + T("\n"));
  215224. const char* const utf8 = withLineFeed.toUTF8();
  215225. fwrite (utf8, strlen (utf8), 1, stdout);
  215226. }
  215227. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  215228. {
  215229. String text;
  215230. va_list args;
  215231. va_start (args, format);
  215232. text.vprintf(format, args);
  215233. outputDebugString (text);
  215234. }
  215235. int SystemStats::getMemorySizeInMegabytes() throw()
  215236. {
  215237. long bytes;
  215238. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  215239. return (int) (((unsigned long) bytes) / (1024 * 1024));
  215240. return 0;
  215241. }
  215242. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  215243. {
  215244. return MacOSX;
  215245. }
  215246. const String SystemStats::getOperatingSystemName() throw()
  215247. {
  215248. return T("Mac OS X");
  215249. }
  215250. bool SystemStats::isOperatingSystem64Bit() throw()
  215251. {
  215252. #if JUCE_64BIT
  215253. return true;
  215254. #else
  215255. //xxx not sure how to find this out?..
  215256. return false;
  215257. #endif
  215258. }
  215259. void SystemStats::initialiseStats() throw()
  215260. {
  215261. static bool initialised = false;
  215262. if (! initialised)
  215263. {
  215264. initialised = true;
  215265. NSApplicationLoad();
  215266. #if JUCE_INTEL
  215267. {
  215268. unsigned int familyModel, extFeatures;
  215269. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  215270. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  215271. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  215272. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  215273. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  215274. }
  215275. #endif
  215276. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  215277. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215278. if (JUCEApplication::getInstance() != 0)
  215279. RegisterAppearanceClient();
  215280. #endif
  215281. TXNInitTextension (0, 0, kTXNWantMoviesMask | kTXNWantGraphicsMask);
  215282. String s (SystemStats::getJUCEVersion());
  215283. rlimit lim;
  215284. getrlimit (RLIMIT_NOFILE, &lim);
  215285. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  215286. setrlimit (RLIMIT_NOFILE, &lim);
  215287. }
  215288. }
  215289. bool SystemStats::hasMMX() throw()
  215290. {
  215291. #if JUCE_INTEL
  215292. return cpuFlags.hasMMX;
  215293. #else
  215294. return false;
  215295. #endif
  215296. }
  215297. bool SystemStats::hasSSE() throw()
  215298. {
  215299. #if JUCE_INTEL
  215300. return cpuFlags.hasSSE;
  215301. #else
  215302. return false;
  215303. #endif
  215304. }
  215305. bool SystemStats::hasSSE2() throw()
  215306. {
  215307. #if JUCE_INTEL
  215308. return cpuFlags.hasSSE2;
  215309. #else
  215310. return false;
  215311. #endif
  215312. }
  215313. bool SystemStats::has3DNow() throw()
  215314. {
  215315. #if JUCE_INTEL
  215316. return cpuFlags.has3DNow;
  215317. #else
  215318. return false;
  215319. #endif
  215320. }
  215321. const String SystemStats::getCpuVendor() throw()
  215322. {
  215323. #if JUCE_INTEL
  215324. char v [16];
  215325. juce_getCpuVendor (v);
  215326. return String (v, 16);
  215327. #else
  215328. return String::empty;
  215329. #endif
  215330. }
  215331. int SystemStats::getCpuSpeedInMegaherz() throw()
  215332. {
  215333. return GetCPUSpeed();
  215334. }
  215335. int SystemStats::getNumCpus() throw()
  215336. {
  215337. return MPProcessors();
  215338. }
  215339. static int64 juce_getMicroseconds() throw()
  215340. {
  215341. UnsignedWide t;
  215342. Microseconds (&t);
  215343. return (((int64) t.hi) << 32) | t.lo;
  215344. }
  215345. uint32 juce_millisecondsSinceStartup() throw()
  215346. {
  215347. return (uint32) (juce_getMicroseconds() / 1000);
  215348. }
  215349. double Time::getMillisecondCounterHiRes() throw()
  215350. {
  215351. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  215352. return juce_getMicroseconds() * 0.001;
  215353. }
  215354. int64 Time::getHighResolutionTicks() throw()
  215355. {
  215356. return (int64) AudioGetCurrentHostTime();
  215357. }
  215358. int64 Time::getHighResolutionTicksPerSecond() throw()
  215359. {
  215360. return highResTimerFrequency;
  215361. }
  215362. int64 SystemStats::getClockCycleCounter() throw()
  215363. {
  215364. jassertfalse
  215365. return 0;
  215366. }
  215367. bool Time::setSystemTimeToThisTime() const throw()
  215368. {
  215369. jassertfalse
  215370. return false;
  215371. }
  215372. int SystemStats::getPageSize() throw()
  215373. {
  215374. jassertfalse
  215375. return 512; //xxx
  215376. }
  215377. void PlatformUtilities::fpuReset()
  215378. {
  215379. }
  215380. END_JUCE_NAMESPACE
  215381. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  215382. /********* Start of inlined file: juce_mac_Threads.cpp *********/
  215383. #include <pthread.h>
  215384. #include <sched.h>
  215385. #include <sys/file.h>
  215386. #include <sys/types.h>
  215387. #include <sys/sysctl.h>
  215388. #include <Carbon/Carbon.h>
  215389. BEGIN_JUCE_NAMESPACE
  215390. /*
  215391. Note that a lot of methods that you'd expect to find in this file actually
  215392. live in juce_posix_SharedCode.cpp!
  215393. */
  215394. void JUCE_API juce_threadEntryPoint (void*);
  215395. void* threadEntryProc (void* userData) throw()
  215396. {
  215397. juce_threadEntryPoint (userData);
  215398. return 0;
  215399. }
  215400. void* juce_createThread (void* userData) throw()
  215401. {
  215402. pthread_t handle = 0;
  215403. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  215404. {
  215405. pthread_detach (handle);
  215406. return (void*) handle;
  215407. }
  215408. return 0;
  215409. }
  215410. void juce_killThread (void* handle) throw()
  215411. {
  215412. if (handle != 0)
  215413. pthread_cancel ((pthread_t) handle);
  215414. }
  215415. void juce_setCurrentThreadName (const String& /*name*/) throw()
  215416. {
  215417. }
  215418. int Thread::getCurrentThreadId() throw()
  215419. {
  215420. return (int) pthread_self();
  215421. }
  215422. void juce_setThreadPriority (void* handle, int priority) throw()
  215423. {
  215424. if (handle == 0)
  215425. handle = (void*) pthread_self();
  215426. struct sched_param param;
  215427. int policy;
  215428. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  215429. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  215430. pthread_setschedparam ((pthread_t) handle, policy, &param);
  215431. }
  215432. void Thread::yield() throw()
  215433. {
  215434. sched_yield();
  215435. }
  215436. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  215437. {
  215438. // xxx
  215439. jassertfalse
  215440. }
  215441. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  215442. {
  215443. static char testResult = 0;
  215444. if (testResult == 0)
  215445. {
  215446. struct kinfo_proc info;
  215447. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  215448. size_t sz = sizeof (info);
  215449. sysctl (m, 4, &info, &sz, 0, 0);
  215450. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  215451. }
  215452. return testResult > 0;
  215453. }
  215454. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  215455. {
  215456. return juce_isRunningUnderDebugger();
  215457. }
  215458. void Process::raisePrivilege()
  215459. {
  215460. jassertfalse
  215461. }
  215462. void Process::lowerPrivilege()
  215463. {
  215464. jassertfalse
  215465. }
  215466. void Process::terminate()
  215467. {
  215468. ExitToShell();
  215469. }
  215470. void Process::setPriority (ProcessPriority p)
  215471. {
  215472. // xxx
  215473. }
  215474. void* Process::loadDynamicLibrary (const String& name)
  215475. {
  215476. // xxx needs to use bundles
  215477. FSSpec fs;
  215478. if (PlatformUtilities::makeFSSpecFromPath (&fs, name))
  215479. {
  215480. CFragConnectionID connID;
  215481. Ptr mainPtr;
  215482. Str255 errorMessage;
  215483. Str63 nm;
  215484. PlatformUtilities::copyToStr63 (nm, name);
  215485. const OSErr err = GetDiskFragment (&fs, 0, kCFragGoesToEOF, nm, kReferenceCFrag, &connID, &mainPtr, errorMessage);
  215486. if (err == noErr)
  215487. return (void*)connID;
  215488. }
  215489. return 0;
  215490. }
  215491. void Process::freeDynamicLibrary (void* handle)
  215492. {
  215493. if (handle != 0)
  215494. CloseConnection ((CFragConnectionID*)&handle);
  215495. }
  215496. void* Process::getProcedureEntryPoint (void* h, const String& procedureName)
  215497. {
  215498. if (h != 0)
  215499. {
  215500. CFragSymbolClass cl;
  215501. Ptr ptr;
  215502. Str255 name;
  215503. PlatformUtilities::copyToStr255 (name, procedureName);
  215504. if (FindSymbol ((CFragConnectionID) h, name, &ptr, &cl) == noErr)
  215505. {
  215506. return ptr;
  215507. }
  215508. }
  215509. return 0;
  215510. }
  215511. END_JUCE_NAMESPACE
  215512. /********* End of inlined file: juce_mac_Threads.cpp *********/
  215513. /********* Start of inlined file: juce_mac_Network.mm *********/
  215514. #include <Cocoa/Cocoa.h>
  215515. #include <IOKit/IOKitLib.h>
  215516. #include <IOKit/network/IOEthernetInterface.h>
  215517. #include <IOKit/network/IONetworkInterface.h>
  215518. #include <IOKit/network/IOEthernetController.h>
  215519. #include <netdb.h>
  215520. #include <arpa/inet.h>
  215521. #include <netinet/in.h>
  215522. #include <sys/types.h>
  215523. #include <sys/socket.h>
  215524. #include <sys/wait.h>
  215525. BEGIN_JUCE_NAMESPACE
  215526. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  215527. // (This file gets included by the mac + linux networking code)
  215528. /** A HTTP input stream that uses sockets.
  215529. */
  215530. class JUCE_HTTPSocketStream
  215531. {
  215532. public:
  215533. JUCE_HTTPSocketStream()
  215534. : readPosition (0),
  215535. socketHandle (-1),
  215536. levelsOfRedirection (0),
  215537. timeoutSeconds (15)
  215538. {
  215539. }
  215540. ~JUCE_HTTPSocketStream()
  215541. {
  215542. closeSocket();
  215543. }
  215544. bool open (const String& url,
  215545. const String& headers,
  215546. const MemoryBlock& postData,
  215547. const bool isPost,
  215548. URL::OpenStreamProgressCallback* callback,
  215549. void* callbackContext)
  215550. {
  215551. closeSocket();
  215552. String hostName, hostPath;
  215553. int hostPort;
  215554. if (! decomposeURL (url, hostName, hostPath, hostPort))
  215555. return false;
  215556. struct hostent* const host
  215557. = gethostbyname ((const char*) hostName.toUTF8());
  215558. if (host == 0)
  215559. return false;
  215560. struct sockaddr_in address;
  215561. zerostruct (address);
  215562. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  215563. address.sin_family = host->h_addrtype;
  215564. address.sin_port = htons (hostPort);
  215565. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  215566. if (socketHandle == -1)
  215567. return false;
  215568. int receiveBufferSize = 16384;
  215569. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  215570. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  215571. #if JUCE_MAC
  215572. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  215573. #endif
  215574. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  215575. {
  215576. closeSocket();
  215577. return false;
  215578. }
  215579. String proxyURL (getenv ("http_proxy"));
  215580. if (! proxyURL.startsWithIgnoreCase (T("http://")))
  215581. proxyURL = String::empty;
  215582. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPath,
  215583. proxyURL, url,
  215584. hostPort,
  215585. headers, postData,
  215586. isPost));
  215587. int totalHeaderSent = 0;
  215588. while (totalHeaderSent < requestHeader.getSize())
  215589. {
  215590. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  215591. if (send (socketHandle,
  215592. ((const char*) requestHeader.getData()) + totalHeaderSent,
  215593. numToSend, 0)
  215594. != numToSend)
  215595. {
  215596. closeSocket();
  215597. return false;
  215598. }
  215599. totalHeaderSent += numToSend;
  215600. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  215601. {
  215602. closeSocket();
  215603. return false;
  215604. }
  215605. }
  215606. const String responseHeader (readResponse());
  215607. if (responseHeader.isNotEmpty())
  215608. {
  215609. //DBG (responseHeader);
  215610. StringArray lines;
  215611. lines.addLines (responseHeader);
  215612. // NB - using charToString() here instead of just T(" "), because that was
  215613. // causing a mysterious gcc internal compiler error...
  215614. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  215615. .substring (0, 3)
  215616. .getIntValue();
  215617. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  215618. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  215619. String location (findHeaderItem (lines, T("Location:")));
  215620. if (statusCode >= 300 && statusCode < 400
  215621. && location.isNotEmpty())
  215622. {
  215623. if (! location.startsWithIgnoreCase (T("http://")))
  215624. location = T("http://") + location;
  215625. if (levelsOfRedirection++ < 3)
  215626. return open (location, headers, postData, isPost, callback, callbackContext);
  215627. }
  215628. else
  215629. {
  215630. levelsOfRedirection = 0;
  215631. return true;
  215632. }
  215633. }
  215634. closeSocket();
  215635. return false;
  215636. }
  215637. int read (void* buffer, int bytesToRead)
  215638. {
  215639. fd_set readbits;
  215640. FD_ZERO (&readbits);
  215641. FD_SET (socketHandle, &readbits);
  215642. struct timeval tv;
  215643. tv.tv_sec = timeoutSeconds;
  215644. tv.tv_usec = 0;
  215645. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  215646. return 0; // (timeout)
  215647. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  215648. readPosition += bytesRead;
  215649. return bytesRead;
  215650. }
  215651. int readPosition;
  215652. juce_UseDebuggingNewOperator
  215653. private:
  215654. int socketHandle, levelsOfRedirection;
  215655. const int timeoutSeconds;
  215656. void closeSocket()
  215657. {
  215658. if (socketHandle >= 0)
  215659. close (socketHandle);
  215660. socketHandle = -1;
  215661. }
  215662. const MemoryBlock createRequestHeader (const String& hostName,
  215663. const String& hostPath,
  215664. const String& proxyURL,
  215665. const String& originalURL,
  215666. const int hostPort,
  215667. const String& headers,
  215668. const MemoryBlock& postData,
  215669. const bool isPost)
  215670. {
  215671. String header (isPost ? "POST " : "GET ");
  215672. if (proxyURL.isEmpty())
  215673. {
  215674. header << hostPath << " HTTP/1.0\r\nHost: "
  215675. << hostName << ':' << hostPort;
  215676. }
  215677. else
  215678. {
  215679. String proxyName, proxyPath;
  215680. int proxyPort;
  215681. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  215682. return MemoryBlock();
  215683. header << originalURL << " HTTP/1.0\r\nHost: "
  215684. << proxyName << ':' << proxyPort;
  215685. /* xxx needs finishing
  215686. const char* proxyAuth = getenv ("http_proxy_auth");
  215687. if (proxyAuth != 0)
  215688. header << T("\r\nProxy-Authorization: ") << Base64Encode (proxyAuth);
  215689. */
  215690. }
  215691. header << "\r\nUser-Agent: JUCE/"
  215692. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  215693. << "\r\nConnection: Close\r\nContent-Length: "
  215694. << postData.getSize() << "\r\n"
  215695. << headers << "\r\n";
  215696. MemoryBlock mb;
  215697. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  215698. mb.append (postData.getData(), postData.getSize());
  215699. return mb;
  215700. }
  215701. const String readResponse()
  215702. {
  215703. int bytesRead = 0, numConsecutiveLFs = 0;
  215704. MemoryBlock buffer (1024, true);
  215705. while (numConsecutiveLFs < 2 && bytesRead < 32768)
  215706. {
  215707. fd_set readbits;
  215708. FD_ZERO (&readbits);
  215709. FD_SET (socketHandle, &readbits);
  215710. struct timeval tv;
  215711. tv.tv_sec = timeoutSeconds;
  215712. tv.tv_usec = 0;
  215713. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  215714. return String::empty; // (timeout)
  215715. buffer.ensureSize (bytesRead + 8, true);
  215716. char* const dest = (char*) buffer.getData() + bytesRead;
  215717. if (recv (socketHandle, dest, 1, 0) == -1)
  215718. return String::empty;
  215719. const char lastByte = *dest;
  215720. ++bytesRead;
  215721. if (lastByte == '\n')
  215722. ++numConsecutiveLFs;
  215723. else if (lastByte != '\r')
  215724. numConsecutiveLFs = 0;
  215725. }
  215726. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  215727. if (header.startsWithIgnoreCase (T("HTTP/")))
  215728. return header.trimEnd();
  215729. return String::empty;
  215730. }
  215731. static bool decomposeURL (const String& url,
  215732. String& host, String& path, int& port)
  215733. {
  215734. if (! url.startsWithIgnoreCase (T("http://")))
  215735. return false;
  215736. const int nextSlash = url.indexOfChar (7, '/');
  215737. int nextColon = url.indexOfChar (7, ':');
  215738. if (nextColon > nextSlash && nextSlash > 0)
  215739. nextColon = -1;
  215740. if (nextColon >= 0)
  215741. {
  215742. host = url.substring (7, nextColon);
  215743. if (nextSlash >= 0)
  215744. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  215745. else
  215746. port = url.substring (nextColon + 1).getIntValue();
  215747. }
  215748. else
  215749. {
  215750. port = 80;
  215751. if (nextSlash >= 0)
  215752. host = url.substring (7, nextSlash);
  215753. else
  215754. host = url.substring (7);
  215755. }
  215756. if (nextSlash >= 0)
  215757. path = url.substring (nextSlash);
  215758. else
  215759. path = T("/");
  215760. return true;
  215761. }
  215762. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  215763. {
  215764. for (int i = 0; i < lines.size(); ++i)
  215765. if (lines[i].startsWithIgnoreCase (itemName))
  215766. return lines[i].substring (itemName.length()).trim();
  215767. return String::empty;
  215768. }
  215769. };
  215770. bool juce_isOnLine()
  215771. {
  215772. return true;
  215773. }
  215774. void* juce_openInternetFile (const String& url,
  215775. const String& headers,
  215776. const MemoryBlock& postData,
  215777. const bool isPost,
  215778. URL::OpenStreamProgressCallback* callback,
  215779. void* callbackContext)
  215780. {
  215781. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  215782. if (s->open (url, headers, postData, isPost,
  215783. callback, callbackContext))
  215784. return s;
  215785. delete s;
  215786. return 0;
  215787. }
  215788. void juce_closeInternetFile (void* handle)
  215789. {
  215790. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215791. if (s != 0)
  215792. delete s;
  215793. }
  215794. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  215795. {
  215796. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215797. if (s != 0)
  215798. return s->read (buffer, bytesToRead);
  215799. return 0;
  215800. }
  215801. int juce_seekInInternetFile (void* handle, int newPosition)
  215802. {
  215803. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215804. if (s != 0)
  215805. return s->readPosition;
  215806. return 0;
  215807. }
  215808. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  215809. static bool GetEthernetIterator (io_iterator_t* matchingServices) throw()
  215810. {
  215811. mach_port_t masterPort;
  215812. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  215813. {
  215814. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  215815. if (dict != 0)
  215816. {
  215817. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  215818. 0,
  215819. &kCFTypeDictionaryKeyCallBacks,
  215820. &kCFTypeDictionaryValueCallBacks);
  215821. if (propDict != 0)
  215822. {
  215823. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  215824. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  215825. CFRelease (propDict);
  215826. }
  215827. }
  215828. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  215829. }
  215830. return false;
  215831. }
  215832. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  215833. {
  215834. int numResults = 0;
  215835. io_iterator_t it;
  215836. if (GetEthernetIterator (&it))
  215837. {
  215838. io_object_t i;
  215839. while ((i = IOIteratorNext (it)) != 0)
  215840. {
  215841. io_object_t controller;
  215842. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  215843. {
  215844. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  215845. CFSTR (kIOMACAddress),
  215846. kCFAllocatorDefault,
  215847. 0);
  215848. if (data != 0)
  215849. {
  215850. UInt8 addr [kIOEthernetAddressSize];
  215851. zeromem (addr, sizeof (addr));
  215852. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  215853. CFRelease (data);
  215854. int64 a = 0;
  215855. for (int i = 6; --i >= 0;)
  215856. a = (a << 8) | addr[i];
  215857. if (! littleEndian)
  215858. a = (int64) swapByteOrder ((uint64) a);
  215859. if (numResults < maxNum)
  215860. {
  215861. *addresses++ = a;
  215862. ++numResults;
  215863. }
  215864. }
  215865. IOObjectRelease (controller);
  215866. }
  215867. IOObjectRelease (i);
  215868. }
  215869. IOObjectRelease (it);
  215870. }
  215871. return numResults;
  215872. }
  215873. class AutoPool
  215874. {
  215875. public:
  215876. AutoPool() { pool = [[NSAutoreleasePool alloc] init]; }
  215877. ~AutoPool() { [pool release]; }
  215878. private:
  215879. NSAutoreleasePool* pool;
  215880. };
  215881. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  215882. const String& emailSubject,
  215883. const String& bodyText,
  215884. const StringArray& filesToAttach)
  215885. {
  215886. const AutoPool pool;
  215887. String script;
  215888. script << "tell application \"Mail\"\r\n"
  215889. "set newMessage to make new outgoing message with properties {subject:\""
  215890. << emailSubject.replace (T("\""), T("\\\""))
  215891. << "\", content:\""
  215892. << bodyText.replace (T("\""), T("\\\""))
  215893. << "\" & return & return}\r\n"
  215894. "tell newMessage\r\n"
  215895. "set visible to true\r\n"
  215896. "set sender to \"sdfsdfsdfewf\"\r\n"
  215897. "make new to recipient at end of to recipients with properties {address:\""
  215898. << targetEmailAddress
  215899. << "\"}\r\n";
  215900. for (int i = 0; i < filesToAttach.size(); ++i)
  215901. {
  215902. script << "tell content\r\n"
  215903. "make new attachment with properties {file name:\""
  215904. << filesToAttach[i].replace (T("\""), T("\\\""))
  215905. << "\"} at after the last paragraph\r\n"
  215906. "end tell\r\n";
  215907. }
  215908. script << "end tell\r\n"
  215909. "end tell\r\n";
  215910. NSAppleScript* s = [[NSAppleScript alloc]
  215911. initWithSource: [NSString stringWithUTF8String: (const char*) script.toUTF8()]];
  215912. NSDictionary* error = 0;
  215913. const bool ok = [s executeAndReturnError: &error] != nil;
  215914. [s release];
  215915. return ok;
  215916. }
  215917. END_JUCE_NAMESPACE
  215918. /********* End of inlined file: juce_mac_Network.mm *********/
  215919. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215920. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  215921. #if JUCE_USE_CDBURNER
  215922. #import <Cocoa/Cocoa.h>
  215923. #import <DiscRecording/DiscRecording.h>
  215924. BEGIN_JUCE_NAMESPACE
  215925. END_JUCE_NAMESPACE
  215926. @interface OpenDiskDevice : NSObject
  215927. {
  215928. DRDevice* device;
  215929. NSMutableArray* tracks;
  215930. }
  215931. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  215932. - (void) dealloc;
  215933. - (bool) isDiskPresent;
  215934. - (int) getNumAvailableAudioBlocks;
  215935. - (void) addSourceTrack: (juce::AudioSource*) source numSamples: (int) numSamples_;
  215936. - (void) burn: (juce::AudioCDBurner::BurnProgressListener*) listener errorString: (juce::String*) error
  215937. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  215938. @end
  215939. @interface AudioTrackProducer : NSObject
  215940. {
  215941. juce::AudioSource* source;
  215942. int readPosition, lengthInFrames;
  215943. }
  215944. - (AudioTrackProducer*) init: (int) lengthInFrames;
  215945. - (AudioTrackProducer*) initWithAudioSource: (juce::AudioSource*) source numSamples: (int) lengthInSamples;
  215946. - (void) dealloc;
  215947. - (void) setupTrackProperties: (DRTrack*) track;
  215948. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  215949. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  215950. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  215951. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  215952. toMedia:(NSDictionary*)mediaInfo;
  215953. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  215954. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  215955. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  215956. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  215957. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  215958. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  215959. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  215960. ioFlags:(uint32_t*)flags;
  215961. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  215962. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  215963. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  215964. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  215965. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  215966. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  215967. ioFlags:(uint32_t*)flags;
  215968. @end
  215969. @implementation OpenDiskDevice
  215970. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  215971. {
  215972. [super init];
  215973. device = device_;
  215974. tracks = [[NSMutableArray alloc] init];
  215975. return self;
  215976. }
  215977. - (void) dealloc
  215978. {
  215979. [tracks release];
  215980. [super dealloc];
  215981. }
  215982. - (bool) isDiskPresent
  215983. {
  215984. return [device isValid]
  215985. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  215986. isEqualTo: DRDeviceMediaStateMediaPresent];
  215987. }
  215988. - (int) getNumAvailableAudioBlocks
  215989. {
  215990. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  215991. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  215992. }
  215993. - (void) addSourceTrack: (juce::AudioSource*) source_ numSamples: (int) numSamples_
  215994. {
  215995. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  215996. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  215997. [p setupTrackProperties: t];
  215998. [tracks addObject: t];
  215999. [t release];
  216000. [p release];
  216001. }
  216002. - (void) burn: (juce::AudioCDBurner::BurnProgressListener*) listener errorString: (juce::String*) error
  216003. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  216004. {
  216005. DRBurn* burn = [DRBurn burnForDevice: device];
  216006. if (! [device acquireExclusiveAccess])
  216007. {
  216008. *error = "Couldn't open or write to the CD device";
  216009. return;
  216010. }
  216011. [device acquireMediaReservation];
  216012. NSMutableDictionary* d = [[burn properties] mutableCopy];
  216013. [d autorelease];
  216014. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  216015. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  216016. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  216017. forKey: DRBurnCompletionActionKey];
  216018. [burn setProperties: d];
  216019. [burn writeLayout: tracks];
  216020. for (;;)
  216021. {
  216022. juce::Thread::sleep (300);
  216023. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  216024. NSLog ([[burn status] description]);
  216025. if (listener != 0 && listener->audioCDBurnProgress (progress))
  216026. {
  216027. [burn abort];
  216028. *error = "User cancelled the write operation";
  216029. break;
  216030. }
  216031. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  216032. {
  216033. *error = "Write operation failed";
  216034. break;
  216035. }
  216036. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  216037. {
  216038. break;
  216039. }
  216040. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  216041. objectForKey: DRErrorStatusErrorStringKey];
  216042. if ([err length] > 0)
  216043. {
  216044. *error = juce::String::fromUTF8 ((juce::uint8*) [err UTF8String]);
  216045. break;
  216046. }
  216047. }
  216048. [device releaseMediaReservation];
  216049. [device releaseExclusiveAccess];
  216050. }
  216051. @end
  216052. @implementation AudioTrackProducer
  216053. - (AudioTrackProducer*) init: (int) lengthInFrames_
  216054. {
  216055. lengthInFrames = lengthInFrames_;
  216056. readPosition = 0;
  216057. return self;
  216058. }
  216059. - (void) setupTrackProperties: (DRTrack*) track
  216060. {
  216061. NSMutableDictionary* p = [[track properties] mutableCopy];
  216062. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  216063. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  216064. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  216065. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  216066. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  216067. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  216068. [track setProperties: p];
  216069. [p release];
  216070. }
  216071. - (AudioTrackProducer*) initWithAudioSource: (juce::AudioSource*) source_ numSamples: (int) lengthInSamples
  216072. {
  216073. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  216074. if (s != nil)
  216075. s->source = source_;
  216076. return s;
  216077. }
  216078. - (void) dealloc
  216079. {
  216080. if (source != 0)
  216081. {
  216082. source->releaseResources();
  216083. delete source;
  216084. }
  216085. [super dealloc];
  216086. }
  216087. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  216088. {
  216089. }
  216090. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track
  216091. {
  216092. return true;
  216093. }
  216094. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track
  216095. {
  216096. return lengthInFrames;
  216097. }
  216098. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216099. toMedia:(NSDictionary*)mediaInfo
  216100. {
  216101. if (source != 0)
  216102. source->prepareToPlay (44100 / 75, 44100);
  216103. readPosition = 0;
  216104. return true;
  216105. }
  216106. - (BOOL) prepareTrackForVerification:(DRTrack*)track
  216107. {
  216108. if (source != 0)
  216109. source->prepareToPlay (44100 / 75, 44100);
  216110. return true;
  216111. }
  216112. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216113. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216114. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216115. {
  216116. if (source != 0)
  216117. {
  216118. const int numSamples = juce::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  216119. if (numSamples > 0)
  216120. {
  216121. juce::AudioSampleBuffer tempBuffer (2, numSamples);
  216122. juce::AudioSourceChannelInfo info;
  216123. info.buffer = &tempBuffer;
  216124. info.startSample = 0;
  216125. info.numSamples = numSamples;
  216126. source->getNextAudioBlock (info);
  216127. juce::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  216128. buffer, numSamples, 4);
  216129. juce::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  216130. buffer + 2, numSamples, 4);
  216131. readPosition += numSamples;
  216132. }
  216133. return numSamples * 4;
  216134. }
  216135. return 0;
  216136. }
  216137. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216138. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216139. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216140. ioFlags:(uint32_t*)flags
  216141. {
  216142. zeromem (buffer, bufferLength);
  216143. return bufferLength;
  216144. }
  216145. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216146. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216147. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216148. {
  216149. return true;
  216150. }
  216151. @end
  216152. BEGIN_JUCE_NAMESPACE
  216153. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  216154. : internal (0)
  216155. {
  216156. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216157. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  216158. internal = (void*) dev;
  216159. [pool release];
  216160. }
  216161. AudioCDBurner::~AudioCDBurner()
  216162. {
  216163. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216164. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216165. if (dev != 0)
  216166. [dev release];
  216167. [pool release];
  216168. }
  216169. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  216170. {
  216171. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216172. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  216173. if (b->internal == 0)
  216174. deleteAndZero (b);
  216175. [pool release];
  216176. return b;
  216177. }
  216178. static NSArray* findDiskBurnerDevices()
  216179. {
  216180. NSMutableArray* results = [NSMutableArray array];
  216181. NSArray* devs = [DRDevice devices];
  216182. if (devs != 0)
  216183. {
  216184. int num = [devs count];
  216185. int i;
  216186. for (i = 0; i < num; ++i)
  216187. {
  216188. NSDictionary* dic = [[devs objectAtIndex: i] info];
  216189. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  216190. if (name != nil)
  216191. [results addObject: name];
  216192. }
  216193. }
  216194. return results;
  216195. }
  216196. const StringArray AudioCDBurner::findAvailableDevices()
  216197. {
  216198. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216199. NSArray* names = findDiskBurnerDevices();
  216200. StringArray s;
  216201. for (int i = 0; i < [names count]; ++i)
  216202. s.add (String::fromUTF8 ((juce::uint8*) [[names objectAtIndex: i] UTF8String]));
  216203. [pool release];
  216204. return s;
  216205. }
  216206. bool AudioCDBurner::isDiskPresent() const
  216207. {
  216208. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216209. return dev != 0 && [dev isDiskPresent];
  216210. }
  216211. int AudioCDBurner::getNumAvailableAudioBlocks() const
  216212. {
  216213. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216214. return [dev getNumAvailableAudioBlocks];
  216215. }
  216216. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  216217. {
  216218. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216219. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216220. if (dev != 0)
  216221. {
  216222. [dev addSourceTrack: source numSamples: numSamps];
  216223. [pool release];
  216224. return true;
  216225. }
  216226. [pool release];
  216227. return false;
  216228. }
  216229. const String AudioCDBurner::burn (juce::AudioCDBurner::BurnProgressListener* listener,
  216230. const bool ejectDiscAfterwards,
  216231. const bool peformFakeBurnForTesting)
  216232. {
  216233. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216234. juce::String error ("Couldn't open or write to the CD device");
  216235. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216236. if (dev != 0)
  216237. {
  216238. error = juce::String::empty;
  216239. [dev burn: listener
  216240. errorString: &error
  216241. ejectAfterwards: ejectDiscAfterwards
  216242. isFake: peformFakeBurnForTesting];
  216243. }
  216244. [pool release];
  216245. return error;
  216246. }
  216247. END_JUCE_NAMESPACE
  216248. #endif
  216249. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  216250. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  216251. #include <CoreAudio/AudioHardware.h>
  216252. BEGIN_JUCE_NAMESPACE
  216253. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216254. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  216255. #endif
  216256. #undef log
  216257. #if JUCE_COREAUDIO_LOGGING_ENABLED
  216258. #define log(a) Logger::writeToLog (a)
  216259. #else
  216260. #define log(a)
  216261. #endif
  216262. #undef OK
  216263. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216264. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  216265. {
  216266. if (err == noErr)
  216267. return true;
  216268. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  216269. jassertfalse
  216270. return false;
  216271. }
  216272. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  216273. #else
  216274. #define OK(a) (a == noErr)
  216275. #endif
  216276. static const int maxNumChans = 96;
  216277. class CoreAudioInternal : public Timer
  216278. {
  216279. public:
  216280. CoreAudioInternal (AudioDeviceID id)
  216281. : deviceID (id),
  216282. started (false),
  216283. audioBuffer (0),
  216284. numInputChans (0),
  216285. numOutputChans (0),
  216286. callbacksAllowed (true),
  216287. numInputChannelInfos (0),
  216288. numOutputChannelInfos (0),
  216289. inputLatency (0),
  216290. outputLatency (0),
  216291. callback (0),
  216292. inputDevice (0),
  216293. isSlaveDevice (false)
  216294. {
  216295. sampleRate = 0;
  216296. bufferSize = 512;
  216297. if (deviceID == 0)
  216298. {
  216299. error = TRANS("can't open device");
  216300. }
  216301. else
  216302. {
  216303. updateDetailsFromDevice();
  216304. AudioDeviceAddPropertyListener (deviceID,
  216305. kAudioPropertyWildcardChannel,
  216306. kAudioPropertyWildcardSection,
  216307. kAudioPropertyWildcardPropertyID,
  216308. deviceListenerProc, this);
  216309. }
  216310. }
  216311. ~CoreAudioInternal()
  216312. {
  216313. AudioDeviceRemovePropertyListener (deviceID,
  216314. kAudioPropertyWildcardChannel,
  216315. kAudioPropertyWildcardSection,
  216316. kAudioPropertyWildcardPropertyID,
  216317. deviceListenerProc);
  216318. stop (false);
  216319. juce_free (audioBuffer);
  216320. delete inputDevice;
  216321. }
  216322. void setTempBufferSize (const int numChannels, const int numSamples)
  216323. {
  216324. juce_free (audioBuffer);
  216325. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  216326. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  216327. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  216328. int count = 0;
  216329. int i;
  216330. for (i = maxNumChans; --i >= 0;)
  216331. if (activeInputChans[i])
  216332. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  216333. for (i = maxNumChans; --i >= 0;)
  216334. if (activeOutputChans[i])
  216335. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  216336. }
  216337. // returns the number of actual available channels
  216338. void fillInChannelInfo (bool input)
  216339. {
  216340. int chanNum = 0, activeChans = 0;
  216341. UInt32 size;
  216342. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  216343. {
  216344. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  216345. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  216346. {
  216347. const int numStreams = bufList->mNumberBuffers;
  216348. for (int i = 0; i < numStreams; ++i)
  216349. {
  216350. const AudioBuffer& b = bufList->mBuffers[i];
  216351. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  216352. {
  216353. if (input)
  216354. {
  216355. if (activeInputChans[chanNum])
  216356. {
  216357. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  216358. inputChannelInfo [activeChans].streamNum = i;
  216359. inputChannelInfo [activeChans].dataOffsetSamples = j;
  216360. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  216361. ++activeChans;
  216362. numInputChannelInfos = activeChans;
  216363. }
  216364. inChanNames.add (T("input ") + String (chanNum + 1));
  216365. }
  216366. else
  216367. {
  216368. if (activeOutputChans[chanNum])
  216369. {
  216370. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  216371. outputChannelInfo [activeChans].streamNum = i;
  216372. outputChannelInfo [activeChans].dataOffsetSamples = j;
  216373. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  216374. ++activeChans;
  216375. numOutputChannelInfos = activeChans;
  216376. }
  216377. outChanNames.add (T("output ") + String (chanNum + 1));
  216378. }
  216379. ++chanNum;
  216380. }
  216381. }
  216382. }
  216383. juce_free (bufList);
  216384. }
  216385. }
  216386. void updateDetailsFromDevice()
  216387. {
  216388. stopTimer();
  216389. if (deviceID == 0)
  216390. return;
  216391. const ScopedLock sl (callbackLock);
  216392. Float64 sr;
  216393. UInt32 size = sizeof (Float64);
  216394. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  216395. sampleRate = sr;
  216396. UInt32 framesPerBuf;
  216397. size = sizeof (framesPerBuf);
  216398. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  216399. {
  216400. bufferSize = framesPerBuf;
  216401. if (bufferSize > 0)
  216402. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  216403. }
  216404. bufferSizes.clear();
  216405. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  216406. {
  216407. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  216408. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  216409. {
  216410. bufferSizes.add ((int) ranges[0].mMinimum);
  216411. for (int i = 32; i < 8192; i += 32)
  216412. {
  216413. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  216414. {
  216415. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  216416. {
  216417. bufferSizes.addIfNotAlreadyThere (i);
  216418. break;
  216419. }
  216420. }
  216421. }
  216422. if (bufferSize > 0)
  216423. bufferSizes.addIfNotAlreadyThere (bufferSize);
  216424. }
  216425. juce_free (ranges);
  216426. }
  216427. if (bufferSizes.size() == 0 && bufferSize > 0)
  216428. bufferSizes.add (bufferSize);
  216429. sampleRates.clear();
  216430. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  216431. String rates;
  216432. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  216433. {
  216434. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  216435. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  216436. {
  216437. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  216438. {
  216439. bool ok = false;
  216440. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  216441. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  216442. ok = true;
  216443. if (ok)
  216444. {
  216445. sampleRates.add (possibleRates[i]);
  216446. rates << possibleRates[i] << T(" ");
  216447. }
  216448. }
  216449. }
  216450. juce_free (ranges);
  216451. }
  216452. if (sampleRates.size() == 0 && sampleRate > 0)
  216453. {
  216454. sampleRates.add (sampleRate);
  216455. rates << sampleRate;
  216456. }
  216457. log (T("sr: ") + rates);
  216458. inputLatency = 0;
  216459. outputLatency = 0;
  216460. UInt32 lat;
  216461. size = sizeof (UInt32);
  216462. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  216463. inputLatency = (int) lat;
  216464. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  216465. outputLatency = (int) lat;
  216466. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  216467. inChanNames.clear();
  216468. outChanNames.clear();
  216469. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  216470. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  216471. fillInChannelInfo (true);
  216472. fillInChannelInfo (false);
  216473. }
  216474. const StringArray getSources (bool input)
  216475. {
  216476. StringArray s;
  216477. int num = 0;
  216478. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  216479. if (types != 0)
  216480. {
  216481. for (int i = 0; i < num; ++i)
  216482. {
  216483. AudioValueTranslation avt;
  216484. char buffer[256];
  216485. avt.mInputData = (void*) &(types[i]);
  216486. avt.mInputDataSize = sizeof (UInt32);
  216487. avt.mOutputData = buffer;
  216488. avt.mOutputDataSize = 256;
  216489. UInt32 transSize = sizeof (avt);
  216490. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  216491. {
  216492. DBG (buffer);
  216493. s.add (buffer);
  216494. }
  216495. }
  216496. juce_free (types);
  216497. }
  216498. return s;
  216499. }
  216500. int getCurrentSourceIndex (bool input) const
  216501. {
  216502. OSType currentSourceID = 0;
  216503. UInt32 size = 0;
  216504. int result = -1;
  216505. if (deviceID != 0
  216506. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  216507. {
  216508. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  216509. {
  216510. int num = 0;
  216511. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  216512. if (types != 0)
  216513. {
  216514. for (int i = 0; i < num; ++i)
  216515. {
  216516. if (types[num] == currentSourceID)
  216517. {
  216518. result = i;
  216519. break;
  216520. }
  216521. }
  216522. juce_free (types);
  216523. }
  216524. }
  216525. }
  216526. return result;
  216527. }
  216528. void setCurrentSourceIndex (int index, bool input)
  216529. {
  216530. if (deviceID != 0)
  216531. {
  216532. int num = 0;
  216533. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  216534. if (types != 0)
  216535. {
  216536. if (((unsigned int) index) < num)
  216537. {
  216538. OSType typeId = types[index];
  216539. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  216540. }
  216541. juce_free (types);
  216542. }
  216543. }
  216544. }
  216545. const String reopen (const BitArray& inputChannels,
  216546. const BitArray& outputChannels,
  216547. double newSampleRate,
  216548. int bufferSizeSamples)
  216549. {
  216550. error = String::empty;
  216551. log ("CoreAudio reopen");
  216552. callbacksAllowed = false;
  216553. stopTimer();
  216554. stop (false);
  216555. activeInputChans = inputChannels;
  216556. activeOutputChans = outputChannels;
  216557. numInputChans = inputChannels.countNumberOfSetBits();
  216558. numOutputChans = outputChannels.countNumberOfSetBits();
  216559. // set sample rate
  216560. Float64 sr = newSampleRate;
  216561. UInt32 size = sizeof (sr);
  216562. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  216563. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  216564. // change buffer size
  216565. UInt32 framesPerBuf = bufferSizeSamples;
  216566. size = sizeof (framesPerBuf);
  216567. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  216568. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  216569. // wait for the changes to happen (on some devices)
  216570. int i = 30;
  216571. while (--i >= 0)
  216572. {
  216573. updateDetailsFromDevice();
  216574. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  216575. break;
  216576. Thread::sleep (100);
  216577. }
  216578. if (i < 0)
  216579. error = "Couldn't change sample rate/buffer size";
  216580. if (sampleRates.size() == 0)
  216581. error = "Device has no available sample-rates";
  216582. if (bufferSizes.size() == 0)
  216583. error = "Device has no available buffer-sizes";
  216584. numInputChans = jmin (numInputChans, numInputChannelInfos);
  216585. numOutputChans = jmin (numOutputChans, numOutputChannelInfos);
  216586. activeInputChans.setRange (inChanNames.size(),
  216587. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  216588. false);
  216589. activeOutputChans.setRange (outChanNames.size(),
  216590. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  216591. false);
  216592. if (inputDevice != 0 && error.isEmpty())
  216593. error = inputDevice->reopen (inputChannels,
  216594. outputChannels,
  216595. newSampleRate,
  216596. bufferSizeSamples);
  216597. callbacksAllowed = true;
  216598. return error;
  216599. }
  216600. bool start (AudioIODeviceCallback* cb)
  216601. {
  216602. if (! started)
  216603. {
  216604. callback = 0;
  216605. if (deviceID != 0)
  216606. {
  216607. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  216608. {
  216609. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  216610. {
  216611. started = true;
  216612. }
  216613. else
  216614. {
  216615. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  216616. }
  216617. }
  216618. }
  216619. }
  216620. if (started)
  216621. {
  216622. const ScopedLock sl (callbackLock);
  216623. callback = cb;
  216624. }
  216625. if (inputDevice != 0)
  216626. return started && inputDevice->start (cb);
  216627. else
  216628. return started;
  216629. }
  216630. void stop (bool leaveInterruptRunning)
  216631. {
  216632. callbackLock.enter();
  216633. callback = 0;
  216634. callbackLock.exit();
  216635. if (started
  216636. && (deviceID != 0)
  216637. && ! leaveInterruptRunning)
  216638. {
  216639. OK (AudioDeviceStop (deviceID, audioIOProc));
  216640. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  216641. started = false;
  216642. callbackLock.enter();
  216643. callbackLock.exit();
  216644. // wait until it's definately stopped calling back..
  216645. for (int i = 40; --i >= 0;)
  216646. {
  216647. Thread::sleep (50);
  216648. UInt32 running = 0;
  216649. UInt32 size = sizeof (running);
  216650. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  216651. if (running == 0)
  216652. break;
  216653. }
  216654. callbackLock.enter();
  216655. callbackLock.exit();
  216656. }
  216657. if (inputDevice != 0)
  216658. inputDevice->stop (leaveInterruptRunning);
  216659. }
  216660. double getSampleRate() const
  216661. {
  216662. return sampleRate;
  216663. }
  216664. int getBufferSize() const
  216665. {
  216666. return bufferSize;
  216667. }
  216668. void audioCallback (const AudioBufferList* inInputData,
  216669. AudioBufferList* outOutputData)
  216670. {
  216671. int i;
  216672. const ScopedLock sl (callbackLock);
  216673. if (callback != 0)
  216674. {
  216675. if (inputDevice == 0)
  216676. {
  216677. for (i = numInputChans; --i >= 0;)
  216678. {
  216679. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  216680. float* dest = tempInputBuffers [info.sourceChannelNum];
  216681. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  216682. + info.dataOffsetSamples;
  216683. const int stride = info.dataStrideSamples;
  216684. if (stride != 0) // if this is zero, info is invalid
  216685. {
  216686. for (int j = bufferSize; --j >= 0;)
  216687. {
  216688. *dest++ = *src;
  216689. src += stride;
  216690. }
  216691. }
  216692. }
  216693. }
  216694. if (! isSlaveDevice)
  216695. {
  216696. if (inputDevice == 0)
  216697. {
  216698. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  216699. numInputChans,
  216700. tempOutputBuffers,
  216701. numOutputChans,
  216702. bufferSize);
  216703. }
  216704. else
  216705. {
  216706. jassert (inputDevice->bufferSize == bufferSize);
  216707. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  216708. inputDevice->numInputChans,
  216709. tempOutputBuffers,
  216710. numOutputChans,
  216711. bufferSize);
  216712. }
  216713. for (i = numOutputChans; --i >= 0;)
  216714. {
  216715. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  216716. const float* src = tempOutputBuffers [info.sourceChannelNum];
  216717. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  216718. + info.dataOffsetSamples;
  216719. const int stride = info.dataStrideSamples;
  216720. if (stride != 0) // if this is zero, info is invalid
  216721. {
  216722. for (int j = bufferSize; --j >= 0;)
  216723. {
  216724. *dest = *src++;
  216725. dest += stride;
  216726. }
  216727. }
  216728. }
  216729. }
  216730. }
  216731. else
  216732. {
  216733. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  216734. {
  216735. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  216736. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  216737. + info.dataOffsetSamples;
  216738. const int stride = info.dataStrideSamples;
  216739. if (stride != 0) // if this is zero, info is invalid
  216740. {
  216741. for (int j = bufferSize; --j >= 0;)
  216742. {
  216743. *dest = 0.0f;
  216744. dest += stride;
  216745. }
  216746. }
  216747. }
  216748. }
  216749. }
  216750. // called by callbacks
  216751. void deviceDetailsChanged()
  216752. {
  216753. if (callbacksAllowed)
  216754. startTimer (100);
  216755. }
  216756. void timerCallback()
  216757. {
  216758. stopTimer();
  216759. log ("CoreAudio device changed callback");
  216760. const double oldSampleRate = sampleRate;
  216761. const int oldBufferSize = bufferSize;
  216762. updateDetailsFromDevice();
  216763. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  216764. {
  216765. callbacksAllowed = false;
  216766. stop (false);
  216767. updateDetailsFromDevice();
  216768. callbacksAllowed = true;
  216769. }
  216770. }
  216771. CoreAudioInternal* getRelatedDevice() const
  216772. {
  216773. UInt32 size = 0;
  216774. CoreAudioInternal* result = 0;
  216775. if (deviceID != 0
  216776. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  216777. && size > 0)
  216778. {
  216779. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  216780. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  216781. {
  216782. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  216783. {
  216784. if (devs[i] != deviceID && devs[i] != 0)
  216785. {
  216786. result = new CoreAudioInternal (devs[i]);
  216787. if (result->error.isEmpty())
  216788. {
  216789. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  216790. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  216791. if (thisIsInput != otherIsInput)
  216792. break;
  216793. }
  216794. deleteAndZero (result);
  216795. }
  216796. }
  216797. }
  216798. juce_free (devs);
  216799. }
  216800. return result;
  216801. }
  216802. juce_UseDebuggingNewOperator
  216803. String error;
  216804. int inputLatency, outputLatency;
  216805. BitArray activeInputChans, activeOutputChans;
  216806. StringArray inChanNames, outChanNames;
  216807. Array <double> sampleRates;
  216808. Array <int> bufferSizes;
  216809. AudioIODeviceCallback* callback;
  216810. CoreAudioInternal* inputDevice;
  216811. bool isSlaveDevice;
  216812. private:
  216813. CriticalSection callbackLock;
  216814. AudioDeviceID deviceID;
  216815. bool started;
  216816. double sampleRate;
  216817. int bufferSize;
  216818. float* audioBuffer;
  216819. int numInputChans, numOutputChans;
  216820. bool callbacksAllowed;
  216821. struct CallbackDetailsForChannel
  216822. {
  216823. int sourceChannelNum;
  216824. int streamNum;
  216825. int dataOffsetSamples;
  216826. int dataStrideSamples;
  216827. };
  216828. int numInputChannelInfos, numOutputChannelInfos;
  216829. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  216830. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  216831. float* tempInputBuffers [maxNumChans];
  216832. float* tempOutputBuffers [maxNumChans];
  216833. CoreAudioInternal (const CoreAudioInternal&);
  216834. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  216835. static OSStatus audioIOProc (AudioDeviceID inDevice,
  216836. const AudioTimeStamp* inNow,
  216837. const AudioBufferList* inInputData,
  216838. const AudioTimeStamp* inInputTime,
  216839. AudioBufferList* outOutputData,
  216840. const AudioTimeStamp* inOutputTime,
  216841. void* device)
  216842. {
  216843. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  216844. return noErr;
  216845. }
  216846. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  216847. UInt32 inLine,
  216848. Boolean isInput,
  216849. AudioDevicePropertyID inPropertyID,
  216850. void* inClientData)
  216851. {
  216852. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  216853. switch (inPropertyID)
  216854. {
  216855. case kAudioDevicePropertyBufferSize:
  216856. case kAudioDevicePropertyBufferFrameSize:
  216857. case kAudioDevicePropertyNominalSampleRate:
  216858. case kAudioDevicePropertyStreamFormat:
  216859. case kAudioDevicePropertyDeviceIsAlive:
  216860. intern->deviceDetailsChanged();
  216861. break;
  216862. case kAudioDevicePropertyBufferSizeRange:
  216863. case kAudioDevicePropertyVolumeScalar:
  216864. case kAudioDevicePropertyMute:
  216865. case kAudioDevicePropertyPlayThru:
  216866. case kAudioDevicePropertyDataSource:
  216867. case kAudioDevicePropertyDeviceIsRunning:
  216868. break;
  216869. }
  216870. return noErr;
  216871. }
  216872. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  216873. {
  216874. OSType* types = 0;
  216875. UInt32 size = 0;
  216876. num = 0;
  216877. if (deviceID != 0
  216878. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  216879. {
  216880. types = (OSType*) juce_calloc (size);
  216881. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  216882. {
  216883. num = size / sizeof (OSType);
  216884. }
  216885. else
  216886. {
  216887. juce_free (types);
  216888. types = 0;
  216889. }
  216890. }
  216891. return types;
  216892. }
  216893. };
  216894. class CoreAudioIODevice : public AudioIODevice
  216895. {
  216896. public:
  216897. CoreAudioIODevice (const String& deviceName,
  216898. AudioDeviceID deviceId1)
  216899. : AudioIODevice (deviceName, "CoreAudio"),
  216900. isOpen_ (false),
  216901. isStarted (false)
  216902. {
  216903. internal = 0;
  216904. CoreAudioInternal* device = new CoreAudioInternal (deviceId1);
  216905. lastError = device->error;
  216906. if (lastError.isNotEmpty())
  216907. {
  216908. deleteAndZero (device);
  216909. }
  216910. else
  216911. {
  216912. CoreAudioInternal* secondDevice = device->getRelatedDevice();
  216913. if (secondDevice != 0)
  216914. {
  216915. if (device->inChanNames.size() > secondDevice->inChanNames.size())
  216916. swapVariables (device, secondDevice);
  216917. device->inputDevice = secondDevice;
  216918. secondDevice->isSlaveDevice = true;
  216919. }
  216920. }
  216921. internal = device;
  216922. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  216923. hardwareListenerProc, internal);
  216924. }
  216925. ~CoreAudioIODevice()
  216926. {
  216927. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  216928. hardwareListenerProc);
  216929. delete internal;
  216930. }
  216931. const StringArray getOutputChannelNames()
  216932. {
  216933. return internal->outChanNames;
  216934. }
  216935. const StringArray getInputChannelNames()
  216936. {
  216937. if (internal->inputDevice != 0)
  216938. return internal->inputDevice->inChanNames;
  216939. else
  216940. return internal->inChanNames;
  216941. }
  216942. int getNumSampleRates()
  216943. {
  216944. return internal->sampleRates.size();
  216945. }
  216946. double getSampleRate (int index)
  216947. {
  216948. return internal->sampleRates [index];
  216949. }
  216950. int getNumBufferSizesAvailable()
  216951. {
  216952. return internal->bufferSizes.size();
  216953. }
  216954. int getBufferSizeSamples (int index)
  216955. {
  216956. return internal->bufferSizes [index];
  216957. }
  216958. int getDefaultBufferSize()
  216959. {
  216960. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  216961. if (getBufferSizeSamples(i) >= 512)
  216962. return getBufferSizeSamples(i);
  216963. return 512;
  216964. }
  216965. const String open (const BitArray& inputChannels,
  216966. const BitArray& outputChannels,
  216967. double sampleRate,
  216968. int bufferSizeSamples)
  216969. {
  216970. isOpen_ = true;
  216971. if (bufferSizeSamples <= 0)
  216972. bufferSizeSamples = getDefaultBufferSize();
  216973. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  216974. lastError = internal->error;
  216975. return lastError;
  216976. }
  216977. void close()
  216978. {
  216979. isOpen_ = false;
  216980. }
  216981. bool isOpen()
  216982. {
  216983. return isOpen_;
  216984. }
  216985. int getCurrentBufferSizeSamples()
  216986. {
  216987. return internal != 0 ? internal->getBufferSize() : 512;
  216988. }
  216989. double getCurrentSampleRate()
  216990. {
  216991. return internal != 0 ? internal->getSampleRate() : 0;
  216992. }
  216993. int getCurrentBitDepth()
  216994. {
  216995. return 32; // no way to find out, so just assume it's high..
  216996. }
  216997. const BitArray getActiveOutputChannels() const
  216998. {
  216999. return internal != 0 ? internal->activeOutputChans : BitArray();
  217000. }
  217001. const BitArray getActiveInputChannels() const
  217002. {
  217003. BitArray chans;
  217004. if (internal != 0)
  217005. {
  217006. chans = internal->activeInputChans;
  217007. if (internal->inputDevice != 0)
  217008. chans.orWith (internal->inputDevice->activeInputChans);
  217009. }
  217010. return chans;
  217011. }
  217012. int getOutputLatencyInSamples()
  217013. {
  217014. if (internal == 0)
  217015. return 0;
  217016. // this seems like a good guess at getting the latency right - comparing
  217017. // this with a round-trip measurement, it gets it to within a few millisecs
  217018. // for the built-in mac soundcard
  217019. return internal->outputLatency + internal->getBufferSize() * 2;
  217020. }
  217021. int getInputLatencyInSamples()
  217022. {
  217023. if (internal == 0)
  217024. return 0;
  217025. return internal->inputLatency + internal->getBufferSize() * 2;
  217026. }
  217027. void start (AudioIODeviceCallback* callback)
  217028. {
  217029. if (internal != 0 && ! isStarted)
  217030. {
  217031. if (callback != 0)
  217032. callback->audioDeviceAboutToStart (this);
  217033. isStarted = true;
  217034. internal->start (callback);
  217035. }
  217036. }
  217037. void stop()
  217038. {
  217039. if (isStarted && internal != 0)
  217040. {
  217041. AudioIODeviceCallback* const lastCallback = internal->callback;
  217042. isStarted = false;
  217043. internal->stop (true);
  217044. if (lastCallback != 0)
  217045. lastCallback->audioDeviceStopped();
  217046. }
  217047. }
  217048. bool isPlaying()
  217049. {
  217050. if (internal->callback == 0)
  217051. isStarted = false;
  217052. return isStarted;
  217053. }
  217054. const String getLastError()
  217055. {
  217056. return lastError;
  217057. }
  217058. juce_UseDebuggingNewOperator
  217059. private:
  217060. CoreAudioInternal* internal;
  217061. bool isOpen_, isStarted;
  217062. String lastError;
  217063. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  217064. {
  217065. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217066. switch (inPropertyID)
  217067. {
  217068. case kAudioHardwarePropertyDevices:
  217069. intern->deviceDetailsChanged();
  217070. break;
  217071. case kAudioHardwarePropertyDefaultOutputDevice:
  217072. case kAudioHardwarePropertyDefaultInputDevice:
  217073. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  217074. break;
  217075. }
  217076. return noErr;
  217077. }
  217078. CoreAudioIODevice (const CoreAudioIODevice&);
  217079. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  217080. };
  217081. class CoreAudioIODeviceType : public AudioIODeviceType
  217082. {
  217083. public:
  217084. CoreAudioIODeviceType()
  217085. : AudioIODeviceType (T("CoreAudio")),
  217086. hasScanned (false)
  217087. {
  217088. }
  217089. ~CoreAudioIODeviceType()
  217090. {
  217091. }
  217092. void scanForDevices()
  217093. {
  217094. hasScanned = true;
  217095. names.clear();
  217096. ids.clear();
  217097. UInt32 size;
  217098. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  217099. {
  217100. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  217101. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  217102. {
  217103. static bool alreadyLogged = false;
  217104. const int num = size / sizeof (AudioDeviceID);
  217105. for (int i = 0; i < num; ++i)
  217106. {
  217107. char name[1024];
  217108. size = sizeof (name);
  217109. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  217110. {
  217111. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  217112. if (! alreadyLogged)
  217113. log (T("CoreAudio device: ") + nameString);
  217114. names.add (nameString);
  217115. ids.add (devs[i]);
  217116. }
  217117. }
  217118. alreadyLogged = true;
  217119. }
  217120. juce_free (devs);
  217121. }
  217122. }
  217123. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  217124. {
  217125. jassert (hasScanned); // need to call scanForDevices() before doing this
  217126. StringArray namesCopy (names);
  217127. namesCopy.removeDuplicates (true);
  217128. return namesCopy;
  217129. }
  217130. const String getDefaultDeviceName (const bool preferInputNames,
  217131. const int numInputChannelsNeeded,
  217132. const int numOutputChannelsNeeded) const
  217133. {
  217134. jassert (hasScanned); // need to call scanForDevices() before doing this
  217135. String result (names[0]);
  217136. AudioDeviceID deviceID;
  217137. UInt32 size = sizeof (deviceID);
  217138. // if they're asking for any input channels at all, use the default input, so we
  217139. // get the built-in mic rather than the built-in output with no inputs..
  217140. if (AudioHardwareGetProperty (numInputChannelsNeeded > 0
  217141. ? kAudioHardwarePropertyDefaultInputDevice
  217142. : kAudioHardwarePropertyDefaultOutputDevice,
  217143. &size, &deviceID) == noErr)
  217144. {
  217145. for (int i = ids.size(); --i >= 0;)
  217146. if (ids[i] == deviceID)
  217147. result = names[i];
  217148. }
  217149. return result;
  217150. }
  217151. AudioIODevice* createDevice (const String& deviceName)
  217152. {
  217153. jassert (hasScanned); // need to call scanForDevices() before doing this
  217154. const int index = names.indexOf (deviceName);
  217155. if (index >= 0)
  217156. return new CoreAudioIODevice (deviceName, ids [index]);
  217157. return 0;
  217158. }
  217159. juce_UseDebuggingNewOperator
  217160. private:
  217161. StringArray names;
  217162. Array <AudioDeviceID> ids;
  217163. bool hasScanned;
  217164. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  217165. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  217166. };
  217167. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  217168. {
  217169. return new CoreAudioIODeviceType();
  217170. }
  217171. #undef log
  217172. END_JUCE_NAMESPACE
  217173. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  217174. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  217175. #include <CoreMIDI/MIDIServices.h>
  217176. BEGIN_JUCE_NAMESPACE
  217177. #undef log
  217178. #define log(a) Logger::writeToLog(a)
  217179. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  217180. {
  217181. if (err == noErr)
  217182. return true;
  217183. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217184. jassertfalse
  217185. return false;
  217186. }
  217187. #undef OK
  217188. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  217189. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  217190. {
  217191. String result;
  217192. CFStringRef str = 0;
  217193. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  217194. if (str != 0)
  217195. {
  217196. result = PlatformUtilities::cfStringToJuceString (str);
  217197. CFRelease (str);
  217198. str = 0;
  217199. }
  217200. MIDIEntityRef entity = 0;
  217201. MIDIEndpointGetEntity (endpoint, &entity);
  217202. if (entity == 0)
  217203. return result; // probably virtual
  217204. if (result.isEmpty())
  217205. {
  217206. // endpoint name has zero length - try the entity
  217207. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  217208. if (str != 0)
  217209. {
  217210. result += PlatformUtilities::cfStringToJuceString (str);
  217211. CFRelease (str);
  217212. str = 0;
  217213. }
  217214. }
  217215. // now consider the device's name
  217216. MIDIDeviceRef device = 0;
  217217. MIDIEntityGetDevice (entity, &device);
  217218. if (device == 0)
  217219. return result;
  217220. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  217221. if (str != 0)
  217222. {
  217223. const String s (PlatformUtilities::cfStringToJuceString (str));
  217224. CFRelease (str);
  217225. // if an external device has only one entity, throw away
  217226. // the endpoint name and just use the device name
  217227. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  217228. {
  217229. result = s;
  217230. }
  217231. else if (! result.startsWithIgnoreCase (s))
  217232. {
  217233. // prepend the device name to the entity name
  217234. result = (s + T(" ") + result).trimEnd();
  217235. }
  217236. }
  217237. return result;
  217238. }
  217239. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  217240. {
  217241. String result;
  217242. // Does the endpoint have connections?
  217243. CFDataRef connections = 0;
  217244. int numConnections = 0;
  217245. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  217246. if (connections != 0)
  217247. {
  217248. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  217249. if (numConnections > 0)
  217250. {
  217251. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  217252. for (int i = 0; i < numConnections; ++i, ++pid)
  217253. {
  217254. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  217255. MIDIObjectRef connObject;
  217256. MIDIObjectType connObjectType;
  217257. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  217258. if (err == noErr)
  217259. {
  217260. String s;
  217261. if (connObjectType == kMIDIObjectType_ExternalSource
  217262. || connObjectType == kMIDIObjectType_ExternalDestination)
  217263. {
  217264. // Connected to an external device's endpoint (10.3 and later).
  217265. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  217266. }
  217267. else
  217268. {
  217269. // Connected to an external device (10.2) (or something else, catch-all)
  217270. CFStringRef str = 0;
  217271. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  217272. if (str != 0)
  217273. {
  217274. s = PlatformUtilities::cfStringToJuceString (str);
  217275. CFRelease (str);
  217276. }
  217277. }
  217278. if (s.isNotEmpty())
  217279. {
  217280. if (result.isNotEmpty())
  217281. result += (", ");
  217282. result += s;
  217283. }
  217284. }
  217285. }
  217286. }
  217287. CFRelease (connections);
  217288. }
  217289. if (result.isNotEmpty())
  217290. return result;
  217291. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  217292. return getEndpointName (endpoint, false);
  217293. }
  217294. const StringArray MidiOutput::getDevices()
  217295. {
  217296. StringArray s;
  217297. const ItemCount num = MIDIGetNumberOfDestinations();
  217298. for (ItemCount i = 0; i < num; ++i)
  217299. {
  217300. MIDIEndpointRef dest = MIDIGetDestination (i);
  217301. if (dest != 0)
  217302. {
  217303. String name (getConnectedEndpointName (dest));
  217304. if (name.isEmpty())
  217305. name = "<error>";
  217306. s.add (name);
  217307. }
  217308. else
  217309. {
  217310. s.add ("<error>");
  217311. }
  217312. }
  217313. return s;
  217314. }
  217315. int MidiOutput::getDefaultDeviceIndex()
  217316. {
  217317. return 0;
  217318. }
  217319. static MIDIClientRef globalMidiClient;
  217320. static bool hasGlobalClientBeenCreated = false;
  217321. static bool makeSureClientExists()
  217322. {
  217323. if (! hasGlobalClientBeenCreated)
  217324. {
  217325. String name (T("JUCE"));
  217326. if (JUCEApplication::getInstance() != 0)
  217327. name = JUCEApplication::getInstance()->getApplicationName();
  217328. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  217329. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  217330. CFRelease (appName);
  217331. }
  217332. return hasGlobalClientBeenCreated;
  217333. }
  217334. struct MidiPortAndEndpoint
  217335. {
  217336. MIDIPortRef port;
  217337. MIDIEndpointRef endPoint;
  217338. };
  217339. MidiOutput* MidiOutput::openDevice (int index)
  217340. {
  217341. MidiOutput* mo = 0;
  217342. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  217343. {
  217344. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  217345. CFStringRef pname;
  217346. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  217347. {
  217348. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  217349. if (makeSureClientExists())
  217350. {
  217351. MIDIPortRef port;
  217352. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  217353. {
  217354. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  217355. mpe->port = port;
  217356. mpe->endPoint = endPoint;
  217357. mo = new MidiOutput();
  217358. mo->internal = (void*)mpe;
  217359. }
  217360. }
  217361. CFRelease (pname);
  217362. }
  217363. }
  217364. return mo;
  217365. }
  217366. MidiOutput::~MidiOutput()
  217367. {
  217368. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  217369. MIDIPortDispose (mpe->port);
  217370. delete mpe;
  217371. }
  217372. void MidiOutput::reset()
  217373. {
  217374. }
  217375. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  217376. {
  217377. return false;
  217378. }
  217379. void MidiOutput::setVolume (float leftVol, float rightVol)
  217380. {
  217381. }
  217382. void MidiOutput::sendMessageNow (const MidiMessage& message)
  217383. {
  217384. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  217385. if (message.isSysEx())
  217386. {
  217387. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  217388. packets->numPackets = 1;
  217389. packets->packet[0].timeStamp = 0;
  217390. packets->packet[0].length = message.getRawDataSize();
  217391. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  217392. MIDISend (mpe->port, mpe->endPoint, packets);
  217393. juce_free (packets);
  217394. }
  217395. else
  217396. {
  217397. MIDIPacketList packets;
  217398. packets.numPackets = 1;
  217399. packets.packet[0].timeStamp = 0;
  217400. packets.packet[0].length = message.getRawDataSize();
  217401. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  217402. MIDISend (mpe->port, mpe->endPoint, &packets);
  217403. }
  217404. }
  217405. const StringArray MidiInput::getDevices()
  217406. {
  217407. StringArray s;
  217408. const ItemCount num = MIDIGetNumberOfSources();
  217409. for (ItemCount i = 0; i < num; ++i)
  217410. {
  217411. MIDIEndpointRef source = MIDIGetSource (i);
  217412. if (source != 0)
  217413. {
  217414. String name (getConnectedEndpointName (source));
  217415. if (name.isEmpty())
  217416. name = "<error>";
  217417. s.add (name);
  217418. }
  217419. else
  217420. {
  217421. s.add ("<error>");
  217422. }
  217423. }
  217424. return s;
  217425. }
  217426. int MidiInput::getDefaultDeviceIndex()
  217427. {
  217428. return 0;
  217429. }
  217430. struct MidiPortAndCallback
  217431. {
  217432. MidiInput* input;
  217433. MIDIPortRef port;
  217434. MIDIEndpointRef endPoint;
  217435. MidiInputCallback* callback;
  217436. MemoryBlock pendingData;
  217437. int pendingBytes;
  217438. double pendingDataTime;
  217439. bool active;
  217440. };
  217441. static CriticalSection callbackLock;
  217442. static VoidArray activeCallbacks;
  217443. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  217444. {
  217445. if (*d == 0xf0)
  217446. {
  217447. mpe->pendingBytes = 0;
  217448. mpe->pendingDataTime = time;
  217449. }
  217450. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  217451. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  217452. uint8* dest = totalMessage + mpe->pendingBytes;
  217453. while (size > 0)
  217454. {
  217455. if (mpe->pendingBytes > 0 && *d >= 0x80)
  217456. {
  217457. if (*d >= 0xfa || *d == 0xf8)
  217458. {
  217459. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  217460. ++d;
  217461. --size;
  217462. }
  217463. else
  217464. {
  217465. if (*d == 0xf7)
  217466. {
  217467. *dest++ = *d++;
  217468. mpe->pendingBytes++;
  217469. --size;
  217470. }
  217471. break;
  217472. }
  217473. }
  217474. else
  217475. {
  217476. *dest++ = *d++;
  217477. mpe->pendingBytes++;
  217478. --size;
  217479. }
  217480. }
  217481. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  217482. {
  217483. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  217484. mpe->pendingBytes,
  217485. mpe->pendingDataTime));
  217486. mpe->pendingBytes = 0;
  217487. }
  217488. else
  217489. {
  217490. mpe->callback->handlePartialSysexMessage (mpe->input,
  217491. totalMessage,
  217492. mpe->pendingBytes,
  217493. mpe->pendingDataTime);
  217494. }
  217495. }
  217496. static void midiInputProc (const MIDIPacketList* pktlist,
  217497. void* readProcRefCon,
  217498. void* srcConnRefCon)
  217499. {
  217500. double time = Time::getMillisecondCounterHiRes() * 0.001;
  217501. const double originalTime = time;
  217502. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  217503. const ScopedLock sl (callbackLock);
  217504. if (activeCallbacks.contains (mpe) && mpe->active)
  217505. {
  217506. const MIDIPacket* packet = &pktlist->packet[0];
  217507. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  217508. {
  217509. const uint8* d = (const uint8*) (packet->data);
  217510. int size = packet->length;
  217511. while (size > 0)
  217512. {
  217513. time = originalTime;
  217514. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  217515. {
  217516. processSysex (mpe, d, size, time);
  217517. }
  217518. else
  217519. {
  217520. int used = 0;
  217521. const MidiMessage m (d, size, used, 0, time);
  217522. if (used <= 0)
  217523. {
  217524. jassertfalse // malformed midi message
  217525. break;
  217526. }
  217527. else
  217528. {
  217529. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  217530. }
  217531. size -= used;
  217532. d += used;
  217533. }
  217534. }
  217535. packet = MIDIPacketNext (packet);
  217536. }
  217537. }
  217538. }
  217539. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  217540. {
  217541. MidiInput* mi = 0;
  217542. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  217543. {
  217544. MIDIEndpointRef endPoint = MIDIGetSource (index);
  217545. if (endPoint != 0)
  217546. {
  217547. CFStringRef pname;
  217548. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  217549. {
  217550. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  217551. if (makeSureClientExists())
  217552. {
  217553. MIDIPortRef port;
  217554. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  217555. mpe->active = false;
  217556. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  217557. {
  217558. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  217559. {
  217560. mpe->port = port;
  217561. mpe->endPoint = endPoint;
  217562. mpe->callback = callback;
  217563. mpe->pendingBytes = 0;
  217564. mpe->pendingData.ensureSize (128);
  217565. mi = new MidiInput (getDevices() [index]);
  217566. mpe->input = mi;
  217567. mi->internal = (void*) mpe;
  217568. const ScopedLock sl (callbackLock);
  217569. activeCallbacks.add (mpe);
  217570. }
  217571. else
  217572. {
  217573. OK (MIDIPortDispose (port));
  217574. delete mpe;
  217575. }
  217576. }
  217577. else
  217578. {
  217579. delete mpe;
  217580. }
  217581. }
  217582. }
  217583. CFRelease (pname);
  217584. }
  217585. }
  217586. return mi;
  217587. }
  217588. MidiInput::MidiInput (const String& name_)
  217589. : name (name_)
  217590. {
  217591. }
  217592. MidiInput::~MidiInput()
  217593. {
  217594. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217595. mpe->active = false;
  217596. callbackLock.enter();
  217597. activeCallbacks.removeValue (mpe);
  217598. callbackLock.exit();
  217599. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  217600. OK (MIDIPortDispose (mpe->port));
  217601. delete mpe;
  217602. }
  217603. void MidiInput::start()
  217604. {
  217605. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217606. const ScopedLock sl (callbackLock);
  217607. mpe->active = true;
  217608. }
  217609. void MidiInput::stop()
  217610. {
  217611. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217612. const ScopedLock sl (callbackLock);
  217613. mpe->active = false;
  217614. }
  217615. #undef log
  217616. END_JUCE_NAMESPACE
  217617. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  217618. /********* Start of inlined file: juce_mac_FileChooser.cpp *********/
  217619. #include <Carbon/Carbon.h>
  217620. #include <fnmatch.h>
  217621. BEGIN_JUCE_NAMESPACE
  217622. struct JuceNavInfo
  217623. {
  217624. StringArray filters;
  217625. AEDesc defaultLocation;
  217626. bool defaultLocationValid;
  217627. };
  217628. static void pascal juceNavEventProc (NavEventCallbackMessage callbackSelector,
  217629. NavCBRecPtr callbackParms,
  217630. void *callBackUD)
  217631. {
  217632. if (callbackSelector == kNavCBStart)
  217633. {
  217634. if (((JuceNavInfo*) callBackUD)->defaultLocationValid)
  217635. {
  217636. NavCustomControl (callbackParms->context,
  217637. kNavCtlSetLocation,
  217638. (void*) &((JuceNavInfo*) callBackUD)->defaultLocation);
  217639. }
  217640. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  217641. {
  217642. Component* const c = Desktop::getInstance().getComponent (i);
  217643. if (c != 0 && c->isAlwaysOnTop() && c->isVisible())
  217644. {
  217645. SetWindowGroup (callbackParms->window,
  217646. GetWindowGroup ((WindowRef) c->getWindowHandle()));
  217647. break;
  217648. }
  217649. }
  217650. BringToFront (callbackParms->window);
  217651. SelectWindow (callbackParms->window);
  217652. SetUserFocusWindow (callbackParms->window);
  217653. }
  217654. }
  217655. static Boolean pascal juceNavFilterProc (AEDesc* theItem,
  217656. void*,
  217657. void* callBackUD,
  217658. NavFilterModes filterMode)
  217659. {
  217660. // must return true if we don't understand the object
  217661. bool result = true;
  217662. if (filterMode == kNavFilteringBrowserList)
  217663. {
  217664. AEDesc desc;
  217665. if (AECoerceDesc (theItem, typeFSRef, &desc) == noErr)
  217666. {
  217667. Size size = AEGetDescDataSize (&desc);
  217668. if (size > 0)
  217669. {
  217670. void* data = juce_calloc (size);
  217671. if (AEGetDescData (&desc, data, size) == noErr)
  217672. {
  217673. const String path (PlatformUtilities::makePathFromFSRef ((FSRef*) data));
  217674. if (path.isNotEmpty())
  217675. {
  217676. const File file (path);
  217677. if ((! file.isDirectory()) || PlatformUtilities::isBundle (path))
  217678. {
  217679. const String filename (file.getFileName().toLowerCase());
  217680. const char* const filenameUTF8 = filename.toUTF8();
  217681. const JuceNavInfo* const info = (const JuceNavInfo*) callBackUD;
  217682. if (info != 0)
  217683. {
  217684. result = false;
  217685. for (int i = info->filters.size(); --i >= 0;)
  217686. {
  217687. const String wildcard (info->filters[i].toLowerCase());
  217688. if (fnmatch (wildcard.toUTF8(), filenameUTF8, 0) == 0)
  217689. {
  217690. result = true;
  217691. break;
  217692. }
  217693. }
  217694. }
  217695. }
  217696. }
  217697. }
  217698. juce_free (data);
  217699. }
  217700. AEDisposeDesc (&desc);
  217701. }
  217702. }
  217703. return result;
  217704. }
  217705. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  217706. const String& title,
  217707. const File& currentFileOrDirectory,
  217708. const String& filter,
  217709. bool selectsDirectory,
  217710. bool isSaveDialogue,
  217711. bool warnAboutOverwritingExistingFiles,
  217712. bool selectMultipleFiles,
  217713. FilePreviewComponent* extraInfoComponent)
  217714. {
  217715. JuceNavInfo userInfo;
  217716. userInfo.filters.addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  217717. userInfo.filters.trim();
  217718. userInfo.filters.removeEmptyStrings();
  217719. userInfo.defaultLocationValid = false;
  217720. void* const userInfoPtr = (void*) &userInfo;
  217721. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  217722. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  217723. NavEventUPP eventProc = NewNavEventUPP (juceNavEventProc);
  217724. NavObjectFilterUPP filterProc = NewNavObjectFilterUPP (juceNavFilterProc);
  217725. FSRef defaultRef;
  217726. if ((currentFileOrDirectory.isOnHardDisk()
  217727. && PlatformUtilities::makeFSRefFromPath (&defaultRef,
  217728. currentFileOrDirectory.getFullPathName()))
  217729. || (currentFileOrDirectory.getParentDirectory().isOnHardDisk()
  217730. && PlatformUtilities::makeFSRefFromPath (&defaultRef,
  217731. currentFileOrDirectory.getParentDirectory().getFullPathName())))
  217732. {
  217733. if (AECreateDesc (typeFSRef, &defaultRef, sizeof (defaultRef), &userInfo.defaultLocation) == noErr)
  217734. {
  217735. userInfo.defaultLocationValid = true;
  217736. }
  217737. }
  217738. WindowRef lastFocused = GetUserFocusWindow();
  217739. NavDialogCreationOptions options;
  217740. if (NavGetDefaultDialogCreationOptions (&options) == noErr)
  217741. {
  217742. options.optionFlags |= kNavSelectDefaultLocation
  217743. | kNavSupportPackages
  217744. | kNavAllowPreviews;
  217745. if (! warnAboutOverwritingExistingFiles)
  217746. options.optionFlags |= kNavDontConfirmReplacement;
  217747. if (selectMultipleFiles)
  217748. options.optionFlags |= kNavAllowMultipleFiles;
  217749. const String name (selectsDirectory ? TRANS("Choose folder")
  217750. : TRANS("Choose file"));
  217751. options.clientName = PlatformUtilities::juceStringToCFString (name);
  217752. CFStringRef message = PlatformUtilities::juceStringToCFString (title);
  217753. // nasty layout bug if the message text is set for a directory browser..
  217754. if (selectsDirectory)
  217755. options.windowTitle = message;
  217756. else
  217757. options.message = message;
  217758. NavDialogRef dialog = 0;
  217759. bool ok = false;
  217760. if (selectsDirectory)
  217761. {
  217762. ok = (NavCreateChooseFolderDialog (&options, eventProc, 0, userInfoPtr, &dialog) == noErr);
  217763. }
  217764. else if (isSaveDialogue)
  217765. {
  217766. ok = (NavCreatePutFileDialog (&options, 0, 0, eventProc, userInfoPtr, &dialog) == noErr);
  217767. }
  217768. else
  217769. {
  217770. ok = (NavCreateGetFileDialog (&options, 0, eventProc, 0, filterProc, userInfoPtr, &dialog) == noErr);
  217771. }
  217772. if (ok && (NavDialogRun (dialog) == noErr))
  217773. {
  217774. NavReplyRecord reply;
  217775. if (NavDialogGetReply (dialog, &reply) == noErr)
  217776. {
  217777. if (reply.validRecord)
  217778. {
  217779. long count;
  217780. if (AECountItems (&(reply.selection), &count) == noErr
  217781. && count > 0)
  217782. {
  217783. AEKeyword theKeyword;
  217784. DescType actualType;
  217785. Size actualSize;
  217786. FSRef file;
  217787. for (int i = 1; i <= count; ++i)
  217788. {
  217789. // Get a pointer to selected file
  217790. if (AEGetNthPtr (&(reply.selection),
  217791. i,
  217792. typeFSRef,
  217793. &theKeyword,
  217794. &actualType,
  217795. &file,
  217796. sizeof (file),
  217797. &actualSize) == noErr)
  217798. {
  217799. String result (PlatformUtilities::makePathFromFSRef (&file));
  217800. if (result.isNotEmpty() && isSaveDialogue && ! selectsDirectory)
  217801. {
  217802. CFStringRef saveName = NavDialogGetSaveFileName (dialog);
  217803. result = File (result)
  217804. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (PlatformUtilities::cfStringToJuceString (saveName)))
  217805. .getFullPathName();
  217806. }
  217807. results.add (new File (result));
  217808. }
  217809. }
  217810. }
  217811. }
  217812. NavDisposeReply (&reply);
  217813. }
  217814. }
  217815. if (dialog != 0)
  217816. NavDialogDispose (dialog);
  217817. CFRelease (message);
  217818. CFRelease (options.clientName);
  217819. }
  217820. if (userInfo.defaultLocationValid)
  217821. AEDisposeDesc (&userInfo.defaultLocation);
  217822. DisposeNavEventUPP (eventProc);
  217823. DisposeNavObjectFilterUPP (filterProc);
  217824. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  217825. SetUserFocusWindow (lastFocused);
  217826. }
  217827. END_JUCE_NAMESPACE
  217828. /********* End of inlined file: juce_mac_FileChooser.cpp *********/
  217829. /********* Start of inlined file: juce_mac_Fonts.cpp *********/
  217830. #include <ApplicationServices/ApplicationServices.h>
  217831. BEGIN_JUCE_NAMESPACE
  217832. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  217833. void* callBackDataPtr)
  217834. {
  217835. Path* const p = (Path*) callBackDataPtr;
  217836. p->startNewSubPath (pt->x, pt->y);
  217837. return noErr;
  217838. }
  217839. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  217840. void* callBackDataPtr)
  217841. {
  217842. Path* const p = (Path*) callBackDataPtr;
  217843. p->lineTo (pt->x, pt->y);
  217844. return noErr;
  217845. }
  217846. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  217847. const Float32Point *pt2,
  217848. const Float32Point *pt3,
  217849. void* callBackDataPtr)
  217850. {
  217851. Path* const p = (Path*) callBackDataPtr;
  217852. p->cubicTo (pt1->x, pt1->y,
  217853. pt2->x, pt2->y,
  217854. pt3->x, pt3->y);
  217855. return noErr;
  217856. }
  217857. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  217858. {
  217859. Path* const p = (Path*) callBackDataPtr;
  217860. p->closeSubPath();
  217861. return noErr;
  217862. }
  217863. class ATSFontHelper
  217864. {
  217865. ATSUFontID fontId;
  217866. ATSUStyle style;
  217867. ATSCubicMoveToUPP moveToProc;
  217868. ATSCubicLineToUPP lineToProc;
  217869. ATSCubicCurveToUPP curveToProc;
  217870. ATSCubicClosePathUPP closePathProc;
  217871. float totalSize, ascent;
  217872. TextToUnicodeInfo encodingInfo;
  217873. public:
  217874. String name;
  217875. bool isBold, isItalic;
  217876. float fontSize;
  217877. int refCount;
  217878. ATSFontHelper (const String& name_,
  217879. const bool bold_,
  217880. const bool italic_,
  217881. const float size_)
  217882. : fontId (0),
  217883. name (name_),
  217884. isBold (bold_),
  217885. isItalic (italic_),
  217886. fontSize (size_),
  217887. refCount (1)
  217888. {
  217889. const char* const nameUtf8 = name_.toUTF8();
  217890. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  217891. strlen (nameUtf8),
  217892. kFontFullName,
  217893. kFontNoPlatformCode,
  217894. kFontNoScriptCode,
  217895. kFontNoLanguageCode,
  217896. &fontId);
  217897. ATSUCreateStyle (&style);
  217898. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  217899. kATSUQDBoldfaceTag,
  217900. kATSUQDItalicTag,
  217901. kATSUSizeTag };
  217902. ByteCount attSizes[] = { sizeof (ATSUFontID),
  217903. sizeof (Boolean),
  217904. sizeof (Boolean),
  217905. sizeof (Fixed) };
  217906. Boolean bold = bold_, italic = italic_;
  217907. Fixed size = X2Fix (size_);
  217908. ATSUAttributeValuePtr attValues[] = { &fontId,
  217909. &bold,
  217910. &italic,
  217911. &size };
  217912. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  217913. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  217914. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  217915. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  217916. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  217917. ascent = 0.0f;
  217918. float kern, descent = 0.0f;
  217919. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  217920. totalSize = ascent + descent;
  217921. }
  217922. ~ATSFontHelper()
  217923. {
  217924. ATSUDisposeStyle (style);
  217925. DisposeATSCubicMoveToUPP (moveToProc);
  217926. DisposeATSCubicLineToUPP (lineToProc);
  217927. DisposeATSCubicCurveToUPP (curveToProc);
  217928. DisposeATSCubicClosePathUPP (closePathProc);
  217929. }
  217930. bool getPathAndKerning (const juce_wchar char1,
  217931. const juce_wchar char2,
  217932. Path* path,
  217933. float& kerning,
  217934. float* ascent,
  217935. float* descent)
  217936. {
  217937. bool ok = false;
  217938. UniChar buffer[4];
  217939. buffer[0] = T(' ');
  217940. buffer[1] = char1;
  217941. buffer[2] = char2;
  217942. buffer[3] = 0;
  217943. UniCharCount count = kATSUToTextEnd;
  217944. ATSUTextLayout layout;
  217945. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  217946. 0,
  217947. 2,
  217948. 2,
  217949. 1,
  217950. &count,
  217951. &style,
  217952. &layout);
  217953. if (err == noErr)
  217954. {
  217955. ATSUSetTransientFontMatching (layout, true);
  217956. ATSLayoutRecord* layoutRecords;
  217957. ItemCount numRecords;
  217958. Fixed* deltaYs;
  217959. ItemCount numDeltaYs;
  217960. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  217961. 0,
  217962. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  217963. (void**) &layoutRecords,
  217964. &numRecords);
  217965. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  217966. 0,
  217967. kATSUDirectDataBaselineDeltaFixedArray,
  217968. (void**) &deltaYs,
  217969. &numDeltaYs);
  217970. if (numRecords > 2)
  217971. {
  217972. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  217973. - Fix2X (layoutRecords[1].realPos));
  217974. if (ascent != 0)
  217975. {
  217976. ATSUTextMeasurement asc;
  217977. ByteCount actualSize;
  217978. ATSUGetLineControl (layout,
  217979. 0,
  217980. kATSULineAscentTag,
  217981. sizeof (ATSUTextMeasurement),
  217982. &asc,
  217983. &actualSize);
  217984. *ascent = (float) Fix2X (asc);
  217985. }
  217986. if (descent != 0)
  217987. {
  217988. ATSUTextMeasurement desc;
  217989. ByteCount actualSize;
  217990. ATSUGetLineControl (layout,
  217991. 0,
  217992. kATSULineDescentTag,
  217993. sizeof (ATSUTextMeasurement),
  217994. &desc,
  217995. &actualSize);
  217996. *descent = (float) Fix2X (desc);
  217997. }
  217998. if (path != 0)
  217999. {
  218000. OSStatus callbackResult;
  218001. ok = (ATSUGlyphGetCubicPaths (style,
  218002. layoutRecords[1].glyphID,
  218003. moveToProc,
  218004. lineToProc,
  218005. curveToProc,
  218006. closePathProc,
  218007. (void*) path,
  218008. &callbackResult) == noErr);
  218009. if (numDeltaYs > 0 && ok)
  218010. {
  218011. const float dy = (float) Fix2X (deltaYs[1]);
  218012. path->applyTransform (AffineTransform::translation (0.0f, dy));
  218013. }
  218014. }
  218015. else
  218016. {
  218017. ok = true;
  218018. }
  218019. }
  218020. if (deltaYs != 0)
  218021. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  218022. (void**) &deltaYs);
  218023. if (layoutRecords != 0)
  218024. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218025. (void**) &layoutRecords);
  218026. ATSUDisposeTextLayout (layout);
  218027. }
  218028. return kerning;
  218029. }
  218030. float getAscent()
  218031. {
  218032. return ascent;
  218033. }
  218034. float getTotalHeight()
  218035. {
  218036. return totalSize;
  218037. }
  218038. juce_wchar getDefaultChar()
  218039. {
  218040. return 0;
  218041. }
  218042. };
  218043. class ATSFontHelperCache : public Timer,
  218044. public DeletedAtShutdown
  218045. {
  218046. VoidArray cache;
  218047. public:
  218048. ATSFontHelperCache()
  218049. {
  218050. }
  218051. ~ATSFontHelperCache()
  218052. {
  218053. for (int i = cache.size(); --i >= 0;)
  218054. {
  218055. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218056. delete f;
  218057. }
  218058. clearSingletonInstance();
  218059. }
  218060. ATSFontHelper* getFont (const String& name,
  218061. const bool bold,
  218062. const bool italic,
  218063. const float size = 1024)
  218064. {
  218065. for (int i = cache.size(); --i >= 0;)
  218066. {
  218067. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218068. if (f->name == name
  218069. && f->isBold == bold
  218070. && f->isItalic == italic
  218071. && f->fontSize == size)
  218072. {
  218073. f->refCount++;
  218074. return f;
  218075. }
  218076. }
  218077. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  218078. cache.add (f);
  218079. return f;
  218080. }
  218081. void releaseFont (ATSFontHelper* f)
  218082. {
  218083. for (int i = cache.size(); --i >= 0;)
  218084. {
  218085. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  218086. if (f == f2)
  218087. {
  218088. f->refCount--;
  218089. if (f->refCount == 0)
  218090. startTimer (5000);
  218091. break;
  218092. }
  218093. }
  218094. }
  218095. void timerCallback()
  218096. {
  218097. stopTimer();
  218098. for (int i = cache.size(); --i >= 0;)
  218099. {
  218100. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218101. if (f->refCount == 0)
  218102. {
  218103. cache.remove (i);
  218104. delete f;
  218105. }
  218106. }
  218107. if (cache.size() == 0)
  218108. delete this;
  218109. }
  218110. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  218111. };
  218112. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  218113. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  218114. bool bold,
  218115. bool italic,
  218116. bool addAllGlyphsToFont) throw()
  218117. {
  218118. // This method is only safe to be called from the normal UI thread..
  218119. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218120. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218121. ->getFont (fontName, bold, italic);
  218122. clear();
  218123. setAscent (helper->getAscent() / helper->getTotalHeight());
  218124. setName (fontName);
  218125. setDefaultCharacter (helper->getDefaultChar());
  218126. setBold (bold);
  218127. setItalic (italic);
  218128. if (addAllGlyphsToFont)
  218129. {
  218130. //xxx
  218131. jassertfalse
  218132. }
  218133. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218134. }
  218135. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  218136. {
  218137. // This method is only safe to be called from the normal UI thread..
  218138. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218139. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218140. ->getFont (getName(), isBold(), isItalic());
  218141. Path path;
  218142. float width;
  218143. bool foundOne = false;
  218144. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  218145. {
  218146. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  218147. 1.0f / helper->getTotalHeight()));
  218148. addGlyph (character, path, width / helper->getTotalHeight());
  218149. for (int i = 0; i < glyphs.size(); ++i)
  218150. {
  218151. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  218152. float kerning;
  218153. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  218154. {
  218155. kerning = (kerning - width) / helper->getTotalHeight();
  218156. if (kerning != 0)
  218157. addKerningPair (character, g->getCharacter(), kerning);
  218158. }
  218159. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  218160. {
  218161. kerning = kerning / helper->getTotalHeight() - g->width;
  218162. if (kerning != 0)
  218163. addKerningPair (g->getCharacter(), character, kerning);
  218164. }
  218165. }
  218166. foundOne = true;
  218167. }
  218168. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218169. return foundOne;
  218170. }
  218171. const StringArray Font::findAllTypefaceNames() throw()
  218172. {
  218173. StringArray names;
  218174. ATSFontIterator iter;
  218175. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  218176. 0,
  218177. 0,
  218178. kATSOptionFlagsRestrictedScope,
  218179. &iter) == noErr)
  218180. {
  218181. ATSFontRef font;
  218182. while (ATSFontIteratorNext (iter, &font) == noErr)
  218183. {
  218184. CFStringRef name;
  218185. if (ATSFontGetName (font,
  218186. kATSOptionFlagsDefault,
  218187. &name) == noErr)
  218188. {
  218189. const String nm (PlatformUtilities::cfStringToJuceString (name));
  218190. if (nm.isNotEmpty())
  218191. names.add (nm);
  218192. CFRelease (name);
  218193. }
  218194. }
  218195. ATSFontIteratorRelease (&iter);
  218196. }
  218197. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  218198. // a plain version of. This is only necessary because of Carbon's total lack of support
  218199. // for dealing with font families...
  218200. for (int j = names.size(); --j >= 0;)
  218201. {
  218202. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  218203. " oblque", " bold oblique", " boldoblique" };
  218204. for (int i = 0; i < numElementsInArray (endings); ++i)
  218205. {
  218206. const String ending (endings[i]);
  218207. if (names[j].endsWithIgnoreCase (ending))
  218208. {
  218209. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  218210. if (names.contains (root)
  218211. || names.contains (root + T(" plain"), true))
  218212. {
  218213. names.remove (j);
  218214. break;
  218215. }
  218216. }
  218217. }
  218218. }
  218219. names.sort (true);
  218220. return names;
  218221. }
  218222. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  218223. {
  218224. defaultSans = "Lucida Grande";
  218225. defaultSerif = "Times New Roman";
  218226. defaultFixed = "Monaco";
  218227. }
  218228. END_JUCE_NAMESPACE
  218229. /********* End of inlined file: juce_mac_Fonts.cpp *********/
  218230. /********* Start of inlined file: juce_mac_Messaging.cpp *********/
  218231. #include <Carbon/Carbon.h>
  218232. BEGIN_JUCE_NAMESPACE
  218233. #undef Point
  218234. static int kJUCEClass = FOUR_CHAR_CODE ('JUCE');
  218235. const int kJUCEKind = 1;
  218236. const int kCallbackKind = 2;
  218237. extern void juce_HandleProcessFocusChange();
  218238. extern void juce_maximiseAllMinimisedWindows();
  218239. extern void juce_InvokeMainMenuCommand (const HICommand& command);
  218240. extern void juce_MainMenuAboutToBeUsed();
  218241. static pascal OSStatus EventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218242. {
  218243. void* event = 0;
  218244. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof (void*), 0, &event);
  218245. if (event != 0)
  218246. MessageManager::getInstance()->deliverMessage (event);
  218247. return noErr;
  218248. }
  218249. struct CallbackMessagePayload
  218250. {
  218251. MessageCallbackFunction* function;
  218252. void* parameter;
  218253. void* volatile result;
  218254. bool volatile hasBeenExecuted;
  218255. };
  218256. static pascal OSStatus CallbackHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218257. {
  218258. CallbackMessagePayload* pl = 0;
  218259. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof(pl), 0, &pl);
  218260. if (pl != 0)
  218261. {
  218262. pl->result = (*pl->function) (pl->parameter);
  218263. pl->hasBeenExecuted = true;
  218264. }
  218265. return noErr;
  218266. }
  218267. static pascal OSStatus MouseClickHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218268. {
  218269. ::Point where;
  218270. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof(::Point), 0, &where);
  218271. WindowRef window;
  218272. if (FindWindow (where, &window) == inMenuBar)
  218273. {
  218274. // turn off the wait cursor before going in here..
  218275. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  218276. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  218277. if (Component::getCurrentlyModalComponent() != 0)
  218278. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  218279. juce_MainMenuAboutToBeUsed();
  218280. MenuSelect (where);
  218281. HiliteMenu (0);
  218282. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  218283. return noErr;
  218284. }
  218285. return eventNotHandledErr;
  218286. }
  218287. static pascal OSErr QuitAppleEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  218288. {
  218289. if (JUCEApplication::getInstance() != 0)
  218290. JUCEApplication::getInstance()->systemRequestedQuit();
  218291. return noErr;
  218292. }
  218293. static pascal OSErr OpenDocEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  218294. {
  218295. AEDescList docs;
  218296. StringArray files;
  218297. if (AEGetParamDesc (appleEvt, keyDirectObject, typeAEList, &docs) == noErr)
  218298. {
  218299. long num;
  218300. if (AECountItems (&docs, &num) == noErr)
  218301. {
  218302. for (int i = 1; i <= num; ++i)
  218303. {
  218304. FSRef file;
  218305. AEKeyword keyword;
  218306. DescType type;
  218307. Size size;
  218308. if (AEGetNthPtr (&docs, i, typeFSRef, &keyword, &type,
  218309. &file, sizeof (file), &size) == noErr)
  218310. {
  218311. const String path (PlatformUtilities::makePathFromFSRef (&file));
  218312. if (path.isNotEmpty())
  218313. files.add (path.quoted());
  218314. }
  218315. }
  218316. if (files.size() > 0
  218317. && JUCEApplication::getInstance() != 0)
  218318. {
  218319. JUCE_TRY
  218320. {
  218321. JUCEApplication::getInstance()
  218322. ->anotherInstanceStarted (files.joinIntoString (T(" ")));
  218323. }
  218324. JUCE_CATCH_ALL
  218325. }
  218326. }
  218327. AEDisposeDesc (&docs);
  218328. };
  218329. return noErr;
  218330. }
  218331. static pascal OSStatus AppEventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218332. {
  218333. const UInt32 eventClass = GetEventClass (theEvent);
  218334. if (eventClass == kEventClassCommand)
  218335. {
  218336. HICommand command;
  218337. if (GetEventParameter (theEvent, kEventParamHICommand, typeHICommand, 0, sizeof (command), 0, &command) == noErr
  218338. || GetEventParameter (theEvent, kEventParamDirectObject, typeHICommand, 0, sizeof (command), 0, &command) == noErr)
  218339. {
  218340. if (command.commandID == kHICommandQuit)
  218341. {
  218342. if (JUCEApplication::getInstance() != 0)
  218343. JUCEApplication::getInstance()->systemRequestedQuit();
  218344. return noErr;
  218345. }
  218346. else if (command.commandID == kHICommandMaximizeAll
  218347. || command.commandID == kHICommandMaximizeWindow
  218348. || command.commandID == kHICommandBringAllToFront)
  218349. {
  218350. juce_maximiseAllMinimisedWindows();
  218351. return noErr;
  218352. }
  218353. else
  218354. {
  218355. juce_InvokeMainMenuCommand (command);
  218356. }
  218357. }
  218358. }
  218359. else if (eventClass == kEventClassApplication)
  218360. {
  218361. if (GetEventKind (theEvent) == kEventAppFrontSwitched)
  218362. {
  218363. juce_HandleProcessFocusChange();
  218364. }
  218365. else if (GetEventKind (theEvent) == kEventAppShown)
  218366. {
  218367. // this seems to blank the windows, so we need to do a repaint..
  218368. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  218369. {
  218370. Component* const c = Desktop::getInstance().getComponent (i);
  218371. if (c != 0)
  218372. c->repaint();
  218373. }
  218374. }
  218375. }
  218376. return eventNotHandledErr;
  218377. }
  218378. static EventQueueRef mainQueue;
  218379. static EventHandlerRef juceEventHandler = 0;
  218380. static EventHandlerRef callbackEventHandler = 0;
  218381. void MessageManager::doPlatformSpecificInitialisation()
  218382. {
  218383. static bool initialised = false;
  218384. if (! initialised)
  218385. {
  218386. initialised = true;
  218387. #if MACOS_10_3_OR_EARLIER
  218388. // work-around for a bug in MacOS 10.2..
  218389. ProcessSerialNumber junkPSN;
  218390. (void) GetCurrentProcess (&junkPSN);
  218391. #endif
  218392. mainQueue = GetMainEventQueue();
  218393. // if we're linking a Juce app to one or more dynamic libraries, we'll need different values
  218394. // for this so each module doesn't interfere with the others.
  218395. UnsignedWide t;
  218396. Microseconds (&t);
  218397. kJUCEClass ^= t.lo;
  218398. }
  218399. const EventTypeSpec type1 = { kJUCEClass, kJUCEKind };
  218400. InstallApplicationEventHandler (NewEventHandlerUPP (EventHandlerProc), 1, &type1, 0, &juceEventHandler);
  218401. const EventTypeSpec type2 = { kJUCEClass, kCallbackKind };
  218402. InstallApplicationEventHandler (NewEventHandlerUPP (CallbackHandlerProc), 1, &type2, 0, &callbackEventHandler);
  218403. // only do this stuff if we're running as an application rather than a library..
  218404. if (JUCEApplication::getInstance() != 0)
  218405. {
  218406. const EventTypeSpec type3 = { kEventClassMouse, kEventMouseDown };
  218407. InstallApplicationEventHandler (NewEventHandlerUPP (MouseClickHandlerProc), 1, &type3, 0, 0);
  218408. const EventTypeSpec type4[] = { { kEventClassApplication, kEventAppShown },
  218409. { kEventClassApplication, kEventAppFrontSwitched },
  218410. { kEventClassCommand, kEventProcessCommand } };
  218411. InstallApplicationEventHandler (NewEventHandlerUPP (AppEventHandlerProc), 3, type4, 0, 0);
  218412. AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
  218413. NewAEEventHandlerUPP (QuitAppleEventHandler), 0, false);
  218414. AEInstallEventHandler (kCoreEventClass, kAEOpenDocuments,
  218415. NewAEEventHandlerUPP (OpenDocEventHandler), 0, false);
  218416. }
  218417. }
  218418. void MessageManager::doPlatformSpecificShutdown()
  218419. {
  218420. if (juceEventHandler != 0)
  218421. {
  218422. RemoveEventHandler (juceEventHandler);
  218423. juceEventHandler = 0;
  218424. }
  218425. if (callbackEventHandler != 0)
  218426. {
  218427. RemoveEventHandler (callbackEventHandler);
  218428. callbackEventHandler = 0;
  218429. }
  218430. }
  218431. bool juce_postMessageToSystemQueue (void* message)
  218432. {
  218433. jassert (mainQueue == GetMainEventQueue());
  218434. EventRef event;
  218435. if (CreateEvent (0, kJUCEClass, kJUCEKind, 0, kEventAttributeUserEvent, &event) == noErr)
  218436. {
  218437. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &message);
  218438. const bool ok = PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr;
  218439. ReleaseEvent (event);
  218440. return ok;
  218441. }
  218442. return false;
  218443. }
  218444. void MessageManager::broadcastMessage (const String& value) throw()
  218445. {
  218446. }
  218447. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  218448. void* data)
  218449. {
  218450. if (isThisTheMessageThread())
  218451. {
  218452. return (*callback) (data);
  218453. }
  218454. else
  218455. {
  218456. jassert (mainQueue == GetMainEventQueue());
  218457. CallbackMessagePayload cmp;
  218458. cmp.function = callback;
  218459. cmp.parameter = data;
  218460. cmp.result = 0;
  218461. cmp.hasBeenExecuted = false;
  218462. EventRef event;
  218463. if (CreateEvent (0, kJUCEClass, kCallbackKind, 0, kEventAttributeUserEvent, &event) == noErr)
  218464. {
  218465. void* v = &cmp;
  218466. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &v);
  218467. if (PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr)
  218468. {
  218469. while (! cmp.hasBeenExecuted)
  218470. Thread::yield();
  218471. return cmp.result;
  218472. }
  218473. }
  218474. return 0;
  218475. }
  218476. }
  218477. END_JUCE_NAMESPACE
  218478. /********* End of inlined file: juce_mac_Messaging.cpp *********/
  218479. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  218480. #include <Cocoa/Cocoa.h>
  218481. #include <WebKit/WebKit.h>
  218482. #include <WebKit/HIWebView.h>
  218483. #include <WebKit/WebPolicyDelegate.h>
  218484. #include <WebKit/CarbonUtils.h>
  218485. BEGIN_JUCE_NAMESPACE
  218486. END_JUCE_NAMESPACE
  218487. @interface DownloadClickDetector : NSObject
  218488. {
  218489. juce::WebBrowserComponent* ownerComponent;
  218490. }
  218491. - (DownloadClickDetector*) initWithOwner: (juce::WebBrowserComponent*) ownerComponent;
  218492. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  218493. request: (NSURLRequest*) request
  218494. frame: (WebFrame*) frame
  218495. decisionListener: (id<WebPolicyDecisionListener>) listener;
  218496. @end
  218497. @implementation DownloadClickDetector
  218498. - (DownloadClickDetector*) initWithOwner: (juce::WebBrowserComponent*) ownerComponent_
  218499. {
  218500. [super init];
  218501. ownerComponent = ownerComponent_;
  218502. return self;
  218503. }
  218504. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  218505. {
  218506. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  218507. if (ownerComponent->pageAboutToLoad (juce::String::fromUTF8 ((const juce::uint8*) [[url absoluteString] UTF8String])))
  218508. [listener use];
  218509. else
  218510. [listener ignore];
  218511. }
  218512. @end
  218513. BEGIN_JUCE_NAMESPACE
  218514. class WebBrowserComponentInternal : public Timer
  218515. {
  218516. public:
  218517. WebBrowserComponentInternal (WebBrowserComponent* owner_)
  218518. : owner (owner_),
  218519. view (0),
  218520. webView (0)
  218521. {
  218522. HIWebViewCreate (&view);
  218523. ComponentPeer* const peer = owner_->getPeer();
  218524. jassert (peer != 0);
  218525. if (view != 0 && peer != 0)
  218526. {
  218527. WindowRef parentWindow = (WindowRef) peer->getNativeHandle();
  218528. WindowAttributes attributes;
  218529. GetWindowAttributes (parentWindow, &attributes);
  218530. HIViewRef parentView = 0;
  218531. if ((attributes & kWindowCompositingAttribute) != 0)
  218532. {
  218533. HIViewRef root = HIViewGetRoot (parentWindow);
  218534. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  218535. if (parentView == 0)
  218536. parentView = root;
  218537. }
  218538. else
  218539. {
  218540. GetRootControl (parentWindow, (ControlRef*) &parentView);
  218541. if (parentView == 0)
  218542. CreateRootControl (parentWindow, (ControlRef*) &parentView);
  218543. }
  218544. HIViewAddSubview (parentView, view);
  218545. updateBounds();
  218546. show();
  218547. webView = HIWebViewGetWebView (view);
  218548. clickListener = [[DownloadClickDetector alloc] initWithOwner: owner_];
  218549. [webView setPolicyDelegate: clickListener];
  218550. }
  218551. startTimer (500);
  218552. }
  218553. ~WebBrowserComponentInternal()
  218554. {
  218555. [webView setPolicyDelegate: nil];
  218556. [clickListener release];
  218557. if (view != 0)
  218558. CFRelease (view);
  218559. }
  218560. // Horrific bodge-workaround for the fact that the webview somehow hangs onto key
  218561. // focus when you pop up a new window, no matter what that window does to
  218562. // try to grab focus for itself. This catches such a situation and forces
  218563. // focus away from the webview, then back to the place it should be..
  218564. void timerCallback()
  218565. {
  218566. WindowRef viewWindow = HIViewGetWindow (view);
  218567. WindowRef focusedWindow = GetUserFocusWindow();
  218568. if (focusedWindow != viewWindow)
  218569. {
  218570. if (HIViewSubtreeContainsFocus (view))
  218571. {
  218572. HIViewAdvanceFocus (HIViewGetRoot (viewWindow), 0);
  218573. HIViewAdvanceFocus (HIViewGetRoot (focusedWindow), 0);
  218574. }
  218575. }
  218576. }
  218577. void show()
  218578. {
  218579. HIViewSetVisible (view, true);
  218580. }
  218581. void hide()
  218582. {
  218583. HIViewSetVisible (view, false);
  218584. }
  218585. void goToURL (const String& url,
  218586. const StringArray* headers,
  218587. const MemoryBlock* postData)
  218588. {
  218589. char** headerNamesAsChars = 0;
  218590. char** headerValuesAsChars = 0;
  218591. int numHeaders = 0;
  218592. if (headers != 0)
  218593. {
  218594. numHeaders = headers->size();
  218595. headerNamesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  218596. headerValuesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  218597. int i;
  218598. for (i = 0; i < numHeaders; ++i)
  218599. {
  218600. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  218601. headerNamesAsChars[i] = (char*) juce_calloc (headerName.copyToUTF8 (0));
  218602. headerName.copyToUTF8 ((juce::uint8*) headerNamesAsChars[i]);
  218603. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  218604. headerValuesAsChars[i] = (char*) juce_calloc (headerValue.copyToUTF8 (0));
  218605. headerValue.copyToUTF8 ((juce::uint8*) headerValuesAsChars[i]);
  218606. }
  218607. }
  218608. sendWebViewToURL ((const char*) url.toUTF8(),
  218609. (const char**) headerNamesAsChars,
  218610. (const char**) headerValuesAsChars,
  218611. numHeaders,
  218612. postData != 0 ? (const char*) postData->getData() : 0,
  218613. postData != 0 ? postData->getSize() : 0);
  218614. for (int i = 0; i < numHeaders; ++i)
  218615. {
  218616. juce_free (headerNamesAsChars[i]);
  218617. juce_free (headerValuesAsChars[i]);
  218618. }
  218619. juce_free (headerNamesAsChars);
  218620. juce_free (headerValuesAsChars);
  218621. }
  218622. void goBack()
  218623. {
  218624. [webView goBack];
  218625. }
  218626. void goForward()
  218627. {
  218628. [webView goForward];
  218629. }
  218630. void stop()
  218631. {
  218632. [webView stopLoading: nil];
  218633. }
  218634. void updateBounds()
  218635. {
  218636. HIRect r;
  218637. r.origin.x = (float) owner->getScreenX() - owner->getTopLevelComponent()->getScreenX();
  218638. r.origin.y = (float) owner->getScreenY() - owner->getTopLevelComponent()->getScreenY();
  218639. r.size.width = (float) owner->getWidth();
  218640. r.size.height = (float) owner->getHeight();
  218641. HIViewSetFrame (view, &r);
  218642. }
  218643. private:
  218644. WebBrowserComponent* const owner;
  218645. HIViewRef view;
  218646. WebView* webView;
  218647. DownloadClickDetector* clickListener;
  218648. void sendWebViewToURL (const char* utf8URL,
  218649. const char** headerNames,
  218650. const char** headerValues,
  218651. int numHeaders,
  218652. const char* postData,
  218653. int postDataSize)
  218654. {
  218655. NSMutableURLRequest* r = [NSMutableURLRequest
  218656. requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: utf8URL]]
  218657. cachePolicy: NSURLRequestUseProtocolCachePolicy
  218658. timeoutInterval: 30.0];
  218659. if (postDataSize > 0)
  218660. {
  218661. [ r setHTTPMethod: @"POST"];
  218662. [ r setHTTPBody: [NSData dataWithBytes: postData length: postDataSize]];
  218663. }
  218664. int i;
  218665. for (i = 0; i < numHeaders; ++i)
  218666. {
  218667. [ r setValue: [NSString stringWithUTF8String: headerValues[i]]
  218668. forHTTPHeaderField: [NSString stringWithUTF8String: headerNames[i]]];
  218669. }
  218670. [[webView mainFrame] stopLoading ];
  218671. [[webView mainFrame] loadRequest: r];
  218672. }
  218673. WebBrowserComponentInternal (const WebBrowserComponentInternal&);
  218674. const WebBrowserComponentInternal& operator= (const WebBrowserComponentInternal&);
  218675. };
  218676. WebBrowserComponent::WebBrowserComponent()
  218677. : browser (0),
  218678. associatedWindow (0),
  218679. blankPageShown (false)
  218680. {
  218681. setOpaque (true);
  218682. }
  218683. WebBrowserComponent::~WebBrowserComponent()
  218684. {
  218685. deleteBrowser();
  218686. }
  218687. void WebBrowserComponent::goToURL (const String& url,
  218688. const StringArray* headers,
  218689. const MemoryBlock* postData)
  218690. {
  218691. lastURL = url;
  218692. lastHeaders.clear();
  218693. if (headers != 0)
  218694. lastHeaders = *headers;
  218695. lastPostData.setSize (0);
  218696. if (postData != 0)
  218697. lastPostData = *postData;
  218698. blankPageShown = false;
  218699. if (browser != 0)
  218700. browser->goToURL (url, headers, postData);
  218701. }
  218702. void WebBrowserComponent::stop()
  218703. {
  218704. if (browser != 0)
  218705. browser->stop();
  218706. }
  218707. void WebBrowserComponent::goBack()
  218708. {
  218709. lastURL = String::empty;
  218710. blankPageShown = false;
  218711. if (browser != 0)
  218712. browser->goBack();
  218713. }
  218714. void WebBrowserComponent::goForward()
  218715. {
  218716. lastURL = String::empty;
  218717. if (browser != 0)
  218718. browser->goForward();
  218719. }
  218720. void WebBrowserComponent::paint (Graphics& g)
  218721. {
  218722. if (browser == 0)
  218723. g.fillAll (Colours::white);
  218724. }
  218725. void WebBrowserComponent::checkWindowAssociation()
  218726. {
  218727. void* const window = getWindowHandle();
  218728. if (window != associatedWindow
  218729. || (browser == 0 && window != 0))
  218730. {
  218731. associatedWindow = window;
  218732. deleteBrowser();
  218733. createBrowser();
  218734. }
  218735. if (browser != 0)
  218736. {
  218737. if (associatedWindow != 0 && isShowing())
  218738. {
  218739. browser->show();
  218740. if (blankPageShown)
  218741. goBack();
  218742. }
  218743. else
  218744. {
  218745. if (! blankPageShown)
  218746. {
  218747. // when the component becomes invisible, some stuff like flash
  218748. // carries on playing audio, so we need to force it onto a blank
  218749. // page to avoid this..
  218750. blankPageShown = true;
  218751. browser->goToURL ("about:blank", 0, 0);
  218752. }
  218753. browser->hide();
  218754. }
  218755. }
  218756. }
  218757. void WebBrowserComponent::createBrowser()
  218758. {
  218759. deleteBrowser();
  218760. if (isShowing())
  218761. {
  218762. WebInitForCarbon();
  218763. browser = new WebBrowserComponentInternal (this);
  218764. reloadLastURL();
  218765. }
  218766. }
  218767. void WebBrowserComponent::deleteBrowser()
  218768. {
  218769. deleteAndZero (browser);
  218770. }
  218771. void WebBrowserComponent::reloadLastURL()
  218772. {
  218773. if (lastURL.isNotEmpty())
  218774. {
  218775. goToURL (lastURL, &lastHeaders, &lastPostData);
  218776. lastURL = String::empty;
  218777. }
  218778. }
  218779. void WebBrowserComponent::updateBrowserPosition()
  218780. {
  218781. if (getPeer() != 0 && browser != 0)
  218782. browser->updateBounds();
  218783. }
  218784. void WebBrowserComponent::parentHierarchyChanged()
  218785. {
  218786. checkWindowAssociation();
  218787. }
  218788. void WebBrowserComponent::moved()
  218789. {
  218790. updateBrowserPosition();
  218791. }
  218792. void WebBrowserComponent::resized()
  218793. {
  218794. updateBrowserPosition();
  218795. }
  218796. void WebBrowserComponent::visibilityChanged()
  218797. {
  218798. checkWindowAssociation();
  218799. }
  218800. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218801. {
  218802. return true;
  218803. }
  218804. END_JUCE_NAMESPACE
  218805. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  218806. /********* Start of inlined file: juce_mac_Windowing.cpp *********/
  218807. #include <Carbon/Carbon.h>
  218808. #include <IOKit/IOKitLib.h>
  218809. #include <IOKit/IOCFPlugIn.h>
  218810. #include <IOKit/hid/IOHIDLib.h>
  218811. #include <IOKit/hid/IOHIDKeys.h>
  218812. #include <fnmatch.h>
  218813. #if JUCE_OPENGL
  218814. #include <AGL/agl.h>
  218815. #endif
  218816. BEGIN_JUCE_NAMESPACE
  218817. #undef Point
  218818. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  218819. static HIObjectClassRef viewClassRef = 0;
  218820. static CFStringRef juceHiViewClassNameCFString = 0;
  218821. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  218822. static VoidArray keysCurrentlyDown;
  218823. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  218824. {
  218825. if (keysCurrentlyDown.contains ((void*) keyCode))
  218826. return true;
  218827. if (keyCode >= 'A' && keyCode <= 'Z'
  218828. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  218829. return true;
  218830. if (keyCode >= 'a' && keyCode <= 'z'
  218831. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  218832. return true;
  218833. return false;
  218834. }
  218835. static VoidArray minimisedWindows;
  218836. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  218837. {
  218838. if (isMinimised != minimisedWindows.contains (ref))
  218839. CollapseWindow (ref, isMinimised);
  218840. }
  218841. void juce_maximiseAllMinimisedWindows()
  218842. {
  218843. const VoidArray minWin (minimisedWindows);
  218844. for (int i = minWin.size(); --i >= 0;)
  218845. setWindowMinimised ((WindowRef) (minWin[i]), false);
  218846. }
  218847. class HIViewComponentPeer;
  218848. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  218849. static int currentModifiers = 0;
  218850. static void updateModifiers (EventRef theEvent)
  218851. {
  218852. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  218853. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  218854. UInt32 m;
  218855. if (theEvent != 0)
  218856. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  218857. else
  218858. m = GetCurrentEventKeyModifiers();
  218859. if ((m & (shiftKey | rightShiftKey)) != 0)
  218860. currentModifiers |= ModifierKeys::shiftModifier;
  218861. if ((m & (controlKey | rightControlKey)) != 0)
  218862. currentModifiers |= ModifierKeys::ctrlModifier;
  218863. if ((m & (optionKey | rightOptionKey)) != 0)
  218864. currentModifiers |= ModifierKeys::altModifier;
  218865. if ((m & cmdKey) != 0)
  218866. currentModifiers |= ModifierKeys::commandModifier;
  218867. }
  218868. void ModifierKeys::updateCurrentModifiers() throw()
  218869. {
  218870. currentModifierFlags = currentModifiers;
  218871. }
  218872. static int64 getEventTime (EventRef event)
  218873. {
  218874. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  218875. : GetCurrentEventTime()));
  218876. static int64 offset = 0;
  218877. if (offset == 0)
  218878. offset = Time::currentTimeMillis() - millis;
  218879. return offset + millis;
  218880. }
  218881. class MacBitmapImage : public Image
  218882. {
  218883. public:
  218884. CGColorSpaceRef colourspace;
  218885. CGDataProviderRef provider;
  218886. MacBitmapImage (const PixelFormat format_,
  218887. const int w, const int h, const bool clearImage)
  218888. : Image (format_, w, h)
  218889. {
  218890. jassert (format_ == RGB || format_ == ARGB);
  218891. pixelStride = (format_ == RGB) ? 3 : 4;
  218892. lineStride = (w * pixelStride + 3) & ~3;
  218893. const int imageSize = lineStride * h;
  218894. if (clearImage)
  218895. imageData = (uint8*) juce_calloc (imageSize);
  218896. else
  218897. imageData = (uint8*) juce_malloc (imageSize);
  218898. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  218899. CMProfileRef prof;
  218900. CMGetSystemProfile (&prof);
  218901. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  218902. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  218903. CMCloseProfile (prof);
  218904. }
  218905. MacBitmapImage::~MacBitmapImage()
  218906. {
  218907. CGDataProviderRelease (provider);
  218908. CGColorSpaceRelease (colourspace);
  218909. juce_free (imageData);
  218910. imageData = 0; // to stop the base class freeing this
  218911. }
  218912. void blitToContext (CGContextRef context, const float dx, const float dy)
  218913. {
  218914. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  218915. 8, pixelStride << 3, lineStride, colourspace,
  218916. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  218917. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  218918. : kCGImageAlphaNone,
  218919. #else
  218920. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  218921. : kCGImageAlphaNone,
  218922. #endif
  218923. provider, 0, false,
  218924. kCGRenderingIntentDefault);
  218925. HIRect r;
  218926. r.origin.x = dx;
  218927. r.origin.y = dy;
  218928. r.size.width = (float) getWidth();
  218929. r.size.height = (float) getHeight();
  218930. HIViewDrawCGImage (context, &r, tempImage);
  218931. CGImageRelease (tempImage);
  218932. }
  218933. juce_UseDebuggingNewOperator
  218934. };
  218935. class MouseCheckTimer : private Timer,
  218936. private DeletedAtShutdown
  218937. {
  218938. public:
  218939. MouseCheckTimer()
  218940. : lastX (0),
  218941. lastY (0)
  218942. {
  218943. lastPeerUnderMouse = 0;
  218944. resetMouseMoveChecker();
  218945. #if ! MACOS_10_2_OR_EARLIER
  218946. // Just putting this in here because it's a convenient object that'll get deleted at shutdown
  218947. CGDisplayRegisterReconfigurationCallback (&displayChangeCallback, 0);
  218948. #endif
  218949. }
  218950. ~MouseCheckTimer()
  218951. {
  218952. #if ! MACOS_10_2_OR_EARLIER
  218953. CGDisplayRemoveReconfigurationCallback (&displayChangeCallback, 0);
  218954. #endif
  218955. clearSingletonInstance();
  218956. }
  218957. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  218958. bool hasEverHadAMouseMove;
  218959. void moved (HIViewComponentPeer* const peer)
  218960. {
  218961. if (hasEverHadAMouseMove)
  218962. startTimer (200);
  218963. lastPeerUnderMouse = peer;
  218964. }
  218965. void resetMouseMoveChecker()
  218966. {
  218967. hasEverHadAMouseMove = false;
  218968. startTimer (1000 / 16);
  218969. }
  218970. void timerCallback();
  218971. private:
  218972. HIViewComponentPeer* lastPeerUnderMouse;
  218973. int lastX, lastY;
  218974. #if ! MACOS_10_2_OR_EARLIER
  218975. static void displayChangeCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void*)
  218976. {
  218977. Desktop::getInstance().refreshMonitorSizes();
  218978. }
  218979. #endif
  218980. };
  218981. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  218982. #if JUCE_QUICKTIME
  218983. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  218984. Component* topLevelComp);
  218985. #endif
  218986. class HIViewComponentPeer : public ComponentPeer,
  218987. private Timer
  218988. {
  218989. public:
  218990. HIViewComponentPeer (Component* const component,
  218991. const int windowStyleFlags,
  218992. HIViewRef viewToAttachTo)
  218993. : ComponentPeer (component, windowStyleFlags),
  218994. fullScreen (false),
  218995. isCompositingWindow (false),
  218996. windowRef (0),
  218997. viewRef (0)
  218998. {
  218999. repainter = new RepaintManager (this);
  219000. eventHandlerRef = 0;
  219001. if (viewToAttachTo != 0)
  219002. {
  219003. isSharedWindow = true;
  219004. }
  219005. else
  219006. {
  219007. isSharedWindow = false;
  219008. WindowRef newWindow = createNewWindow (windowStyleFlags);
  219009. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  219010. jassert (viewToAttachTo != 0);
  219011. HIViewRef growBox = 0;
  219012. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  219013. if (growBox != 0)
  219014. HIGrowBoxViewSetTransparent (growBox, true);
  219015. }
  219016. createNewHIView();
  219017. HIViewAddSubview (viewToAttachTo, viewRef);
  219018. HIViewSetVisible (viewRef, component->isVisible());
  219019. setTitle (component->getName());
  219020. if (component->isVisible() && ! isSharedWindow)
  219021. {
  219022. ShowWindow (windowRef);
  219023. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  219024. }
  219025. }
  219026. ~HIViewComponentPeer()
  219027. {
  219028. minimisedWindows.removeValue (windowRef);
  219029. if (IsValidWindowPtr (windowRef))
  219030. {
  219031. if (! isSharedWindow)
  219032. {
  219033. CFRelease (viewRef);
  219034. viewRef = 0;
  219035. DisposeWindow (windowRef);
  219036. }
  219037. else
  219038. {
  219039. if (eventHandlerRef != 0)
  219040. RemoveEventHandler (eventHandlerRef);
  219041. CFRelease (viewRef);
  219042. viewRef = 0;
  219043. }
  219044. windowRef = 0;
  219045. }
  219046. if (currentlyFocusedPeer == this)
  219047. currentlyFocusedPeer = 0;
  219048. delete repainter;
  219049. }
  219050. void* getNativeHandle() const
  219051. {
  219052. return windowRef;
  219053. }
  219054. void setVisible (bool shouldBeVisible)
  219055. {
  219056. HIViewSetVisible (viewRef, shouldBeVisible);
  219057. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219058. {
  219059. if (shouldBeVisible)
  219060. ShowWindow (windowRef);
  219061. else
  219062. HideWindow (windowRef);
  219063. resizeViewToFitWindow();
  219064. // If nothing else is focused, then grab the focus too
  219065. if (shouldBeVisible
  219066. && Component::getCurrentlyFocusedComponent() == 0
  219067. && Process::isForegroundProcess())
  219068. {
  219069. component->toFront (true);
  219070. }
  219071. }
  219072. }
  219073. void setTitle (const String& title)
  219074. {
  219075. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219076. {
  219077. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  219078. SetWindowTitleWithCFString (windowRef, t);
  219079. CFRelease (t);
  219080. }
  219081. }
  219082. void setPosition (int x, int y)
  219083. {
  219084. if (isSharedWindow)
  219085. {
  219086. HIViewPlaceInSuperviewAt (viewRef, x, y);
  219087. }
  219088. else if (IsValidWindowPtr (windowRef))
  219089. {
  219090. Rect r;
  219091. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219092. r.right += x - r.left;
  219093. r.bottom += y - r.top;
  219094. r.left = x;
  219095. r.top = y;
  219096. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219097. }
  219098. }
  219099. void setSize (int w, int h)
  219100. {
  219101. w = jmax (0, w);
  219102. h = jmax (0, h);
  219103. if (w != getComponent()->getWidth()
  219104. || h != getComponent()->getHeight())
  219105. {
  219106. repainter->repaint (0, 0, w, h);
  219107. }
  219108. if (isSharedWindow)
  219109. {
  219110. HIRect r;
  219111. HIViewGetFrame (viewRef, &r);
  219112. r.size.width = (float) w;
  219113. r.size.height = (float) h;
  219114. HIViewSetFrame (viewRef, &r);
  219115. }
  219116. else if (IsValidWindowPtr (windowRef))
  219117. {
  219118. Rect r;
  219119. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219120. r.right = r.left + w;
  219121. r.bottom = r.top + h;
  219122. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219123. }
  219124. }
  219125. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  219126. {
  219127. fullScreen = isNowFullScreen;
  219128. w = jmax (0, w);
  219129. h = jmax (0, h);
  219130. if (w != getComponent()->getWidth()
  219131. || h != getComponent()->getHeight())
  219132. {
  219133. repainter->repaint (0, 0, w, h);
  219134. }
  219135. if (isSharedWindow)
  219136. {
  219137. HIRect r;
  219138. r.origin.x = (float) x;
  219139. r.origin.y = (float) y;
  219140. r.size.width = (float) w;
  219141. r.size.height = (float) h;
  219142. HIViewSetFrame (viewRef, &r);
  219143. }
  219144. else if (IsValidWindowPtr (windowRef))
  219145. {
  219146. Rect r;
  219147. r.left = x;
  219148. r.top = y;
  219149. r.right = x + w;
  219150. r.bottom = y + h;
  219151. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219152. }
  219153. }
  219154. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  219155. {
  219156. HIRect hiViewPos;
  219157. HIViewGetFrame (viewRef, &hiViewPos);
  219158. if (global)
  219159. {
  219160. HIViewRef content = 0;
  219161. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  219162. HIPoint p = { 0.0f, 0.0f };
  219163. HIViewConvertPoint (&p, viewRef, content);
  219164. x = (int) p.x;
  219165. y = (int) p.y;
  219166. if (IsValidWindowPtr (windowRef))
  219167. {
  219168. Rect windowPos;
  219169. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  219170. x += windowPos.left;
  219171. y += windowPos.top;
  219172. }
  219173. }
  219174. else
  219175. {
  219176. x = (int) hiViewPos.origin.x;
  219177. y = (int) hiViewPos.origin.y;
  219178. }
  219179. w = (int) hiViewPos.size.width;
  219180. h = (int) hiViewPos.size.height;
  219181. }
  219182. void getBounds (int& x, int& y, int& w, int& h) const
  219183. {
  219184. getBounds (x, y, w, h, ! isSharedWindow);
  219185. }
  219186. int getScreenX() const
  219187. {
  219188. int x, y, w, h;
  219189. getBounds (x, y, w, h, true);
  219190. return x;
  219191. }
  219192. int getScreenY() const
  219193. {
  219194. int x, y, w, h;
  219195. getBounds (x, y, w, h, true);
  219196. return y;
  219197. }
  219198. void relativePositionToGlobal (int& x, int& y)
  219199. {
  219200. int wx, wy, ww, wh;
  219201. getBounds (wx, wy, ww, wh, true);
  219202. x += wx;
  219203. y += wy;
  219204. }
  219205. void globalPositionToRelative (int& x, int& y)
  219206. {
  219207. int wx, wy, ww, wh;
  219208. getBounds (wx, wy, ww, wh, true);
  219209. x -= wx;
  219210. y -= wy;
  219211. }
  219212. void setMinimised (bool shouldBeMinimised)
  219213. {
  219214. if (! isSharedWindow)
  219215. setWindowMinimised (windowRef, shouldBeMinimised);
  219216. }
  219217. bool isMinimised() const
  219218. {
  219219. return minimisedWindows.contains (windowRef);
  219220. }
  219221. void setFullScreen (bool shouldBeFullScreen)
  219222. {
  219223. if (! isSharedWindow)
  219224. {
  219225. Rectangle r (lastNonFullscreenBounds);
  219226. setMinimised (false);
  219227. if (fullScreen != shouldBeFullScreen)
  219228. {
  219229. if (shouldBeFullScreen)
  219230. r = Desktop::getInstance().getMainMonitorArea();
  219231. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  219232. if (r != getComponent()->getBounds() && ! r.isEmpty())
  219233. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219234. }
  219235. }
  219236. }
  219237. bool isFullScreen() const
  219238. {
  219239. return fullScreen;
  219240. }
  219241. bool contains (int x, int y, bool trueIfInAChildWindow) const
  219242. {
  219243. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  219244. || ((unsigned int) y) >= (unsigned int) component->getHeight()
  219245. || ! IsValidWindowPtr (windowRef))
  219246. return false;
  219247. Rect r;
  219248. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219249. ::Point p;
  219250. p.h = r.left + x;
  219251. p.v = r.top + y;
  219252. WindowRef ref2 = 0;
  219253. FindWindow (p, &ref2);
  219254. if (windowRef != ref2)
  219255. return false;
  219256. if (trueIfInAChildWindow)
  219257. return true;
  219258. HIPoint p2;
  219259. p2.x = (float) x;
  219260. p2.y = (float) y;
  219261. HIViewRef hit;
  219262. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  219263. return hit == 0 || hit == viewRef;
  219264. }
  219265. const BorderSize getFrameSize() const
  219266. {
  219267. return BorderSize();
  219268. }
  219269. bool setAlwaysOnTop (bool alwaysOnTop)
  219270. {
  219271. // can't do this so return false and let the component create a new window
  219272. return false;
  219273. }
  219274. void toFront (bool makeActiveWindow)
  219275. {
  219276. makeActiveWindow = makeActiveWindow
  219277. && component->isValidComponent()
  219278. && (component->getWantsKeyboardFocus()
  219279. || component->isCurrentlyModal());
  219280. if (windowRef != FrontWindow()
  219281. || (makeActiveWindow && ! IsWindowActive (windowRef))
  219282. || ! Process::isForegroundProcess())
  219283. {
  219284. if (! Process::isForegroundProcess())
  219285. {
  219286. ProcessSerialNumber psn;
  219287. GetCurrentProcess (&psn);
  219288. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  219289. }
  219290. if (IsValidWindowPtr (windowRef))
  219291. {
  219292. if (makeActiveWindow)
  219293. {
  219294. SelectWindow (windowRef);
  219295. SetUserFocusWindow (windowRef);
  219296. HIViewAdvanceFocus (viewRef, 0);
  219297. }
  219298. else
  219299. {
  219300. BringToFront (windowRef);
  219301. }
  219302. handleBroughtToFront();
  219303. }
  219304. }
  219305. }
  219306. void toBehind (ComponentPeer* other)
  219307. {
  219308. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  219309. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  219310. {
  219311. if (windowRef == otherWindow->windowRef)
  219312. {
  219313. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  219314. }
  219315. else
  219316. {
  219317. SendBehind (windowRef, otherWindow->windowRef);
  219318. }
  219319. }
  219320. }
  219321. void setIcon (const Image& /*newIcon*/)
  219322. {
  219323. // to do..
  219324. }
  219325. void viewFocusGain()
  219326. {
  219327. const MessageManagerLock messLock;
  219328. if (currentlyFocusedPeer != this)
  219329. {
  219330. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  219331. currentlyFocusedPeer->handleFocusLoss();
  219332. currentlyFocusedPeer = this;
  219333. handleFocusGain();
  219334. }
  219335. }
  219336. void viewFocusLoss()
  219337. {
  219338. if (currentlyFocusedPeer == this)
  219339. {
  219340. currentlyFocusedPeer = 0;
  219341. handleFocusLoss();
  219342. }
  219343. }
  219344. bool isFocused() const
  219345. {
  219346. return windowRef == GetUserFocusWindow()
  219347. && HIViewSubtreeContainsFocus (viewRef);
  219348. }
  219349. void grabFocus()
  219350. {
  219351. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  219352. {
  219353. SetUserFocusWindow (windowRef);
  219354. HIViewAdvanceFocus (viewRef, 0);
  219355. }
  219356. }
  219357. void repaint (int x, int y, int w, int h)
  219358. {
  219359. if (Rectangle::intersectRectangles (x, y, w, h,
  219360. 0, 0,
  219361. getComponent()->getWidth(),
  219362. getComponent()->getHeight()))
  219363. {
  219364. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  219365. {
  219366. if (isCompositingWindow)
  219367. {
  219368. #if MACOS_10_3_OR_EARLIER
  219369. RgnHandle rgn = NewRgn();
  219370. SetRectRgn (rgn, x, y, x + w, y + h);
  219371. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  219372. DisposeRgn (rgn);
  219373. #else
  219374. HIRect r;
  219375. r.origin.x = x;
  219376. r.origin.y = y;
  219377. r.size.width = w;
  219378. r.size.height = h;
  219379. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  219380. #endif
  219381. }
  219382. else
  219383. {
  219384. if (! isTimerRunning())
  219385. startTimer (20);
  219386. }
  219387. }
  219388. repainter->repaint (x, y, w, h);
  219389. }
  219390. }
  219391. void timerCallback()
  219392. {
  219393. performAnyPendingRepaintsNow();
  219394. }
  219395. void performAnyPendingRepaintsNow()
  219396. {
  219397. stopTimer();
  219398. if (component->isVisible())
  219399. {
  219400. #if MACOS_10_2_OR_EARLIER
  219401. if (! isCompositingWindow)
  219402. {
  219403. Rect w;
  219404. GetWindowBounds (windowRef, windowRegionToUse, &w);
  219405. const int offsetInWindowX = component->getScreenX() - getScreenX();
  219406. const int offsetInWindowY = component->getScreenY() - getScreenY();
  219407. for (RectangleList::Iterator i (repainter->getRegionsNeedingRepaint()); i.next();)
  219408. {
  219409. const Rectangle& r = *i.getRectangle();
  219410. w.left = offsetInWindowX + r.getX();
  219411. w.top = offsetInWindowY + r.getY();
  219412. w.right = offsetInWindowX + r.getRight();
  219413. w.bottom = offsetInWindowY + r.getBottom();
  219414. InvalWindowRect (windowRef, &w);
  219415. }
  219416. }
  219417. else
  219418. {
  219419. EventRef theEvent;
  219420. EventTypeSpec eventTypes[1];
  219421. eventTypes[0].eventClass = kEventClassControl;
  219422. eventTypes[0].eventKind = kEventControlDraw;
  219423. int n = 3;
  219424. while (--n >= 0
  219425. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  219426. {
  219427. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  219428. {
  219429. EventRecord eventRec;
  219430. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  219431. AEProcessAppleEvent (&eventRec);
  219432. }
  219433. else
  219434. {
  219435. EventTargetRef theTarget = GetEventDispatcherTarget();
  219436. SendEventToEventTarget (theEvent, theTarget);
  219437. }
  219438. ReleaseEvent (theEvent);
  219439. }
  219440. }
  219441. #else
  219442. if (HIViewGetNeedsDisplay (viewRef) || repainter->isRepaintNeeded())
  219443. HIViewRender (viewRef);
  219444. #endif
  219445. }
  219446. }
  219447. juce_UseDebuggingNewOperator
  219448. WindowRef windowRef;
  219449. HIViewRef viewRef;
  219450. private:
  219451. EventHandlerRef eventHandlerRef;
  219452. bool fullScreen, isSharedWindow, isCompositingWindow;
  219453. StringArray dragAndDropFiles;
  219454. class RepaintManager : public Timer
  219455. {
  219456. public:
  219457. RepaintManager (HIViewComponentPeer* const peer_)
  219458. : peer (peer_),
  219459. image (0)
  219460. {
  219461. }
  219462. ~RepaintManager()
  219463. {
  219464. delete image;
  219465. }
  219466. void timerCallback()
  219467. {
  219468. stopTimer();
  219469. deleteAndZero (image);
  219470. }
  219471. void repaint (int x, int y, int w, int h)
  219472. {
  219473. regionsNeedingRepaint.add (x, y, w, h);
  219474. }
  219475. bool isRepaintNeeded() const throw()
  219476. {
  219477. return ! regionsNeedingRepaint.isEmpty();
  219478. }
  219479. void repaintAnyRemainingRegions()
  219480. {
  219481. // if any regions have been invaldated during the paint callback,
  219482. // we need to repaint them explicitly because the mac throws this
  219483. // stuff away
  219484. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  219485. {
  219486. const Rectangle& r = *i.getRectangle();
  219487. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  219488. }
  219489. }
  219490. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  219491. {
  219492. if (w > 0 && h > 0)
  219493. {
  219494. bool refresh = false;
  219495. int imW = image != 0 ? image->getWidth() : 0;
  219496. int imH = image != 0 ? image->getHeight() : 0;
  219497. if (imW < w || imH < h)
  219498. {
  219499. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  219500. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  219501. delete image;
  219502. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  219503. : Image::ARGB,
  219504. imW, imH, false);
  219505. refresh = true;
  219506. }
  219507. else if (imageX > x || imageY > y
  219508. || imageX + imW < x + w
  219509. || imageY + imH < y + h)
  219510. {
  219511. refresh = true;
  219512. }
  219513. if (refresh)
  219514. {
  219515. regionsNeedingRepaint.clear();
  219516. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  219517. imageX = x;
  219518. imageY = y;
  219519. }
  219520. LowLevelGraphicsSoftwareRenderer context (*image);
  219521. context.setOrigin (-imageX, -imageY);
  219522. if (context.reduceClipRegion (regionsNeedingRepaint))
  219523. {
  219524. regionsNeedingRepaint.clear();
  219525. if (! peer->getComponent()->isOpaque())
  219526. {
  219527. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  219528. {
  219529. const Rectangle& r = *i.getRectangle();
  219530. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  219531. }
  219532. }
  219533. regionsNeedingRepaint.clear();
  219534. peer->clearMaskedRegion();
  219535. peer->handlePaint (context);
  219536. }
  219537. else
  219538. {
  219539. regionsNeedingRepaint.clear();
  219540. }
  219541. if (! peer->maskedRegion.isEmpty())
  219542. {
  219543. RectangleList total (Rectangle (x, y, w, h));
  219544. total.subtract (peer->maskedRegion);
  219545. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  219546. int n = 0;
  219547. for (RectangleList::Iterator i (total); i.next();)
  219548. {
  219549. const Rectangle& r = *i.getRectangle();
  219550. rects[n].origin.x = (int) r.getX();
  219551. rects[n].origin.y = (int) r.getY();
  219552. rects[n].size.width = roundFloatToInt (r.getWidth());
  219553. rects[n++].size.height = roundFloatToInt (r.getHeight());
  219554. }
  219555. CGContextClipToRects (cgContext, rects, n);
  219556. juce_free (rects);
  219557. }
  219558. if (peer->isSharedWindow)
  219559. {
  219560. CGRect clip;
  219561. clip.origin.x = x;
  219562. clip.origin.y = y;
  219563. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  219564. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  219565. CGContextClipToRect (cgContext, clip);
  219566. }
  219567. image->blitToContext (cgContext, imageX, imageY);
  219568. }
  219569. startTimer (3000);
  219570. }
  219571. private:
  219572. HIViewComponentPeer* const peer;
  219573. MacBitmapImage* image;
  219574. int imageX, imageY;
  219575. RectangleList regionsNeedingRepaint;
  219576. RepaintManager (const RepaintManager&);
  219577. const RepaintManager& operator= (const RepaintManager&);
  219578. };
  219579. RepaintManager* repainter;
  219580. friend class RepaintManager;
  219581. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  219582. EventRef theEvent,
  219583. void* userData)
  219584. {
  219585. // don't draw the frame..
  219586. return noErr;
  219587. }
  219588. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  219589. {
  219590. updateModifiers (theEvent);
  219591. UniChar unicodeChars [4];
  219592. zeromem (unicodeChars, sizeof (unicodeChars));
  219593. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  219594. int keyCode = (int) (unsigned int) unicodeChars[0];
  219595. UInt32 rawKey = 0;
  219596. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  219597. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0
  219598. && keyCode >= 1 && keyCode <= 26)
  219599. {
  219600. keyCode += ('A' - 1);
  219601. }
  219602. else
  219603. {
  219604. static const int keyTranslations[] =
  219605. {
  219606. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  219607. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  219608. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  219609. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  219610. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  219611. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  219612. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  219613. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  219614. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  219615. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  219616. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  219617. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  219618. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  219619. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  219620. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  219621. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  219622. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  219623. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  219624. };
  219625. if (((unsigned int) rawKey) < (unsigned int) numElementsInArray (keyTranslations)
  219626. && keyTranslations [rawKey] != 0)
  219627. {
  219628. keyCode = keyTranslations [rawKey];
  219629. }
  219630. if ((rawKey == 0 && textCharacter != 0)
  219631. || (CharacterFunctions::isLetterOrDigit ((juce_wchar) keyCode)
  219632. && CharacterFunctions::isLetterOrDigit (textCharacter))) // correction for azerty-type layouts..
  219633. {
  219634. keyCode = CharacterFunctions::toLowerCase (textCharacter);
  219635. }
  219636. }
  219637. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  219638. textCharacter = 0;
  219639. static juce_wchar lastTextCharacter = 0;
  219640. switch (GetEventKind (theEvent))
  219641. {
  219642. case kEventRawKeyDown:
  219643. {
  219644. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  219645. lastTextCharacter = textCharacter;
  219646. const bool used1 = handleKeyUpOrDown();
  219647. const bool used2 = handleKeyPress (keyCode, textCharacter);
  219648. if (used1 || used2)
  219649. return noErr;
  219650. break;
  219651. }
  219652. case kEventRawKeyUp:
  219653. keysCurrentlyDown.removeValue ((void*) keyCode);
  219654. lastTextCharacter = 0;
  219655. if (handleKeyUpOrDown())
  219656. return noErr;
  219657. break;
  219658. case kEventRawKeyRepeat:
  219659. if (handleKeyPress (keyCode, lastTextCharacter))
  219660. return noErr;
  219661. break;
  219662. case kEventRawKeyModifiersChanged:
  219663. handleModifierKeysChange();
  219664. break;
  219665. default:
  219666. jassertfalse
  219667. break;
  219668. }
  219669. return eventNotHandledErr;
  219670. }
  219671. OSStatus handleTextInputEvent (EventRef theEvent)
  219672. {
  219673. UInt32 numBytesRequired = 0;
  219674. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &numBytesRequired, 0);
  219675. MemoryBlock buffer (numBytesRequired, true);
  219676. UniChar* const uc = (UniChar*) buffer.getData();
  219677. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, numBytesRequired, &numBytesRequired, uc);
  219678. EventRef originalEvent;
  219679. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  219680. OSStatus res = noErr;
  219681. for (int i = 0; i < numBytesRequired / sizeof (UniChar); ++i)
  219682. res = handleKeyEvent (originalEvent, (juce_wchar) uc[i]);
  219683. return res;
  219684. }
  219685. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  219686. {
  219687. MouseCheckTimer::getInstance()->moved (this);
  219688. ::Point where;
  219689. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  219690. int x = where.h;
  219691. int y = where.v;
  219692. globalPositionToRelative (x, y);
  219693. int64 time = getEventTime (theEvent);
  219694. switch (GetEventKind (theEvent))
  219695. {
  219696. case kEventMouseMoved:
  219697. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  219698. updateModifiers (theEvent);
  219699. handleMouseMove (x, y, time);
  219700. break;
  219701. case kEventMouseDragged:
  219702. updateModifiers (theEvent);
  219703. handleMouseDrag (x, y, time);
  219704. break;
  219705. case kEventMouseDown:
  219706. {
  219707. if (! Process::isForegroundProcess())
  219708. {
  219709. ProcessSerialNumber psn;
  219710. GetCurrentProcess (&psn);
  219711. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  219712. toFront (true);
  219713. }
  219714. #if JUCE_QUICKTIME
  219715. {
  219716. long mods;
  219717. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  219718. ::Point where;
  219719. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  219720. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  219721. }
  219722. #endif
  219723. if (component->isBroughtToFrontOnMouseClick()
  219724. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  219725. {
  219726. //ActivateWindow (windowRef, true);
  219727. SelectWindow (windowRef);
  219728. }
  219729. EventMouseButton button;
  219730. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  219731. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  219732. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  219733. // this is all I can think of doing about it..
  219734. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  219735. if (button == kEventMouseButtonPrimary)
  219736. currentModifiers |= ModifierKeys::leftButtonModifier;
  219737. else if (button == kEventMouseButtonSecondary)
  219738. currentModifiers |= ModifierKeys::rightButtonModifier;
  219739. else if (button == kEventMouseButtonTertiary)
  219740. currentModifiers |= ModifierKeys::middleButtonModifier;
  219741. updateModifiers (theEvent);
  219742. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  219743. handleMouseDown (x, y, time);
  219744. break;
  219745. }
  219746. case kEventMouseUp:
  219747. {
  219748. const int oldModifiers = currentModifiers;
  219749. EventMouseButton button;
  219750. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  219751. if (button == kEventMouseButtonPrimary)
  219752. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  219753. else if (button == kEventMouseButtonSecondary)
  219754. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  219755. updateModifiers (theEvent);
  219756. juce_currentMouseTrackingPeer = 0;
  219757. handleMouseUp (oldModifiers, x, y, time);
  219758. break;
  219759. }
  219760. case kEventMouseWheelMoved:
  219761. {
  219762. EventMouseWheelAxis axis;
  219763. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  219764. SInt32 delta;
  219765. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  219766. typeLongInteger, 0, sizeof (delta), 0, &delta);
  219767. updateModifiers (theEvent);
  219768. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  219769. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  219770. time);
  219771. break;
  219772. }
  219773. }
  219774. return noErr;
  219775. }
  219776. void doDragDropEnter (EventRef theEvent)
  219777. {
  219778. updateDragAndDropFileList (theEvent);
  219779. if (dragAndDropFiles.size() > 0)
  219780. {
  219781. int x, y;
  219782. component->getMouseXYRelative (x, y);
  219783. handleFileDragMove (dragAndDropFiles, x, y);
  219784. }
  219785. }
  219786. void doDragDropMove (EventRef theEvent)
  219787. {
  219788. if (dragAndDropFiles.size() > 0)
  219789. {
  219790. int x, y;
  219791. component->getMouseXYRelative (x, y);
  219792. handleFileDragMove (dragAndDropFiles, x, y);
  219793. }
  219794. }
  219795. void doDragDropExit (EventRef theEvent)
  219796. {
  219797. if (dragAndDropFiles.size() > 0)
  219798. handleFileDragExit (dragAndDropFiles);
  219799. }
  219800. void doDragDrop (EventRef theEvent)
  219801. {
  219802. updateDragAndDropFileList (theEvent);
  219803. if (dragAndDropFiles.size() > 0)
  219804. {
  219805. int x, y;
  219806. component->getMouseXYRelative (x, y);
  219807. handleFileDragDrop (dragAndDropFiles, x, y);
  219808. }
  219809. }
  219810. void updateDragAndDropFileList (EventRef theEvent)
  219811. {
  219812. dragAndDropFiles.clear();
  219813. DragRef dragRef;
  219814. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  219815. {
  219816. UInt16 numItems = 0;
  219817. if (CountDragItems (dragRef, &numItems) == noErr)
  219818. {
  219819. for (int i = 0; i < (int) numItems; ++i)
  219820. {
  219821. DragItemRef ref;
  219822. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  219823. {
  219824. const FlavorType flavorType = kDragFlavorTypeHFS;
  219825. Size size = 0;
  219826. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  219827. {
  219828. void* data = juce_calloc (size);
  219829. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  219830. {
  219831. HFSFlavor* f = (HFSFlavor*) data;
  219832. FSRef fsref;
  219833. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  219834. {
  219835. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  219836. if (path.isNotEmpty())
  219837. dragAndDropFiles.add (path);
  219838. }
  219839. }
  219840. juce_free (data);
  219841. }
  219842. }
  219843. }
  219844. dragAndDropFiles.trim();
  219845. dragAndDropFiles.removeEmptyStrings();
  219846. }
  219847. }
  219848. }
  219849. void resizeViewToFitWindow()
  219850. {
  219851. HIRect r;
  219852. if (isSharedWindow)
  219853. {
  219854. HIViewGetFrame (viewRef, &r);
  219855. r.size.width = (float) component->getWidth();
  219856. r.size.height = (float) component->getHeight();
  219857. }
  219858. else
  219859. {
  219860. r.origin.x = 0;
  219861. r.origin.y = 0;
  219862. Rect w;
  219863. GetWindowBounds (windowRef, windowRegionToUse, &w);
  219864. r.size.width = (float) (w.right - w.left);
  219865. r.size.height = (float) (w.bottom - w.top);
  219866. }
  219867. HIViewSetFrame (viewRef, &r);
  219868. #if MACOS_10_3_OR_EARLIER
  219869. component->repaint();
  219870. #endif
  219871. }
  219872. OSStatus hiViewDraw (EventRef theEvent)
  219873. {
  219874. CGContextRef context = 0;
  219875. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  219876. CGrafPtr oldPort;
  219877. CGrafPtr port = 0;
  219878. if (context == 0)
  219879. {
  219880. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  219881. GetPort (&oldPort);
  219882. SetPort (port);
  219883. if (port != 0)
  219884. QDBeginCGContext (port, &context);
  219885. if (! isCompositingWindow)
  219886. {
  219887. Rect bounds;
  219888. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  219889. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  219890. CGContextScaleCTM (context, 1.0, -1.0);
  219891. }
  219892. if (isSharedWindow)
  219893. {
  219894. // NB - Had terrible problems trying to correctly get the position
  219895. // of this view relative to the window, and this seems wrong, but
  219896. // works better than any other method I've tried..
  219897. HIRect hiViewPos;
  219898. HIViewGetFrame (viewRef, &hiViewPos);
  219899. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  219900. }
  219901. }
  219902. #if MACOS_10_2_OR_EARLIER
  219903. RgnHandle rgn = 0;
  219904. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  219905. CGRect clip;
  219906. // (avoid doing this in plugins because of some strange redraw bugs..)
  219907. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  219908. {
  219909. Rect bounds;
  219910. GetRegionBounds (rgn, &bounds);
  219911. clip.origin.x = bounds.left;
  219912. clip.origin.y = bounds.top;
  219913. clip.size.width = bounds.right - bounds.left;
  219914. clip.size.height = bounds.bottom - bounds.top;
  219915. }
  219916. else
  219917. {
  219918. HIViewGetBounds (viewRef, &clip);
  219919. clip.origin.x = 0;
  219920. clip.origin.y = 0;
  219921. }
  219922. #else
  219923. CGRect clip (CGContextGetClipBoundingBox (context));
  219924. #endif
  219925. clip = CGRectIntegral (clip);
  219926. if (clip.origin.x < 0)
  219927. {
  219928. clip.size.width += clip.origin.x;
  219929. clip.origin.x = 0;
  219930. }
  219931. if (clip.origin.y < 0)
  219932. {
  219933. clip.size.height += clip.origin.y;
  219934. clip.origin.y = 0;
  219935. }
  219936. if (! component->isOpaque())
  219937. CGContextClearRect (context, clip);
  219938. repainter->paint (context,
  219939. (int) clip.origin.x, (int) clip.origin.y,
  219940. (int) clip.size.width, (int) clip.size.height);
  219941. if (port != 0)
  219942. {
  219943. CGContextFlush (context);
  219944. QDEndCGContext (port, &context);
  219945. SetPort (oldPort);
  219946. }
  219947. repainter->repaintAnyRemainingRegions();
  219948. return noErr;
  219949. }
  219950. OSStatus handleWindowClassEvent (EventRef theEvent)
  219951. {
  219952. switch (GetEventKind (theEvent))
  219953. {
  219954. case kEventWindowBoundsChanged:
  219955. resizeViewToFitWindow();
  219956. break; // allow other handlers in the event chain to also get a look at the events
  219957. case kEventWindowBoundsChanging:
  219958. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  219959. {
  219960. UInt32 atts = 0;
  219961. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  219962. 0, sizeof (UInt32), 0, &atts);
  219963. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  219964. {
  219965. if (component->isCurrentlyBlockedByAnotherModalComponent())
  219966. {
  219967. Component* const modal = Component::getCurrentlyModalComponent();
  219968. if (modal != 0)
  219969. {
  219970. static uint32 lastDragTime = 0;
  219971. const uint32 now = Time::currentTimeMillis();
  219972. if (now > lastDragTime + 1000)
  219973. {
  219974. lastDragTime = now;
  219975. modal->inputAttemptWhenModal();
  219976. }
  219977. const Rectangle currentRect (getComponent()->getBounds());
  219978. Rect current;
  219979. current.left = currentRect.getX();
  219980. current.top = currentRect.getY();
  219981. current.right = currentRect.getRight();
  219982. current.bottom = currentRect.getBottom();
  219983. // stop the window getting dragged..
  219984. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  219985. sizeof (Rect), &current);
  219986. return noErr;
  219987. }
  219988. }
  219989. if ((atts & kWindowBoundsChangeUserResize) != 0
  219990. && constrainer != 0 && ! isSharedWindow)
  219991. {
  219992. Rect current;
  219993. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  219994. 0, sizeof (Rect), 0, &current);
  219995. int x = current.left;
  219996. int y = current.top;
  219997. int w = current.right - current.left;
  219998. int h = current.bottom - current.top;
  219999. const Rectangle currentRect (getComponent()->getBounds());
  220000. constrainer->checkBounds (x, y, w, h, currentRect,
  220001. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  220002. y != currentRect.getY() && y + h == currentRect.getBottom(),
  220003. x != currentRect.getX() && x + w == currentRect.getRight(),
  220004. y == currentRect.getY() && y + h != currentRect.getBottom(),
  220005. x == currentRect.getX() && x + w != currentRect.getRight());
  220006. current.left = x;
  220007. current.top = y;
  220008. current.right = x + w;
  220009. current.bottom = y + h;
  220010. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220011. sizeof (Rect), &current);
  220012. return noErr;
  220013. }
  220014. }
  220015. }
  220016. break;
  220017. case kEventWindowFocusAcquired:
  220018. keysCurrentlyDown.clear();
  220019. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  220020. viewFocusGain();
  220021. break; // allow other handlers in the event chain to also get a look at the events
  220022. case kEventWindowFocusRelinquish:
  220023. keysCurrentlyDown.clear();
  220024. viewFocusLoss();
  220025. break; // allow other handlers in the event chain to also get a look at the events
  220026. case kEventWindowCollapsed:
  220027. minimisedWindows.addIfNotAlreadyThere (windowRef);
  220028. handleMovedOrResized();
  220029. break; // allow other handlers in the event chain to also get a look at the events
  220030. case kEventWindowExpanded:
  220031. minimisedWindows.removeValue (windowRef);
  220032. handleMovedOrResized();
  220033. break; // allow other handlers in the event chain to also get a look at the events
  220034. case kEventWindowShown:
  220035. break; // allow other handlers in the event chain to also get a look at the events
  220036. case kEventWindowClose:
  220037. if (isSharedWindow)
  220038. break; // break to let the OS delete the window
  220039. handleUserClosingWindow();
  220040. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  220041. default:
  220042. break;
  220043. }
  220044. return eventNotHandledErr;
  220045. }
  220046. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  220047. {
  220048. switch (GetEventClass (theEvent))
  220049. {
  220050. case kEventClassMouse:
  220051. {
  220052. static HIViewComponentPeer* lastMouseDownPeer = 0;
  220053. const UInt32 eventKind = GetEventKind (theEvent);
  220054. HIViewRef view = 0;
  220055. if (eventKind == kEventMouseDragged)
  220056. {
  220057. view = viewRef;
  220058. }
  220059. else
  220060. {
  220061. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  220062. if (view != viewRef)
  220063. {
  220064. if ((eventKind == kEventMouseUp
  220065. || eventKind == kEventMouseExited)
  220066. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  220067. {
  220068. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  220069. }
  220070. return eventNotHandledErr;
  220071. }
  220072. }
  220073. if (eventKind == kEventMouseDown
  220074. || eventKind == kEventMouseDragged
  220075. || eventKind == kEventMouseEntered)
  220076. {
  220077. lastMouseDownPeer = this;
  220078. }
  220079. return handleMouseEvent (callRef, theEvent);
  220080. }
  220081. break;
  220082. case kEventClassWindow:
  220083. return handleWindowClassEvent (theEvent);
  220084. case kEventClassKeyboard:
  220085. if (isFocused())
  220086. return handleKeyEvent (theEvent, 0);
  220087. break;
  220088. case kEventClassTextInput:
  220089. if (isFocused())
  220090. return handleTextInputEvent (theEvent);
  220091. break;
  220092. default:
  220093. break;
  220094. }
  220095. return eventNotHandledErr;
  220096. }
  220097. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  220098. {
  220099. MessageManager::delayWaitCursor();
  220100. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  220101. const MessageManagerLock messLock;
  220102. if (ComponentPeer::isValidPeer (peer))
  220103. return peer->handleWindowEventForPeer (callRef, theEvent);
  220104. return eventNotHandledErr;
  220105. }
  220106. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  220107. {
  220108. MessageManager::delayWaitCursor();
  220109. const UInt32 eventKind = GetEventKind (theEvent);
  220110. const UInt32 eventClass = GetEventClass (theEvent);
  220111. if (eventClass == kEventClassHIObject)
  220112. {
  220113. switch (eventKind)
  220114. {
  220115. case kEventHIObjectConstruct:
  220116. {
  220117. void* data = juce_calloc (sizeof (void*));
  220118. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  220119. typeVoidPtr, sizeof (void*), &data);
  220120. return noErr;
  220121. }
  220122. case kEventHIObjectInitialize:
  220123. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  220124. return noErr;
  220125. case kEventHIObjectDestruct:
  220126. juce_free (userData);
  220127. return noErr;
  220128. default:
  220129. break;
  220130. }
  220131. }
  220132. else if (eventClass == kEventClassControl)
  220133. {
  220134. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  220135. const MessageManagerLock messLock;
  220136. if (! ComponentPeer::isValidPeer (peer))
  220137. return eventNotHandledErr;
  220138. switch (eventKind)
  220139. {
  220140. case kEventControlDraw:
  220141. return peer->hiViewDraw (theEvent);
  220142. case kEventControlBoundsChanged:
  220143. {
  220144. HIRect bounds;
  220145. HIViewGetBounds (peer->viewRef, &bounds);
  220146. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  220147. peer->handleMovedOrResized();
  220148. return noErr;
  220149. }
  220150. case kEventControlHitTest:
  220151. {
  220152. HIPoint where;
  220153. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  220154. HIRect bounds;
  220155. HIViewGetBounds (peer->viewRef, &bounds);
  220156. ControlPartCode part = kControlNoPart;
  220157. if (CGRectContainsPoint (bounds, where))
  220158. part = 1;
  220159. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  220160. return noErr;
  220161. }
  220162. break;
  220163. case kEventControlSetFocusPart:
  220164. {
  220165. ControlPartCode desiredFocus;
  220166. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  220167. break;
  220168. if (desiredFocus == kControlNoPart)
  220169. peer->viewFocusLoss();
  220170. else
  220171. peer->viewFocusGain();
  220172. return noErr;
  220173. }
  220174. break;
  220175. case kEventControlDragEnter:
  220176. {
  220177. #if MACOS_10_2_OR_EARLIER
  220178. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  220179. #endif
  220180. Boolean accept = true;
  220181. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  220182. peer->doDragDropEnter (theEvent);
  220183. return noErr;
  220184. }
  220185. case kEventControlDragWithin:
  220186. peer->doDragDropMove (theEvent);
  220187. return noErr;
  220188. case kEventControlDragLeave:
  220189. peer->doDragDropExit (theEvent);
  220190. return noErr;
  220191. case kEventControlDragReceive:
  220192. peer->doDragDrop (theEvent);
  220193. return noErr;
  220194. case kEventControlOwningWindowChanged:
  220195. return peer->ownerWindowChanged (theEvent);
  220196. #if ! MACOS_10_2_OR_EARLIER
  220197. case kEventControlGetFrameMetrics:
  220198. {
  220199. CallNextEventHandler (myHandler, theEvent);
  220200. HIViewFrameMetrics metrics;
  220201. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  220202. metrics.top = metrics.bottom = 0;
  220203. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  220204. return noErr;
  220205. }
  220206. #endif
  220207. case kEventControlInitialize:
  220208. {
  220209. UInt32 features = kControlSupportsDragAndDrop
  220210. | kControlSupportsFocus
  220211. | kControlHandlesTracking
  220212. | kControlSupportsEmbedding
  220213. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  220214. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  220215. return noErr;
  220216. }
  220217. default:
  220218. break;
  220219. }
  220220. }
  220221. return eventNotHandledErr;
  220222. }
  220223. WindowRef createNewWindow (const int windowStyleFlags)
  220224. {
  220225. jassert (windowRef == 0);
  220226. static ToolboxObjectClassRef customWindowClass = 0;
  220227. if (customWindowClass == 0)
  220228. {
  220229. // Register our window class
  220230. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  220231. UnsignedWide t;
  220232. Microseconds (&t);
  220233. const String randomString ((int) (t.lo & 0x7ffffff));
  220234. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  220235. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  220236. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  220237. 0, 1, customTypes,
  220238. NewEventHandlerUPP (handleFrameRepaintEvent),
  220239. 0, &customWindowClass);
  220240. CFRelease (juceWindowClassNameCFString);
  220241. }
  220242. Rect pos;
  220243. pos.left = getComponent()->getX();
  220244. pos.top = getComponent()->getY();
  220245. pos.right = getComponent()->getRight();
  220246. pos.bottom = getComponent()->getBottom();
  220247. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  220248. if ((windowStyleFlags & windowHasDropShadow) == 0)
  220249. attributes |= kWindowNoShadowAttribute;
  220250. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  220251. attributes |= kWindowIgnoreClicksAttribute;
  220252. #if ! MACOS_10_3_OR_EARLIER
  220253. if ((windowStyleFlags & windowIsTemporary) != 0)
  220254. attributes |= kWindowDoesNotCycleAttribute;
  220255. #endif
  220256. WindowRef newWindow = 0;
  220257. if ((windowStyleFlags & windowHasTitleBar) == 0)
  220258. {
  220259. attributes |= kWindowCollapseBoxAttribute;
  220260. WindowDefSpec customWindowSpec;
  220261. customWindowSpec.defType = kWindowDefObjectClass;
  220262. customWindowSpec.u.classRef = customWindowClass;
  220263. CreateCustomWindow (&customWindowSpec,
  220264. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  220265. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  220266. : kDocumentWindowClass),
  220267. attributes,
  220268. &pos,
  220269. &newWindow);
  220270. }
  220271. else
  220272. {
  220273. if ((windowStyleFlags & windowHasCloseButton) != 0)
  220274. attributes |= kWindowCloseBoxAttribute;
  220275. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  220276. attributes |= kWindowCollapseBoxAttribute;
  220277. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  220278. attributes |= kWindowFullZoomAttribute;
  220279. if ((windowStyleFlags & windowIsResizable) != 0)
  220280. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  220281. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  220282. }
  220283. jassert (newWindow != 0);
  220284. if (newWindow != 0)
  220285. {
  220286. HideWindow (newWindow);
  220287. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  220288. if (! getComponent()->isOpaque())
  220289. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  220290. }
  220291. return newWindow;
  220292. }
  220293. OSStatus ownerWindowChanged (EventRef theEvent)
  220294. {
  220295. WindowRef newWindow = 0;
  220296. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  220297. if (windowRef != newWindow)
  220298. {
  220299. if (eventHandlerRef != 0)
  220300. {
  220301. RemoveEventHandler (eventHandlerRef);
  220302. eventHandlerRef = 0;
  220303. }
  220304. windowRef = newWindow;
  220305. if (windowRef != 0)
  220306. {
  220307. const EventTypeSpec eventTypes[] =
  220308. {
  220309. { kEventClassWindow, kEventWindowBoundsChanged },
  220310. { kEventClassWindow, kEventWindowBoundsChanging },
  220311. { kEventClassWindow, kEventWindowFocusAcquired },
  220312. { kEventClassWindow, kEventWindowFocusRelinquish },
  220313. { kEventClassWindow, kEventWindowCollapsed },
  220314. { kEventClassWindow, kEventWindowExpanded },
  220315. { kEventClassWindow, kEventWindowShown },
  220316. { kEventClassWindow, kEventWindowClose },
  220317. { kEventClassMouse, kEventMouseDown },
  220318. { kEventClassMouse, kEventMouseUp },
  220319. { kEventClassMouse, kEventMouseMoved },
  220320. { kEventClassMouse, kEventMouseDragged },
  220321. { kEventClassMouse, kEventMouseEntered },
  220322. { kEventClassMouse, kEventMouseExited },
  220323. { kEventClassMouse, kEventMouseWheelMoved },
  220324. { kEventClassKeyboard, kEventRawKeyUp },
  220325. { kEventClassKeyboard, kEventRawKeyRepeat },
  220326. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  220327. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  220328. };
  220329. static EventHandlerUPP handleWindowEventUPP = 0;
  220330. if (handleWindowEventUPP == 0)
  220331. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  220332. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  220333. GetEventTypeCount (eventTypes), eventTypes,
  220334. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  220335. WindowAttributes attributes;
  220336. GetWindowAttributes (windowRef, &attributes);
  220337. #if MACOS_10_3_OR_EARLIER
  220338. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  220339. #else
  220340. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  220341. #endif
  220342. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  220343. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  220344. }
  220345. }
  220346. resizeViewToFitWindow();
  220347. return noErr;
  220348. }
  220349. void createNewHIView()
  220350. {
  220351. jassert (viewRef == 0);
  220352. if (viewClassRef == 0)
  220353. {
  220354. // Register our HIView class
  220355. EventTypeSpec viewEvents[] =
  220356. {
  220357. { kEventClassHIObject, kEventHIObjectConstruct },
  220358. { kEventClassHIObject, kEventHIObjectInitialize },
  220359. { kEventClassHIObject, kEventHIObjectDestruct },
  220360. { kEventClassControl, kEventControlInitialize },
  220361. { kEventClassControl, kEventControlDraw },
  220362. { kEventClassControl, kEventControlBoundsChanged },
  220363. { kEventClassControl, kEventControlSetFocusPart },
  220364. { kEventClassControl, kEventControlHitTest },
  220365. { kEventClassControl, kEventControlDragEnter },
  220366. { kEventClassControl, kEventControlDragLeave },
  220367. { kEventClassControl, kEventControlDragWithin },
  220368. { kEventClassControl, kEventControlDragReceive },
  220369. { kEventClassControl, kEventControlOwningWindowChanged }
  220370. };
  220371. UnsignedWide t;
  220372. Microseconds (&t);
  220373. const String randomString ((int) (t.lo & 0x7ffffff));
  220374. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  220375. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  220376. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  220377. kHIViewClassID, 0,
  220378. NewEventHandlerUPP (hiViewEventHandler),
  220379. GetEventTypeCount (viewEvents),
  220380. viewEvents, 0,
  220381. &viewClassRef);
  220382. }
  220383. EventRef event;
  220384. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  220385. void* thisPointer = this;
  220386. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  220387. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  220388. SetControlDragTrackingEnabled (viewRef, true);
  220389. if (isSharedWindow)
  220390. {
  220391. setBounds (component->getX(), component->getY(),
  220392. component->getWidth(), component->getHeight(), false);
  220393. }
  220394. }
  220395. };
  220396. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  220397. {
  220398. return juceHiViewClassNameCFString != 0
  220399. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  220400. }
  220401. bool juce_isWindowCreatedByJuce (WindowRef window)
  220402. {
  220403. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220404. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  220405. return true;
  220406. return false;
  220407. }
  220408. static void trackNextMouseEvent()
  220409. {
  220410. UInt32 mods;
  220411. MouseTrackingResult result;
  220412. ::Point where;
  220413. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  220414. &where, &mods, &result) != noErr
  220415. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  220416. {
  220417. juce_currentMouseTrackingPeer = 0;
  220418. return;
  220419. }
  220420. if (result == kMouseTrackingTimedOut)
  220421. return;
  220422. #if MACOS_10_3_OR_EARLIER
  220423. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  220424. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  220425. #else
  220426. HIPoint p;
  220427. p.x = where.h;
  220428. p.y = where.v;
  220429. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  220430. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  220431. const int x = p.x;
  220432. const int y = p.y;
  220433. #endif
  220434. if (result == kMouseTrackingMouseDragged)
  220435. {
  220436. updateModifiers (0);
  220437. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  220438. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  220439. {
  220440. juce_currentMouseTrackingPeer = 0;
  220441. return;
  220442. }
  220443. }
  220444. else if (result == kMouseTrackingMouseUp
  220445. || result == kMouseTrackingUserCancelled
  220446. || result == kMouseTrackingMouseMoved)
  220447. {
  220448. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  220449. juce_currentMouseTrackingPeer = 0;
  220450. if (ComponentPeer::isValidPeer (oldPeer))
  220451. {
  220452. const int oldModifiers = currentModifiers;
  220453. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  220454. updateModifiers (0);
  220455. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  220456. }
  220457. }
  220458. }
  220459. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  220460. {
  220461. if (juce_currentMouseTrackingPeer != 0)
  220462. trackNextMouseEvent();
  220463. EventRef theEvent;
  220464. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  220465. : kEventDurationForever,
  220466. true, &theEvent) == noErr)
  220467. {
  220468. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  220469. {
  220470. EventRecord eventRec;
  220471. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  220472. AEProcessAppleEvent (&eventRec);
  220473. }
  220474. else
  220475. {
  220476. EventTargetRef theTarget = GetEventDispatcherTarget();
  220477. SendEventToEventTarget (theEvent, theTarget);
  220478. }
  220479. ReleaseEvent (theEvent);
  220480. return true;
  220481. }
  220482. return false;
  220483. }
  220484. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  220485. {
  220486. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  220487. }
  220488. void MouseCheckTimer::timerCallback()
  220489. {
  220490. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  220491. return;
  220492. if (Process::isForegroundProcess())
  220493. {
  220494. bool stillOver = false;
  220495. int x = 0, y = 0, w = 0, h = 0;
  220496. int mx = 0, my = 0;
  220497. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  220498. if (validWindow)
  220499. {
  220500. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  220501. Desktop::getMousePosition (mx, my);
  220502. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  220503. if (stillOver)
  220504. {
  220505. // check if it's over an embedded HIView
  220506. int rx = mx, ry = my;
  220507. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  220508. HIPoint hipoint;
  220509. hipoint.x = rx;
  220510. hipoint.y = ry;
  220511. HIViewRef root;
  220512. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  220513. HIViewRef hitview;
  220514. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  220515. {
  220516. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  220517. }
  220518. }
  220519. }
  220520. if (! stillOver)
  220521. {
  220522. // mouse is outside our windows so set a normal cursor (only
  220523. // if we're running as an app, not a plugin)
  220524. if (JUCEApplication::getInstance() != 0)
  220525. SetThemeCursor (kThemeArrowCursor);
  220526. if (validWindow)
  220527. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  220528. if (hasEverHadAMouseMove)
  220529. stopTimer();
  220530. }
  220531. if ((! hasEverHadAMouseMove) && validWindow
  220532. && (mx != lastX || my != lastY))
  220533. {
  220534. lastX = mx;
  220535. lastY = my;
  220536. if (stillOver)
  220537. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  220538. }
  220539. }
  220540. }
  220541. // called from juce_Messaging.cpp
  220542. void juce_HandleProcessFocusChange()
  220543. {
  220544. keysCurrentlyDown.clear();
  220545. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  220546. {
  220547. if (Process::isForegroundProcess())
  220548. currentlyFocusedPeer->handleFocusGain();
  220549. else
  220550. currentlyFocusedPeer->handleFocusLoss();
  220551. }
  220552. }
  220553. static bool performDrag (DragRef drag)
  220554. {
  220555. EventRecord event;
  220556. event.what = mouseDown;
  220557. event.message = 0;
  220558. event.when = TickCount();
  220559. int x, y;
  220560. Desktop::getMousePosition (x, y);
  220561. event.where.h = x;
  220562. event.where.v = y;
  220563. event.modifiers = GetCurrentKeyModifiers();
  220564. RgnHandle rgn = NewRgn();
  220565. RgnHandle rgn2 = NewRgn();
  220566. SetRectRgn (rgn,
  220567. event.where.h - 8, event.where.v - 8,
  220568. event.where.h + 8, event.where.v + 8);
  220569. CopyRgn (rgn, rgn2);
  220570. InsetRgn (rgn2, 1, 1);
  220571. DiffRgn (rgn, rgn2, rgn);
  220572. DisposeRgn (rgn2);
  220573. bool result = TrackDrag (drag, &event, rgn) == noErr;
  220574. DisposeRgn (rgn);
  220575. return result;
  220576. }
  220577. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220578. {
  220579. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220580. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  220581. DragRef drag;
  220582. bool result = false;
  220583. if (NewDrag (&drag) == noErr)
  220584. {
  220585. for (int i = 0; i < files.size(); ++i)
  220586. {
  220587. HFSFlavor hfsData;
  220588. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  220589. {
  220590. FInfo info;
  220591. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  220592. {
  220593. hfsData.fileType = info.fdType;
  220594. hfsData.fileCreator = info.fdCreator;
  220595. hfsData.fdFlags = info.fdFlags;
  220596. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  220597. result = true;
  220598. }
  220599. }
  220600. }
  220601. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  220602. : kDragActionCopy, false);
  220603. if (result)
  220604. result = performDrag (drag);
  220605. DisposeDrag (drag);
  220606. }
  220607. return result;
  220608. }
  220609. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220610. {
  220611. jassertfalse // not implemented!
  220612. return false;
  220613. }
  220614. bool Process::isForegroundProcess() throw()
  220615. {
  220616. ProcessSerialNumber psn, front;
  220617. GetCurrentProcess (&psn);
  220618. GetFrontProcess (&front);
  220619. Boolean b;
  220620. return (SameProcess (&psn, &front, &b) == noErr) && b;
  220621. }
  220622. bool Desktop::canUseSemiTransparentWindows() throw()
  220623. {
  220624. return true;
  220625. }
  220626. void Desktop::getMousePosition (int& x, int& y) throw()
  220627. {
  220628. CGrafPtr currentPort;
  220629. GetPort (&currentPort);
  220630. if (! IsValidPort (currentPort))
  220631. {
  220632. WindowRef front = FrontWindow();
  220633. if (front != 0)
  220634. {
  220635. SetPortWindowPort (front);
  220636. }
  220637. else
  220638. {
  220639. x = y = 0;
  220640. return;
  220641. }
  220642. }
  220643. ::Point p;
  220644. GetMouse (&p);
  220645. LocalToGlobal (&p);
  220646. x = p.h;
  220647. y = p.v;
  220648. SetPort (currentPort);
  220649. }
  220650. void Desktop::setMousePosition (int x, int y) throw()
  220651. {
  220652. // this rubbish needs to be done around the warp call, to avoid causing a
  220653. // bizarre glitch..
  220654. CGAssociateMouseAndMouseCursorPosition (false);
  220655. CGSetLocalEventsSuppressionInterval (0);
  220656. CGPoint pos = { x, y };
  220657. CGWarpMouseCursorPosition (pos);
  220658. CGAssociateMouseAndMouseCursorPosition (true);
  220659. }
  220660. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220661. {
  220662. return ModifierKeys (currentModifiers);
  220663. }
  220664. class ScreenSaverDefeater : public Timer,
  220665. public DeletedAtShutdown
  220666. {
  220667. public:
  220668. ScreenSaverDefeater() throw()
  220669. {
  220670. startTimer (10000);
  220671. timerCallback();
  220672. }
  220673. ~ScreenSaverDefeater()
  220674. {
  220675. }
  220676. void timerCallback()
  220677. {
  220678. if (Process::isForegroundProcess())
  220679. UpdateSystemActivity (UsrActivity);
  220680. }
  220681. };
  220682. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220683. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220684. {
  220685. if (screenSaverDefeater == 0)
  220686. screenSaverDefeater = new ScreenSaverDefeater();
  220687. }
  220688. bool Desktop::isScreenSaverEnabled() throw()
  220689. {
  220690. return screenSaverDefeater == 0;
  220691. }
  220692. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220693. {
  220694. int mainMonitorIndex = 0;
  220695. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  220696. CGDisplayCount count = 0;
  220697. CGDirectDisplayID disps [8];
  220698. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  220699. {
  220700. for (int i = 0; i < count; ++i)
  220701. {
  220702. if (mainDisplayID == disps[i])
  220703. mainMonitorIndex = monitorCoords.size();
  220704. GDHandle hGDevice;
  220705. if (clipToWorkArea
  220706. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  220707. {
  220708. Rect rect;
  220709. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  220710. monitorCoords.add (Rectangle (rect.left,
  220711. rect.top,
  220712. rect.right - rect.left,
  220713. rect.bottom - rect.top));
  220714. }
  220715. else
  220716. {
  220717. const CGRect r (CGDisplayBounds (disps[i]));
  220718. monitorCoords.add (Rectangle ((int) r.origin.x,
  220719. (int) r.origin.y,
  220720. (int) r.size.width,
  220721. (int) r.size.height));
  220722. }
  220723. }
  220724. }
  220725. // make sure the first in the list is the main monitor
  220726. if (mainMonitorIndex > 0)
  220727. monitorCoords.swap (mainMonitorIndex, 0);
  220728. jassert (monitorCoords.size() > 0);
  220729. if (monitorCoords.size() == 0)
  220730. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  220731. }
  220732. struct CursorWrapper
  220733. {
  220734. Cursor* cursor;
  220735. ThemeCursor themeCursor;
  220736. };
  220737. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  220738. {
  220739. const int maxW = 16;
  220740. const int maxH = 16;
  220741. const Image* im = &image;
  220742. Image* newIm = 0;
  220743. if (image.getWidth() > maxW || image.getHeight() > maxH)
  220744. {
  220745. im = newIm = image.createCopy (maxW, maxH);
  220746. hotspotX = (hotspotX * maxW) / image.getWidth();
  220747. hotspotY = (hotspotY * maxH) / image.getHeight();
  220748. }
  220749. Cursor* const c = new Cursor();
  220750. c->hotSpot.h = hotspotX;
  220751. c->hotSpot.v = hotspotY;
  220752. for (int y = 0; y < maxH; ++y)
  220753. {
  220754. c->data[y] = 0;
  220755. c->mask[y] = 0;
  220756. for (int x = 0; x < maxW; ++x)
  220757. {
  220758. const Colour pixelColour (im->getPixelAt (15 - x, y));
  220759. if (pixelColour.getAlpha() > 0.5f)
  220760. {
  220761. c->mask[y] |= (1 << x);
  220762. if (pixelColour.getBrightness() < 0.5f)
  220763. c->data[y] |= (1 << x);
  220764. }
  220765. }
  220766. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  220767. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  220768. }
  220769. if (newIm != 0)
  220770. delete newIm;
  220771. CursorWrapper* const cw = new CursorWrapper();
  220772. cw->cursor = c;
  220773. cw->themeCursor = kThemeArrowCursor;
  220774. return (void*) cw;
  220775. }
  220776. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  220777. {
  220778. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  220779. jassert (im != 0);
  220780. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  220781. delete im;
  220782. return curs;
  220783. }
  220784. const unsigned int kSpecialNoCursor = 'nocr';
  220785. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  220786. {
  220787. ThemeCursor cursorId = kThemeArrowCursor;
  220788. switch (type)
  220789. {
  220790. case MouseCursor::NormalCursor:
  220791. cursorId = kThemeArrowCursor;
  220792. break;
  220793. case MouseCursor::NoCursor:
  220794. cursorId = kSpecialNoCursor;
  220795. break;
  220796. case MouseCursor::DraggingHandCursor:
  220797. {
  220798. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220799. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220800. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  220801. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  220802. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  220803. const int cursDataSize = 99;
  220804. return cursorFromData (cursData, cursDataSize, 8, 8);
  220805. }
  220806. break;
  220807. case MouseCursor::CopyingCursor:
  220808. cursorId = kThemeCopyArrowCursor;
  220809. break;
  220810. case MouseCursor::WaitCursor:
  220811. cursorId = kThemeWatchCursor;
  220812. break;
  220813. case MouseCursor::IBeamCursor:
  220814. cursorId = kThemeIBeamCursor;
  220815. break;
  220816. case MouseCursor::PointingHandCursor:
  220817. cursorId = kThemePointingHandCursor;
  220818. break;
  220819. case MouseCursor::LeftRightResizeCursor:
  220820. case MouseCursor::LeftEdgeResizeCursor:
  220821. case MouseCursor::RightEdgeResizeCursor:
  220822. {
  220823. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  220824. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220825. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  220826. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  220827. 58,83,0,0,59 };
  220828. const int cursDataSize = 85;
  220829. return cursorFromData (cursData, cursDataSize, 8, 8);
  220830. }
  220831. case MouseCursor::UpDownResizeCursor:
  220832. case MouseCursor::TopEdgeResizeCursor:
  220833. case MouseCursor::BottomEdgeResizeCursor:
  220834. {
  220835. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  220836. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220837. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  220838. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  220839. 121,84,0,0,59 };
  220840. const int cursDataSize = 85;
  220841. return cursorFromData (cursData, cursDataSize, 8, 8);
  220842. }
  220843. case MouseCursor::TopLeftCornerResizeCursor:
  220844. case MouseCursor::BottomRightCornerResizeCursor:
  220845. {
  220846. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  220847. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220848. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  220849. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  220850. 104,174,131,208,77,66,28,10,0,59 };
  220851. const int cursDataSize = 90;
  220852. return cursorFromData (cursData, cursDataSize, 8, 8);
  220853. }
  220854. case MouseCursor::TopRightCornerResizeCursor:
  220855. case MouseCursor::BottomLeftCornerResizeCursor:
  220856. {
  220857. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  220858. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220859. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  220860. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  220861. 120,46,237,105,239,123,48,80,157,2,0,59 };
  220862. const int cursDataSize = 92;
  220863. return cursorFromData (cursData, cursDataSize, 8, 8);
  220864. }
  220865. case MouseCursor::UpDownLeftRightResizeCursor:
  220866. {
  220867. static const unsigned char cursData[] = {71,73,70,56,57,97,15,0,15,0,145,0,0,0,0,0,255,255,255,0,
  220868. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  220869. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  220870. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  220871. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  220872. const int cursDataSize = 93;
  220873. return cursorFromData (cursData, cursDataSize, 7, 7);
  220874. }
  220875. case MouseCursor::CrosshairCursor:
  220876. cursorId = kThemeCrossCursor;
  220877. break;
  220878. }
  220879. CursorWrapper* cw = new CursorWrapper();
  220880. cw->cursor = 0;
  220881. cw->themeCursor = cursorId;
  220882. return (void*) cw;
  220883. }
  220884. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  220885. {
  220886. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  220887. if (cw != 0)
  220888. {
  220889. delete cw->cursor;
  220890. delete cw;
  220891. }
  220892. }
  220893. void MouseCursor::showInAllWindows() const throw()
  220894. {
  220895. showInWindow (0);
  220896. }
  220897. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  220898. {
  220899. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  220900. if (cw != 0)
  220901. {
  220902. static bool isCursorHidden = false;
  220903. static bool showingWaitCursor = false;
  220904. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  220905. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  220906. if (shouldShowWaitCursor != showingWaitCursor
  220907. && Process::isForegroundProcess())
  220908. {
  220909. showingWaitCursor = shouldShowWaitCursor;
  220910. QDDisplayWaitCursor (shouldShowWaitCursor);
  220911. }
  220912. if (shouldHideCursor != isCursorHidden)
  220913. {
  220914. isCursorHidden = shouldHideCursor;
  220915. if (shouldHideCursor)
  220916. HideCursor();
  220917. else
  220918. ShowCursor();
  220919. }
  220920. if (cw->cursor != 0)
  220921. SetCursor (cw->cursor);
  220922. else if (! (shouldShowWaitCursor || shouldHideCursor))
  220923. SetThemeCursor (cw->themeCursor);
  220924. }
  220925. }
  220926. Image* juce_createIconForFile (const File& file)
  220927. {
  220928. return 0;
  220929. }
  220930. class MainMenuHandler;
  220931. static MainMenuHandler* mainMenu = 0;
  220932. class MainMenuHandler : private MenuBarModelListener,
  220933. private DeletedAtShutdown
  220934. {
  220935. public:
  220936. MainMenuHandler() throw()
  220937. : currentModel (0)
  220938. {
  220939. }
  220940. ~MainMenuHandler() throw()
  220941. {
  220942. setMenu (0);
  220943. jassert (mainMenu == this);
  220944. mainMenu = 0;
  220945. }
  220946. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  220947. {
  220948. if (currentModel != newMenuBarModel)
  220949. {
  220950. if (currentModel != 0)
  220951. currentModel->removeListener (this);
  220952. currentModel = newMenuBarModel;
  220953. if (currentModel != 0)
  220954. currentModel->addListener (this);
  220955. menuBarItemsChanged (0);
  220956. }
  220957. }
  220958. void menuBarItemsChanged (MenuBarModel*)
  220959. {
  220960. ClearMenuBar();
  220961. if (currentModel != 0)
  220962. {
  220963. int menuId = 1000;
  220964. const StringArray menuNames (currentModel->getMenuBarNames());
  220965. for (int i = 0; i < menuNames.size(); ++i)
  220966. {
  220967. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  220968. MenuRef m = createMenu (menu, menuNames [i], menuId, i);
  220969. InsertMenu (m, 0);
  220970. CFRelease (m);
  220971. }
  220972. }
  220973. }
  220974. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  220975. {
  220976. MenuRef menu = 0;
  220977. MenuItemIndex index = 0;
  220978. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  220979. if (menu != 0)
  220980. {
  220981. FlashMenuBar (GetMenuID (menu));
  220982. FlashMenuBar (GetMenuID (menu));
  220983. }
  220984. }
  220985. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  220986. {
  220987. if (currentModel != 0)
  220988. {
  220989. if (commandManager != 0)
  220990. {
  220991. ApplicationCommandTarget::InvocationInfo info (commandId);
  220992. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  220993. commandManager->invoke (info, true);
  220994. }
  220995. currentModel->menuItemSelected (commandId, topLevelIndex);
  220996. }
  220997. }
  220998. MenuBarModel* currentModel;
  220999. private:
  221000. static MenuRef createMenu (const PopupMenu menu,
  221001. const String& menuName,
  221002. int& id,
  221003. const int topLevelIndex)
  221004. {
  221005. MenuRef m = 0;
  221006. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  221007. {
  221008. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  221009. SetMenuTitleWithCFString (m, name);
  221010. CFRelease (name);
  221011. PopupMenu::MenuItemIterator iter (menu);
  221012. while (iter.next())
  221013. {
  221014. MenuItemIndex index = 0;
  221015. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  221016. if (! iter.isEnabled)
  221017. flags |= kMenuItemAttrDisabled;
  221018. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  221019. if (iter.isSeparator)
  221020. {
  221021. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  221022. }
  221023. else if (iter.isSectionHeader)
  221024. {
  221025. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  221026. }
  221027. else if (iter.subMenu != 0)
  221028. {
  221029. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  221030. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  221031. SetMenuItemHierarchicalMenu (m, index, sub);
  221032. CFRelease (sub);
  221033. }
  221034. else
  221035. {
  221036. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  221037. if (iter.isTicked)
  221038. CheckMenuItem (m, index, true);
  221039. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  221040. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  221041. if (iter.commandManager != 0)
  221042. {
  221043. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221044. ->getKeyPressesAssignedToCommand (iter.itemId));
  221045. if (keyPresses.size() > 0)
  221046. {
  221047. const KeyPress& kp = keyPresses.getReference(0);
  221048. int mods = 0;
  221049. if (kp.getModifiers().isShiftDown())
  221050. mods |= kMenuShiftModifier;
  221051. if (kp.getModifiers().isCtrlDown())
  221052. mods |= kMenuControlModifier;
  221053. if (kp.getModifiers().isAltDown())
  221054. mods |= kMenuOptionModifier;
  221055. if (! kp.getModifiers().isCommandDown())
  221056. mods |= kMenuNoCommandModifier;
  221057. tchar keyCode = (tchar) kp.getKeyCode();
  221058. if (kp.getKeyCode() >= KeyPress::numberPad0
  221059. && kp.getKeyCode() <= KeyPress::numberPad9)
  221060. {
  221061. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  221062. }
  221063. SetMenuItemCommandKey (m, index, true, 255);
  221064. if (CharacterFunctions::isLetterOrDigit (keyCode)
  221065. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  221066. {
  221067. SetMenuItemModifiers (m, index, mods);
  221068. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  221069. }
  221070. else
  221071. {
  221072. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  221073. if (glyph != 0)
  221074. {
  221075. SetMenuItemModifiers (m, index, mods);
  221076. SetMenuItemKeyGlyph (m, index, glyph);
  221077. }
  221078. }
  221079. // if we set the key glyph to be a text char, and enable virtual
  221080. // key triggering, it stops the menu automatically triggering the callback
  221081. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  221082. }
  221083. }
  221084. }
  221085. CFRelease (text);
  221086. }
  221087. }
  221088. return m;
  221089. }
  221090. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  221091. {
  221092. if (keyCode == KeyPress::spaceKey)
  221093. return kMenuSpaceGlyph;
  221094. else if (keyCode == KeyPress::returnKey)
  221095. return kMenuReturnGlyph;
  221096. else if (keyCode == KeyPress::escapeKey)
  221097. return kMenuEscapeGlyph;
  221098. else if (keyCode == KeyPress::backspaceKey)
  221099. return kMenuDeleteLeftGlyph;
  221100. else if (keyCode == KeyPress::leftKey)
  221101. return kMenuLeftArrowGlyph;
  221102. else if (keyCode == KeyPress::rightKey)
  221103. return kMenuRightArrowGlyph;
  221104. else if (keyCode == KeyPress::upKey)
  221105. return kMenuUpArrowGlyph;
  221106. else if (keyCode == KeyPress::downKey)
  221107. return kMenuDownArrowGlyph;
  221108. else if (keyCode == KeyPress::pageUpKey)
  221109. return kMenuPageUpGlyph;
  221110. else if (keyCode == KeyPress::pageDownKey)
  221111. return kMenuPageDownGlyph;
  221112. else if (keyCode == KeyPress::endKey)
  221113. return kMenuSoutheastArrowGlyph;
  221114. else if (keyCode == KeyPress::homeKey)
  221115. return kMenuNorthwestArrowGlyph;
  221116. else if (keyCode == KeyPress::deleteKey)
  221117. return kMenuDeleteRightGlyph;
  221118. else if (keyCode == KeyPress::tabKey)
  221119. return kMenuTabRightGlyph;
  221120. else if (keyCode == KeyPress::F1Key)
  221121. return kMenuF1Glyph;
  221122. else if (keyCode == KeyPress::F2Key)
  221123. return kMenuF2Glyph;
  221124. else if (keyCode == KeyPress::F3Key)
  221125. return kMenuF3Glyph;
  221126. else if (keyCode == KeyPress::F4Key)
  221127. return kMenuF4Glyph;
  221128. else if (keyCode == KeyPress::F5Key)
  221129. return kMenuF5Glyph;
  221130. else if (keyCode == KeyPress::F6Key)
  221131. return kMenuF6Glyph;
  221132. else if (keyCode == KeyPress::F7Key)
  221133. return kMenuF7Glyph;
  221134. else if (keyCode == KeyPress::F8Key)
  221135. return kMenuF8Glyph;
  221136. else if (keyCode == KeyPress::F9Key)
  221137. return kMenuF9Glyph;
  221138. else if (keyCode == KeyPress::F10Key)
  221139. return kMenuF10Glyph;
  221140. else if (keyCode == KeyPress::F11Key)
  221141. return kMenuF11Glyph;
  221142. else if (keyCode == KeyPress::F12Key)
  221143. return kMenuF12Glyph;
  221144. else if (keyCode == KeyPress::F13Key)
  221145. return kMenuF13Glyph;
  221146. else if (keyCode == KeyPress::F14Key)
  221147. return kMenuF14Glyph;
  221148. else if (keyCode == KeyPress::F15Key)
  221149. return kMenuF15Glyph;
  221150. return 0;
  221151. }
  221152. };
  221153. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  221154. {
  221155. if (getMacMainMenu() != newMenuBarModel)
  221156. {
  221157. if (newMenuBarModel == 0)
  221158. {
  221159. delete mainMenu;
  221160. jassert (mainMenu == 0); // should be zeroed in the destructor
  221161. }
  221162. else
  221163. {
  221164. if (mainMenu == 0)
  221165. mainMenu = new MainMenuHandler();
  221166. mainMenu->setMenu (newMenuBarModel);
  221167. }
  221168. }
  221169. }
  221170. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  221171. {
  221172. return mainMenu != 0 ? mainMenu->currentModel : 0;
  221173. }
  221174. // these functions are called externally from the message handling code
  221175. void juce_MainMenuAboutToBeUsed()
  221176. {
  221177. // force an update of the items just before the menu appears..
  221178. if (mainMenu != 0)
  221179. mainMenu->menuBarItemsChanged (0);
  221180. }
  221181. void juce_InvokeMainMenuCommand (const HICommand& command)
  221182. {
  221183. if (mainMenu != 0)
  221184. {
  221185. ApplicationCommandManager* commandManager = 0;
  221186. int topLevelIndex = 0;
  221187. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221188. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  221189. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221190. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  221191. {
  221192. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  221193. }
  221194. }
  221195. }
  221196. void PlatformUtilities::beep()
  221197. {
  221198. SysBeep (30);
  221199. }
  221200. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  221201. {
  221202. ClearCurrentScrap();
  221203. ScrapRef ref;
  221204. GetCurrentScrap (&ref);
  221205. const int len = text.length();
  221206. const int numBytes = sizeof (UniChar) * len;
  221207. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  221208. for (int i = 0; i < len; ++i)
  221209. temp[i] = (UniChar) text[i];
  221210. PutScrapFlavor (ref,
  221211. kScrapFlavorTypeUnicode,
  221212. kScrapFlavorMaskNone,
  221213. numBytes,
  221214. temp);
  221215. juce_free (temp);
  221216. }
  221217. const String SystemClipboard::getTextFromClipboard() throw()
  221218. {
  221219. String result;
  221220. ScrapRef ref;
  221221. GetCurrentScrap (&ref);
  221222. Size size = 0;
  221223. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  221224. && size > 0)
  221225. {
  221226. void* const data = juce_calloc (size + 8);
  221227. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  221228. {
  221229. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  221230. }
  221231. juce_free (data);
  221232. }
  221233. return result;
  221234. }
  221235. bool AlertWindow::showNativeDialogBox (const String& title,
  221236. const String& bodyText,
  221237. bool isOkCancel)
  221238. {
  221239. Str255 tit, txt;
  221240. PlatformUtilities::copyToStr255 (tit, title);
  221241. PlatformUtilities::copyToStr255 (txt, bodyText);
  221242. AlertStdAlertParamRec ar;
  221243. ar.movable = true;
  221244. ar.helpButton = false;
  221245. ar.filterProc = 0;
  221246. ar.defaultText = (const unsigned char*)-1;
  221247. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  221248. ar.otherText = 0;
  221249. ar.defaultButton = kAlertStdAlertOKButton;
  221250. ar.cancelButton = 0;
  221251. ar.position = kWindowDefaultPosition;
  221252. SInt16 result;
  221253. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  221254. return result == kAlertStdAlertOKButton;
  221255. }
  221256. const int KeyPress::spaceKey = ' ';
  221257. const int KeyPress::returnKey = kReturnCharCode;
  221258. const int KeyPress::escapeKey = kEscapeCharCode;
  221259. const int KeyPress::backspaceKey = kBackspaceCharCode;
  221260. const int KeyPress::leftKey = kLeftArrowCharCode;
  221261. const int KeyPress::rightKey = kRightArrowCharCode;
  221262. const int KeyPress::upKey = kUpArrowCharCode;
  221263. const int KeyPress::downKey = kDownArrowCharCode;
  221264. const int KeyPress::pageUpKey = kPageUpCharCode;
  221265. const int KeyPress::pageDownKey = kPageDownCharCode;
  221266. const int KeyPress::endKey = kEndCharCode;
  221267. const int KeyPress::homeKey = kHomeCharCode;
  221268. const int KeyPress::deleteKey = kDeleteCharCode;
  221269. const int KeyPress::insertKey = -1;
  221270. const int KeyPress::tabKey = kTabCharCode;
  221271. const int KeyPress::F1Key = 0x10110;
  221272. const int KeyPress::F2Key = 0x10111;
  221273. const int KeyPress::F3Key = 0x10112;
  221274. const int KeyPress::F4Key = 0x10113;
  221275. const int KeyPress::F5Key = 0x10114;
  221276. const int KeyPress::F6Key = 0x10115;
  221277. const int KeyPress::F7Key = 0x10116;
  221278. const int KeyPress::F8Key = 0x10117;
  221279. const int KeyPress::F9Key = 0x10118;
  221280. const int KeyPress::F10Key = 0x10119;
  221281. const int KeyPress::F11Key = 0x1011a;
  221282. const int KeyPress::F12Key = 0x1011b;
  221283. const int KeyPress::F13Key = 0x1011c;
  221284. const int KeyPress::F14Key = 0x1011d;
  221285. const int KeyPress::F15Key = 0x1011e;
  221286. const int KeyPress::F16Key = 0x1011f;
  221287. const int KeyPress::numberPad0 = 0x30020;
  221288. const int KeyPress::numberPad1 = 0x30021;
  221289. const int KeyPress::numberPad2 = 0x30022;
  221290. const int KeyPress::numberPad3 = 0x30023;
  221291. const int KeyPress::numberPad4 = 0x30024;
  221292. const int KeyPress::numberPad5 = 0x30025;
  221293. const int KeyPress::numberPad6 = 0x30026;
  221294. const int KeyPress::numberPad7 = 0x30027;
  221295. const int KeyPress::numberPad8 = 0x30028;
  221296. const int KeyPress::numberPad9 = 0x30029;
  221297. const int KeyPress::numberPadAdd = 0x3002a;
  221298. const int KeyPress::numberPadSubtract = 0x3002b;
  221299. const int KeyPress::numberPadMultiply = 0x3002c;
  221300. const int KeyPress::numberPadDivide = 0x3002d;
  221301. const int KeyPress::numberPadSeparator = 0x3002e;
  221302. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221303. const int KeyPress::numberPadEquals = 0x30030;
  221304. const int KeyPress::numberPadDelete = 0x30031;
  221305. const int KeyPress::playKey = 0x30000;
  221306. const int KeyPress::stopKey = 0x30001;
  221307. const int KeyPress::fastForwardKey = 0x30002;
  221308. const int KeyPress::rewindKey = 0x30003;
  221309. AppleRemoteDevice::AppleRemoteDevice()
  221310. : device (0),
  221311. queue (0),
  221312. remoteId (0)
  221313. {
  221314. }
  221315. AppleRemoteDevice::~AppleRemoteDevice()
  221316. {
  221317. stop();
  221318. }
  221319. static io_object_t getAppleRemoteDevice() throw()
  221320. {
  221321. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  221322. io_iterator_t iter = 0;
  221323. io_object_t iod = 0;
  221324. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  221325. && iter != 0)
  221326. {
  221327. iod = IOIteratorNext (iter);
  221328. }
  221329. IOObjectRelease (iter);
  221330. return iod;
  221331. }
  221332. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  221333. {
  221334. jassert (*device == 0);
  221335. io_name_t classname;
  221336. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  221337. {
  221338. IOCFPlugInInterface** cfPlugInInterface = 0;
  221339. SInt32 score = 0;
  221340. if (IOCreatePlugInInterfaceForService (iod,
  221341. kIOHIDDeviceUserClientTypeID,
  221342. kIOCFPlugInInterfaceID,
  221343. &cfPlugInInterface,
  221344. &score) == kIOReturnSuccess)
  221345. {
  221346. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  221347. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  221348. device);
  221349. (void) hr;
  221350. (*cfPlugInInterface)->Release (cfPlugInInterface);
  221351. }
  221352. }
  221353. return *device != 0;
  221354. }
  221355. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  221356. {
  221357. if (queue != 0)
  221358. return true;
  221359. stop();
  221360. bool result = false;
  221361. io_object_t iod = getAppleRemoteDevice();
  221362. if (iod != 0)
  221363. {
  221364. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  221365. result = true;
  221366. else
  221367. stop();
  221368. IOObjectRelease (iod);
  221369. }
  221370. return result;
  221371. }
  221372. void AppleRemoteDevice::stop() throw()
  221373. {
  221374. if (queue != 0)
  221375. {
  221376. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  221377. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  221378. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  221379. queue = 0;
  221380. }
  221381. if (device != 0)
  221382. {
  221383. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  221384. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  221385. device = 0;
  221386. }
  221387. }
  221388. bool AppleRemoteDevice::isActive() const throw()
  221389. {
  221390. return queue != 0;
  221391. }
  221392. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  221393. {
  221394. if (result == kIOReturnSuccess)
  221395. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  221396. }
  221397. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  221398. {
  221399. #if ! MACOS_10_2_OR_EARLIER
  221400. Array <int> cookies;
  221401. CFArrayRef elements;
  221402. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  221403. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  221404. return false;
  221405. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  221406. {
  221407. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  221408. // get the cookie
  221409. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  221410. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  221411. continue;
  221412. long number;
  221413. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  221414. continue;
  221415. cookies.add ((int) number);
  221416. }
  221417. CFRelease (elements);
  221418. if ((*(IOHIDDeviceInterface**) device)
  221419. ->open ((IOHIDDeviceInterface**) device,
  221420. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  221421. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  221422. {
  221423. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  221424. if (queue != 0)
  221425. {
  221426. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  221427. for (int i = 0; i < cookies.size(); ++i)
  221428. {
  221429. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  221430. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  221431. }
  221432. CFRunLoopSourceRef eventSource;
  221433. if ((*(IOHIDQueueInterface**) queue)
  221434. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  221435. {
  221436. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  221437. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  221438. {
  221439. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  221440. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  221441. return true;
  221442. }
  221443. }
  221444. }
  221445. }
  221446. #endif
  221447. return false;
  221448. }
  221449. void AppleRemoteDevice::handleCallbackInternal()
  221450. {
  221451. int totalValues = 0;
  221452. AbsoluteTime nullTime = { 0, 0 };
  221453. char cookies [12];
  221454. int numCookies = 0;
  221455. while (numCookies < numElementsInArray (cookies))
  221456. {
  221457. IOHIDEventStruct e;
  221458. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  221459. break;
  221460. if ((int) e.elementCookie == 19)
  221461. {
  221462. remoteId = e.value;
  221463. buttonPressed (switched, false);
  221464. }
  221465. else
  221466. {
  221467. totalValues += e.value;
  221468. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  221469. }
  221470. }
  221471. cookies [numCookies++] = 0;
  221472. static const char buttonPatterns[] =
  221473. {
  221474. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  221475. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  221476. 14, 12, 11, 6, 5, 0,
  221477. 14, 13, 11, 6, 5, 0,
  221478. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  221479. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  221480. 14, 6, 5, 4, 2, 0,
  221481. 14, 6, 5, 3, 2, 0,
  221482. 14, 6, 5, 14, 6, 5, 0,
  221483. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  221484. 19, 0
  221485. };
  221486. int buttonNum = (int) menuButton;
  221487. int i = 0;
  221488. while (i < numElementsInArray (buttonPatterns))
  221489. {
  221490. if (strcmp (cookies, buttonPatterns + i) == 0)
  221491. {
  221492. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  221493. break;
  221494. }
  221495. i += strlen (buttonPatterns + i) + 1;
  221496. ++buttonNum;
  221497. }
  221498. }
  221499. #if JUCE_OPENGL
  221500. class WindowedGLContext : public OpenGLContext
  221501. {
  221502. public:
  221503. WindowedGLContext (Component* const component,
  221504. const OpenGLPixelFormat& pixelFormat_,
  221505. AGLContext sharedContext)
  221506. : renderContext (0),
  221507. pixelFormat (pixelFormat_)
  221508. {
  221509. jassert (component != 0);
  221510. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221511. if (peer == 0)
  221512. return;
  221513. GLint attribs [64];
  221514. int n = 0;
  221515. attribs[n++] = AGL_RGBA;
  221516. attribs[n++] = AGL_DOUBLEBUFFER;
  221517. attribs[n++] = AGL_ACCELERATED;
  221518. attribs[n++] = AGL_RED_SIZE;
  221519. attribs[n++] = pixelFormat.redBits;
  221520. attribs[n++] = AGL_GREEN_SIZE;
  221521. attribs[n++] = pixelFormat.greenBits;
  221522. attribs[n++] = AGL_BLUE_SIZE;
  221523. attribs[n++] = pixelFormat.blueBits;
  221524. attribs[n++] = AGL_ALPHA_SIZE;
  221525. attribs[n++] = pixelFormat.alphaBits;
  221526. attribs[n++] = AGL_DEPTH_SIZE;
  221527. attribs[n++] = pixelFormat.depthBufferBits;
  221528. attribs[n++] = AGL_STENCIL_SIZE;
  221529. attribs[n++] = pixelFormat.stencilBufferBits;
  221530. attribs[n++] = AGL_ACCUM_RED_SIZE;
  221531. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221532. attribs[n++] = AGL_ACCUM_GREEN_SIZE;
  221533. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221534. attribs[n++] = AGL_ACCUM_BLUE_SIZE;
  221535. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221536. attribs[n++] = AGL_ACCUM_ALPHA_SIZE;
  221537. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221538. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  221539. attribs[n++] = AGL_SAMPLE_BUFFERS_ARB;
  221540. attribs[n++] = 1;
  221541. attribs[n++] = AGL_SAMPLES_ARB;
  221542. attribs[n++] = 4;
  221543. attribs[n++] = AGL_CLOSEST_POLICY;
  221544. attribs[n++] = AGL_NO_RECOVERY;
  221545. attribs[n++] = AGL_NONE;
  221546. renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attribs),
  221547. sharedContext);
  221548. aglSetDrawable (renderContext, GetWindowPort (peer->windowRef));
  221549. }
  221550. ~WindowedGLContext()
  221551. {
  221552. makeInactive();
  221553. aglSetDrawable (renderContext, 0);
  221554. aglDestroyContext (renderContext);
  221555. }
  221556. bool makeActive() const throw()
  221557. {
  221558. jassert (renderContext != 0);
  221559. return aglSetCurrentContext (renderContext);
  221560. }
  221561. bool makeInactive() const throw()
  221562. {
  221563. return (! isActive()) || aglSetCurrentContext (0);
  221564. }
  221565. bool isActive() const throw()
  221566. {
  221567. return aglGetCurrentContext() == renderContext;
  221568. }
  221569. const OpenGLPixelFormat getPixelFormat() const
  221570. {
  221571. return pixelFormat;
  221572. }
  221573. void* getRawContext() const throw()
  221574. {
  221575. return renderContext;
  221576. }
  221577. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  221578. {
  221579. GLint bufferRect[4];
  221580. bufferRect[0] = x;
  221581. bufferRect[1] = outerWindowHeight - (y + h);
  221582. bufferRect[2] = w;
  221583. bufferRect[3] = h;
  221584. aglSetInteger (renderContext, AGL_BUFFER_RECT, bufferRect);
  221585. aglEnable (renderContext, AGL_BUFFER_RECT);
  221586. }
  221587. void swapBuffers()
  221588. {
  221589. aglSwapBuffers (renderContext);
  221590. }
  221591. bool setSwapInterval (const int numFramesPerSwap)
  221592. {
  221593. return aglSetInteger (renderContext, AGL_SWAP_INTERVAL, (const GLint*) &numFramesPerSwap);
  221594. }
  221595. int getSwapInterval() const
  221596. {
  221597. GLint numFrames = 0;
  221598. aglGetInteger (renderContext, AGL_SWAP_INTERVAL, &numFrames);
  221599. return numFrames;
  221600. }
  221601. void repaint()
  221602. {
  221603. }
  221604. juce_UseDebuggingNewOperator
  221605. AGLContext renderContext;
  221606. private:
  221607. OpenGLPixelFormat pixelFormat;
  221608. WindowedGLContext (const WindowedGLContext&);
  221609. const WindowedGLContext& operator= (const WindowedGLContext&);
  221610. };
  221611. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  221612. const OpenGLPixelFormat& pixelFormat,
  221613. const OpenGLContext* const contextToShareWith)
  221614. {
  221615. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  221616. contextToShareWith != 0 ? (AGLContext) contextToShareWith->getRawContext() : 0);
  221617. if (c->renderContext == 0)
  221618. deleteAndZero (c);
  221619. return c;
  221620. }
  221621. void juce_glViewport (const int w, const int h)
  221622. {
  221623. glViewport (0, 0, w, h);
  221624. }
  221625. static int getAGLAttribute (AGLPixelFormat p, const GLint attrib)
  221626. {
  221627. GLint result = 0;
  221628. aglDescribePixelFormat (p, attrib, &result);
  221629. return result;
  221630. }
  221631. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  221632. OwnedArray <OpenGLPixelFormat>& results)
  221633. {
  221634. GLint attribs [64];
  221635. int n = 0;
  221636. attribs[n++] = AGL_RGBA;
  221637. attribs[n++] = AGL_DOUBLEBUFFER;
  221638. attribs[n++] = AGL_ACCELERATED;
  221639. attribs[n++] = AGL_NO_RECOVERY;
  221640. attribs[n++] = AGL_NONE;
  221641. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  221642. while (p != 0)
  221643. {
  221644. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  221645. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  221646. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  221647. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  221648. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  221649. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  221650. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  221651. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  221652. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  221653. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  221654. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  221655. results.add (pf);
  221656. p = aglNextPixelFormat (p);
  221657. }
  221658. }
  221659. #endif
  221660. END_JUCE_NAMESPACE
  221661. /********* End of inlined file: juce_mac_Windowing.cpp *********/
  221662. #endif
  221663. #endif